Fix CodeQL code-scanning alerts
- Values pasted into eval'd or inline-script code go through lit() (scripts/lib/js-literal.js), which escapes <, >, /, U+2028 and U+2029 after JSON.stringify - build test and i18n-check read script tags with a DOM parser or a plain search, not HTML regexes - mcp.js parses the Authorization header without a backtracking regex
This commit is contained in:
parent
e7729d0a1e
commit
dd6e4f4f8a
89 changed files with 316 additions and 213 deletions
|
|
@ -12,6 +12,7 @@ const http = require('node:http');
|
|||
const path = require('node:path');
|
||||
const { assemble, ROOT } = require('./lib/page');
|
||||
const { createRelay } = require('./agent/relay');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
|
||||
// --host/--port; a bare --host binds loopback (never undefined, which would listen on every interface).
|
||||
const argOf = (k) => { const i = process.argv.indexOf(k); return i >= 0 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--') ? process.argv[i + 1] : null; };
|
||||
|
|
@ -27,7 +28,7 @@ const clients = new Set();
|
|||
function page() {
|
||||
const { html, map } = assemble({ dev: true });
|
||||
// Errors report a line of the assembled page; the console also says which file under src/ that is.
|
||||
const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${JSON.stringify(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`;
|
||||
const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${lit(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`;
|
||||
return html.replace('</body>', `${hint}${RELOAD}</body>`);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ const os = require('node:os');
|
|||
const http = require('node:http');
|
||||
const path = require('node:path');
|
||||
const { assemble, ROOT } = require('./lib/page');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (k, d) => { const i = args.indexOf('--' + k); return i >= 0 ? args[i + 1] : d; };
|
||||
|
|
@ -27,7 +28,7 @@ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; ch
|
|||
// An exported save is {app, version, S}; a plain one is S itself.
|
||||
const save = (() => { const d = JSON.parse(fs.readFileSync(SAVE, 'utf8')); return JSON.stringify({ S: d && d.S && d.S.pops ? d.S : d }); })();
|
||||
const client = fs.readFileSync(path.join(__dirname, 'lib', 'gpu-bench-client.js'), 'utf8');
|
||||
const page = () => assemble().html.replace('</body>', `<script>window.__BENCH__=${JSON.stringify({ secs: SECS })};</script><script>${client}</script></body>`);
|
||||
const page = () => assemble().html.replace('</body>', `<script>window.__BENCH__=${lit({ secs: SECS })};</script><script>${client}</script></body>`);
|
||||
|
||||
/* Only the page this server hands out may talk to it. Any other site open in the same browser could otherwise
|
||||
POST results (printed to this terminal, written to --out) or, through DNS rebinding, read the save. So the Host
|
||||
|
|
|
|||
|
|
@ -20,10 +20,21 @@ const SITE = path.join(__dirname, '..', 'site');
|
|||
const page = () => require('./lib/page').assemble({ dev: true }).html;
|
||||
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
|
||||
|
||||
// The bodies of the page's bare <script> tags. Our own assembled page, so a plain search is enough.
|
||||
function inlineScripts(html) {
|
||||
const out = [];
|
||||
for (let i = html.indexOf('<script>'); i >= 0; i = html.indexOf('<script>', i)) {
|
||||
const end = html.indexOf('</script>', i += 8);
|
||||
if (end < 0) break;
|
||||
out.push(html.slice(i, end)); i = end;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The labels the game uses, with problems in how they are used.
|
||||
function sourceLabels(html) {
|
||||
const labels = new Set(), problems = [];
|
||||
const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((m) => m[1]).join('\n');
|
||||
const scripts = inlineScripts(html).join('\n');
|
||||
for (const m of scripts.matchAll(CALL)) {
|
||||
const l = m[2].slice(1, -1);
|
||||
if (!LABEL.test(l)) problems.push(`${m[1]}(${m[2].slice(0, 60)}…): not a label like 'area.some_words'`);
|
||||
|
|
|
|||
5
scripts/lib/js-literal.js
Normal file
5
scripts/lib/js-literal.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
// A value as a JavaScript literal, safe to paste into code that is eval'd or into an inline <script>: JSON, with the
|
||||
// characters that could end a script tag or break a string (<, >, /, U+2028, U+2029) written as \u escapes.
|
||||
const ESC = /[<>\/\u2028\u2029]/g;
|
||||
const lit = (v) => { const s = JSON.stringify(v); return s === undefined ? 'undefined' : s.replace(ESC, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')); };
|
||||
module.exports = { lit };
|
||||
|
|
@ -3,6 +3,7 @@
|
|||
// an exchange port at home on day 0, a NOC intern on standing orders for transit and routers, then the generator's
|
||||
// plan one step at a time whenever the bank allows it, upgrading any wave that runs hot. It never reads the goal, so the
|
||||
// same seed and plan always play the same game, and the generator can calibrate a goal from what it reached.
|
||||
const { lit } = require('./js-literal');
|
||||
const BOT = String.raw`(()=>{
|
||||
const B=window.__wsBot={};
|
||||
const cheapNet=(c,avoid)=>NETS.filter(n=>n.price&&sellsAt(n,c)&&!avoid.includes(n.id)&&!S.transit.some(t=>t.city===c&&t.net===n.id)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0];
|
||||
|
|
@ -41,9 +42,9 @@ const install = (ev) => { if (!ev('!!window.__wsBot')) ev(BOT); };
|
|||
// run out. Returns the day the goal was first met (or null), what the goal measure read each day, and the end state.
|
||||
function play(ev, file, plan, { days, stop = true, measure = 'wsMeasure()' } = {}) {
|
||||
install(ev);
|
||||
ev(`localStorage.removeItem('sot-wkscn');wsBegin(${JSON.stringify(file)},'Ref');if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`);
|
||||
ev(`localStorage.removeItem('sot-wkscn');wsBegin(${lit(file)},'Ref');if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`);
|
||||
if (ev('!!(S.scn&&S.scn.wk)') !== true) throw new Error('the game would not start this scenario');
|
||||
ev(`__wsBot.start(${JSON.stringify(plan)})`);
|
||||
ev(`__wsBot.start(${lit(plan)})`);
|
||||
const won0 = ev('wsOk()'), n = days || ev('S.scn.days');
|
||||
// Each day: the bot moves, the day ticks (scnTick records a win), and we note the measure.
|
||||
const out = JSON.parse(ev(`(()=>{const m=[];let won=null;for(let i=0;i<${n};i++){__wsBot.day();dayTick();closeModal();m.push(+(${measure}).toFixed(3));if(won===null&&S.scn.done)won=S.scn.done;if(won!==null&&${stop})break;if(S.lost)break;}return JSON.stringify({won,m,lost:!!S.lost,day:S.day,cash:Math.round(S.cash)});})()`));
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
// ['scrub', c, tier] a scrubbing center ['pnis'] a PNI with every unreached network that takes one
|
||||
// ['pni', c, net, tier] one PNI with that network there ['last', c] transit there only as a last resort
|
||||
// ['loans'] take every loan the banks offer, from now on (the cheese plans)
|
||||
const { lit } = require('./js-literal');
|
||||
const REF = String.raw`(()=>{
|
||||
const Q=window.__ref={log:[]};
|
||||
const quiet=f=>{const t=window.toast;window.toast=()=>{};try{return f();}finally{window.toast=t;}};
|
||||
|
|
@ -66,7 +67,7 @@ Q.start=(steps,o={})=>quiet(()=>{Q.steps=steps;Q.i=0;Q.avoid=o.avoid||[];Q.step(
|
|||
function play(ev, id, plan, { seed, days, avoid } = {}) {
|
||||
ev(`localStorage.removeItem('sot-scn');beginGame('Ref',SCN.find(x=>x.id==='${id}').city,{scn:SCN.find(x=>x.id==='${id}')${seed ? ',seed:' + seed : ''}});if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`);
|
||||
if (ev('typeof __ref') === 'undefined') ev(REF);
|
||||
ev(`__ref.start(${JSON.stringify(plan)},${JSON.stringify({ avoid })})`);
|
||||
ev(`__ref.start(${lit(plan)},${lit({ avoid })})`);
|
||||
const n = days || ev('S.scn.days');
|
||||
return JSON.parse(ev(`(()=>{let won=null;for(let i=0;i<${n};i++){__ref.day();dayTick();closeModal();if(S.scn.done){won=S.scn.done;break;}if(S.lost||S.scn.failed)break;}
|
||||
return JSON.stringify({won,lost:!!S.lost,day:S.day,limit:S.scn.days,cash:Math.round(S.cash),served:Math.round(R.served)});})()`));
|
||||
|
|
|
|||
|
|
@ -137,8 +137,9 @@ function createHttpServer(factory, { host, allow = [], token = null } = {}) {
|
|||
const o = validateOriginHeader(req.headers.origin, origins);
|
||||
if (!o.ok) return deny(res, 403, 'Origin not allowed: a web page may not drive this server.');
|
||||
if (token) {
|
||||
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization || '');
|
||||
if (!m || !sameToken(m[1].trim(), token)) return deny(res, 401, 'A bearer token is required.', { 'www-authenticate': 'Bearer realm="seriesoftubes"' });
|
||||
const auth = String(req.headers.authorization || '').trim(), sp = auth.search(/\s/);
|
||||
const given = sp > 0 && auth.slice(0, sp).toLowerCase() === 'bearer' ? auth.slice(sp + 1).trim() : '';
|
||||
if (!given || !sameToken(given, token)) return deny(res, 401, 'A bearer token is required.', { 'www-authenticate': 'Bearer realm="seriesoftubes"' });
|
||||
}
|
||||
handle(req, res);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ const args = process.argv.slice(2);
|
|||
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const page = require('./lib/page');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
// Pages as files: the browser run opens them from disk.
|
||||
const HEAD = opt('--head', null) || page.pageFile();
|
||||
const BASE = opt('--base', null) || (opt('--base-ref', null) && (() => {
|
||||
|
|
@ -46,7 +47,7 @@ const METRICS = [
|
|||
|
||||
function open(file) {
|
||||
const { ev, errors } = load({ file, seed: 777 });
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();renderAll();`);
|
||||
ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();renderAll();`);
|
||||
const time = (body) => ev(`(()=>{const t=performance.now();${body};return performance.now()-t;})()`);
|
||||
// What the network carries, to tell a pure speed-up from a change in how traffic is routed.
|
||||
const outcome = () => ev(`(()=>{compute();const r=[R.served,R.demand,R.reach,R.peered,JSON.stringify(R.egT),...Object.keys(R.citySrv).sort().map(c=>R.citySrv[c]),...S.links.map(l=>R.load[l.id]||0)];
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@
|
|||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { game, world } = require('./weekly-puzzle');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const SCHEMA = 1, HISTORY = 4, ATTEMPTS = 40, DEM_MAX = 380;
|
||||
|
|
@ -38,7 +39,7 @@ const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`));
|
|||
// ---------- playing the game ----------
|
||||
// Load a run definition into the page as this week's, with the briefs known so far.
|
||||
function stage(ev, key, hq, briefs) {
|
||||
ev(`UI.arWk={key:'${key}',def:{id:arWkId('${key}'),key:'${key}',wk:true,n:'',j:'',hq:'${hq}',via:[],budget:2e7,briefs:${JSON.stringify(briefs)},rev:1},at:Date.now()}`);
|
||||
ev(`UI.arWk={key:'${key}',def:{id:arWkId('${key}'),key:'${key}',wk:true,n:'',j:'',hq:'${hq}',via:[],budget:2e7,briefs:${lit(briefs)},rev:1},at:Date.now()}`);
|
||||
}
|
||||
// Lay one tube the way a player does: a diverse trench when the pair already has one overland. The size is what all
|
||||
// the traffic needs (100G, or 400G once there is more than 100G), smaller where a long cable cannot take it.
|
||||
|
|
@ -62,7 +63,7 @@ function step(ev, s) {
|
|||
}
|
||||
// Room for the traffic: upsize the busiest tube that is not cut (or, when it cannot grow, lay a second one beside it).
|
||||
function makeRoom(ev, W, steps, cut) {
|
||||
const ls = J(ev, `(()=>{${cut ? `for(const l of S.links)if(pzUnit(l)===${JSON.stringify(cut)})l.cut=1;` : ''}compute();const o=S.links.map((l,i)=>({i,a:l.a,b:l.b,cut:!!l.cut,tier:l.tier,u:(R.load[l.id]||0)/capOf(l)})).filter(x=>!x.cut).sort((x,y)=>y.u-x.u);for(const l of S.links)l.cut=0;compute();return o;})()`);
|
||||
const ls = J(ev, `(()=>{${cut ? `for(const l of S.links)if(pzUnit(l)===${lit(cut)})l.cut=1;` : ''}compute();const o=S.links.map((l,i)=>({i,a:l.a,b:l.b,cut:!!l.cut,tier:l.tier,u:(R.load[l.id]||0)/capOf(l)})).filter(x=>!x.cut).sort((x,y)=>y.u-x.u);for(const l of S.links)l.cut=0;compute();return o;})()`);
|
||||
for (const l of ls.slice(0, 3)) {
|
||||
if (l.tier < 2) { const t = ev(`(()=>{const l=S.links[${l.i}];ACT.pzTier({id:l.id,tier:${l.tier + 1}});return S.links[${l.i}].tier;})()`); if (t === l.tier + 1) { steps.push(['@tier', l.i, t]); return; } }
|
||||
const o = W.opts(l.a, l.b).filter((x) => !x.second).sort((x, y) => x.cost - y.cost)[0];
|
||||
|
|
@ -90,7 +91,7 @@ function solveBrief(ev, W, steps) {
|
|||
const f = reviewFail(ev); if (!f) return;
|
||||
if (f.short.length && !f.gold.length) { makeRoom(ev, W, steps, f.u); continue; }
|
||||
// A cut strands a mission-critical site: join the stranded side to the rest another way.
|
||||
const rest = J(ev, `Object.keys(S.pops).filter(c=>!${JSON.stringify(f.dark)}.includes(c))`), o = best(f.dark, rest, f.u);
|
||||
const rest = J(ev, `Object.keys(S.pops).filter(c=>!${lit(f.dark)}.includes(c))`), o = best(f.dark, rest, f.u);
|
||||
if (!o) throw new Error('no second way'); steps.push(lay(ev, o.a, o.b, o.via));
|
||||
}
|
||||
throw new Error('the brief would not pass');
|
||||
|
|
@ -113,7 +114,7 @@ function design(kind, ev, W, r, s) {
|
|||
if (kind === 'grow') { const cs = pops.filter((c) => c !== hq).map((c) => [c, ev(`arDem('${c}')`)]).sort((x, y) => y[1] - x[1]); if (!cs.length || s.room < 60) return null;
|
||||
const [c, d] = cs[0], g = d + Math.min(s.room, pick(r, [60, 90, 120])); s.room -= g - d; return { dem: { [c]: g } }; }
|
||||
if (kind === 'ring') { const cs = pops.filter((c) => c !== hq).sort((a, b) => W.km(hq, a) - W.km(hq, b)).slice(0, 2); if (cs.length < 2) return null;
|
||||
const ring = [hq, ...cs]; if (ev(`arRingOk(${JSON.stringify(ring)})`)) return null; return { ring }; }
|
||||
const ring = [hq, ...cs]; if (ev(`arRingOk(${lit(ring)})`)) return null; return { ring }; }
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -142,11 +143,11 @@ function play(g, W, key, hq, plan, r, sites) {
|
|||
|
||||
// Replay a file the way a player would, from its own reference: it must pass every brief and earn three stars.
|
||||
function verify(g, j, key) {
|
||||
const { ev } = g, def = J(ev, `arWkValid(${JSON.stringify(j)},'${key}')`);
|
||||
const { ev } = g, def = J(ev, `arWkValid(${lit(j)},'${key}')`);
|
||||
if (!def) return { ok: false, why: 'the game rejects it' };
|
||||
if (!j.ref || !Array.isArray(j.ref.steps) || j.ref.steps.length !== def.briefs.length) return { ok: false, why: 'no reference' };
|
||||
try {
|
||||
ev(`UI.arWk={key:'${key}',def:arWkValid(${JSON.stringify(j)},'${key}'),at:Date.now()}`);
|
||||
ev(`UI.arWk={key:'${key}',def:arWkValid(${lit(j)},'${key}'),at:Date.now()}`);
|
||||
ev(`ACT.pzArStart({id:arWkId('${key}')})`);
|
||||
for (let i = 0; i < def.briefs.length; i++) {
|
||||
for (const st of j.ref.steps[i]) step(ev, st);
|
||||
|
|
@ -189,7 +190,7 @@ function check(g, dir, now = Date.now()) {
|
|||
const { ev } = g, bad = [], keys = list(dir);
|
||||
for (const k of keys) {
|
||||
let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; }
|
||||
if (!ev(`!!arWkValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
|
||||
if (!ev(`!!arWkValid(${lit(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
|
||||
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); }
|
||||
}
|
||||
if (keys.length) {
|
||||
|
|
@ -204,7 +205,7 @@ function refresh(g, dir, now = Date.now()) {
|
|||
const { ev } = g, fixed = [], bad = [];
|
||||
for (const k of list(dir)) {
|
||||
let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated below */ }
|
||||
const valid = !!j && ev(`!!arWkValid(${JSON.stringify(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
|
||||
const valid = !!j && ev(`!!arWkValid(${lit(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
|
||||
if (valid && (!live || verify(g, j, k).ok)) continue;
|
||||
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
|
||||
try { writeWeek(dir, Object.assign(generate(g, k, dir), { rev })); fixed.push(`${k}: regenerated as rev ${rev}`); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); }
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ const path = require('node:path');
|
|||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const SV = require('./lib/puzzle-solver');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
const SCHEMA = 2, HISTORY = 4, THEME_GAP = 3, REG_GAP = 2, ATTEMPTS = 40, KEEP = 6;
|
||||
const THEMES = ['tour', 'ring', 'detour', 'ocean', 'islands', 'sprint'];
|
||||
|
||||
|
|
@ -255,7 +256,7 @@ const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^
|
|||
// too, for the N-1 build), as the game routes it, with the cheapest routers that fit.
|
||||
const TIER_G = [10, 100, 400];
|
||||
function size(ev, def, links, n1) {
|
||||
ev(`pzBegin(${JSON.stringify(def)})`);
|
||||
ev(`pzBegin(${lit(def)})`);
|
||||
const tot = def.dem.reduce((a, f) => a + f.g, 0), t0 = Math.max(0, TIER_G.findIndex((g) => g >= tot));
|
||||
for (let t = t0; t < TIER_G.length; t++) {
|
||||
const L = [...links.map((l) => [l.a, l.b, l.via, t, 0]), ...def.dem.map((f, i) => f.ms ? ['@route', i, 'fast'] : null).filter(Boolean)], j = SV.judge(ev, L);
|
||||
|
|
@ -265,8 +266,8 @@ function size(ev, def, links, n1) {
|
|||
}
|
||||
// Plays a sized build (links and routers) in the game and returns the stars it earns.
|
||||
function play(ev, def, b) {
|
||||
ev(`localStorage.removeItem('sot-puzzles');pzBegin(${JSON.stringify(def)})`);
|
||||
SV.judge(ev, b.links); ev(`pzsApplyRt(${JSON.stringify(b.rt)})`);
|
||||
ev(`localStorage.removeItem('sot-puzzles');pzBegin(${lit(def)})`);
|
||||
SV.judge(ev, b.links); ev(`pzsApplyRt(${lit(b.rt)})`);
|
||||
return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))'));
|
||||
}
|
||||
const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, src: P.src, dem: P.dem, via: P.via, avoid: P.avoid, budget,
|
||||
|
|
@ -285,7 +286,7 @@ function sized(g, W, P, def) {
|
|||
}
|
||||
// The game's own validator decides what a puzzle is; then both references must earn their stars.
|
||||
function verify(g, W, j, key, known) {
|
||||
const { ev } = g, def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(j)},'${key}'))`));
|
||||
const { ev } = g, def = JSON.parse(ev(`JSON.stringify(pzWkValid(${lit(j)},'${key}'))`));
|
||||
if (!def) return { ok: false, why: 'the game rejects the file' };
|
||||
const P = shape(def), sol = known || sized(g, W, P, def);
|
||||
if (!sol) return { ok: false, why: 'no build delivers the traffic and survives a cut' };
|
||||
|
|
@ -321,7 +322,7 @@ function generate(g, key, dir) {
|
|||
cands.sort((a, b) => b.score - a.score);
|
||||
for (const c of cands) {
|
||||
// Sized with the traffic: the budget sits just above the cheapest N-1 build found.
|
||||
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(fileOf(key, c.P, 1e6, c.w, { one: { cost: 0 }, three: { cost: 0 } }))},'${key}'))`));
|
||||
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${lit(fileOf(key, c.P, 1e6, c.w, { one: { cost: 0 }, three: { cost: 0 } }))},'${key}'))`));
|
||||
const sol = def && sized(g, W, c.P, def);
|
||||
if (!sol) { console.warn(`${key}: rejected a ${theme} puzzle: no build carries its traffic`); continue; }
|
||||
const j = fileOf(key, c.P, budgetOf(sol), c.w, sol), v = verify(g, W, j, key, sol);
|
||||
|
|
@ -337,7 +338,7 @@ function check(g, dir, now = Date.now()) {
|
|||
const { ev } = g, W = world(ev), bad = [], keys = list(dir);
|
||||
for (const k of keys) {
|
||||
let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; }
|
||||
if (!ev(`!!pzWkValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
|
||||
if (!ev(`!!pzWkValid(${lit(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
|
||||
if (!j.ref || !Number.isInteger(j.ref.one) || !Number.isInteger(j.ref.three) || j.ref.one > j.ref.three || j.ref.three > j.budget) { bad.push(`${k}: bad ref`); continue; }
|
||||
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, W, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); }
|
||||
}
|
||||
|
|
@ -359,7 +360,7 @@ function refresh(g, dir, now = Date.now()) {
|
|||
for (const k of list(dir)) {
|
||||
const f = path.join(dir, k + '.json');
|
||||
let j = null; try { j = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { /* regenerated below */ }
|
||||
const valid = !!j && ev(`!!pzWkValid(${JSON.stringify(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
|
||||
const valid = !!j && ev(`!!pzWkValid(${lit(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
|
||||
if (valid && !live) continue;
|
||||
const v = valid ? verify(g, W, j, k) : null;
|
||||
if (v && v.ok) {
|
||||
|
|
@ -369,7 +370,7 @@ function refresh(g, dir, now = Date.now()) {
|
|||
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
|
||||
let n = null;
|
||||
if (valid) {
|
||||
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(j)},'${k}'))`));
|
||||
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${lit(j)},'${k}'))`));
|
||||
const sol = sized(g, W, shape(def), def);
|
||||
if (sol) {
|
||||
const c = Object.assign({}, j, { budget: budgetOf(sol), ref: { one: sol.one.cost, three: sol.three.cost }, rev });
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@
|
|||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const BOT = require('./lib/scenario-bot');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const SCHEMA = 1, HISTORY = 4, THEME_GAP = 4, REG_GAP = 3, ATTEMPTS = 12, AT = 0.8, MARGIN = 0.9;
|
||||
|
|
@ -144,7 +145,7 @@ const fileOf = (key, d, seed, extra) => ({ v: SCHEMA, key, theme: d.f.theme, cit
|
|||
// Cable plans are made in the game, once the scenario's rules are in force: the shortest chain of POPs to each target.
|
||||
function cablePlan(ev, plan) {
|
||||
if (!plan.targets) return plan;
|
||||
const steps = J(ev, `(()=>{const home=S.scn.home,T=${JSON.stringify(plan.targets)},fast=${!!plan.fast},out=[],have=new Set([home]);
|
||||
const steps = J(ev, `(()=>{const home=S.scn.home,T=${lit(plan.targets)},fast=${!!plan.fast},out=[],have=new Set([home]);
|
||||
const ok=c=>pzCityOk(c)&&cityOn(c)&&!cnCity(c);
|
||||
const edges=u=>{const o=[];for(const p of CABLE_PAIRS){const v=p.a===u?p.b:p.b===u?p.a:null;if(!v||!ok(v))continue;const cs=cablesOk(u,v);if(!cs.length)continue;
|
||||
const c=cs.slice().sort((x,y)=>x.km*(CAB[x.cid].lat||1)-y.km*(CAB[y.cid].lat||1))[0];o.push([v,c.km*(CAB[c.cid].lat||1)/200,c.cid]);}
|
||||
|
|
@ -158,7 +159,7 @@ function cablePlan(ev, plan) {
|
|||
// Starts the draft in the game (so its rules apply), finishes the plan, and plays it with the reference player.
|
||||
function run(g, file, plan, days) {
|
||||
const { ev } = g;
|
||||
ev(`localStorage.removeItem('sot-wkscn');wsBegin(${JSON.stringify(file)},'Ref');if(UI.pendGame)ACT.pitchSkip()`);
|
||||
ev(`localStorage.removeItem('sot-wkscn');wsBegin(${lit(file)},'Ref');if(UI.pendGame)ACT.pitchSkip()`);
|
||||
const p = cablePlan(ev, plan); if (!p || (plan.targets && p.steps.length < 2)) return null;
|
||||
return { plan: p, res: BOT.play(ev, { ...file, ref: p }, p, { days, stop: false }) };
|
||||
}
|
||||
|
|
@ -195,7 +196,7 @@ function calibrate(g, d, key, seed) {
|
|||
// The game's validator decides what a scenario is; then it must need play, and the reference must win with time to spare.
|
||||
function verify(g, j) {
|
||||
const { ev } = g;
|
||||
if (!ev(`!!wsValid(${JSON.stringify(j)},'${j.key}')`)) return { ok: false, why: 'the game rejects the file' };
|
||||
if (!ev(`!!wsValid(${lit(j)},'${j.key}')`)) return { ok: false, why: 'the game rejects the file' };
|
||||
// Played with the longest clock the game allows, so a late win still shows its day (the days change nothing else).
|
||||
const res = BOT.play(ev, { ...j, days: 400 }, j.ref, { stop: true });
|
||||
if (res.won0) return { ok: false, why: 'won on day 0' };
|
||||
|
|
@ -242,7 +243,7 @@ function check(g, dir, now = Date.now()) {
|
|||
const { ev } = g, bad = [], keys = list(dir);
|
||||
for (const k of keys) {
|
||||
let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; }
|
||||
if (!ev(`!!wsValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
|
||||
if (!ev(`!!wsValid(${lit(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
|
||||
if (!j.ref || !Array.isArray(j.ref.steps)) { bad.push(`${k}: no reference plan`); continue; }
|
||||
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j); if (!v.ok) bad.push(`${k}: ${v.why}`); else if (v.par !== j.par) bad.push(`${k}: par is ${j.par}, the reference wins on day ${v.par}`); }
|
||||
}
|
||||
|
|
@ -258,7 +259,7 @@ function refresh(g, dir, now = Date.now()) {
|
|||
const { ev } = g, fixed = [], bad = [];
|
||||
for (const k of list(dir)) {
|
||||
let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated */ }
|
||||
const valid = !!j && ev(`!!wsValid(${JSON.stringify(j)},'${k}')`) && j.ref && Array.isArray(j.ref.steps), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
|
||||
const valid = !!j && ev(`!!wsValid(${lit(j)},'${k}')`) && j.ref && Array.isArray(j.ref.steps), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
|
||||
if (valid && !live) continue;
|
||||
const v = valid ? verify(g, j) : null;
|
||||
if (v && v.ok) { if (v.par !== j.par) { j.par = v.par; writeWeek(dir, j); fixed.push(`${k}: new par ${v.par}`); } continue; }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue