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:
Frederic Jung 2026-11-05 21:24:26 +01:00
parent e7729d0a1e
commit dd6e4f4f8a
No known key found for this signature in database
89 changed files with 316 additions and 213 deletions

View file

@ -12,6 +12,7 @@ const http = require('node:http');
const path = require('node:path'); const path = require('node:path');
const { assemble, ROOT } = require('./lib/page'); const { assemble, ROOT } = require('./lib/page');
const { createRelay } = require('./agent/relay'); 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). // --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; }; 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() { function page() {
const { html, map } = assemble({ dev: true }); const { html, map } = assemble({ dev: true });
// Errors report a line of the assembled page; the console also says which file under src/ that is. // 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>`); return html.replace('</body>', `${hint}${RELOAD}</body>`);
} }

View file

@ -15,6 +15,7 @@ const os = require('node:os');
const http = require('node:http'); const http = require('node:http');
const path = require('node:path'); const path = require('node:path');
const { assemble, ROOT } = require('./lib/page'); const { assemble, ROOT } = require('./lib/page');
const { lit } = require('./lib/js-literal');
const args = process.argv.slice(2); const args = process.argv.slice(2);
const opt = (k, d) => { const i = args.indexOf('--' + k); return i >= 0 ? args[i + 1] : d; }; 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. // 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 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 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 /* 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 POST results (printed to this terminal, written to --out) or, through DNS rebinding, read the save. So the Host

View file

@ -20,10 +20,21 @@ const SITE = path.join(__dirname, '..', 'site');
const page = () => require('./lib/page').assemble({ dev: true }).html; const page = () => require('./lib/page').assemble({ dev: true }).html;
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/; 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. // The labels the game uses, with problems in how they are used.
function sourceLabels(html) { function sourceLabels(html) {
const labels = new Set(), problems = []; 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)) { for (const m of scripts.matchAll(CALL)) {
const l = m[2].slice(1, -1); 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'`); if (!LABEL.test(l)) problems.push(`${m[1]}(${m[2].slice(0, 60)}…): not a label like 'area.some_words'`);

View 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 };

View file

@ -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 // 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 // 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. // 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 BOT = String.raw`(()=>{
const B=window.__wsBot={}; 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]; 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. // 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()' } = {}) { function play(ev, file, plan, { days, stop = true, measure = 'wsMeasure()' } = {}) {
install(ev); 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'); 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'); 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. // 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)});})()`)); 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)});})()`));

View file

@ -11,6 +11,7 @@
// ['scrub', c, tier] a scrubbing center ['pnis'] a PNI with every unreached network that takes one // ['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 // ['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) // ['loans'] take every loan the banks offer, from now on (the cheese plans)
const { lit } = require('./js-literal');
const REF = String.raw`(()=>{ const REF = String.raw`(()=>{
const Q=window.__ref={log:[]}; const Q=window.__ref={log:[]};
const quiet=f=>{const t=window.toast;window.toast=()=>{};try{return f();}finally{window.toast=t;}}; 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 } = {}) { 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()`); 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); 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'); 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.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)});})()`)); return JSON.stringify({won,lost:!!S.lost,day:S.day,limit:S.scn.days,cash:Math.round(S.cash),served:Math.round(R.served)});})()`));

View file

@ -137,8 +137,9 @@ function createHttpServer(factory, { host, allow = [], token = null } = {}) {
const o = validateOriginHeader(req.headers.origin, origins); 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 (!o.ok) return deny(res, 403, 'Origin not allowed: a web page may not drive this server.');
if (token) { if (token) {
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization || ''); const auth = String(req.headers.authorization || '').trim(), sp = auth.search(/\s/);
if (!m || !sameToken(m[1].trim(), token)) return deny(res, 401, 'A bearer token is required.', { 'www-authenticate': 'Bearer realm="seriesoftubes"' }); 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); handle(req, res);
}); });

View file

@ -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 opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
const ROOT = path.join(__dirname, '..'); const ROOT = path.join(__dirname, '..');
const page = require('./lib/page'); const page = require('./lib/page');
const { lit } = require('./lib/js-literal');
// Pages as files: the browser run opens them from disk. // Pages as files: the browser run opens them from disk.
const HEAD = opt('--head', null) || page.pageFile(); const HEAD = opt('--head', null) || page.pageFile();
const BASE = opt('--base', null) || (opt('--base-ref', null) && (() => { const BASE = opt('--base', null) || (opt('--base-ref', null) && (() => {
@ -46,7 +47,7 @@ const METRICS = [
function open(file) { function open(file) {
const { ev, errors } = load({ file, seed: 777 }); 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;})()`); 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. // 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)]; 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)];

View file

@ -21,6 +21,7 @@
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { game, world } = require('./weekly-puzzle'); const { game, world } = require('./weekly-puzzle');
const { lit } = require('./lib/js-literal');
const ROOT = path.join(__dirname, '..'); const ROOT = path.join(__dirname, '..');
const SCHEMA = 1, HISTORY = 4, ATTEMPTS = 40, DEM_MAX = 380; 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 ---------- // ---------- playing the game ----------
// Load a run definition into the page as this week's, with the briefs known so far. // Load a run definition into the page as this week's, with the briefs known so far.
function stage(ev, key, hq, briefs) { 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 // 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. // 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). // 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) { 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)) { 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; } } 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]; 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; const f = reviewFail(ev); if (!f) return;
if (f.short.length && !f.gold.length) { makeRoom(ev, W, steps, f.u); continue; } 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. // 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)); 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'); 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; 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 } }; } 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; 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; 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. // 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) { 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 (!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' }; if (!j.ref || !Array.isArray(j.ref.steps) || j.ref.steps.length !== def.briefs.length) return { ok: false, why: 'no reference' };
try { 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}')})`); ev(`ACT.pzArStart({id:arWkId('${key}')})`);
for (let i = 0; i < def.briefs.length; i++) { for (let i = 0; i < def.briefs.length; i++) {
for (const st of j.ref.steps[i]) step(ev, st); 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); const { ev } = g, bad = [], keys = list(dir);
for (const k of keys) { 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; } 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 (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); }
} }
if (keys.length) { if (keys.length) {
@ -204,7 +205,7 @@ function refresh(g, dir, now = Date.now()) {
const { ev } = g, fixed = [], bad = []; const { ev } = g, fixed = [], bad = [];
for (const k of list(dir)) { 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 */ } 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; if (valid && (!live || verify(g, j, k).ok)) continue;
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1; 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})`); } 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})`); }

View file

@ -24,6 +24,7 @@ const path = require('node:path');
const ROOT = path.join(__dirname, '..'); const ROOT = path.join(__dirname, '..');
const SV = require('./lib/puzzle-solver'); 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 SCHEMA = 2, HISTORY = 4, THEME_GAP = 3, REG_GAP = 2, ATTEMPTS = 40, KEEP = 6;
const THEMES = ['tour', 'ring', 'detour', 'ocean', 'islands', 'sprint']; 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. // too, for the N-1 build), as the game routes it, with the cheapest routers that fit.
const TIER_G = [10, 100, 400]; const TIER_G = [10, 100, 400];
function size(ev, def, links, n1) { 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)); 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++) { 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); 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. // Plays a sized build (links and routers) in the game and returns the stars it earns.
function play(ev, def, b) { function play(ev, def, b) {
ev(`localStorage.removeItem('sot-puzzles');pzBegin(${JSON.stringify(def)})`); ev(`localStorage.removeItem('sot-puzzles');pzBegin(${lit(def)})`);
SV.judge(ev, b.links); ev(`pzsApplyRt(${JSON.stringify(b.rt)})`); 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()))')); 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, 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. // The game's own validator decides what a puzzle is; then both references must earn their stars.
function verify(g, W, j, key, known) { 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' }; if (!def) return { ok: false, why: 'the game rejects the file' };
const P = shape(def), sol = known || sized(g, W, P, def); 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' }; 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); cands.sort((a, b) => b.score - a.score);
for (const c of cands) { for (const c of cands) {
// Sized with the traffic: the budget sits just above the cheapest N-1 build found. // 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); const sol = def && sized(g, W, c.P, def);
if (!sol) { console.warn(`${key}: rejected a ${theme} puzzle: no build carries its traffic`); continue; } 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); 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); const { ev } = g, W = world(ev), bad = [], keys = list(dir);
for (const k of keys) { 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; } 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 (!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}`); } 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)) { for (const k of list(dir)) {
const f = path.join(dir, k + '.json'); const f = path.join(dir, k + '.json');
let j = null; try { j = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { /* regenerated below */ } 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; if (valid && !live) continue;
const v = valid ? verify(g, W, j, k) : null; const v = valid ? verify(g, W, j, k) : null;
if (v && v.ok) { 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; const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
let n = null; let n = null;
if (valid) { 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); const sol = sized(g, W, shape(def), def);
if (sol) { if (sol) {
const c = Object.assign({}, j, { budget: budgetOf(sol), ref: { one: sol.one.cost, three: sol.three.cost }, rev }); const c = Object.assign({}, j, { budget: budgetOf(sol), ref: { one: sol.one.cost, three: sol.three.cost }, rev });

View file

@ -20,6 +20,7 @@
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const BOT = require('./lib/scenario-bot'); const BOT = require('./lib/scenario-bot');
const { lit } = require('./lib/js-literal');
const ROOT = path.join(__dirname, '..'); const ROOT = path.join(__dirname, '..');
const SCHEMA = 1, HISTORY = 4, THEME_GAP = 4, REG_GAP = 3, ATTEMPTS = 12, AT = 0.8, MARGIN = 0.9; 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. // 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) { function cablePlan(ev, plan) {
if (!plan.targets) return 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 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 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]);} 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. // 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) { function run(g, file, plan, days) {
const { ev } = g; 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; 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 }) }; 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. // 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) { function verify(g, j) {
const { ev } = g; 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). // 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 }); const res = BOT.play(ev, { ...j, days: 400 }, j.ref, { stop: true });
if (res.won0) return { ok: false, why: 'won on day 0' }; 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); const { ev } = g, bad = [], keys = list(dir);
for (const k of keys) { 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; } 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 (!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}`); } 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 = []; const { ev } = g, fixed = [], bad = [];
for (const k of list(dir)) { for (const k of list(dir)) {
let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated */ } 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; if (valid && !live) continue;
const v = valid ? verify(g, j) : null; 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; } if (v && v.ok) { if (v.par !== j.par) { j.par = v.par; writeWeek(dir, j); fixed.push(`${k}: new par ${v.par}`); } continue; }

View file

@ -19,6 +19,7 @@ const { createRelay } = require('../scripts/agent/relay');
const { createRelaySession } = require('../scripts/lib/relay-client'); const { createRelaySession } = require('../scripts/lib/relay-client');
const SERVER = path.join(ROOT, 'scripts', 'mcp.js'); const SERVER = path.join(ROOT, 'scripts', 'mcp.js');
const { wait, until, freePort, kill } = require('./net'); const { wait, until, freePort, kill } = require('./net');
const { lit } = require('../scripts/lib/js-literal');
let PORT; // a free one from the OS, before the first test let PORT; // a free one from the OS, before the first test
test.before(async () => { PORT = await freePort(); }); test.before(async () => { PORT = await freePort(); });
@ -242,7 +243,7 @@ test('the agent\'s clock moves only with advance; a running clock only with time
const { TOOLS } = require('../scripts/lib/mcp-game'); const { TOOLS } = require('../scripts/lib/mcp-game');
const s = createBrowserSession({ port: PORT }); const s = createBrowserSession({ port: PORT });
const w = await TOOLS.find((x) => x.name === 'wait').run(s, { days: 1, maxSeconds: 10 }); const w = await TOOLS.find((x) => x.name === 'wait').run(s, { days: 1, maxSeconds: 10 });
assert.ok(w.daysRun >= 1, `wait returns once a day has passed (${JSON.stringify(w)})`); assert.ok(w.daysRun >= 1, `wait returns once a day has passed (${lit(w)})`);
assert.equal(w.stoppedBecause, null); assert.equal(w.stoppedBecause, null);
await s.close(); await s.close();
} finally { clearInterval(frames); } } finally { clearInterval(frames); }

View file

@ -4,6 +4,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const prefs = (ms = 60000, on = true) => ({ 'sot-agent': JSON.stringify({ on, ms }) }); const prefs = (ms = 60000, on = true) => ({ 'sot-agent': JSON.stringify({ on, ms }) });
const agent = (o = {}) => load({ agent: true, storage: prefs(o.ms), ...o }); const agent = (o = {}) => load({ agent: true, storage: prefs(o.ms), ...o });
@ -51,7 +52,7 @@ test('agent mode only exists where a relay can be reached', () => {
assert.match(a.ev('settingsHtml()'), /Agent API/, 'the Settings sheet has the section'); assert.match(a.ev('settingsHtml()'), /Agent API/, 'the Settings sheet has the section');
// Plain http to an address: yes, wherever the operator bound the dev server. https (the public site cannot even // Plain http to an address: yes, wherever the operator bound the dev server. https (the public site cannot even
// open ws:// from its pages), and DNS names (the relay refuses them): no. // open ws:// from its pages), and DNS names (the relay refuses them): no.
const gate = (p, h) => a.ev(`apiAgentLocal(${JSON.stringify(p)},${JSON.stringify(h)})`); const gate = (p, h) => a.ev(`apiAgentLocal(${lit(p)},${lit(h)})`);
for (const h of ['127.0.0.1', 'localhost', 'tubes.localhost', '10.0.0.4', '192.168.1.5', '203.0.113.7', '[::1]']) assert.equal(gate('http:', h), true, h); for (const h of ['127.0.0.1', 'localhost', 'tubes.localhost', '10.0.0.4', '192.168.1.5', '203.0.113.7', '[::1]']) assert.equal(gate('http:', h), true, h);
assert.equal(gate('https:', 'seriesoftub.es'), false, 'the public site has no relay behind it'); assert.equal(gate('https:', 'seriesoftub.es'), false, 'the public site has no relay behind it');
assert.equal(gate('http:', 'seriesoftub.es'), false); assert.equal(gate('http:', 'seriesoftub.es'), false);

View file

@ -1,8 +1,9 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const choose = (ev, v) => ev(`(()=>{const s=document.getElementById('homeSel');s.value=${JSON.stringify(v)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`); const choose = (ev, v) => ev(`(()=>{const s=document.getElementById('homeSel');s.value=${lit(v)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`);
test('the title screen has one drawer for the home city: the five suggested first, then every city by continent', () => { test('the title screen has one drawer for the home city: the five suggested first, then every city by continent', () => {
const { ev, errors } = load(); const { ev, errors } = load();
assert.equal(ev('S'), null, 'before any game exists'); assert.equal(ev('S'), null, 'before any game exists');

View file

@ -1,15 +1,16 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// #185's sales and repair engines now run as the NOC intern's standing orders, once per game day. // #185's sales and repair engines now run as the NOC intern's standing orders, once per game day.
function setup(ev) { function setup(ev) {
ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});S.lvl=2;S.ops.intern='kevin';S.ops.floor=0;S.rules=makeRules('freeze');compute()"); ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});S.lvl=2;S.ops.intern='kevin';S.ops.floor=0;S.rules=makeRules('freeze');compute()");
} }
const orders = (ev, on) => ev(`for(const k of ${JSON.stringify(on)})S.ops.on[k]=true`); const orders = (ev, on) => ev(`for(const k of ${lit(on)})S.ops.on[k]=true`);
const shift = ev => ev('opsDay(S.day)'); const shift = ev => ev('opsDay(S.day)');
function offer(ev, id, extra = {}) { function offer(ev, id, extra = {}) {
ev(`S.offers.push(${JSON.stringify({ id, city: 'fra', name: id, type: 'dia', bw: 1, rate: 600, reqs: [], exp: 30, ...extra })})`); ev(`S.offers.push(${lit({ id, city: 'fra', name: id, type: 'dia', bw: 1, rate: 600, reqs: [], exp: 30, ...extra })})`);
} }
test('the sales order signs ready offers once per shift, and pausing it stops it', () => { test('the sales order signs ready offers once per shift, and pausing it stops it', () => {

View file

@ -1,9 +1,10 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0"; const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0";
const g = n => `RG.findIndex(r=>r.n===${JSON.stringify(n)})`; const g = n => `RG.findIndex(r=>r.n===${lit(n)})`;
test('every router is classed by the highest backbone it runs', () => { test('every router is classed by the highest backbone it runs', () => {
const { ev, errors } = load(); const { ev, errors } = load();

View file

@ -3,6 +3,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// The preset is read from S.rules.preset until the ruleset feature lands with rulePreset(). // The preset is read from S.rules.preset until the ruleset feature lands with rulePreset().
const start = (ev, preset) => { const start = (ev, preset) => {
@ -140,10 +141,10 @@ test('a variant named after an Object prototype key is not a variant', () => {
const { ev, errors } = load(); const { ev, errors } = load();
start(ev); start(ev);
for (const k of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) { for (const k of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {
ev(`const o=JSON.parse(JSON.stringify(S));o.ach={hello:3};o.achP={hello:${JSON.stringify(k)}};S=migrate(o)`); ev(`const o=JSON.parse(JSON.stringify(S));o.ach={hello:3};o.achP={hello:${lit(k)}};S=migrate(o)`);
assert.equal(ev('S.achP.hello'), 'oncall', k); assert.equal(ev('S.achP.hello'), 'oncall', k);
assert.equal(ev(`bvar(${JSON.stringify(k)}).k`), 'oncall', `bvar(${k})`); assert.equal(ev(`bvar(${lit(k)}).k`), 'oncall', `bvar(${k})`);
ev(`S.rules={preset:${JSON.stringify(k)}}`); ev(`S.rules={preset:${lit(k)}}`);
assert.equal(ev('badgeVar()'), 'oncall', `badgeVar() under preset ${k}`); assert.equal(ev('badgeVar()'), 'oncall', `badgeVar() under preset ${k}`);
} }
ev("S.rules={preset:'oncall'};S.achP.hello='constructor';shareCanvas()"); ev("S.rules={preset:'oncall'};S.achP.hello='constructor';shareCanvas()");

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0"; const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0";
@ -49,7 +50,7 @@ test('transit and peers in Bilbao: the big carriers, Drizzle Electric and Tanger
// A save from before: a Marea link between Ashburn and Madrid. // A save from before: a Marea link between Ashburn and Madrid.
ev("ACT.buildPop({city:'ash'});ACT.buildPop({city:'mad'})"); ev("ACT.buildPop({city:'ash'});ACT.buildPop({city:'mad'})");
const save = JSON.parse(ev("JSON.stringify(Object.assign(JSON.parse(JSON.stringify(S)),{links:[{id:'old1',a:'ash',b:'mad',kind:'wave',tier:2,km:6500,mo:100,cut:0,sub:true,cable:'marea',ready:0}]}))")); const save = JSON.parse(ev("JSON.stringify(Object.assign(JSON.parse(JSON.stringify(S)),{links:[{id:'old1',a:'ash',b:'mad',kind:'wave',tier:2,km:6500,mo:100,cut:0,sub:true,cable:'marea',ready:0}]}))"));
const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(save))})).links.map(l=>[l.a,l.b,l.cable]))`)); const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${lit(JSON.stringify(save))})).links.map(l=>[l.a,l.b,l.cable]))`));
assert.deepEqual(out, [['ash', 'mad', null]], 'the link survives as a plain subsea link'); assert.deepEqual(out, [['ash', 'mad', null]], 'the link survives as a plain subsea link');
for (const z of [0.35, 1.4, 6]) ev(`cam.z=${z};draw(performance.now())`); for (const z of [0.35, 1.4, 6]) ev(`cam.z=${z};draw(performance.now())`);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);

View file

@ -5,6 +5,7 @@ const path = require('node:path');
const { execFileSync } = require('node:child_process'); const { execFileSync } = require('node:child_process');
const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('node:os').tmpdir(), 'tubes-build-')); const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('node:os').tmpdir(), 'tubes-build-'));
const { JSDOM } = require('jsdom');
const root = path.join(__dirname, '..'); const root = path.join(__dirname, '..');
test('build stamps version and date into the site', () => { test('build stamps version and date into the site', () => {
@ -31,9 +32,9 @@ test('head carries the SEO and social metadata', () => {
for (const needle of ['<link rel="canonical" href="https://seriesoftub.es/">', 'property="og:image"', 'name="twitter:card"', 'application/ld+json', 'rel="manifest"', 'name="description"']) { for (const needle of ['<link rel="canonical" href="https://seriesoftub.es/">', 'property="og:image"', 'name="twitter:card"', 'application/ld+json', 'rel="manifest"', 'name="description"']) {
assert.ok(html.includes(needle), `missing ${needle}`); assert.ok(html.includes(needle), `missing ${needle}`);
} }
for (const block of html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/g)) { const ld = new JSDOM(html).window.document.querySelectorAll('script[type="application/ld+json"]');
JSON.parse(block.replace(/<\/?script[^>]*>/g, '')); assert.ok(ld.length > 0, 'structured data is there');
} for (const s of ld) JSON.parse(s.textContent);
}); });
test('a release build refuses to ship without release notes', () => { test('a release build refuses to ship without release notes', () => {
@ -51,7 +52,7 @@ test('src: partials follow the layout rules (docs/adr/0002-one-page-assembled-at
for (const dev of [false, true]) { for (const dev of [false, true]) {
const { html, map } = assemble({ dev }); const { html, map } = assemble({ dev });
assert.equal((html.match(/^const ACT=\{$/gm) || []).length, 1, 'ACT is declared once; other action files use Object.assign(ACT,{…})'); assert.equal((html.match(/^const ACT=\{$/gm) || []).length, 1, 'ACT is declared once; other action files use Object.assign(ACT,{…})');
assert.equal((html.match(/<script>/g) || []).length, 2, 'the language loader and the game: one inline game script'); assert.equal([...new JSDOM(html).window.document.scripts].filter((s) => !s.attributes.length).length, 2, 'the language loader and the game: one inline game script');
assert.ok(map.length > 50 && map.every((m) => m.to >= m.from), 'the line map covers every partial'); assert.ok(map.length > 50 && map.every((m) => m.to >= m.from), 'the line map covers every partial');
} }
}); });

View file

@ -1,8 +1,9 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const g = n => `RG.findIndex(r=>r.n===${JSON.stringify(n)})`; const g = n => `RG.findIndex(r=>r.n===${lit(n)})`;
const setup = (ev, router) => ev(`ACT.start({});S.cash=1e8;S.nextFail=1e9;S.nextEvent=1e9;S.pops.fra.rgen=${g(router)};S.caches=[];compute()`); const setup = (ev, router) => ev(`ACT.start({});S.cash=1e8;S.nextFail=1e9;S.nextEvent=1e9;S.pops.fra.rgen=${g(router)};S.caches=[];compute()`);
const boxes = (n, site = 'a') => `for(let i=0;i<${n};i++)S.caches.push({id:'c${site}'+i,city:'fra',net:'cfl',site:'${site}'});`; const boxes = (n, site = 'a') => `for(let i=0;i<${n};i++)S.caches.push({id:'c${site}'+i,city:'fra',net:'cfl',site:'${site}'});`;

View file

@ -1,13 +1,14 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Calling a bank (#251). rating() comes from revenue and costs, so the tests pin it and the revenue to the case at hand: // Calling a bank (#251). rating() comes from revenue and costs, so the tests pin it and the revenue to the case at hand:
// what is under test is what a rating gets you, not how a rating is earned. // what is under test is what a rating gets you, not how a rating is earned.
function game(t, rt = 'AAA', rev = 5e6) { function game(t, rt = 'AAA', rev = 5e6) {
const h = load(); const h = load();
t.after(() => h.dom.window.close()); t.after(() => h.dom.window.close());
h.ev(`ACT.start({});closeModal();UI.speed=0;S.nextFail=S.nextEvent=1e9;S.loanOffers=[];S.loans=[];window.__rt=${JSON.stringify(rt)};rating=()=>window.__rt;R.revMo=${rev};`); h.ev(`ACT.start({});closeModal();UI.speed=0;S.nextFail=S.nextEvent=1e9;S.loanOffers=[];S.loans=[];window.__rt=${lit(rt)};rating=()=>window.__rt;R.revMo=${rev};`);
return h; return h;
} }
// Arrays from the page belong to another realm: JSON brings them over, so deepEqual compares what is in them. // Arrays from the page belong to another realm: JSON brings them over, so deepEqual compares what is in them.
@ -38,7 +39,7 @@ test('each rating gets its own bank, rate, conditions and payment, and better cr
assert.equal(o.pay, ev(`Math.round(annuity(1e6,${o.apr},36))`)); assert.equal(o.pay, ev(`Math.round(annuity(1e6,${o.apr},36))`));
assert.ok(!o.share, 'no slice of revenue on a called loan'); assert.ok(!o.share, 'no slice of revenue on a called loan');
assert.equal(ev(`rIdx(window.__rt)>=rIdx(BANKS['${o.bank}'].min)`), true, 'the bank would lend at this rating'); assert.equal(ev(`rIdx(window.__rt)>=rIdx(BANKS['${o.bank}'].min)`), true, 'the bank would lend at this rating');
assert.equal(ev(`${JSON.stringify(o.covs)}.every(c=>!!COVS[c])`), true, 'conditions the game knows'); assert.equal(ev(`${lit(o.covs)}.every(c=>!!COVS[c])`), true, 'conditions the game knows');
} }
assert.deepEqual([seen.AA.bank, seen.AAA.bank], ['gs', 'gs']); assert.deepEqual([seen.AA.bank, seen.AAA.bank], ['gs', 'gs']);
assert.deepEqual([seen.AA.apr, seen.AAA.apr], [0.075, 0.06]); assert.deepEqual([seen.AA.apr, seen.AAA.apr], [0.075, 0.06]);
@ -161,7 +162,7 @@ test('weird conditions always apply, and turn over every week, not every call',
ev('S.day=0'); ev('S.day=0');
const w0 = odd(); const w0 = odd();
assert.equal(w0.length, 1); assert.equal(w0.length, 1);
assert.equal(ev(`CALL_ODD.includes(${JSON.stringify(w0[0])})`), true, 'from the weird list'); assert.equal(ev(`CALL_ODD.includes(${lit(w0[0])})`), true, 'from the weird list');
ev('S.day=6'); ev('S.day=6');
assert.deepEqual(odd(), w0, 'calling again the same week gets the same quirk'); assert.deepEqual(odd(), w0, 'calling again the same week gets the same quirk');
ev('S.day=7'); ev('S.day=7');

View file

@ -1,11 +1,12 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// A small network on a fixed seed: Frankfurt, Amsterdam, London and Paris in a ring, with a spur out to Zurich. // A small network on a fixed seed: Frankfurt, Amsterdam, London and Paris in a ring, with a spur out to Zurich.
function net(preset) { function net(preset) {
const { ev, errors, dom } = load(); const { ev, errors, dom } = load();
ev(`beginGame('Monkey Testers','fra',${JSON.stringify({ mode: 'normal', preset })});if(UI.pendGame)ACT.pitchSkip()`); ev(`beginGame('Monkey Testers','fra',${lit({ mode: 'normal', preset })});if(UI.pendGame)ACT.pitchSkip()`);
ev("S.cash=1e9;S.lvl=4;for(const c of ['ams','lon','par','zrh'])ACT.buildPop({city:c})"); ev("S.cash=1e9;S.lvl=4;for(const c of ['ams','lon','par','zrh'])ACT.buildPop({city:c})");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1})"); ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1})");
ev("for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra'],['fra','zrh']]){UI.pending={a,b};ACT.buildLink({tier:1});}closeModal()"); ev("for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra'],['fra','zrh']]){UI.pending={a,b};ACT.buildLink({tier:1});}closeModal()");

View file

@ -3,10 +3,11 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.close()); const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.close());
h.ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();`); return h; }; h.ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();`); return h; };
// R as JSON; DDoS reports hold the live attack, whose `worst` dayTick updates, so it is named by id. // R as JSON; DDoS reports hold the live attack, whose `worst` dayTick updates, so it is named by id.
const rj = (ev) => ev("JSON.stringify(R,(k,v)=>k==='attack'||k==='parent'?(v&&v.id):v)"); const rj = (ev) => ev("JSON.stringify(R,(k,v)=>k==='attack'||k==='parent'?(v&&v.id):v)");

View file

@ -4,11 +4,12 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','lon','par'])ACT.buildPop({city:c});compute()"; const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','lon','par'])ACT.buildPop({city:c});compute()";
// A signed customer, as an accepted offer makes it. // A signed customer, as an accepted offer makes it.
const sign = (ev, o) => ev(`(()=>{const b=clSign(offerCustomer(Object.assign({id:'c'+Math.random().toString(36).slice(2),city:'ams',city2:null,name:'Test Co',type:'dia',bw:5,rate:600,reqs:[],exp:S.day+40},${JSON.stringify(o || {})})));S.biz.push(b);return b.id;})()`); const sign = (ev, o) => ev(`(()=>{const b=clSign(offerCustomer(Object.assign({id:'c'+Math.random().toString(36).slice(2),city:'ams',city2:null,name:'Test Co',type:'dia',bw:5,rate:600,reqs:[],exp:S.day+40},${lit(o || {})})));S.biz.push(b);return b.id;})()`);
const B = (ev, id, k) => ev(`S.biz.find(b=>b.id===${JSON.stringify(id)})${k ? '.' + k : ''}`); const B = (ev, id, k) => ev(`S.biz.find(b=>b.id===${lit(id)})${k ? '.' + k : ''}`);
// An id whose roll for question q (at term end te) is below p, or at least p when above is true. // An id whose roll for question q (at term end te) is below p, or at least p when above is true.
// The rolls hash who the customer is, so the id found here is also its name (a Enterprise DIA in Amsterdam). // The rolls hash who the customer is, so the id found here is also its name (a Enterprise DIA in Amsterdam).
const idFor = (ev, q, p, te, above = false) => ev(`(()=>{for(let i=0;i<20000;i++){const id='x'+i,r=clR({type:'dia',city:'ams',name:id,te:${te}},'${q}');if(${above ? 'r>=' : 'r<'}${p})return id;}})()`); const idFor = (ev, q, p, te, above = false) => ev(`(()=>{for(let i=0;i<20000;i++){const id='x'+i,r=clR({type:'dia',city:'ams',name:id,te:${te}},'${q}');if(${above ? 'r>=' : 'r<'}${p})return id;}})()`);
@ -100,7 +101,7 @@ test('a haggle: 30 days ahead, in Deals; match, meet halfway, let go, or no answ
ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'${id}',type:'dia',bw:5,rate:600,reqs:[],mood:90,since:S.day-800,te:${te},mk:1})`); ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'${id}',type:'dia',bw:5,rate:600,reqs:[],mood:90,since:S.day-800,te:${te},mk:1})`);
ev(`clDay(S.day)`); ev(`clDay(S.day)`);
const hag = JSON.parse(ev(`JSON.stringify(S.biz.find(b=>b.id==='${id}').hag)`)); const hag = JSON.parse(ev(`JSON.stringify(S.biz.find(b=>b.id==='${id}').hag)`));
assert.ok(hag && hag.rate < 600 && hag.rate >= 480 && hag.until === te, `asks 8–20% off until the term ends (${JSON.stringify(hag)})`); assert.ok(hag && hag.rate < 600 && hag.rate >= 480 && hag.until === te, `asks 8–20% off until the term ends (${lit(hag)})`);
ev("UI.left='deals';renderLeft()"); ev("UI.left='deals';renderLeft()");
const deals = ev("document.getElementById('leftBody')?document.getElementById('leftBody').innerHTML:document.getElementById('left').innerHTML"); const deals = ev("document.getElementById('leftBody')?document.getElementById('leftBody').innerHTML:document.getElementById('left').innerHTML");
assert.match(deals, /data-act="renewMatch"/); assert.match(deals, /data-act="renewMatch"/);
@ -180,7 +181,7 @@ test('old saves: renewals spread over the next year, the market from the signing
for (let i = 0; i < 200; i++) s.biz.push({ id: 'old' + i, city: 'ams', name: 'Old ' + i, type: i % 2 ? 'dia' : 'host', bw: 5, rate: 600, mood: 90, since: 200 }); for (let i = 0; i < 200; i++) s.biz.push({ id: 'old' + i, city: 'ams', name: 'Old ' + i, type: i % 2 ? 'dia' : 'host', bw: 5, rate: 600, mood: 90, since: 200 });
s.biz.push({ id: 'bad', city: 'ams', name: 'Bad', type: 'dia', bw: 5, rate: 600, mood: 90, since: 200, te: 'soon', mk: -3, hag: { rate: 'x' } }); s.biz.push({ id: 'bad', city: 'ams', name: 'Bad', type: 'dia', bw: 5, rate: 600, mood: 90, since: 200, te: 'soon', mk: -3, hag: { rate: 'x' } });
s.cl = { odd: 'never', mo: [{ m: 30, won: 3, lost: { acq: 1, nonsense: 5 } }, 'junk'] }; s.cl = { odd: 'never', mo: [{ m: 30, won: 3, lost: { acq: 1, nonsense: 5 } }, 'junk'] };
const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})))`)); const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${lit(JSON.stringify(s))})))`));
const tes = out.biz.map(b => b.te - 1500); const tes = out.biz.map(b => b.te - 1500);
assert.ok(tes.every(t => t >= 30 && t <= 365), 'within the next year, never on day one'); assert.ok(tes.every(t => t >= 30 && t <= 365), 'within the next year, never on day one');
assert.ok(new Set(tes).size > 100, 'spread out, not one wave'); assert.ok(new Set(tes).size > 100, 'spread out, not one wave');

View file

@ -2,6 +2,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Frankfurt has the eyeballs and no transit; all transit is in Amsterdam, 100G of wave away. // Frankfurt has the eyeballs and no transit; all transit is in Amsterdam, 100G of wave away.
const remoteTransit = (ev, flip) => { const remoteTransit = (ev, flip) => {
@ -50,7 +51,7 @@ test('fourteen attacks on a big network keep the save small, and 2.0 saves with
const fs = require('node:fs'), path = require('node:path'); const fs = require('node:fs'), path = require('node:path');
const fx = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8')); const fx = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'));
const { ev, errors } = load({ seed: 3 }); const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(fx.S || fx))}));UI.started=true;compute()`); ev(`S=migrate(JSON.parse(${lit(JSON.stringify(fx.S || fx))}));UI.started=true;compute()`);
const before = ev('JSON.stringify(S).length'); const before = ev('JSON.stringify(S).length');
ev("S.day=Math.max(S.day,50);for(let i=0;i<14;i++){S.ddosStarts=[];ddosAttack(false);}compute()"); ev("S.day=Math.max(S.day,50);for(let i=0;i<14;i++){S.ddosStarts=[];ddosAttack(false);}compute()");
assert.equal(ev('ddosAll().length'), 14); assert.equal(ev('ddosAll().length'), 14);

View file

@ -6,21 +6,22 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Frankfurt with 200 G of subscribers, one 100G Cogentle transit, a game server (the target) and a DIA customer. // Frankfurt with 200 G of subscribers, one 100G Cogentle transit, a game server (the target) and a DIA customer.
function fra(ev, rg = 'Arrrhipster 7280R') { function fra(ev, rg = 'Arrrhipster 7280R') {
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1})"); ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1})");
ev(`S.pops.fra.rgen=RG.findIndex(r=>r.n===${JSON.stringify(rg)})`); ev(`S.pops.fra.rgen=RG.findIndex(r=>r.n===${lit(rg)})`);
ev("S.biz.push({id:'g',type:'game',name:'Lag Lords',city:'fra',bw:10,rate:100,mood:80,since:0,reqs:[]},{id:'d',type:'dia',name:'Bystander',city:'fra',bw:5,rate:100,mood:80,since:0,reqs:[]});compute()"); ev("S.biz.push({id:'g',type:'game',name:'Lag Lords',city:'fra',bw:10,rate:100,mood:80,since:0,reqs:[]},{id:'d',type:'dia',name:'Bystander',city:'fra',bw:5,rate:100,mood:80,since:0,reqs:[]});compute()");
} }
const flood = (ev, o) => ev(`(()=>{const a=Object.assign({id:'a'+Math.random().toString(36).slice(2,7),city:'fra',tgt:'g',vec:'dns',gbps:200,start:S.day,until:S.day+2,bh:false},${JSON.stringify(o || {})});if(!S.ev.ddos)S.ev.ddos=a;else S.ev.ddosMore.push(a);compute();return a.id})()`); const flood = (ev, o) => ev(`(()=>{const a=Object.assign({id:'a'+Math.random().toString(36).slice(2,7),city:'fra',tgt:'g',vec:'dns',gbps:200,start:S.day,until:S.day+2,bh:false},${lit(o || {})});if(!S.ev.ddos)S.ev.ddos=a;else S.ev.ddosMore.push(a);compute();return a.id})()`);
const rep = (ev, id, expr) => ev(`(()=>{const m=ddosReport(ddosAll().find(a=>a.id==='${id}'));return ${expr};})()`); const rep = (ev, id, expr) => ev(`(()=>{const m=ddosReport(ddosAll().find(a=>a.id==='${id}'));return ${expr};})()`);
const sfB = (ev, id) => ev(`bizSf(S.biz.find(b=>b.id==='${id}'),linkIds())`); const sfB = (ev, id) => ev(`bizSf(S.biz.find(b=>b.id==='${id}'),linkIds())`);
test('sizes come from the world: the same draws give the same floods however big you are', () => { test('sizes come from the world: the same draws give the same floods however big you are', () => {
const { ev, errors } = load({ seed: 3 }); const { ev, errors } = load({ seed: 3 });
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));S.day=400;compute()`); ev(`S=migrate(JSON.parse(${lit(SAVE)}));S.day=400;compute()`);
const draw = () => JSON.parse(ev("__reseed(42);JSON.stringify(Array.from({length:2000},()=>ddosSize({tgt:ddosPickTgt()[0]})))")); const draw = () => JSON.parse(ev("__reseed(42);JSON.stringify(Array.from({length:2000},()=>ddosSize({tgt:ddosPickTgt()[0]})))"));
const xs = draw().sort((a, b) => a - b); const xs = draw().sort((a, b) => a - b);
assert.ok(xs[1000] < 60, `median ${xs[1000]} G on a network carrying ${Math.round(ev('R.demand'))} G`); assert.ok(xs[1000] < 60, `median ${xs[1000]} G on a network carrying ${Math.round(ev('R.demand'))} G`);
@ -143,7 +144,7 @@ test('held, sacrificed and got through are scored at the end', () => {
test('how often: never in Change Freeze, Sandbox or puzzles; BGP at 3 a.m. about twice On-call', () => { test('how often: never in Change Freeze, Sandbox or puzzles; BGP at 3 a.m. about twice On-call', () => {
const count = (preset, mode = 'normal') => { const count = (preset, mode = 'normal') => {
const { ev } = load({ seed: 11 }); const { ev } = load({ seed: 11 });
ev(`beginGame('T','fra',${JSON.stringify({ mode, preset })});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;ACT.launchBB({city:'fra'})`); ev(`beginGame('T','fra',${lit({ mode, preset })});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;ACT.launchBB({city:'fra'})`);
return ev("window.__n=0;const real=ddosAttack;ddosAttack=()=>{window.__n++;};for(let d=41;d<1136;d++){S.day=d;ddosTick();}ddosAttack=real;window.__n"); return ev("window.__n=0;const real=ddosAttack;ddosAttack=()=>{window.__n++;};for(let d=41;d<1136;d++){S.day=d;ddosTick();}ddosAttack=real;window.__n");
}; };
const oncall = count('oncall'), bgp = count('bgp'); const oncall = count('oncall'), bgp = count('bgp');
@ -232,7 +233,7 @@ test('a sacrificial PNI takes all of its peer\'s junk, and a clean pipe scrubs a
const id = flood(ev, { gbps: 150 }); const id = flood(ev, { gbps: 150 });
const ports = JSON.parse(rep(ev, id, 'JSON.stringify(m.portList.map(p=>[p.lab,Math.round(p.off)]))')); const ports = JSON.parse(rep(ev, id, 'JSON.stringify(m.portList.map(p=>[p.lab,Math.round(p.off)]))'));
assert.equal(ports.length, 2); assert.equal(ports.length, 2);
assert.ok(ports.find((p) => /Cogentle/.test(p[0]))[1] < ports.find((p) => !/Cogentle/.test(p[0]))[1] / 5, `the clean pipe took most of its share: ${JSON.stringify(ports)}`); assert.ok(ports.find((p) => /Cogentle/.test(p[0]))[1] < ports.find((p) => !/Cogentle/.test(p[0]))[1] / 5, `the clean pipe took most of its share: ${lit(ports)}`);
// A PNI with a network that also comes in over transit: once sacrificial, that network's junk goes only there. // A PNI with a network that also comes in over transit: once sacrificial, that network's junk goes only there.
ev("S.pni.push({id:'px',city:'fra',net:'ggl',tier:1,ready:0,sacrif:true});S.ev.ddos=null;S.ev.ddosMore=[];compute()"); ev("S.pni.push({id:'px',city:'fra',net:'ggl',tier:1,ready:0,sacrif:true});S.ev.ddos=null;S.ev.ddosMore=[];compute()");
const id2 = flood(ev, { gbps: 150 }); const id2 = flood(ev, { gbps: 150 });

View file

@ -3,6 +3,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
test('#289 scrubbed traffic coming back to the target is not counted as DDoS junk on the backbone', () => { test('#289 scrubbed traffic coming back to the target is not counted as DDoS junk on the backbone', () => {
const { ev, errors } = load(); const { ev, errors } = load();
@ -15,8 +16,8 @@ test('#289 scrubbed traffic coming back to the target is not counted as DDoS jun
assert.equal(m.pulled, 12, 'the whole flood is pulled to the scrubbing center'); assert.equal(m.pulled, 12, 'the whole flood is pulled to the scrubbing center');
assert.equal(m.over, 0, 'and cleaned in full'); assert.equal(m.over, 0, 'and cleaned in full');
const net = JSON.parse(ev("JSON.stringify(R.ef[edgeKey(S.links.find(l=>l.a==='fra'&&l.b==='ams'||l.a==='ams'&&l.b==='fra'))].net)")); const net = JSON.parse(ev("JSON.stringify(R.ef[edgeKey(S.links.find(l=>l.a==='fra'&&l.b==='ams'||l.a==='ams'&&l.b==='fra'))].net)"));
assert.ok(!(net.junk > 1e-6), `no junk on the link: ${JSON.stringify(net)}`); assert.ok(!(net.junk > 1e-6), `no junk on the link: ${lit(net)}`);
assert.ok(net.scrub > 50, `the clean traffic is shown as such: ${JSON.stringify(net)}`); assert.ok(net.scrub > 50, `the clean traffic is shown as such: ${lit(net)}`);
const h = ev("trafficSection(S.links.find(l=>l.a==='fra'&&l.b==='ams'||l.a==='ams'&&l.b==='fra'))"); const h = ev("trafficSection(S.links.find(l=>l.a==='fra'&&l.b==='ams'||l.a==='ams'&&l.b==='fra'))");
assert.doesNotMatch(h, /DDoS junk/); assert.doesNotMatch(h, /DDoS junk/);
assert.match(h, new RegExp(ev("tr('common.scrubbed_traffic')"))); assert.match(h, new RegExp(ev("tr('common.scrubbed_traffic')")));
@ -30,7 +31,7 @@ test('#289 a flood that does ride the backbone is still DDoS junk', () => {
ev("S.biz.push({id:'g',type:'game',name:'Lag Lords',city:'fra',bw:10,rate:100,mood:80,since:0,reqs:[]})"); ev("S.biz.push({id:'g',type:'game',name:'Lag Lords',city:'fra',bw:10,rate:100,mood:80,since:0,reqs:[]})");
ev("S.ev.ddos={id:'atk',city:'fra',tgt:'g',vec:'ack',gbps:20,start:S.day,until:S.day+2,bh:false};compute()"); ev("S.ev.ddos={id:'atk',city:'fra',tgt:'g',vec:'ack',gbps:20,start:S.day,until:S.day+2,bh:false};compute()");
const net = JSON.parse(ev("JSON.stringify(R.ef[edgeKey(S.links.find(l=>l.a==='fra'&&l.b==='ams'||l.a==='ams'&&l.b==='fra'))].net)")); const net = JSON.parse(ev("JSON.stringify(R.ef[edgeKey(S.links.find(l=>l.a==='fra'&&l.b==='ams'||l.a==='ams'&&l.b==='fra'))].net)"));
assert.ok(net.junk > 1, `junk on the link: ${JSON.stringify(net)}`); assert.ok(net.junk > 1, `junk on the link: ${lit(net)}`);
assert.ok(!(net.scrub > 0)); assert.ok(!(net.scrub > 0));
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });

View file

@ -6,12 +6,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open(opts = {}) { function open(opts = {}) {
const h = load({ seed: 777, ...opts }); const h = load({ seed: 777, ...opts });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();console.warn=()=>{};`); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();console.warn=()=>{};`);
// The readout refreshes on an interval: closing the window stops it, so the test process can end. // The readout refreshes on an interval: closing the window stops it, so the test process can end.
h.done = () => h.dom.window.close(); h.done = () => h.dom.window.close();
return h; return h;
@ -77,7 +78,7 @@ test('?fps and ?vp open it, ?nofps closes it, and it stays open on this device',
for (const [url, storage, want] of [['?fps', {}, true], ['?vp', {}, true], ['?nofps', { 'sot-vp': '1' }, false], ['', { 'sot-vp': '1' }, true], ['', {}, false]]) { for (const [url, storage, want] of [['?fps', {}, true], ['?vp', {}, true], ['?nofps', { 'sot-vp': '1' }, false], ['', { 'sot-vp': '1' }, true], ['', {}, false]]) {
const h = load({ seed: 777, url: 'https://tests.invalid/' + url, storage }); const h = load({ seed: 777, url: 'https://tests.invalid/' + url, storage });
try { try {
assert.equal(h.ev('!!document.getElementById("diag")'), want, `${url || 'no flag'} ${JSON.stringify(storage)}`); assert.equal(h.ev('!!document.getElementById("diag")'), want, `${url || 'no flag'} ${lit(storage)}`);
assert.equal(h.ev('localStorage.getItem("sot-vp")'), want ? '1' : null, 'remembered as one setting'); assert.equal(h.ev('localStorage.getItem("sot-vp")'), want ? '1' : null, 'remembered as one setting');
} finally { h.dom.window.close(); } } finally { h.dom.window.close(); }
} }

View file

@ -1,13 +1,14 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const start = "ACT.start({});S.nextFail=1e9;S.nextEvent=1e9"; const start = "ACT.start({});S.nextFail=1e9;S.nextEvent=1e9";
test('find a city by its name, without accents, by country or by its exchange (#218)', () => { test('find a city by its name, without accents, by country or by its exchange (#218)', () => {
const { ev, errors } = load(); const { ev, errors } = load();
ev(start); ev(start);
const find = q => ev(`findCities(${JSON.stringify(q)}).join()`).split(','); const find = q => ev(`findCities(${lit(q)}).join()`).split(',');
assert.equal(find('amster')[0], 'ams', 'the start of a name'); assert.equal(find('amster')[0], 'ams', 'the start of a name');
assert.equal(find('AMSTERDAM')[0], 'ams', 'any case'); assert.equal(find('AMSTERDAM')[0], 'ams', 'any case');
assert.equal(find('sao paulo')[0], 'sao', 'accents are optional'); assert.equal(find('sao paulo')[0], 'sao', 'accents are optional');

View file

@ -6,6 +6,7 @@ const path = require('node:path');
const fs = require('node:fs'); const fs = require('node:fs');
const { execFileSync } = require('node:child_process'); const { execFileSync } = require('node:child_process');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Every exception names what breaks the rule and why. One per line, sorted within each rule. // Every exception names what breaks the rule and why. One per line, sorted within each rule.
const EXCEPTIONS = { const EXCEPTIONS = {
@ -241,7 +242,7 @@ test('M2: presets are ordered: Best Effort never harsher than Change Freeze, Cha
const n = {}; const n = {};
for (const p of ['soft', 'freeze', 'oncall', 'bgp']) { for (const p of ['soft', 'freeze', 'oncall', 'bgp']) {
const g = load(); const g = load();
g.ev(`beginGame('Order','fra',${JSON.stringify({ mode: 'normal', preset: p })});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});__reseed(4242);for(let i=0;i<360;i++)dayTick()`); g.ev(`beginGame('Order','fra',${lit({ mode: 'normal', preset: p })});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});__reseed(4242);for(let i=0;i<360;i++)dayTick()`);
n[p] = g.ev('S.inc.length+S.stats.survived+(S.stats.incidents||0)'); n[p] = g.ev('S.inc.length+S.stats.survived+(S.stats.incidents||0)');
assert.deepEqual(g.errors, []); assert.deepEqual(g.errors, []);
} }
@ -254,7 +255,7 @@ test('M3: every subsystem that can annoy the player reads a rule', () => {
['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'],
['dfBuildDays', 'leadDays'], ['dayPre', "rule('clock')"], ['snub', "rule('market')"], ['fireFailure', 'shipsOn()'], ['dfBuildDays', 'leadDays'], ['dayPre', "rule('clock')"], ['snub', "rule('market')"], ['fireFailure', 'shipsOn()'],
['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()']]; ['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()']];
fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${JSON.stringify(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)');
// and in play: no chaos and no market means a quiet year // and in play: no chaos and no market means a quiet year
const g = load(); const g = load();
g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()"); g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()");

View file

@ -2,6 +2,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const start = (ev) => ev(`beginGame('T','icn',{scn:SCN.find(x=>x.id==='gangnam')});if(UI.pendGame)ACT.pitchSkip();closeModal();S.cash=1e8`); const start = (ev) => ev(`beginGame('T','icn',{scn:SCN.find(x=>x.id==='gangnam')});if(UI.pendGame)ACT.pitchSkip();closeModal();S.cash=1e8`);
const seoul = "ACT.launchBB({city:'icn'});ACT.buyTransit({city:'icn',net:'cog',tier:1});compute();for(let i=0;i<20;i++)dayTick();compute()"; const seoul = "ACT.launchBB({city:'icn'});ACT.buyTransit({city:'icn',net:'cog',tier:1});compute();for(let i=0;i<20;i++)dayTick();compute()";
@ -48,7 +49,7 @@ test('an older Gangnam save picks up the sender-pays rule', () => {
const { ev, errors } = load(); const { ev, errors } = load();
start(ev); start(ev);
const s = ev("(()=>{const o=JSON.parse(JSON.stringify(S));o.scn.rules={};return JSON.stringify(o);})()"); const s = ev("(()=>{const o=JSON.parse(JSON.stringify(S));o.scn.rules={};return JSON.stringify(o);})()");
ev(`S=migrate(JSON.parse(${JSON.stringify(s)}))`); ev(`S=migrate(JSON.parse(${lit(s)}))`);
assert.ok(ev("S.scn.rules.sender===true")); assert.ok(ev("S.scn.rules.sender===true"));
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });

View file

@ -6,15 +6,16 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const CLIENT = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'gpu-bench-client.js'), 'utf8'); const CLIENT = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'gpu-bench-client.js'), 'utf8');
function open(cfg = {}) { function open(cfg = {}) {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`window.__BENCH__=${JSON.stringify({ expose: true, secs: 0.15, warm: 0, settleMs: 300, ...cfg })};`); h.ev(`window.__BENCH__=${lit({ expose: true, secs: 0.15, warm: 0, settleMs: 300, ...cfg })};`);
h.ev(CLIENT); h.ev(CLIENT);
h.ev(`__bench.setSave(${JSON.stringify(SAVE)});save=()=>{};`); h.ev(`__bench.setSave(${lit(SAVE)});save=()=>{};`);
return h; return h;
} }
const wait = (ms) => new Promise((r) => setTimeout(r, ms)); const wait = (ms) => new Promise((r) => setTimeout(r, ms));

View file

@ -3,6 +3,7 @@ const assert = require('node:assert/strict');
const path = require('node:path'); const path = require('node:path');
const { load, seed } = require('./harness'); const { load, seed } = require('./harness');
const { loadDict, brokenEntries } = require('../scripts/i18n-check'); const { loadDict, brokenEntries } = require('../scripts/i18n-check');
const { lit } = require('../scripts/lib/js-literal');
const SCREENS = ['hud', 'panelBody', 'leftBody', 'modalCard', 'dashCard', 'bankCard', 'toasts', 'coach', 'hint', 'mega']; const SCREENS = ['hud', 'panelBody', 'leftBody', 'modalCard', 'dashCard', 'bankCard', 'toasts', 'coach', 'hint', 'mega'];
@ -13,9 +14,9 @@ function tour(ev) {
const thrown = [], leaks = new Set(); const thrown = [], leaks = new Set();
const step = (label, src) => { const step = (label, src) => {
try { ev(src); } catch (e) { thrown.push(`${label}: ${e.message}`); } try { ev(src); } catch (e) { thrown.push(`${label}: ${e.message}`); }
const txt = ev(`${JSON.stringify(SCREENS)}.map(i=>{const e=document.getElementById(i);return e?e.textContent:''}).join('\\n')`); const txt = ev(`${lit(SCREENS)}.map(i=>{const e=document.getElementById(i);return e?e.textContent:''}).join('\\n')`);
for (const m of txt.match(/[^\n]{0,40}(\{[a-z]\w*\}|undefined|NaN)[^\n]{0,40}/g) || []) leaks.add(m.trim()); for (const m of txt.match(/[^\n]{0,40}(\{[a-z]\w*\}|undefined|NaN)[^\n]{0,40}/g) || []) leaks.add(m.trim());
for (const m of txt.match(/[a-z0-9_]+(\.[a-z0-9_]+)+/g) || []) if (ev(`!!EN[${JSON.stringify(m)}]`)) leaks.add(`raw label: ${m}`); for (const m of txt.match(/[a-z0-9_]+(\.[a-z0-9_]+)+/g) || []) if (ev(`!!EN[${lit(m)}]`)) leaks.add(`raw label: ${m}`);
}; };
step('title', 'showTitle()'); step('title', 'showTitle()');
step('start', 'ACT.start({});S.cash=1e8;S.lvl=4;S.day=100'); step('start', 'ACT.start({});S.cash=1e8;S.lvl=4;S.day=100');

View file

@ -3,18 +3,19 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit: js } = require('../scripts/lib/js-literal');
const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=4;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" + const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=4;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
"ACT.launchBB({city:'fra'});S.pops.fra.rgen=2;ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});S.pops.ams.rgen=2;compute();" + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=2;ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});S.pops.ams.rgen=2;compute();" +
"ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()"; "ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()";
// A ROADMaster fiber Frankfurt–Amsterdam, dark or lit with `ch`, running at `hot` of what it carries. // A ROADMaster fiber Frankfurt–Amsterdam, dark or lit with `ch`, running at `hot` of what it carries.
const fiber = (ch, hot) => `S.links.push({id:'f',a:'fra',b:'ams',kind:'df',sys:'roadm',ch:${JSON.stringify(ch)},km:450,sub:false,ready:0,cut:0,mo:1,trench:'f'});compute();R.load.f=dfCap(S.links.at(-1))*${hot}`; const fiber = (ch, hot) => `S.links.push({id:'f',a:'fra',b:'ams',kind:'df',sys:'roadm',ch:${js(ch)},km:450,sub:false,ready:0,cut:0,mo:1,trench:'f'});compute();R.load.f=dfCap(S.links.at(-1))*${hot}`;
function game(t, ch, hot, p, cap) { function game(t, ch, hot, p, cap) {
const h = load(); const h = load();
t.after(() => h.dom.window.close()); t.after(() => h.dom.window.close());
h.ev(BASE); h.ev(BASE);
h.ev(fiber(ch, hot)); h.ev(fiber(ch, hot));
h.ev(`S.ops.on.optics=true;S.ops.p.optics=${JSON.stringify(p)};${cap === undefined ? '' : `S.ops.cap.optics=${cap};`}opsDay(S.day)`); h.ev(`S.ops.on.optics=true;S.ops.p.optics=${js(p)};${cap === undefined ? '' : `S.ops.cap.optics=${cap};`}opsDay(S.day)`);
return h; return h;
} }
const lit = (ev) => JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='f').ch)")); const lit = (ev) => JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='f').ch)"));
@ -43,7 +44,7 @@ test('#262 the biggest optic that fits the budget, and it never swaps what is al
test('#262 the setting is saved, an unknown value falls back, and it shows on the phone', (t) => { test('#262 the setting is saved, an unknown value falls back, and it shows on the phone', (t) => {
const { ev, dom, errors } = game(t, [], 0, { pick: 'big' }); const { ev, dom, errors } = game(t, [], 0, { pick: 'big' });
const back = (p) => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p.optics=${JSON.stringify(p)};sanitize(s);return JSON.stringify(s.ops.p.optics);})()`); const back = (p) => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p.optics=${js(p)};sanitize(s);return JSON.stringify(s.ops.p.optics);})()`);
assert.deepEqual(JSON.parse(back({ pick: 'big' })), { pick: 'big' }); assert.deepEqual(JSON.parse(back({ pick: 'big' })), { pick: 'big' });
assert.deepEqual(JSON.parse(back({ pick: 'huge' })), {}); assert.deepEqual(JSON.parse(back({ pick: 'huge' })), {});
assert.deepEqual(JSON.parse(back(undefined)), {}, 'an old save without it'); assert.deepEqual(JSON.parse(back(undefined)), {}, 'an old save without it');

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// The intern's "Keep peering headroom" order: PNI and IX ports above a multiple of today's traffic. One port at a POP with // The intern's "Keep peering headroom" order: PNI and IX ports above a multiple of today's traffic. One port at a POP with
// several routers gets a second in a LAG; anything else moves up a port size. Same setup as the other standing-order tests: // several routers gets a second in a LAG; anything else moves up a port size. Same setup as the other standing-order tests:
@ -17,7 +18,7 @@ function game(t, extra = '') {
const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()"); const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()");
// Hiring recomputes, which would wipe the traffic a case stages: hire first, then stage. // Hiring recomputes, which would wipe the traffic a case stages: hire first, then stage.
function hired(t, extra) { const h = game(t); hire(h.ev); h.ev(extra); return h; } function hired(t, extra) { const h = game(t); hire(h.ev); h.ev(extra); return h; }
const on = (ev, p = { x: 1.5 }, cap) => ev(`S.ops.on.ports=true;S.ops.p.ports=${JSON.stringify(p)};${cap === undefined ? '' : `S.ops.cap.ports=${cap};`}`); const on = (ev, p = { x: 1.5 }, cap) => ev(`S.ops.on.ports=true;S.ops.p.ports=${lit(p)};${cap === undefined ? '' : `S.ops.cap.ports=${cap};`}`);
const shift = ev => ev('opsDay(S.day)'); const shift = ev => ev('opsDay(S.day)');
const cash = ev => ev('S.cash'); const cash = ev => ev('S.cash');
// A 10G PNI with a small network at Frankfurt, carrying `use` Gbps today. PNIs are up the moment they are ordered, so the // A 10G PNI with a small network at Frankfurt, carrying `use` Gbps today. PNIs are up the moment they are ordered, so the

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
function base(ev) { function base(ev) {
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
@ -39,8 +40,8 @@ test('#5 export writes a file and import restores it, with checks', () => {
ev("S.cash=1;S.name='Other'"); ev("S.cash=1;S.name='Other'");
assert.match(ev(`parseSave('{"nope":1}').err`), /does not look/); assert.match(ev(`parseSave('{"nope":1}').err`), /does not look/);
assert.match(ev(`parseSave('not json').err`), /not valid JSON/); assert.match(ev(`parseSave('not json').err`), /not valid JSON/);
assert.match(ev(`parseSave(JSON.stringify(Object.assign(JSON.parse(${JSON.stringify(txt)}).S,{lost:true}))).err`), /bankrupt/); assert.match(ev(`parseSave(JSON.stringify(Object.assign(JSON.parse(${lit(txt)}).S,{lost:true}))).err`), /bankrupt/);
ev(`UI.importing=parseSave(${JSON.stringify(txt)}).s;ACT.importGo()`); ev(`UI.importing=parseSave(${lit(txt)}).s;ACT.importGo()`);
assert.equal(ev("S.name"), 'Export Me'); assert.equal(ev("S.name"), 'Export Me');
assert.equal(ev("S.cash"), 1234567); assert.equal(ev("S.cash"), 1234567);
assert.equal(ev("JSON.parse(slotRaw(UI.slot)).name"), 'Export Me', 'saved on this device'); assert.equal(ev("JSON.parse(slotRaw(UI.slot)).name"), 'Export Me', 'saved on this device');
@ -725,7 +726,7 @@ test('connections in the NOC dashboard can be cancelled right there, after a con
base(ev); base(ev);
ev("ACT.buildPop({city:'ams'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'ams',tier:1});S.pni.push({id:'pn1',city:'fra',net:'nfx',tier:1});S.caches.push({id:'cc1',city:'fra',net:'ggl'},{id:'cc2',city:'fra',net:'ggl'});S.nni.push({city:'fra',prov:'mgp',tier:0});compute();ACT.connOpen()"); ev("ACT.buildPop({city:'ams'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'ams',tier:1});S.pni.push({id:'pn1',city:'fra',net:'nfx',tier:1});S.caches.push({id:'cc1',city:'fra',net:'ggl'},{id:'cc2',city:'fra',net:'ggl'});S.nni.push({city:'fra',prov:'mgp',tier:0});compute();ACT.connOpen()");
const card = () => ev("document.getElementById('dashCard').textContent"); const card = () => ev("document.getElementById('dashCard').textContent");
const click = (k, id) => ev(`ACT.connCancel(${JSON.stringify({ k, id })})`); const click = (k, id) => ev(`ACT.connCancel(${lit({ k, id })})`);
assert.equal(ev("conns().length"), 5); assert.equal(ev("conns().length"), 5);
const tid = ev("S.transit[0].id"); const tid = ev("S.transit[0].id");
click('t', tid); click('t', tid);
@ -912,7 +913,7 @@ test('opening a link on desktop keeps the NOC sidebar available', () => {
test('#77 waves can join any route already dug between two cities', () => { test('#77 waves can join any route already dug between two cities', () => {
const { ev, errors } = load(); const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'})"); ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'})");
const add = r => ev(`UI.via=null;UI.lmode='wave';UI.route=${JSON.stringify(r)};openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal()`); const add = r => ev(`UI.via=null;UI.lmode='wave';UI.route=${lit(r)};openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal()`);
add('diverse'); // first wave: the main route add('diverse'); // first wave: the main route
add('diverse'); // second: a diverse route add('diverse'); // second: a diverse route
const ts = () => JSON.parse(ev("JSON.stringify(landTrenches('fra','ams').map(t=>[t.k,t.n]))")); const ts = () => JSON.parse(ev("JSON.stringify(landTrenches('fra','ams').map(t=>[t.k,t.n]))"));
@ -1218,7 +1219,7 @@ test('#113 Red Sea Crisis wants traffic into Asia for a month, not broadband and
for(const p of CABLE_PAIRS){if(bp.has(p.cid+':'+p.a+'-'+p.b)||bp.has(p.cid+':'+p.b+'-'+p.a)||bc.has(p.a)||bc.has(p.b))continue;(adj[p.a]=adj[p.a]||[]).push([p.b,p.km]);(adj[p.b]=adj[p.b]||[]).push([p.a,p.km]);} for(const p of CABLE_PAIRS){if(bp.has(p.cid+':'+p.a+'-'+p.b)||bp.has(p.cid+':'+p.b+'-'+p.a)||bc.has(p.a)||bc.has(p.b))continue;(adj[p.a]=adj[p.a]||[]).push([p.b,p.km]);(adj[p.b]=adj[p.b]||[]).push([p.a,p.km]);}
const D={mrs:0},P={},Q=['mrs'],seen=new Set();while(Q.length){Q.sort((x,y)=>D[x]-D[y]);const u=Q.shift();if(seen.has(u))continue;seen.add(u);for(const [v,km] of adj[u]||[]){if(D[v]===undefined||D[u]+km<D[v]){D[v]=D[u]+km;P[v]=u;Q.push(v);}}} const D={mrs:0},P={},Q=['mrs'],seen=new Set();while(Q.length){Q.sort((x,y)=>D[x]-D[y]);const u=Q.shift();if(seen.has(u))continue;seen.add(u);for(const [v,km] of adj[u]||[]){if(D[v]===undefined||D[u]+km<D[v]){D[v]=D[u]+km;P[v]=u;Q.push(v);}}}
const r=['sin'];while(r[0]!=='mrs')r.unshift(P[r[0]]);return JSON.stringify(r);})()`)); const r=['sin'];while(r[0]!=='mrs')r.unshift(P[r[0]]);return JSON.stringify(r);})()`));
const build = (tier) => ev(`for(const c of ${JSON.stringify(route)})if(!S.pops[c])ACT.buildPop({city:c});const r=${JSON.stringify(route)}; const build = (tier) => ev(`for(const c of ${lit(route)})if(!S.pops[c])ACT.buildPop({city:c});const r=${lit(route)};
for(let i=1;i<r.length;i++){UI.pending=null;UI.via=null;UI.lmode='wave';UI.route='main';openLinkModal(r[i-1],r[i]);ACT.buildLink({tier:${tier}});closeModal();}`); for(let i=1;i<r.length;i++){UI.pending=null;UI.via=null;UI.lmode='wave';UI.route='main';openLinkModal(r[i-1],r[i]);ACT.buildLink({tier:${tier}});closeModal();}`);
// the old exploit: broadband with local transit everywhere for 300 Gbps served, and a 10G path // the old exploit: broadband with local transit everywhere for 300 Gbps served, and a 10G path
build(0); build(0);

View file

@ -3,11 +3,12 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Spawn many mars offers from a network at two cities only: most are between the two. // Spawn many mars offers from a network at two cities only: most are between the two.
const marsOnly = "eval('('+spawnOffer.toString().replace('const t=pick(types)',\"const t='mars'\")+')')"; const marsOnly = "eval('('+spawnOffer.toString().replace('const t=pick(types)',\"const t='mars'\")+')')";
const spawn = (ev, n) => ev(`(()=>{S.offers=[];const f=${marsOnly};for(let i=0;i<${n};i++)f();return JSON.stringify(S.offers.map(o=>[o.city,o.city2,o.latMax]));})()`); const spawn = (ev, n) => ev(`(()=>{S.offers=[];const f=${marsOnly};for(let i=0;i<${n};i++)f();return JSON.stringify(S.offers.map(o=>[o.city,o.city2,o.latMax]));})()`);
const start = (ev, cities) => ev(`ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=13;S.pops={};for(const c of ${JSON.stringify(cities)})S.pops[c]={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};compute()`); const start = (ev, cities) => ev(`ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=13;S.pops={};for(const c of ${lit(cities)})S.pops[c]={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};compute()`);
test('#273 no latency offer between Iqaluit and Nuuk: no buildable path meets the straight-line ceiling', () => { test('#273 no latency offer between Iqaluit and Nuuk: no buildable path meets the straight-line ceiling', () => {
const { ev, errors } = load(); const { ev, errors } = load();

View file

@ -1,10 +1,11 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const fresh = ev => ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); const fresh = ev => ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
// Fake a network of n POPs spread over the given regions, without building anything. // Fake a network of n POPs spread over the given regions, without building anything.
const fake = (ev, n, regs, peak) => ev(`(()=>{const rs=${JSON.stringify(regs)},pick=[];for(const r of rs){const c=CITIES.find(x=>x.reg===r&&!pick.includes(x.id));pick.push(c.id);}for(const c of CITIES){if(pick.length>=${n})break;if(!pick.includes(c.id)&&rs.includes(c.reg))pick.push(c.id);}S.pops={};for(const c of pick)S.pops[c]={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};S.stats.peak=${peak};return custLevel();})()`); const fake = (ev, n, regs, peak) => ev(`(()=>{const rs=${lit(regs)},pick=[];for(const r of rs){const c=CITIES.find(x=>x.reg===r&&!pick.includes(x.id));pick.push(c.id);}for(const c of CITIES){if(pick.length>=${n})break;if(!pick.includes(c.id)&&rs.includes(c.reg))pick.push(c.id);}S.pops={};for(const c of pick)S.pops[c]={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};S.stats.peak=${peak};return custLevel();})()`);
test('thirteen customer levels, each harder than the last', () => { test('thirteen customer levels, each harder than the last', () => {
const { ev, errors } = load(); const { ev, errors } = load();

View file

@ -5,6 +5,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { createSession, TOOLS } = require('../scripts/lib/mcp-game'); const { createSession, TOOLS } = require('../scripts/lib/mcp-game');
const { lit } = require('../scripts/lib/js-literal');
function sandbox() { function sandbox() {
const s = createSession(), T = (name, args = {}) => TOOLS.find((t) => t.name === name).run(s, args), ev = (x) => s.game.ev(x); const s = createSession(), T = (name, args = {}) => TOOLS.find((t) => t.name === name).run(s, args), ev = (x) => s.game.ev(x);
@ -24,7 +25,7 @@ test('a dark fiber IRU, a wave or a cable from a city with no POP is refused, an
const why = new RegExp(`You have no POP in ${city}`); const why = new RegExp(`You have no POP in ${city}`);
const q = act(action, args, true); const q = act(action, args, true);
assert.equal(q.outcome, 'quote', action); assert.equal(q.outcome, 'quote', action);
assert.ok(q.quote.blocked.some((b) => why.test(b)), `${action} ${args.a}→${args.b}: ${JSON.stringify(q.quote.blocked)}`); assert.ok(q.quote.blocked.some((b) => why.test(b)), `${action} ${args.a}→${args.b}: ${lit(q.quote.blocked)}`);
const r = act(action, args); const r = act(action, args);
assert.equal(r.outcome, 'rejected', `${action} ${args.a}→${args.b}`); assert.equal(r.outcome, 'rejected', `${action} ${args.a}→${args.b}`);
assert.ok(r.toasts.some((t) => why.test(t)), JSON.stringify(r.toasts)); assert.ok(r.toasts.some((t) => why.test(t)), JSON.stringify(r.toasts));
@ -95,11 +96,11 @@ test('founding your own exchange says why it cannot: mainland China, an exchange
const name = (c) => ev(`CITY.${c}.name`); const name = (c) => ev(`CITY.${c}.name`);
const refused = (city, why) => { const refused = (city, why) => {
const q = act('foundIx', { city }, true); const q = act('foundIx', { city }, true);
assert.equal(q.quote.blocked.length, 1, `${city}: ${JSON.stringify(q.quote.blocked)}`); assert.equal(q.quote.blocked.length, 1, `${city}: ${lit(q.quote.blocked)}`);
assert.match(q.quote.blocked[0], why, city); assert.match(q.quote.blocked[0], why, city);
const r = act('foundIx', { city }); const r = act('foundIx', { city });
assert.equal(r.outcome, 'rejected', city); assert.equal(r.outcome, 'rejected', city);
assert.ok(r.toasts.some((t) => why.test(t)), `${city}: ${JSON.stringify(r.toasts)}`); assert.ok(r.toasts.some((t) => why.test(t)), `${city}: ${lit(r.toasts)}`);
assert.equal(r.charged, 0); assert.equal(r.charged, 0);
}; };
// mainland China comes first: a POP there would not help (Charlie's Shanghai and Beijing had POPs) // mainland China comes first: a POP there would not help (Charlie's Shanghai and Beijing had POPs)

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Work done once when a game loads (the possible-diversity map, link curves, the map's sea and hills) has shortcuts; // Work done once when a game loads (the possible-diversity map, link curves, the map's sea and hills) has shortcuts;
// each must give exactly what the plain version gives. // each must give exactly what the plain version gives.
@ -17,7 +18,7 @@ test('diversity map: the indexed graph answers like disjointRoutes() over every
for(const f of FABS)if(f.cities.includes(a)&&f.cities.includes(b))add(a,b,'fab:'+f.id);}return links;}`); for(const f of FABS)if(f.cities.includes(a)&&f.cities.includes(b))add(a,b,'fab:'+f.id);}return links;}`);
const cp = ev('CABLE_PAIRS[0].cid+":"+CABLE_PAIRS[0].a+"-"+CABLE_PAIRS[0].b'); const cp = ev('CABLE_PAIRS[0].cid+":"+CABLE_PAIRS[0].a+"-"+CABLE_PAIRS[0].b');
for (const st of [{ won: false }, { won: true }, { won: false, scn: { rules: { banCities: ['jam', 'lon'], banPairs: [cp] } } }]) { for (const st of [{ won: false }, { won: true }, { won: false, scn: { rules: { banCities: ['jam', 'lon'], banPairs: [cp] } } }]) {
const r = JSON.parse(ev(`(()=>{const st=${JSON.stringify(st)},L=plainLinks(st);diversityMap=null;diversityPossible('fra','nyc',st); const r = JSON.parse(ev(`(()=>{const st=${lit(st)},L=plainLinks(st);diversityMap=null;diversityPossible('fra','nyc',st);
const ids=CITIES.map(c=>c.id),bad=[];let n=0;for(let i=0;i<ids.length;i+=3)for(let j=i+1;j<ids.length;j+=3){n++;const a=ids[i],b=ids[j]; const ids=CITIES.map(c=>c.id),bad=[];let n=0;for(let i=0;i<ids.length;i+=3)for(let j=i+1;j<ids.length;j+=3){n++;const a=ids[i],b=ids[j];
const want=(st.scn&&st.scn.rules.banCities.some(x=>x===a||x===b))?diversityPossible(a,b,st):disjointRoutes(a,b,L);if(diversityPossible(a,b,st)!==want)bad.push(a+'-'+b);} const want=(st.scn&&st.scn.rules.banCities.some(x=>x===a||x===b))?diversityPossible(a,b,st):disjointRoutes(a,b,L);if(diversityPossible(a,b,st)!==want)bad.push(a+'-'+b);}
return JSON.stringify({links:L.length,mine:diversityMap.links,n,bad})})()`)); return JSON.stringify({links:L.length,mine:diversityMap.links,n,bad})})()`));

View file

@ -7,13 +7,14 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
// The big network on a 1280×800 screen at 2× in 2D. Canvases are counted as they are made; their contexts take any call. // The big network on a 1280×800 screen at 2× in 2D. Canvases are counted as they are made; their contexts take any call.
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute(); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false,false); window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false,false);
DPR=2;CW=1280;CH=800;cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=0.6;window.__cv=0; DPR=2;CW=1280;CH=800;cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=0.6;window.__cv=0;
const ce=document.createElement.bind(document);document.createElement=function(t){const e=ce(t);if(String(t).toLowerCase()==='canvas')__cv++;return e;}; const ce=document.createElement.bind(document);document.createElement=function(t){const e=ce(t);if(String(t).toLowerCase()==='canvas')__cv++;return e;};

View file

@ -18,6 +18,7 @@ const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const page = require('../scripts/lib/page'); const page = require('../scripts/lib/page');
const { openPage, playGame, rng } = require('../scripts/lib/route-fuzz'); const { openPage, playGame, rng } = require('../scripts/lib/route-fuzz');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
@ -97,7 +98,7 @@ function problems(r, where) {
if (r.lost) out.push(`${where}: ${r.lost} pictures drawn without a canvas`); if (r.lost) out.push(`${where}: ${r.lost} pictures drawn without a canvas`);
if (r.shared || r.badCanvas) out.push(`${where}: ${r.shared} pictures share a canvas, ${r.badCanvas} have none or one of the wrong size`); if (r.shared || r.badCanvas) out.push(`${where}: ${r.shared} pictures share a canvas, ${r.badCanvas} have none or one of the wrong size`);
if (r.pad) out.push(`${where}: the card's shared canvas was made`); if (r.pad) out.push(`${where}: the card's shared canvas was made`);
if (r.sprs || r.glsFrame || !r.ctx0 || r.glShown) out.push(`${where}: card state leaked into 2D ${JSON.stringify({ sprs: r.sprs, glsFrame: r.glsFrame, ctx0: r.ctx0, glShown: r.glShown })}`); if (r.sprs || r.glsFrame || !r.ctx0 || r.glShown) out.push(`${where}: card state leaked into 2D ${lit({ sprs: r.sprs, glsFrame: r.glsFrame, ctx0: r.ctx0, glShown: r.glShown })}`);
return out; return out;
} }
@ -111,7 +112,7 @@ const GLSTUB = `window.__GLSTUB=(()=>{const calls=[];const gl=new Proxy({calls},
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute(); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false);`); window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false);`);
h.ev(KIT); h.ev(KIT);
return h; return h;
@ -157,7 +158,7 @@ test('the 2D map draws the same frame from kept pictures as from fresh ones, wha
VIEWS.forEach(({ city, u }, v) => { VIEWS.forEach(({ city, u }, v) => {
if (on && city !== on) return; if (on && city !== on) return;
const at = city === 'pop' ? 'Object.keys(S.pops).indexOf(S.home)/Object.keys(S.pops).length' : 'CITIES.findIndex(c=>c.id===__OTHER)/CITIES.length'; const at = city === 'pop' ? 'Object.keys(S.pops).indexOf(S.home)/Object.keys(S.pops).length' : 'CITIES.findIndex(c=>c.id===__OTHER)/CITIES.length';
ev(`window.__U=${JSON.stringify(u)};__U[1]=${at}+1e-9;0`); ev(`window.__U=${lit(u)};__U[1]=${at}+1e-9;0`);
found.push(...problems(JSON.parse(ev('JSON.stringify(__M2D.check(__U))')), `after "${step}", view ${v} (${city})`)); found.push(...problems(JSON.parse(ev('JSON.stringify(__M2D.check(__U))')), `after "${step}", view ${v} (${city})`));
checks++; checks++;
}); });
@ -174,7 +175,7 @@ test('the 2D map draws the same from kept pictures as from fresh ones, and tubes
// Now and then a day passes (failures and events on), so cuts, builds, floods and offers come and go. // Now and then a day passes (failures and events on), so cuts, builds, floods and offers come and go.
if (i % 6 === 5) ev('S.nextFail=S.day;S.nextEvent=S.day;dayTick();compute();'); if (i % 6 === 5) ev('S.nextFail=S.day;S.nextEvent=S.day;dayTick();compute();');
const u = Array.from({ length: 9 }, () => r()); const u = Array.from({ length: 9 }, () => r());
found.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`)), `view ${i} (day ${ev('S.day')})`)); found.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${lit(u)}))`)), `view ${i} (day ${ev('S.day')})`));
} }
assert.deepEqual(found.slice(0, 5), []); assert.deepEqual(found.slice(0, 5), []);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
@ -196,12 +197,12 @@ test('in seeded random games, after every move and day, the 2D map draws the sam
const g = playGame(P, seed, { moves: 40, maxDays: 4, onMove: () => { const g = playGame(P, seed, { moves: 40, maxDays: 4, onMove: () => {
const u = Array.from({ length: 9 }, () => r()); const u = Array.from({ length: 9 }, () => r());
for (const p of [P.base, P.head]) { for (const p of [P.base, P.head]) {
const out = JSON.parse(p.ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`)); const out = JSON.parse(p.ev(`JSON.stringify(__M2D.check(${lit(u)}))`));
if (out) checks++; if (out) checks++;
found.push(...problems(out, `seed ${seed}, page ${p.label}`)); found.push(...problems(out, `seed ${seed}, page ${p.label}`));
} }
} }); } });
assert.equal(g.div, null, `seed ${seed}: the two pages parted: ${JSON.stringify(g.div && { where: g.div.where, last: g.div.last })}`); assert.equal(g.div, null, `seed ${seed}: the two pages parted: ${lit(g.div && { where: g.div.where, last: g.div.last })}`);
assert.ok(checks >= 20, `seed ${seed}: the map was checked (${checks})`); assert.ok(checks >= 20, `seed ${seed}: the map was checked (${checks})`);
assert.deepEqual(found.slice(0, 5), [], `seed ${seed}`); assert.deepEqual(found.slice(0, 5), [], `seed ${seed}`);
assert.deepEqual(g.errors, [], `seed ${seed}`); assert.deepEqual(g.errors, [], `seed ${seed}`);
@ -212,7 +213,7 @@ test('in seeded random games, after every move and day, the 2D map draws the sam
test('a 2D map without WebGL2 never asks for it again, and its pictures each keep their own canvas', () => { test('a 2D map without WebGL2 never asks for it again, and its pictures each keep their own canvas', () => {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
// Auto mode, in a browser where WebGL2 is not there. // Auto mode, in a browser where WebGL2 is not there.
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute(); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});`); window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});`);
h.ev(KIT); h.ev(KIT);
h.ev('mapGl(true,false);draw(__T);'); h.ev('mapGl(true,false);draw(__T);');
@ -235,7 +236,7 @@ test('the 2D map after the card is given up, or switched off, draws as a 2D map
const out = []; const out = [];
for (let v = 0; v < 8; v++) { for (let v = 0; v < 8; v++) {
const u = [0.2, v / 8, 0.5, 0.5, (v % 5) / 5 + 0.01, v / 8, 0.3, v % 2 ? 0.1 : 0.9, v / 8]; const u = [0.2, v / 8, 0.5, 0.5, (v % 5) / 5 + 0.01, v / 8, 0.3, v % 2 ? 0.1 : 0.9, v / 8];
out.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`)), `${tag}, view ${v}`)); out.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${lit(u)}))`)), `${tag}, view ${v}`));
} }
return out; return out;
}; };

View file

@ -13,6 +13,7 @@ const { createSession, TOOLS } = require('../scripts/lib/mcp-game');
const { createBrowserSession } = require('../scripts/lib/mcp-browser'); const { createBrowserSession } = require('../scripts/lib/mcp-browser');
const { freePort } = require('./net'); const { freePort } = require('./net');
const { lit } = require('../scripts/lib/js-literal');
let PORT; let PORT;
test.before(async () => { PORT = await freePort(); }); test.before(async () => { PORT = await freePort(); });
const HEADLESS_JS = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'mcp-headless.js'), 'utf8'); const HEADLESS_JS = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'mcp-headless.js'), 'utf8');
@ -70,7 +71,7 @@ test('the same scripted session gives the same outcomes headless and through the
// ready() waits for the page itself, generously: jsdom on a busy runner can take seconds to dial. // ready() waits for the page itself, generously: jsdom on a busy runner can take seconds to dial.
assert.deepEqual(await s.ready({ waitMs: 20000 }), { ok: true }, 'the tab serves this checkout\'s contract'); assert.deepEqual(await s.ready({ waitMs: 20000 }), { ok: true }, 'the tab serves this checkout\'s contract');
const there = await play(s); const there = await play(s);
for (let i = 0; i < SCRIPT.length; i++) assert.deepEqual(there[i], here[i], `step ${i}: ${SCRIPT[i][0]} ${JSON.stringify(SCRIPT[i][1] || {})}`); for (let i = 0; i < SCRIPT.length; i++) assert.deepEqual(there[i], here[i], `step ${i}: ${SCRIPT[i][0]} ${lit(SCRIPT[i][1] || {})}`);
assert.ok(here.some(([n, v]) => n === 'act' && v.outcome === 'decision'), 'the script meets a question'); assert.ok(here.some(([n, v]) => n === 'act' && v.outcome === 'decision'), 'the script meets a question');
assert.ok(here.some(([, v]) => v.error), 'and an error'); assert.ok(here.some(([, v]) => v.error), 'and an error');
assert.equal(a.ev('S.day'), 90); assert.equal(a.ev('S.day'), 90);

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
test('sandbox: endless money, every unlock, nothing breaks, no badges', () => { test('sandbox: endless money, every unlock, nothing breaks, no badges', () => {
const { ev, errors } = load(); const { ev, errors } = load();
@ -215,7 +216,7 @@ test('#27 new networks get a random name, and "Another one" never repeats it', (
const { ev, errors } = load(); const { ev, errors } = load();
assert.ok(ev("NETWORK_NAMES.every(n=>n.length<=24)&&new Set(NETWORK_NAMES).size===NETWORK_NAMES.length")); assert.ok(ev("NETWORK_NAMES.every(n=>n.length<=24)&&new Set(NETWORK_NAMES).size===NETWORK_NAMES.length"));
const first = ev("document.getElementById('nmIn').value"); const first = ev("document.getElementById('nmIn').value");
assert.ok(ev(`NETWORK_NAMES.includes(${JSON.stringify(first)})`)); assert.ok(ev(`NETWORK_NAMES.includes(${lit(first)})`));
let prev = first; let prev = first;
for (let i = 0; i < 40; i++) { for (let i = 0; i < 40; i++) {
ev("ACT.randomName()"); ev("ACT.randomName()");
@ -452,8 +453,8 @@ test('RouteScript: help, ready-made scripts and the AI button', () => {
ev('Math.random=()=>0.5;ACT.teSlop()'); ev('Math.random=()=>0.5;ACT.teSlop()');
const good = ev("document.getElementById('teSrc').value"); const good = ev("document.getElementById('teSrc').value");
assert.match(good, /Written by/); assert.match(good, /Written by/);
assert.equal(ev(`teParse(${JSON.stringify(good)}).errors.length`), 0); assert.equal(ev(`teParse(${lit(good)}).errors.length`), 0);
assert.ok(ev(`teTrial(${JSON.stringify(good)}).after.served`) >= served * 0.99); assert.ok(ev(`teTrial(${lit(good)}).after.served`) >= served * 0.99);
assert.equal(ev('R.served'), served, 'thinking about it changes nothing'); assert.equal(ev('R.served'), served, 'thinking about it changes nothing');
ev('ACT.teDeploy()'); ev('ACT.teDeploy()');
assert.equal(ev('S.te.script'), good); assert.equal(ev('S.te.script'), good);
@ -462,7 +463,7 @@ test('RouteScript: help, ready-made scripts and the AI button', () => {
const bad = ev("document.getElementById('teSrc').value"); const bad = ev("document.getElementById('teSrc').value");
assert.match(bad, /cap transit cogentle at 0 gbps/); assert.match(bad, /cap transit cogentle at 0 gbps/);
assert.match(bad, /Confidence: 100%/); assert.match(bad, /Confidence: 100%/);
assert.ok(ev(`teTrial(${JSON.stringify(bad)}).after.served`) < served * 0.5, 'it takes the network down'); assert.ok(ev(`teTrial(${lit(bad)}).after.served`) < served * 0.5, 'it takes the network down');
ev('ACT.teDeploy()'); ev('ACT.teDeploy()');
assert.match(ev("document.getElementById('toasts').textContent"), /The AI apologises/); assert.match(ev("document.getElementById('toasts').textContent"), /The AI apologises/);
ev('ACT.teEdit();ACT.teSlop();ACT.teHelp();ACT.teBack()'); ev('ACT.teEdit();ACT.teSlop();ACT.teHelp();ACT.teBack()');

View file

@ -2,6 +2,7 @@ const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load, browser } = require('./harness'); const { load, browser } = require('./harness');
const { until } = require('./net'); const { until } = require('./net');
const { lit } = require('../scripts/lib/js-literal');
// A game window and its NOC window in one fake browser: shared localStorage, broadcast channels and locks. // A game window and its NOC window in one fake browser: shared localStorage, broadcast channels and locks.
// Waits for the page's async work (storage, channels) to land: up to 20 s, as a busy runner may need. // Waits for the page's async work (storage, channels) to land: up to 20 s, as a busy runner may need.
@ -21,7 +22,7 @@ async function pair(t) {
return { b, G, W, id }; return { b, G, W, id };
} }
const pump = (G) => G.ev('NOC.sent=-1e9;nocPump(performance.now())'); const pump = (G) => G.ev('NOC.sent=-1e9;nocPump(performance.now())');
const click = (h, sel) => h.ev(`document.querySelector(${JSON.stringify(sel)}).click()`); const click = (h, sel) => h.ev(`document.querySelector(${lit(sel)}).click()`);
test('with no NOC window nothing is sent and nothing is scheduled', (t) => { test('with no NOC window nothing is sent and nothing is scheduled', (t) => {
const b = browser(); const b = browser();
@ -78,7 +79,7 @@ test('every button the dashboard draws is in exactly one list', async (t) => {
const { G, W } = await pair(t); const { G, W } = await pair(t);
const local = JSON.parse(G.ev('JSON.stringify(NOC_LOCAL)')), go = JSON.parse(G.ev('JSON.stringify(NOC_GO)')); const local = JSON.parse(G.ev('JSON.stringify(NOC_LOCAL)')), go = JSON.parse(G.ev('JSON.stringify(NOC_GO)'));
assert.deepEqual(local.filter((x) => go.includes(x)), []); assert.deepEqual(local.filter((x) => go.includes(x)), []);
for (const k of [...local, ...go]) assert.equal(G.ev(`typeof ACT[${JSON.stringify(k)}]`), 'function', k); for (const k of [...local, ...go]) assert.equal(G.ev(`typeof ACT[${lit(k)}]`), 'function', k);
const seen = JSON.parse(G.ev("(()=>{$('dash').hidden=false;S.biz.push({id:'b1',type:Object.keys(BIZ_T)[0],city:'fra',reqs:[],mood:50,name:'x',g:1,mo:1,day:0});const o=new Set();for(const k of DTABS){UI.dtab=k;UI._dh=null;renderDash();for(const e of document.querySelectorAll('#dashCard [data-act],#dashCard [data-chg]'))o.add(e.dataset.act||e.dataset.chg);}S.biz.pop();return JSON.stringify([...o])})()")); const seen = JSON.parse(G.ev("(()=>{$('dash').hidden=false;S.biz.push({id:'b1',type:Object.keys(BIZ_T)[0],city:'fra',reqs:[],mood:50,name:'x',g:1,mo:1,day:0});const o=new Set();for(const k of DTABS){UI.dtab=k;UI._dh=null;renderDash();for(const e of document.querySelectorAll('#dashCard [data-act],#dashCard [data-chg]'))o.add(e.dataset.act||e.dataset.chg);}S.biz.pop();return JSON.stringify([...o])})()"));
assert.ok(seen.includes('lagP') && seen.includes('buyIx'), 'the upgrade buttons are there'); assert.ok(seen.includes('lagP') && seen.includes('buyIx'), 'the upgrade buttons are there');
assert.deepEqual(seen.filter((x) => !local.includes(x) && !go.includes(x)), [], 'a new dashboard button must be sorted into a list'); assert.deepEqual(seen.filter((x) => !local.includes(x) && !go.includes(x)), [], 'a new dashboard button must be sorted into a list');
@ -105,7 +106,7 @@ test('view clicks stay in the window; the game ignores anything off its list', a
W.ev("nocView('details')"); W.ev("nocView('details')");
click(W, '#dashCard [data-act="dashTab"][data-args*="infra"]'); click(W, '#dashCard [data-act="dashTab"][data-args*="infra"]');
assert.equal(W.ev('UI.dtab'), 'infra'); assert.notEqual(G.ev('UI.dtab'), 'infra'); assert.equal(W.ev('UI.dtab'), 'infra'); assert.notEqual(G.ev('UI.dtab'), 'infra');
W.ev(`NOC.ctl.postMessage({t:'act',id:${JSON.stringify(id)},act:'newgame',args:{}});NOC.ctl.postMessage({t:'act',id:${JSON.stringify(id)},act:'takeLoan',args:{id:'x'}});ACT.newgame({});ACT.buildPop({city:'ams'})`); W.ev(`NOC.ctl.postMessage({t:'act',id:${lit(id)},act:'newgame',args:{}});NOC.ctl.postMessage({t:'act',id:${lit(id)},act:'takeLoan',args:{id:'x'}});ACT.newgame({});ACT.buildPop({city:'ams'})`);
await wait(); await wait();
assert.equal(G.ev('S.cash'), c0); assert.equal(G.ev('S.cash'), c0);
assert.equal(G.ev('!!S.pops.ams'), false, 'buildPop is not on the list'); assert.equal(G.ev('!!S.pops.ams'), false, 'buildPop is not on the list');

View file

@ -1,13 +1,14 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
test('pick your own AS number next to the name, or leave it empty for a random one (#135)', () => { test('pick your own AS number next to the name, or leave it empty for a random one (#135)', () => {
const { ev, errors } = load(); const { ev, errors } = load();
assert.ok(ev("!!document.querySelector('.network-name .nmwrap #nmIn')&&!!document.querySelector('.nmwrap .reroll[data-act=randomName]')"), 'round reroll button inside the name box'); assert.ok(ev("!!document.querySelector('.network-name .nmwrap #nmIn')&&!!document.querySelector('.nmwrap .reroll[data-act=randomName]')"), 'round reroll button inside the name box');
const sug = ev("+document.getElementById('asnIn').placeholder"); const sug = ev("+document.getElementById('asnIn').placeholder");
assert.ok(ev(`asnOk(${sug})`), 'the suggestion is usable'); assert.ok(ev(`asnOk(${sug})`), 'the suggestion is usable');
const set = v => ev(`(()=>{const i=document.getElementById('asnIn');i.value=${JSON.stringify(v)};i.dispatchEvent(new Event('input'));return i.value})()`); const set = v => ev(`(()=>{const i=document.getElementById('asnIn');i.value=${lit(v)};i.dispatchEvent(new Event('input'));return i.value})()`);
assert.equal(set('AS 2-0-1-9-1-7'), '201917', 'only digits stay'); assert.equal(set('AS 2-0-1-9-1-7'), '201917', 'only digits stay');
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
assert.equal(ev('S.asn'), 201917); assert.equal(ev('S.asn'), 201917);

View file

@ -1,12 +1,13 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
function setup(ev) { function setup(ev) {
ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()"); ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()");
} }
// Math.random returns these, then 0.5: [ask?, which IX, a real network?, (which one), fresh PeeringDB?] // Math.random returns these, then 0.5: [ask?, which IX, a real network?, (which one), fresh PeeringDB?]
const seq = (ev, a) => ev(`(()=>{const q=${JSON.stringify(a)};Math.random=()=>q.length?q.shift():0.5;})()`); const seq = (ev, a) => ev(`(()=>{const q=${lit(a)};Math.random=()=>q.length?q.shift():0.5;})()`);
const REAL = [0.01, 0.01, 0.01, 0.01, 0.01], STALE = [0.01, 0.01, 0.9, 0.1], FRESH = [0.01, 0.01, 0.9, 0.9]; const REAL = [0.01, 0.01, 0.01, 0.01, 0.01], STALE = [0.01, 0.01, 0.9, 0.1], FRESH = [0.01, 0.01, 0.9, 0.9];
test('peering requests are answered by policy: Open accepts all, Selective the worthwhile ones, Closed none', () => { test('peering requests are answered by policy: Open accepts all, Selective the worthwhile ones, Closed none', () => {

View file

@ -5,6 +5,7 @@ const { execFileSync } = require('node:child_process');
const { load } = require('./harness'); const { load } = require('./harness');
const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('node:os').tmpdir(), 'tubes-build-')); const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('node:os').tmpdir(), 'tubes-build-'));
const { lit } = require('../scripts/lib/js-literal');
const root = path.join(__dirname, '..'); const root = path.join(__dirname, '..');
function playedGame() { function playedGame() {
@ -113,13 +114,13 @@ test('in-app release notes stay short and link to the full notes on GitHub', ()
const { ev, errors } = load(); const { ev, errors } = load();
const long = ['Tier 1 networks can lay their own subsea cable (#22). Pick two cities with a landing station, pay a lot, wait.', const long = ['Tier 1 networks can lay their own subsea cable (#22). Pick two cities with a landing station, pay a lot, wait.',
'Short one.', 'A 1.6T wave is now cheaper. More text here.', 'Four.', 'Five.', 'Six.', 'Seven.']; 'Short one.', 'A 1.6T wave is now cheaper. More text here.', 'Four.', 'Five.', 'Six.', 'Seven.'];
const h = ev(`notesHtml(${JSON.stringify(long)},'9.9.9')`); const h = ev(`notesHtml(${lit(long)},'9.9.9')`);
assert.match(h, /lay their own subsea cable \(#22\)\./); assert.match(h, /lay their own subsea cable \(#22\)\./);
assert.doesNotMatch(h, /Pick two cities/, 'only the first sentence'); assert.doesNotMatch(h, /Pick two cities/, 'only the first sentence');
assert.match(h, /A 1\.6T wave is now cheaper\./, 'decimals do not end a sentence'); assert.match(h, /A 1\.6T wave is now cheaper\./, 'decimals do not end a sentence');
assert.match(h, /and 2 more changes/); assert.match(h, /and 2 more changes/);
assert.match(h, /releases\/tag\/v9\.9\.9/, 'links to the full notes'); assert.match(h, /releases\/tag\/v9\.9\.9/, 'links to the full notes');
const short = ev(`notesHtml(${JSON.stringify(['One fix.', 'Another fix.'])},'9.9.9')`); const short = ev(`notesHtml(${lit(['One fix.', 'Another fix.'])},'9.9.9')`);
assert.doesNotMatch(short, /releases\/tag/, 'short notes need no link'); assert.doesNotMatch(short, /releases\/tag/, 'short notes need no link');
assert.equal(ev(`slimNote('${'x'.repeat(300)}')`).length <= 140, true); assert.equal(ev(`slimNote('${'x'.repeat(300)}')`).length <= 140, true);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
@ -129,7 +130,7 @@ test('the big-network benchmark save loads cleanly and routes traffic', () => {
const fs = require('node:fs'), path = require('node:path'); const fs = require('node:fs'), path = require('node:path');
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const { ev, errors } = load(); const { ev, errors } = load();
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;compute();renderAll()`); ev(`S=migrate(JSON.parse(${lit(save)}));UI.started=true;compute();renderAll()`);
assert.ok(ev('Object.keys(S.pops).length') >= 100 && ev('S.pni.length') >= 900 && ev('S.caches.length') >= 800, 'still a big network'); assert.ok(ev('Object.keys(S.pops).length') >= 100 && ev('S.pni.length') >= 900 && ev('S.caches.length') >= 800, 'still a big network');
assert.ok(ev('R.served') > 10000, 'and it carries traffic'); assert.ok(ev('R.served') > 10000, 'and it carries traffic');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);

View file

@ -1,8 +1,9 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const g = n => `RG.findIndex(r=>r.n===${JSON.stringify(n)})`; const g = n => `RG.findIndex(r=>r.n===${lit(n)})`;
const start = "ACT.start({});S.cash=1e8;S.lvl=13;S.nextFail=1e9;S.nextEvent=1e9"; const start = "ACT.start({});S.cash=1e8;S.lvl=13;S.nextFail=1e9;S.nextEvent=1e9";
test('a standard POP: new POPs get its router model and count at once, without downtime (#240)', () => { test('a standard POP: new POPs get its router model and count at once, without downtime (#240)', () => {

View file

@ -4,6 +4,7 @@ const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const SV = require('../scripts/lib/puzzle-solver'); const SV = require('../scripts/lib/puzzle-solver');
const { lit } = require('../scripts/lib/js-literal');
/* Reference solutions, played through the player's own actions. A link is [a, b, route ('land' or a cable id), tier /* Reference solutions, played through the player's own actions. A link is [a, b, route ('land' or a cable id), tier
(0 = 10G, 1 = 100G, 2 = 400G), same]: a further overland link on a pair takes a diverse route, or with same = k (0 = 10G, 1 = 100G, 2 = 400G), same]: a further overland link on a pair takes a diverse route, or with same = k
@ -61,12 +62,12 @@ test('puzzle data: every puzzle is valid, carries traffic, and its references ea
ev(`pzBegin(pzDef('${id}'))`); ev(`pzBegin(pzDef('${id}'))`);
build(ev, REF[id].one); build(ev, REF[id].one);
let e = evalP(ev); let e = evalP(ev);
assert.ok(e.goal, `${id}: the one-star reference delivers everything (${JSON.stringify(e.flows.map((x) => [x.g, x.ms]))})`); assert.ok(e.goal, `${id}: the one-star reference delivers everything (${lit(e.flows.map((x) => [x.g, x.ms]))})`);
ev('ACT.pzReset({})'); ev('ACT.pzReset({})');
assert.equal(evalP(ev).stars, 0, `${id}: reset clears it`); assert.equal(evalP(ev).stars, 0, `${id}: reset clears it`);
build(ev, REF[id].three); build(ev, REF[id].three);
e = evalP(ev); e = evalP(ev);
assert.equal(e.stars, 3, `${id}: three stars (spend ${e.spend} of ${ev('S.pz.budget')}, n1 ${e.n1}, worst cut ${JSON.stringify(e.worst)})`); assert.equal(e.stars, 3, `${id}: three stars (spend ${e.spend} of ${ev('S.pz.budget')}, n1 ${e.n1}, worst cut ${lit(e.worst)})`);
} }
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
@ -88,7 +89,7 @@ test('budgets follow the teaching curve, and each 3-star reference is the cheape
assert.ok(j.three && Math.abs(j.spend - e.spend) < 1, `${id}: solver ${j.spend} vs game ${e.spend}`); assert.ok(j.three && Math.abs(j.spend - e.spend) < 1, `${id}: solver ${j.spend} vs game ${e.spend}`);
// No single change (drop a link, shrink one, move it to another route or trench) keeps three stars for less. // No single change (drop a link, shrink one, move it to another route or trench) keeps three stars for less.
const r = SV.improve(ev, L); const r = SV.improve(ev, L);
assert.ok(r.spend >= e.spend - 1, `${id}: ${JSON.stringify(r.links)} is cheaper (${r.spend})`); assert.ok(r.spend >= e.spend - 1, `${id}: ${lit(r.links)} is cheaper (${r.spend})`);
const slack = budget / e.spend - 1, [lo, hi] = SLACK[pack]; const slack = budget / e.spend - 1, [lo, hi] = SLACK[pack];
assert.ok(slack >= lo && slack <= hi, `${id}: ${(slack * 100).toFixed(1)}% slack, want ${lo * 100}-${hi * 100}%`); assert.ok(slack >= lo && slack <= hi, `${id}: ${(slack * 100).toFixed(1)}% slack, want ${lo * 100}-${hi * 100}%`);
} }

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
function start(ev) { ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0"); } function start(ev) { ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0"); }
@ -177,7 +178,7 @@ test('routers: wave and port sizes match what the box can actually take', () =>
assert.equal(ev("LT[RG[3].maxLT].n"), '6.4T'); assert.equal(ev("LT[RG[3].maxLT].n"), '6.4T');
// an old save with a 1.6T wave (old tier 3) keeps its 1.6T wave after migration // an old save with a 1.6T wave (old tier 3) keeps its 1.6T wave after migration
const old = ev("(()=>{const s=JSON.parse(JSON.stringify(S));delete s.ltv;s.links=[{id:'x',a:'fra',b:'ams',kind:'wave',tier:3,km:364,mo:1,cut:0}];s.pops.ams={day:0,routers:1};return JSON.stringify(s)})()"); const old = ev("(()=>{const s=JSON.parse(JSON.stringify(S));delete s.ltv;s.links=[{id:'x',a:'fra',b:'ams',kind:'wave',tier:3,km:364,mo:1,cut:0}];s.pops.ams={day:0,routers:1};return JSON.stringify(s)})()");
assert.equal(ev(`LT[migrate(JSON.parse(${JSON.stringify(old)})).links[0].tier].n`), '1.6T'); assert.equal(ev(`LT[migrate(JSON.parse(${lit(old)})).links[0].tier].n`), '1.6T');
}); });
test('London–Amsterdam: many cheap cables and dark fiber you can lease under the sea', () => { test('London–Amsterdam: many cheap cables and dark fiber you can lease under the sea', () => {
@ -737,11 +738,11 @@ test('Pacific islands: real landings, real exchanges only, and island hops carry
} }
// only islands with a working exchange today get one // only islands with a working exchange today get one
assert.deepEqual(isl.filter(c => ev(`!!CITY['${c}'].ix`)), ['hnl', 'gum', 'hir', 'nou', 'suv']); assert.deepEqual(isl.filter(c => ev(`!!CITY['${c}'].ix`)), ['hnl', 'gum', 'hir', 'nou', 'suv']);
assert.equal(ev(`NETS.filter(n=>Array.isArray(n.ix)&&n.ix.some(c=>CITY[c]&&!CITY[c].ix&&${JSON.stringify(isl)}.includes(c))).length`), 0); assert.equal(ev(`NETS.filter(n=>Array.isArray(n.ix)&&n.ix.some(c=>CITY[c]&&!CITY[c].ix&&${lit(isl)}.includes(c))).length`), 0);
// every new network is reachable through a Tier 1, so Tier 1 players keep their reach // every new network is reachable through a Tier 1, so Tier 1 players keep their reach
assert.equal(ev(`NETS.filter(n=>n.type!=='t1'&&n.pops.every(c=>${JSON.stringify(isl)}.includes(c)||['tok','syd','lax'].includes(c))&&n.pops.some(c=>${JSON.stringify(isl)}.includes(c))&&!(n.up||[]).some(u=>NET[u].type==='t1')).map(n=>n.id).join()`), ''); assert.equal(ev(`NETS.filter(n=>n.type!=='t1'&&n.pops.every(c=>${lit(isl)}.includes(c)||['tok','syd','lax'].includes(c))&&n.pops.some(c=>${lit(isl)}.includes(c))&&!(n.up||[]).some(u=>NET[u].type==='t1')).map(n=>n.id).join()`), '');
// a wave across the whole ocean carries far less than the same trip broken at the islands // a wave across the whole ocean carries far less than the same trip broken at the islands
const hop = (path) => ev(`Math.min(...${JSON.stringify(path)}.slice(1).map((c,i)=>Math.max(...cablesFor(${JSON.stringify(path)}[i],c).map(p=>subCarrier(p.km)))))`); const hop = (path) => ev(`Math.min(...${lit(path)}.slice(1).map((c,i)=>Math.max(...cablesFor(${lit(path)}[i],c).map(p=>subCarrier(p.km)))))`);
const direct = (a, b) => ev(`Math.max(...cablesFor('${a}','${b}').map(p=>subCarrier(p.km)))`); const direct = (a, b) => ev(`Math.max(...cablesFor('${a}','${b}').map(p=>subCarrier(p.km)))`);
assert.equal(direct('sjc', 'syd'), 400); assert.equal(direct('sjc', 'syd'), 400);
assert.equal(hop(['sjc', 'hnl', 'suv', 'syd']), 1600, 'California to Sydney via Hawaii and Fiji'); assert.equal(hop(['sjc', 'hnl', 'suv', 'syd']), 1600, 'California to Sydney via Hawaii and Fiji');
@ -783,7 +784,7 @@ test('Atlantic islands and Halifax: real landings, real exchanges only, and isla
assert.equal(ev("isSub('hfx','mtl')"), false, 'Halifax is on the mainland'); assert.equal(ev("isSub('hfx','mtl')"), false, 'Halifax is on the mainland');
// exchanges only where one runs today: CVIXP in Praia and HFXIX in Halifax // exchanges only where one runs today: CVIXP in Praia and HFXIX in Halifax
assert.deepEqual(isl.concat('hfx').filter(c => ev(`!!CITY['${c}'].ix`)), ['rai', 'hfx']); assert.deepEqual(isl.concat('hfx').filter(c => ev(`!!CITY['${c}'].ix`)), ['rai', 'hfx']);
assert.equal(ev(`NETS.filter(n=>Array.isArray(n.ix)&&n.ix.some(c=>CITY[c]&&!CITY[c].ix&&${JSON.stringify(isl)}.includes(c))).length`), 0); assert.equal(ev(`NETS.filter(n=>Array.isArray(n.ix)&&n.ix.some(c=>CITY[c]&&!CITY[c].ix&&${lit(isl)}.includes(c))).length`), 0);
// the real landings named in the issue // the real landings named in the issue
const lands = (cid, a, b) => ev(`CABLE_PAIRS.some(p=>p.cid==='${cid}'&&[p.a,p.b].sort().join()==='${[a, b].sort().join()}')`); const lands = (cid, a, b) => ev(`CABLE_PAIRS.some(p=>p.cid==='${cid}'&&[p.a,p.b].sort().join()==='${[a, b].sort().join()}')`);
assert.ok(lands('hibx', 'hfx', 'lon') && lands('nuvem', 'bda', 'lis') && lands('sol', 'bda', 'pdl') && lands('ella', 'for', 'rai') && lands('equi', 'lag', 'jam')); assert.ok(lands('hibx', 'hfx', 'lon') && lands('nuvem', 'bda', 'lis') && lands('sol', 'bda', 'pdl') && lands('ella', 'for', 'rai') && lands('equi', 'lag', 'jam'));
@ -792,8 +793,8 @@ test('Atlantic islands and Halifax: real landings, real exchanges only, and isla
assert.equal(ev("CAB.hibx.pairs[0].slice(0,2).join()"), 'nyc,lon'); assert.equal(ev("CAB.hibx.pairs[0].slice(0,2).join()"), 'nyc,lon');
assert.equal(ev("CAB.nuvem.pairs[0].slice(0,2).join()"), 'lis,atn'); assert.equal(ev("CAB.nuvem.pairs[0].slice(0,2).join()"), 'lis,atn');
// every island network still reaches a Tier 1 // every island network still reaches a Tier 1
assert.equal(ev(`NETS.filter(n=>n.type!=='t1'&&n.pops.some(c=>${JSON.stringify(isl)}.includes(c))&&!(n.up||[]).some(u=>NET[u].type==='t1')&&!n.pops.some(c=>!${JSON.stringify(isl)}.includes(c))).map(n=>n.id).join()`), ''); assert.equal(ev(`NETS.filter(n=>n.type!=='t1'&&n.pops.some(c=>${lit(isl)}.includes(c))&&!(n.up||[]).some(u=>NET[u].type==='t1')&&!n.pops.some(c=>!${lit(isl)}.includes(c))).map(n=>n.id).join()`), '');
const hop = (path) => ev(`Math.min(...${JSON.stringify(path)}.slice(1).map((c,i)=>Math.max(...cablesFor(${JSON.stringify(path)}[i],c).map(p=>subCarrier(p.km)))))`); const hop = (path) => ev(`Math.min(...${lit(path)}.slice(1).map((c,i)=>Math.max(...cablesFor(${lit(path)}[i],c).map(p=>subCarrier(p.km)))))`);
const direct = (a, b) => ev(`Math.max(...cablesFor('${a}','${b}').map(p=>subCarrier(p.km)))`); const direct = (a, b) => ev(`Math.max(...cablesFor('${a}','${b}').map(p=>subCarrier(p.km)))`);
assert.equal(direct('mia', 'mad'), 1200); assert.equal(direct('mia', 'mad'), 1200);
assert.equal(hop(['mia', 'bda', 'pdl', 'bio']), 1600, 'Florida to Spain via Bermuda and the Azores'); assert.equal(hop(['mia', 'bda', 'pdl', 'bio']), 1600, 'Florida to Spain via Bermuda and the Azores');

View file

@ -4,6 +4,7 @@ const assert = require('node:assert/strict');
const path = require('node:path'); const path = require('node:path');
const { execFileSync } = require('node:child_process'); const { execFileSync } = require('node:child_process');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const RN = path.join(__dirname, '..', 'scripts', 'release-notes.js'); const RN = path.join(__dirname, '..', 'scripts', 'release-notes.js');
const run = (...a) => JSON.parse(execFileSync(process.execPath, [RN, ...a], { encoding: 'utf8' })); const run = (...a) => JSON.parse(execFileSync(process.execPath, [RN, ...a], { encoding: 'utf8' }));
@ -22,7 +23,7 @@ test('the release notes script reads a story and the bullets apart', () => {
test('"What\'s new" tells the story in full, with every change one tap away', () => { test('"What\'s new" tells the story in full, with every change one tap away', () => {
const { ev, errors } = load(); const { ev, errors } = load();
const story = run('2.0.0', '--story'); const story = run('2.0.0', '--story');
ev(`RELEASE_STORY.splice(0,0,...${JSON.stringify(story)});RELEASE_NOTES.splice(0,0,...${JSON.stringify(run('2.0.0'))})`); ev(`RELEASE_STORY.splice(0,0,...${lit(story)});RELEASE_NOTES.splice(0,0,...${lit(run('2.0.0'))})`);
ev('openModal(notesHtml(RELEASE_NOTES,APP_VERSION))'); ev('openModal(notesHtml(RELEASE_NOTES,APP_VERSION))');
const html = ev("document.getElementById('modalCard').innerHTML"), text = ev("document.getElementById('modalCard').textContent"); const html = ev("document.getElementById('modalCard').innerHTML"), text = ev("document.getElementById('modalCard').textContent");
assert.equal(ev("document.querySelectorAll('#modalCard .story p').length"), story.length, 'every paragraph, no "and N more"'); assert.equal(ev("document.querySelectorAll('#modalCard .story p').length"), story.length, 'every paragraph, no "and N more"');

View file

@ -7,12 +7,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();compute();`); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();compute();`);
return h; return h;
} }

View file

@ -9,6 +9,7 @@ const os = require('node:os');
const path = require('node:path'); const path = require('node:path');
const page = require('../scripts/lib/page'); const page = require('../scripts/lib/page');
const { openPage, playGame } = require('../scripts/lib/route-fuzz'); const { openPage, playGame } = require('../scripts/lib/route-fuzz');
const { lit } = require('../scripts/lib/js-literal');
function pages() { function pages() {
const head = path.join(os.tmpdir(), `tubes-fuzz-test-${process.pid}-head.html`); const head = path.join(os.tmpdir(), `tubes-fuzz-test-${process.pid}-head.html`);
@ -29,7 +30,7 @@ test('random games route the same as main, with and without the routing cache, m
// Seeds that start a normal game, a sandbox, a scenario and a puzzle, with transit, exchanges, PNIs and RouteScript. // Seeds that start a normal game, a sandbox, a scenario and a puzzle, with transit, exchanges, PNIs and RouteScript.
for (const seed of [20, 23, 27, 26]) { for (const seed of [20, 23, 27, 26]) {
const g = playGame(P, seed, { moves: 35 }); const g = playGame(P, seed, { moves: 35 });
assert.equal(g.div, null, `seed ${seed} diverged: ${JSON.stringify(g.div, null, 1)}`); assert.equal(g.div, null, `seed ${seed} diverged: ${lit(g.div, null, 1)}`);
assert.ok(g.moves >= 35, `seed ${seed} played its moves`); assert.ok(g.moves >= 35, `seed ${seed} played its moves`);
assert.deepEqual(g.errors, [], `seed ${seed}: no page errors`); assert.deepEqual(g.errors, [], `seed ${seed}: no page errors`);
} }

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// #265: with the route server on and an Open policy, the peering desk must not turn // #265: with the route server on and an Open policy, the peering desk must not turn
// networks you already reach through the route server into bilateral sessions. // networks you already reach through the route server into bilateral sessions.
@ -15,7 +16,7 @@ test('#265 peering desk leaves route-server networks on the route server', () =>
ev(`(()=>{const q=[0.01,0.01,0.01,${i / 60},0.9];Math.random=()=>q.length?q.shift():0.5;})()`); ev(`(()=>{const q=[0.01,0.01,0.01,${i / 60},0.9];Math.random=()=>q.length?q.shift():0.5;})()`);
ev(`peeringDeskDay(S.day+${i})`); ev(`peeringDeskDay(S.day+${i})`);
} }
const made = JSON.parse(ev(`JSON.stringify(${JSON.stringify(viaRs)}.filter(id=>S.peers[id+'@ams']))`)); const made = JSON.parse(ev(`JSON.stringify(${lit(viaRs)}.filter(id=>S.peers[id+'@ams']))`));
assert.deepEqual(made, [], 'route-server networks stay "via RS"'); assert.deepEqual(made, [], 'route-server networks stay "via RS"');
const bilateral = JSON.parse(ev("JSON.stringify(Object.keys(S.peers).filter(k=>k.endsWith('@ams')))")); const bilateral = JSON.parse(ev("JSON.stringify(Object.keys(S.peers).filter(k=>k.endsWith('@ams')))"));
assert.ok(bilateral.length > 0, 'networks the route server does not reach still get their own sessions'); assert.ok(bilateral.length > 0, 'networks the route server does not reach still get their own sessions');

View file

@ -3,9 +3,10 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const big = (ev) => ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()`); const big = (ev) => ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()`);
// Everything a player sees from routing: totals, money, every link, port and city. // Everything a player sees from routing: totals, money, every link, port and city.
const digest = "JSON.stringify([R.served,R.demand,R.reach,R.peered,R.revMo,R.costMo,R.cost,R.egT,R.load,R.useT,R.usePni,R.useIx,R.useCache,R.citySrv,R.cityDem])"; const digest = "JSON.stringify([R.served,R.demand,R.reach,R.peered,R.revMo,R.costMo,R.cost,R.egT,R.load,R.useT,R.usePni,R.useIx,R.useCache,R.citySrv,R.cityDem])";
@ -16,7 +17,7 @@ test('a field routing never reads really changes nothing it gives (every key the
const keys = JSON.parse(ev('JSON.stringify([...RK_SKIP])')); const keys = JSON.parse(ev('JSON.stringify([...RK_SKIP])'));
for (const k of keys) { for (const k of keys) {
// Change the field all through: every number moves, every flag flips, text changes, lists grow, objects gain a field. // Change the field all through: every number moves, every flag flips, text changes, lists grow, objects gain a field.
ev(`(()=>{const m=x=>x==null?1:typeof x==='number'?x+12345:typeof x==='string'?x+'x':typeof x==='boolean'?!x:Array.isArray(x)?x.map(m).concat(x.length?[m(x[0])]:[]):Object.assign(Object.fromEntries(Object.entries(x).map(([a,b])=>[a,m(b)])),{zz:1});const v=S[${JSON.stringify(k)}];window.__k=[${JSON.stringify(k)},v];S[${JSON.stringify(k)}]=m(JSON.parse(JSON.stringify(v===undefined?null:v)));compute();})()`); ev(`(()=>{const m=x=>x==null?1:typeof x==='number'?x+12345:typeof x==='string'?x+'x':typeof x==='boolean'?!x:Array.isArray(x)?x.map(m).concat(x.length?[m(x[0])]:[]):Object.assign(Object.fromEntries(Object.entries(x).map(([a,b])=>[a,m(b)])),{zz:1});const v=S[${lit(k)}];window.__k=[${lit(k)},v];S[${lit(k)}]=m(JSON.parse(JSON.stringify(v===undefined?null:v)));compute();})()`);
assert.equal(ev(digest), base, `routing reads S.${k}: take it off RK_SKIP`); assert.equal(ev(digest), base, `routing reads S.${k}: take it off RK_SKIP`);
ev('S[__k[0]]=__k[1];compute()'); ev('S[__k[0]]=__k[1];compute()');
} }
@ -41,7 +42,7 @@ test('routing never even reads a field the shortcut skips (so an empty one canno
const { ev, errors } = load(); const { ev, errors } = load();
big(ev); big(ev);
const read = JSON.parse(ev(`(()=>{const seen=new Set(),real=S;S=new Proxy(real,{get(t,k){if(typeof k==='string')seen.add(k);return t[k];}});try{compute();}finally{S=real;}return JSON.stringify([...seen]);})()`)); const read = JSON.parse(ev(`(()=>{const seen=new Set(),real=S;S=new Proxy(real,{get(t,k){if(typeof k==='string')seen.add(k);return t[k];}});try{compute();}finally{S=real;}return JSON.stringify([...seen]);})()`));
assert.deepEqual(read.filter((k) => ev(`RK_SKIP.has(${JSON.stringify(k)})`)), [], 'routing reads these: take them off RK_SKIP'); assert.deepEqual(read.filter((k) => ev(`RK_SKIP.has(${lit(k)})`)), [], 'routing reads these: take them off RK_SKIP');
assert.ok(read.includes('loans'), 'loans pay into the month, so routing reads them'); assert.ok(read.includes('loans'), 'loans pay into the month, so routing reads them');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });

View file

@ -6,11 +6,12 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.close()); const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.close());
h.dom.window.structuredClone = globalThis.structuredClone; // what postMessage does between the threads h.dom.window.structuredClone = globalThis.structuredClone; // what postMessage does between the threads
h.ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false;compute();`); return h; }; h.ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false;compute();`); return h; };
// R with its lazy parts (R.ef, R.fl) read out, attacks by id. // R with its lazy parts (R.ef, R.fl) read out, attacks by id.
const SIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()"; const SIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()";

View file

@ -2,6 +2,7 @@ const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const referenceAllocation = require('./helpers/reference-allocation'); const referenceAllocation = require('./helpers/reference-allocation');
const { lit } = require('../scripts/lib/js-literal');
function network(ev) { function network(ev) {
ev(`ACT.start({});S.cash=1e10;S.lvl=4;S.day=500;S.biz=[];S.links=[];S.pops={};S.pni=[];S.caches=[];S.transit=[];S.ixp={}; ev(`ACT.start({});S.cash=1e10;S.lvl=4;S.day=500;S.biz=[];S.links=[];S.pops={};S.pni=[];S.caches=[];S.transit=[];S.ixp={};
@ -29,7 +30,7 @@ function network(ev) {
// The reference also builds every table afresh, so the comparison covers what routing keeps between calls. // The reference also builds every table afresh, so the comparison covers what routing keeps between calls.
assert.ok(source.includes('RCON=RC.on'), 'compute() can be told not to keep its tables'); assert.ok(source.includes('RCON=RC.on'), 'compute() can be told not to keep its tables');
const ref = (source.slice(0,start)+referenceAllocation+source.slice(end)).replace('RCON=RC.on', 'RCON=false'); const ref = (source.slice(0,start)+referenceAllocation+source.slice(end)).replace('RCON=RC.on', 'RCON=false');
ev(`window.referenceCompute=eval('('+${JSON.stringify(ref)}+')')`); ev(`window.referenceCompute=eval('('+${lit(ref)}+')')`);
} }
test('indexed routing matches the simple allocation loop across network changes', () => { test('indexed routing matches the simple allocation loop across network changes', () => {

View file

@ -2,13 +2,14 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
test('a loaded save gets the rules of its mode, whatever its rules say', () => { test('a loaded save gets the rules of its mode, whatever its rules say', () => {
const { ev, errors } = load(); const { ev, errors } = load();
ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()"); ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()");
const base = JSON.parse(ev('JSON.stringify(packSave(S))')); const base = JSON.parse(ev('JSON.stringify(packSave(S))'));
const loadAs = (mut) => { const s = JSON.parse(JSON.stringify(base)); mut(s); ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(s))}))`); return JSON.parse(ev('JSON.stringify(S.rules)')); }; const loadAs = (mut) => { const s = JSON.parse(JSON.stringify(base)); mut(s); ev(`S=migrate(JSON.parse(${lit(JSON.stringify(s))}))`); return JSON.parse(ev('JSON.stringify(S.rules)')); };
const preset = (p, o) => JSON.parse(ev(`JSON.stringify(makeRules('${p}'${o ? ',' + JSON.stringify(o) : ''}))`)); const preset = (p, o) => JSON.parse(ev(`JSON.stringify(makeRules('${p}'${o ? ',' + lit(o) : ''}))`));
// Normal games keep one of the three Normal presets, with nothing changed. // Normal games keep one of the three Normal presets, with nothing changed.
for (const p of ['freeze', 'oncall', 'bgp']) assert.deepEqual(loadAs(s => { s.rules = { preset: p }; }), preset(p)); for (const p of ['freeze', 'oncall', 'bgp']) assert.deepEqual(loadAs(s => { s.rules = { preset: p }; }), preset(p));
assert.deepEqual(loadAs(s => { s.rules = { preset: 'oncall', money: 'infinite', gates: 'open', chaos: 'none', lead: 'quick' }; }), preset('oncall'), 'no free money or open gates in On-call'); assert.deepEqual(loadAs(s => { s.rules = { preset: 'oncall', money: 'infinite', gates: 'open', chaos: 'none', lead: 'quick' }; }), preset('oncall'), 'no free money or open gates in On-call');
@ -32,13 +33,13 @@ test('a save that claims to be a puzzle loads as a Normal On-call game with the
ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()"); ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()");
const s = JSON.parse(ev('JSON.stringify(packSave(S))')); const s = JSON.parse(ev('JSON.stringify(packSave(S))'));
s.mode = 'puzzle'; s.rules = { preset: 'puzzle' }; s.mode = 'puzzle'; s.rules = { preset: 'puzzle' };
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(s))}));UI.started=true;compute()`); ev(`S=migrate(JSON.parse(${lit(JSON.stringify(s))}));UI.started=true;compute()`);
assert.equal(ev('S.mode'), 'normal'); assert.equal(ev('S.mode'), 'normal');
assert.equal(ev('pzOn()'), false); assert.equal(ev('pzOn()'), false);
assert.equal(ev("rule('clock')"), true); assert.equal(ev("rule('clock')"), true);
ev('for(let i=0;i<3;i++)dayTick()'); ev('for(let i=0;i<3;i++)dayTick()');
assert.equal(ev('S.day'), 3, 'days pass'); assert.equal(ev('S.day'), 3, 'days pass');
ev(`UI.importing=JSON.parse(${JSON.stringify(JSON.stringify(s))});ACT.importGo()`); ev(`UI.importing=JSON.parse(${lit(JSON.stringify(s))});ACT.importGo()`);
assert.equal(ev('S.mode'), 'normal'); assert.equal(ev('S.mode'), 'normal');
assert.equal(ev('rulePreset()'), 'oncall'); assert.equal(ev('rulePreset()'), 'oncall');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);

View file

@ -1,8 +1,9 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const start = (ev, o) => ev(`beginGame('Rule Testers','fra',${JSON.stringify(o)});if(UI.pendGame)ACT.pitchSkip()`); const start = (ev, o) => ev(`beginGame('Rule Testers','fra',${lit(o)});if(UI.pendGame)ACT.pitchSkip()`);
// Days of a quiet-ish network until n failures have fired, on a fixed seed. // Days of a quiet-ish network until n failures have fired, on a fixed seed.
const fails = (ev, days) => { ev("S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});__reseed(4242)"); ev(`for(let i=0;i<${days};i++)dayTick()`); return ev('S.inc.length+S.stats.survived+(S.stats.incidents||0)'); }; const fails = (ev, days) => { ev("S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});__reseed(4242)"); ev(`for(let i=0;i<${days};i++)dayTick()`); return ev('S.inc.length+S.stats.survived+(S.stats.incidents||0)'); };
@ -10,13 +11,13 @@ test('an old save without rules loads as On-call, a sandbox save as Sandbox', ()
const { ev, errors } = load(); const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
const old = JSON.parse(ev('JSON.stringify(S)')); delete old.rules; const old = JSON.parse(ev('JSON.stringify(S)')); delete old.rules;
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(old))}))`); ev(`S=migrate(JSON.parse(${lit(JSON.stringify(old))}))`);
assert.equal(ev('rulePreset()'), 'oncall'); assert.equal(ev('rulePreset()'), 'oncall');
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.rules)')), JSON.parse(ev("JSON.stringify(makeRules('oncall'))"))); assert.deepEqual(JSON.parse(ev('JSON.stringify(S.rules)')), JSON.parse(ev("JSON.stringify(makeRules('oncall'))")));
assert.equal(ev("rule('chaos')"), 'normal'); assert.equal(ev("rule('chaos')"), 'normal');
assert.equal(ev('chaosMul()'), 1); assert.equal(ev('chaosMul()'), 1);
old.mode = 'sandbox'; old.mode = 'sandbox';
ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(old))}))`); ev(`S=migrate(JSON.parse(${lit(JSON.stringify(old))}))`);
assert.equal(ev('rulePreset()'), 'sandbox'); assert.equal(ev('rulePreset()'), 'sandbox');
assert.equal(ev("rule('money')"), 'infinite'); assert.equal(ev("rule('money')"), 'infinite');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);

View file

@ -3,6 +3,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const start = "ACT.start({});S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','lon','par','fra','nyc','ash'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=3;compute()"; const start = "ACT.start({});S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','lon','par','fra','nyc','ash'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=3;compute()";
// Offers as the day brings them, shaped by whoever is at the desk. // Offers as the day brings them, shaped by whoever is at the desk.
@ -109,10 +110,10 @@ test('the desk in Deals and its sheet, and saves that remember who is at the des
ev("ACT.salesHire({id:'shark'})"); ev("ACT.salesHire({id:'shark'})");
const s = JSON.parse(ev('JSON.stringify(packSave(S))')); const s = JSON.parse(ev('JSON.stringify(packSave(S))'));
s.offers = [{ id: 'o1', city: 'ams', name: 'X', type: 'dia', bw: 1, rate: 600, reqs: [], exp: 99, by: 'pirate' }]; s.offers = [{ id: 'o1', city: 'ams', name: 'X', type: 'dia', bw: 1, rate: 600, reqs: [], exp: 99, by: 'pirate' }];
const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})))`)); const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${lit(JSON.stringify(s))})))`));
assert.equal(out.sales.p, 'shark'); assert.equal(out.sales.p, 'shark');
assert.equal(out.offers[0].by, undefined, 'only real salespeople'); assert.equal(out.offers[0].by, undefined, 'only real salespeople');
s.sales = { p: 'intern', hired: 'yesterday' }; s.sales = { p: 'intern', hired: 'yesterday' };
assert.equal(JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})).sales)`)).p, null); assert.equal(JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${lit(JSON.stringify(s))})).sales)`)).p, null);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });

View file

@ -3,6 +3,7 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// The sales trial (#185, the intern's sales order) runs the pass with the offer first and skips the pass without // The sales trial (#185, the intern's sales order) runs the pass with the offer first and skips the pass without
// it when it cannot change the answer. It must sign exactly the offers the original two-pass trial signs. // it when it cannot change the answer. It must sign exactly the offers the original two-pass trial signs.
@ -23,7 +24,7 @@ test('the faster sales trial signs exactly the offers the two-pass trial signs',
const { ev, dom, errors } = load(); const { ev, dom, errors } = load();
try { try {
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();window.slowOffer=${ORIGINAL};`); ev(`S=migrate(JSON.parse(${lit(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();window.slowOffer=${ORIGINAL};`);
assert.ok(ev('S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day)'), 'the fixture has events booked ahead, so the shortcut runs'); assert.ok(ev('S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day)'), 'the fixture has events booked ahead, so the shortcut runs');
const seen = { yes: 0, no: 0, skipped: 0, third: 0 }; const seen = { yes: 0, no: 0, skipped: 0, third: 0 };
ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}'); ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}');
@ -36,7 +37,7 @@ test('the faster sales trial signs exactly the offers the two-pass trial signs',
ev(`for(const l of S.links.filter(l=>!linkDown(l)&&S.pops[l.a]&&S.pops[l.b]&&R.load[l.id]>1).sort((x,y)=>R.load[y.id]/capOf(y)-R.load[x.id]/capOf(x)).slice(${day},${day}+2)) ev(`for(const l of S.links.filter(l=>!linkDown(l)&&S.pops[l.a]&&S.pops[l.b]&&R.load[l.id]>1).sort((x,y)=>R.load[y.id]/capOf(y)-R.load[x.id]/capOf(x)).slice(${day},${day}+2))
S.offers.push({id:'sq'+l.id,city:l.a,city2:l.b,name:'Squeeze',type:'l2vpn',bw:${day % 2 ? 300 : 2},rate:100,reqs:[],exp:S.day+30})`); S.offers.push({id:'sq'+l.id,city:l.a,city2:l.b,name:'Squeeze',type:'l2vpn',bw:${day % 2 ? 300 : 2},rate:100,reqs:[],exp:S.day+30})`);
for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) { for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) {
const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`; const o = `S.offers.find(x=>x.id===${lit(id)})`;
const before = ev('JSON.stringify(R.load)+R.served'); const before = ev('JSON.stringify(R.load)+R.served');
ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n'); ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n');
assert.equal(ev('JSON.stringify(R.load)+R.served'), before, 'a trial leaves the live result alone'); assert.equal(ev('JSON.stringify(R.load)+R.served'), before, 'a trial leaves the live result alone');
@ -48,9 +49,9 @@ test('the faster sales trial signs exactly the offers the two-pass trial signs',
} }
ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick()'); ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick()');
} }
assert.ok(seen.yes >= 3 && seen.no >= 3, `both answers come up (${JSON.stringify(seen)})`); assert.ok(seen.yes >= 3 && seen.no >= 3, `both answers come up (${lit(seen)})`);
assert.ok(seen.skipped >= 5, `the second pass is often skipped (${JSON.stringify(seen)})`); assert.ok(seen.skipped >= 5, `the second pass is often skipped (${lit(seen)})`);
assert.ok(seen.third >= 3, `and run when the offer hurts someone (${JSON.stringify(seen)})`); assert.ok(seen.third >= 3, `and run when the offer hurts someone (${lit(seen)})`);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
} finally { dom.window.close(); } } finally { dom.window.close(); }
}); });
@ -59,11 +60,11 @@ test('with a scenic circuit the sales trial keeps both passes in their original
const { ev, dom, errors } = load(); const { ev, dom, errors } = load();
try { try {
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.biz.find(b=>BIZ_T[b.type].l2).route='scenic';compute();window.slowOffer=${ORIGINAL};`); ev(`S=migrate(JSON.parse(${lit(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.biz.find(b=>BIZ_T[b.type].l2).route='scenic';compute();window.slowOffer=${ORIGINAL};`);
ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}'); ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}');
ev('__reseed(77);S.offers=[];for(let i=0;i<6;i++)spawnOffer();'); ev('__reseed(77);S.offers=[];for(let i=0;i<6;i++)spawnOffer();');
for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) { for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) {
const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`; const o = `S.offers.find(x=>x.id===${lit(id)})`;
ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n'); ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n');
assert.equal(fast, ev(`JSON.stringify(slowOffer(${o}))`), id); assert.equal(fast, ev(`JSON.stringify(slowOffer(${o}))`), id);
assert.ok(n === 0 || n === 2, 'both passes, as before'); assert.ok(n === 0 || n === 2, 'both passes, as before');

View file

@ -2,9 +2,10 @@ const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { until } = require('./net'); const { until } = require('./net');
const { lit } = require('../scripts/lib/js-literal');
// Make the browser's storage refuse the save: 'QuotaExceededError' (too big) or 'SecurityError' (not allowed). // Make the browser's storage refuse the save: 'QuotaExceededError' (too big) or 'SecurityError' (not allowed).
const refuse = name => `window.__err=${JSON.stringify(name)};{const P=Object.getPrototypeOf(localStorage),set=P.setItem; const refuse = name => `window.__err=${lit(name)};{const P=Object.getPrototypeOf(localStorage),set=P.setItem;
P.setItem=function(k,v){if(k.startsWith('sot-save-v1')&&__err){const e=new Error('no');e.name=__err;throw e;}return set.call(this,k,v);};}`; P.setItem=function(k,v){if(k.startsWith('sot-save-v1')&&__err){const e=new Error('no');e.name=__err;throw e;}return set.call(this,k,v);};}`;
test('#176 a save that does not fit tells the player once, with Export, and the menu says so', () => { test('#176 a save that does not fit tells the player once, with Export, and the menu says so', () => {

View file

@ -2,12 +2,13 @@ const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load, browser, flush } = require('./harness'); const { load, browser, flush } = require('./harness');
const { until } = require('./net'); const { until } = require('./net');
const { lit } = require('../scripts/lib/js-literal');
// Two windows of one browser share localStorage, its storage events, a BroadcastChannel and Web Locks; a reload is a // Two windows of one browser share localStorage, its storage events, a BroadcastChannel and Web Locks; a reload is a
// new window with the same tab (sessionStorage). // new window with the same tab (sessionStorage).
// Waits for the page's async work (storage, channels) to land: up to 20 s, as a busy runner may need. // Waits for the page's async work (storage, channels) to land: up to 20 s, as a busy runner may need.
const settle = async (ev, cond, what) => assert.ok(await until(() => ev(cond)), what || cond); const settle = async (ev, cond, what) => assert.ok(await until(() => ev(cond)), what || cond);
const play = (ev, name, city = 'fra', days = 5) => ev(`UI.pitched=true;UI.nm=${JSON.stringify(name)};if($('nmIn'))$('nmIn').value=UI.nm;ACT.pickStart({city:'${city}'});ACT.start({});ACT.launchBB({city:'${city}'});for(let i=0;i<${days};i++)dayTick();save(true)`); const play = (ev, name, city = 'fra', days = 5) => ev(`UI.pitched=true;UI.nm=${lit(name)};if($('nmIn'))$('nmIn').value=UI.nm;ACT.pickStart({city:'${city}'});ACT.start({});ACT.launchBB({city:'${city}'});for(let i=0;i<${days};i++)dayTick();save(true)`);
const idx = (ev) => JSON.parse(ev("JSON.stringify(slotIdx())")); const idx = (ev) => JSON.parse(ev("JSON.stringify(slotIdx())"));
const card = (ev) => ev("document.getElementById('modalCard').textContent"); const card = (ev) => ev("document.getElementById('modalCard').textContent");
@ -185,7 +186,7 @@ test('without Web Locks or BroadcastChannel the heartbeat still keeps one writer
w1.ev('slotBeat()'); w1.ev('slotBeat()');
const w2 = load({ browser: b }); const w2 = load({ browser: b });
await flush(); await flush();
assert.equal(w2.ev('slotBusy(' + JSON.stringify(id) + ')'), true); assert.equal(w2.ev('slotBusy(' + lit(id) + ')'), true);
w2.ev(`ACT.cont({id:'${id}'})`); w2.ev(`ACT.cont({id:'${id}'})`);
await flush(); await flush();
assert.match(card(w2.ev), /open in another window/); assert.match(card(w2.ev), /open in another window/);
@ -287,7 +288,7 @@ test('export the network on screen, or any network from the list; import adds a
a.ev('ACT.exportSave({})'); a.ev('ACT.exportSave({})');
const txt = await text(files[0]); const txt = await text(files[0]);
// Import it back: a second network, the first untouched. // Import it back: a second network, the first untouched.
a.ev(`UI.importing=parseSave(${JSON.stringify(txt)}).s;ACT.importGo()`); a.ev(`UI.importing=parseSave(${lit(txt)}).s;ACT.importGo()`);
assert.notEqual(a.ev('UI.slot'), first, 'a new slot'); assert.notEqual(a.ev('UI.slot'), first, 'a new slot');
assert.equal(a.ev('S.name'), 'Exported Net'); assert.equal(a.ev('S.name'), 'Exported Net');
assert.equal(a.ev('S.day'), 7); assert.equal(a.ev('S.day'), 7);
@ -300,7 +301,7 @@ test('export the network on screen, or any network from the list; import adds a
const j = JSON.parse(await text(files[1])); const j = JSON.parse(await text(files[1]));
assert.equal(j.app, 'series-of-tubes'); assert.equal(j.app, 'series-of-tubes');
assert.equal(j.S.name, 'Exported Net'); assert.equal(j.S.name, 'Exported Net');
assert.equal(a.ev(`parseSave(${JSON.stringify(JSON.stringify(j))}).err||null`), null, 'and it imports'); assert.equal(a.ev(`parseSave(${lit(JSON.stringify(j))}).err||null`), null, 'and it imports');
assert.deepEqual(a.errors, []); assert.deepEqual(a.errors, []);
}); });
@ -349,7 +350,7 @@ test('a big save still compressing when a puzzle starts lands in its network, an
a.ev("S.name='Big One v1';save(true);S.name='Big One v2';save(true)");// one compressing, one queued a.ev("S.name='Big One v1';save(true);S.name='Big One v2';save(true)");// one compressing, one queued
a.ev("ACT.pzStart({id:'hello'})"); a.ev("ACT.pzStart({id:'hello'})");
await settle(a.ev, '!UI.gzBusy&&!SLOT.gzQ.size'); await settle(a.ev, '!UI.gzBusy&&!SLOT.gzQ.size');
const t = await a.dom.window.eval(`gunzip(slotRaw(${JSON.stringify(id)}))`); const t = await a.dom.window.eval(`gunzip(slotRaw(${lit(id)}))`);
assert.equal(JSON.parse(t).name, 'Big One v2', 'the queued save landed too'); assert.equal(JSON.parse(t).name, 'Big One v2', 'the queued save landed too');
a.ev('ACT.pzLeave({})'); a.ev('ACT.pzLeave({})');
assert.equal(a.ev('S.name'), 'Big One v2'); assert.equal(a.ev('S.name'), 'Big One v2');
@ -363,14 +364,14 @@ test('leaving a puzzle when the network cannot be loaded marks it damaged, and C
const id = a.ev('UI.slot'); const id = a.ev('UI.slot');
a.ev("ACT.pzStart({id:'hello'})"); a.ev("ACT.pzStart({id:'hello'})");
// The network set aside is gone from memory and its save is unreadable (another version, a broken disk…). // The network set aside is gone from memory and its save is unreadable (another version, a broken disk…).
a.ev(`UI.pzKeep=null;localStorage.setItem(SLOT_K+${JSON.stringify(id)},'{"v":1,"day":"x","pops":7}')`); a.ev(`UI.pzKeep=null;localStorage.setItem(SLOT_K+${lit(id)},'{"v":1,"day":"x","pops":7}')`);
a.ev(`window.__m=migrate;migrate=s=>{if(s&&s.pops===7)throw new Error('bad');return __m(s);}`); a.ev(`window.__m=migrate;migrate=s=>{if(s&&s.pops===7)throw new Error('bad');return __m(s);}`);
a.ev('ACT.pzLeave({})'); a.ev('ACT.pzLeave({})');
a.ev('migrate=__m'); a.ev('migrate=__m');
assert.match(a.ev("document.getElementById('toasts').textContent"), /could not be loaded/); assert.match(a.ev("document.getElementById('toasts').textContent"), /could not be loaded/);
assert.equal(idx(a.ev)[0].broken, true); assert.equal(idx(a.ev)[0].broken, true);
assert.ok(b.ls.has('sot-save-v1:' + id), 'kept, so it can be exported'); assert.ok(b.ls.has('sot-save-v1:' + id), 'kept, so it can be exported');
a.ev(`ACT.cont({id:${JSON.stringify(id)}})`); a.ev(`ACT.cont({id:${lit(id)}})`);
await flush(); await flush();
assert.equal(a.ev('!!UI.started'), false); assert.equal(a.ev('!!UI.started'), false);
a.ev('ACT.cont({})'); a.ev('ACT.cont({})');

View file

@ -5,12 +5,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h; return h;
} }

View file

@ -6,6 +6,7 @@ const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { play } = require('../scripts/lib/scenario-ref'); const { play } = require('../scripts/lib/scenario-ref');
const { lit } = require('../scripts/lib/js-literal');
const HIRE = ['hire', ['transit', 'routers', 'repair', 'sales', 'ix']]; const HIRE = ['hire', ['transit', 'routers', 'repair', 'sales', 'ix']];
const home = (c) => [['bb', c], ['tr', c, 1], ['ix', c]]; const home = (c) => [['bb', c], ['tr', c, 1], ['ix', c]];
@ -57,7 +58,7 @@ for (const [id, P] of Object.entries(PLAY)) {
test(`${id}: the reference wins in its days, the shortcut does not`, () => { test(`${id}: the reference wins in its days, the shortcut does not`, () => {
const g = load(); const g = load();
const r = play(g.ev, id, P.ref, { avoid: P.avoid }); const r = play(g.ev, id, P.ref, { avoid: P.avoid });
assert.ok(r.won !== null, `${id}: the reference does not win (${JSON.stringify(r)})`); assert.ok(r.won !== null, `${id}: the reference does not win (${lit(r)})`);
assert.ok(r.won >= P.win[0] && r.won <= P.win[1] && (id === 'carnaval' || r.won <= r.limit * 0.75), `${id}: won on day ${r.won}, want ${P.win.join('-')} of ${r.limit}`); assert.ok(r.won >= P.win[0] && r.won <= P.win[1] && (id === 'carnaval' || r.won <= r.limit * 0.75), `${id}: won on day ${r.won}, want ${P.win.join('-')} of ${r.limit}`);
const c = play(g.ev, id, P.cheese, { days: P.by || undefined }); const c = play(g.ev, id, P.cheese, { days: P.by || undefined });
assert.ok(c.won === null, `${id}: the shortcut wins on day ${c.won}${P.by ? ` (before day ${P.by})` : ''}`); assert.ok(c.won === null, `${id}: the shortcut wins on day ${c.won}${P.by ? ` (before day ${P.by})` : ''}`);

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Check the surveyed part independently against the original coastline segments. // Check the surveyed part independently against the original coastline segments.
// City markers may sit inland: their two short shore approaches are excluded. // City markers may sit inland: their two short shore approaches are excluded.
@ -21,7 +22,7 @@ function assertMarine(path, start, end, coast, passes = []) {
for (const [p, q] of edges) { for (const [p, q] of edges) {
const shift = 360 * Math.round((a[0] - p[0]) / 360), c = [p[0] + shift, p[1]], d = [q[0] + shift, q[1]]; const shift = 360 * Math.round((a[0] - p[0]) / 360), c = [p[0] + shift, p[1]], d = [q[0] + shift, q[1]];
assert.ok(!(turn(a, b, c) * turn(a, b, d) < -1e-12 && turn(c, d, a) * turn(c, d, b) < -1e-12), assert.ok(!(turn(a, b, c) * turn(a, b, d) < -1e-12 && turn(c, d, a) * turn(c, d, b) < -1e-12),
`sea segment ${JSON.stringify([a, b])} crosses a coastline`); `sea segment ${lit([a, b])} crosses a coastline`);
} }
} }
} }
@ -38,7 +39,7 @@ test('surveyed designs avoid land, use real path lengths and improve latency', (
assert.ok(Number.isFinite(q.km) && q.pts.length > 2); assert.ok(Number.isFinite(q.km) && q.pts.length > 2);
// the fastest design may follow the corridor of an existing cable instead, which is drawn as that cable is // the fastest design may follow the corridor of an existing cable instead, which is drawn as that cable is
if (!q.cor) assertMarine(q.pts, ...q.shore, coast, passes); if (!q.cor) assertMarine(q.pts, ...q.shore, coast, passes);
assert.equal(q.km, ev(`seaLength(${JSON.stringify(q.pts)})`)); assert.equal(q.km, ev(`seaLength(${lit(q.pts)})`));
if (i) { if (i) {
assert.ok(q.km <= quotes[i - 1].km, 'premium surveys never lengthen the route'); assert.ok(q.km <= quotes[i - 1].km, 'premium surveys never lengthen the route');
assert.ok(q.ms < quotes[i - 1].ms, 'premium latency is strictly lower'); assert.ok(q.ms < quotes[i - 1].ms, 'premium latency is strictly lower');
@ -140,7 +141,7 @@ test('the fastest design is as fast as the fastest cable, and the Red Sea Crisis
const best = ev(`Math.min(...cablesFor('${a}','${b}').map(c=>linkLat({kind:'wave',km:c.km,cable:c.cid})))`); const best = ev(`Math.min(...cablesFor('${a}','${b}').map(c=>linkLat({kind:'wave',km:c.km,cable:c.cid})))`);
const q = JSON.parse(ev(`JSON.stringify(seaQuote('${a}','${b}','express'))`)); const q = JSON.parse(ev(`JSON.stringify(seaQuote('${a}','${b}','express'))`));
assert.ok(q.ms <= best + 1e-9, `${a}–${b}: ${q.ms.toFixed(2)} ms against ${best.toFixed(2)} ms`); assert.ok(q.ms <= best + 1e-9, `${a}–${b}: ${q.ms.toFixed(2)} ms against ${best.toFixed(2)} ms`);
assert.equal(q.km, ev(`seaLength(${JSON.stringify(q.pts)})`), 'map and price use the same path'); assert.equal(q.km, ev(`seaLength(${lit(q.pts)})`), 'map and price use the same path');
} }
// and where the existing cable takes a detour, the survey beats it // and where the existing cable takes a detour, the survey beats it
assert.ok(ev("seaQuote('lag','bde','express').ms") < ev("Math.min(...cablesFor('lag','bde').map(c=>linkLat({kind:'wave',km:c.km,cable:c.cid})))")); assert.ok(ev("seaQuote('lag','bde','express').ms") < ev("Math.min(...cablesFor('lag','bde').map(c=>linkLat({kind:'wave',km:c.km,cable:c.cid})))"));

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load, seed } = require('./harness'); const { load, seed } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
function network(ev) { function network(ev) {
ev("ACT.start({});S.cash=1e8;S.lvl=4;for(const g of GOALS)S.done[g.id]=0"); ev("ACT.start({});S.cash=1e8;S.lvl=4;for(const g of GOALS)S.done[g.id]=0");
@ -129,7 +130,7 @@ test('customers on an interconnection fabric come in over your NNI port', () =>
assert.ok(o, 'fabric customers show up'); assert.ok(o, 'fabric customers show up');
assert.ok(ev(`FAB['${o.prov}'].cities.includes('${o.city}')`)); assert.ok(ev(`FAB['${o.prov}'].cities.includes('${o.city}')`));
assert.deepEqual(o.reqs, ['nni']); assert.deepEqual(o.reqs, ['nni']);
ev(`S.offers=[${JSON.stringify(o)}];ACT.accept({id:'${o.id}'});compute()`); ev(`S.offers=[${lit(o)}];ACT.accept({id:'${o.id}'});compute()`);
assert.equal(ev(`reqOk(S.biz.find(b=>b.id==='${o.id}'))`), false, 'no NNI port yet'); assert.equal(ev(`reqOk(S.biz.find(b=>b.id==='${o.id}'))`), false, 'no NNI port yet');
ev(`ACT.buyNni({city:'${o.city}',prov:'${o.prov}',tier:1});compute()`); ev(`ACT.buyNni({city:'${o.city}',prov:'${o.prov}',tier:1});compute()`);
assert.equal(ev(`reqOk(S.biz.find(b=>b.id==='${o.id}'))`), true, 'an NNI port with room fixes it'); assert.equal(ev(`reqOk(S.biz.find(b=>b.id==='${o.id}'))`), true, 'an NNI port with room fixes it');

View file

@ -1,11 +1,12 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Specialist play (#187, #173): capability offers, vendor demo units, pioneer fiber, consortium seats, charters. // Specialist play (#187, #173): capability offers, vendor demo units, pioneer fiber, consortium seats, charters.
const start = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"; const start = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})";
const pop = (c) => `S.pops['${c}']=S.pops['${c}']||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};`; const pop = (c) => `S.pops['${c}']=S.pops['${c}']||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};`;
const df = (id, a, b, ch, own = true) => `S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:${own},sys:'roadm',ch:${JSON.stringify(ch)},km:kmBetween('${a}','${b}'),sub:false,cable:null,mo:0,trench:'${id}',cut:0,day:0,ready:0,spares:false});`; const df = (id, a, b, ch, own = true) => `S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:${own},sys:'roadm',ch:${lit(ch)},km:kmBetween('${a}','${b}'),sub:false,cable:null,mo:0,trench:'${id}',cut:0,day:0,ready:0,spares:false});`;
// Spawn offers until one of a type shows up (or give up), with everything else cleared out of the way. // Spawn offers until one of a type shows up (or give up), with everything else cleared out of the way.
const spawnUntil = (ev, type, n = 400) => ev(`(()=>{for(let i=0;i<${n};i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>o.type==='${type}');if(o)return JSON.stringify(o);}return 'null';})()`); const spawnUntil = (ev, type, n = 400) => ev(`(()=>{for(let i=0;i<${n};i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>o.type==='${type}');if(o)return JSON.stringify(o);}return 'null';})()`);
@ -91,7 +92,7 @@ test('#173 a consortium seat: offer, pay, build, light, cut, save', () => {
ev(start); ev(start);
ev("S.lvl=3;S.capDeal={at:S.day,c:'lon'};capDealTick(S.day)"); ev("S.lvl=3;S.capDeal={at:S.day,c:'lon'};capDealTick(S.day)");
const off = JSON.parse(ev('JSON.stringify(S.seatOff)')); const off = JSON.parse(ev('JSON.stringify(S.seatOff)'));
assert.ok(off && ev(`SEAT_ROUTES.lon.some(r=>r[2]===${JSON.stringify(off.name)})`), 'a capacity conference offers a seat on one of its routes'); assert.ok(off && ev(`SEAT_ROUTES.lon.some(r=>r[2]===${lit(off.name)})`), 'a capacity conference offers a seat on one of its routes');
ev("ACT.leftTab({t:'deals'});renderAll()"); ev("ACT.leftTab({t:'deals'});renderAll()");
assert.match(dom.window.document.body.innerHTML, /Consortium seat: /); assert.match(dom.window.document.body.innerHTML, /Consortium seat: /);
// A seat short enough to light with level 2 optics. // A seat short enough to light with level 2 optics.

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// A network on four continents: POPs, waves, transit, IX ports, PNIs, caches and customers. // A network on four continents: POPs, waves, transit, IX ports, PNIs, caches and customers.
function bigNet(ev) { function bigNet(ev) {
@ -117,7 +118,7 @@ test('the map keeps fiber capacities for one frame only, and skips links above o
const calls = (body) => ev(`(()=>{cam.x=CITY.fra.x;cam.y=CITY.fra.y+${'2000'};cam.z=2;${body};const n=ctx.calls.n;draw(0);return ctx.calls.n-n;})()`); const calls = (body) => ev(`(()=>{cam.x=CITY.fra.x;cam.y=CITY.fra.y+${'2000'};cam.z=2;${body};const n=ctx.calls.n;draw(0);return ctx.calls.n-n;})()`);
const withLinks = calls(''), links = ev('JSON.stringify(S.links)'); const withLinks = calls(''), links = ev('JSON.stringify(S.links)');
assert.equal(withLinks, calls('S.links=[]')); assert.equal(withLinks, calls('S.links=[]'));
ev(`S.links=JSON.parse(${JSON.stringify(links)})`); ev(`S.links=JSON.parse(${lit(links)})`);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
@ -336,7 +337,7 @@ test('Auto-TE routes around a full link exactly like the plain path', () => {
S.ixp={};S.pni=[];S.caches=[];S.te={on:true,day:0};S.core={lv:2,run:2,legacy:true};S.nextFail=1e9;S.nextEvent=1e9;`); S.ixp={};S.pni=[];S.caches=[];S.te={on:true,day:0};S.core={lv:2,run:2,legacy:true};S.nextFail=1e9;S.nextEvent=1e9;`);
const sig = () => ev('JSON.stringify({served:R.served,teMoved:R.teMoved,egT:R.egT,load:S.links.map(l=>R.load[l.id]||0),node:R.nodeLoad,t:R.useT})'); const sig = () => ev('JSON.stringify({served:R.served,teMoved:R.teMoved,egT:R.egT,load:S.links.map(l=>R.load[l.id]||0),node:R.nodeLoad,t:R.useT})');
for (const script of ['', 'spill at 70%']) { for (const script of ['', 'spill at 70%']) {
ev(`S.te.script=${JSON.stringify(script)}`); ev(`S.te.script=${lit(script)}`);
ev('compute()'); const fast = sig(); ev('compute()'); const fast = sig();
ev('__plain()'); const ref = sig(); ev('__plain()'); const ref = sig();
assert.equal(fast, ref, `fast and plain route the same around the full link (${script || 'no script'})`); assert.equal(fast, ref, `fast and plain route the same around the full link (${script || 'no script'})`);

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// A small network with a hired intern, every order off, no cash floor and no fat fingers (Change Freeze). // A small network with a hired intern, every order off, no cash floor and no fat fingers (Change Freeze).
const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=3;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" + const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=3;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
@ -13,7 +14,7 @@ function game(t, extra = '') {
return h; return h;
} }
const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()"); const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()");
const on = (ev, k, p = {}, cap) => ev(`S.ops.on.${k}=true;S.ops.p.${k}=${JSON.stringify(p)};${cap === undefined ? '' : `S.ops.cap.${k}=${cap};`}`); const on = (ev, k, p = {}, cap) => ev(`S.ops.on.${k}=true;S.ops.p.${k}=${lit(p)};${cap === undefined ? '' : `S.ops.cap.${k}=${cap};`}`);
const shift = ev => ev('opsDay(S.day)'); const shift = ev => ev('opsDay(S.day)');
const cash = ev => ev('S.cash'); const cash = ev => ev('S.cash');
// The same game twice: the intern's shift in one, the player's own clicks in the other. Both must cost the same and end the same. // The same game twice: the intern's shift in one, the player's own clicks in the other. Both must cost the same and end the same.
@ -572,7 +573,7 @@ test('#226 the shift report\'s Open button in the NOC opens the Ops sheet, and s
assert.match(ev('S.log[0].t'), /^Kevin's week/); assert.match(ev('S.log[0].t'), /^Kevin's week/);
ev("S=migrate(JSON.parse(JSON.stringify(S)));closeModal();ACT.leftTab({t:'noc'})"); ev("S=migrate(JSON.parse(JSON.stringify(S)));closeModal();ACT.leftTab({t:'noc'})");
const doc = dom.window.document; const doc = dom.window.document;
const b = doc.querySelector(`#leftBody [data-act=logOpen][data-args='${JSON.stringify({ id: ev('S.log[0].id') })}']`); const b = doc.querySelector(`#leftBody [data-act=logOpen][data-args='${lit({ id: ev('S.log[0].id') })}']`);
assert.ok(b, 'the report has an Open button'); assert.ok(b, 'the report has an Open button');
b.click(); b.click();
assert.equal(doc.getElementById('modal').hidden, false, 'a sheet opened'); assert.equal(doc.getElementById('modal').hidden, false, 'a sheet opened');

View file

@ -3,6 +3,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// A transit-free network in Frankfurt with a PNI to every Tier 1 it needs. // A transit-free network in Frankfurt with a PNI to every Tier 1 it needs.
const t1Club = (ev) => { const t1Club = (ev) => {
@ -187,7 +188,7 @@ test('a traceroute down a two-level cone shows every network on the way', () =>
test('#114 Only Spätzle-IX still takes more than the exchange and two Tier 1 PNIs, now that cones count', () => { test('#114 Only Spätzle-IX still takes more than the exchange and two Tier 1 PNIs, now that cones count', () => {
const { ev, errors } = load(); const { ev, errors } = load();
ev("UI.pitched=true;beginGame('T','stg',{scn:SCN.find(x=>x.id==='stg')});S.cash=1e9;S.lvl=10;S.pops.stg.bb={d:400};S.ixp.stg=0;for(const id of ixMembers('stg'))S.peers[id+'@stg']=1;compute()"); ev("UI.pitched=true;beginGame('T','stg',{scn:SCN.find(x=>x.id==='stg')});S.cash=1e9;S.lvl=10;S.pops.stg.bb={d:400};S.ixp.stg=0;for(const id of ixMembers('stg'))S.peers[id+'@stg']=1;compute()");
const reach = (ts) => ev(`S.pni=[];for(const t of ${JSON.stringify(ts)})S.pni.push({id:'p'+t,net:t,city:'stg',tier:2});compute();R.reach`); const reach = (ts) => ev(`S.pni=[];for(const t of ${lit(ts)})S.pni.push({id:'p'+t,net:t,city:'stg',tier:2});compute();R.reach`);
const T = ['lvl', 'ntt', 'tly', 'cog', 'tat']; const T = ['lvl', 'ntt', 'tly', 'cog', 'tat'];
const goal = ev("SCN.find(x=>x.id==='stg').ok.toString()"); const goal = ev("SCN.find(x=>x.id==='stg').ok.toString()");
assert.match(goal, /R\.reach>=0\.5/); assert.match(goal, /R\.reach>=0\.5/);

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// A triangle: Frankfurt-Amsterdam direct, or round through Paris. // A triangle: Frankfurt-Amsterdam direct, or round through Paris.
function setup(ev) { function setup(ev) {
@ -9,7 +10,7 @@ function setup(ev) {
[['fra', 'par'], ['par', 'ams'], ['fra', 'ams']].forEach(([a, b], i) => ev(`UI.via=null;openLinkModal('${a}','${b}');ACT.buildLink({tier:1});closeModal();S.links[S.links.length-1].tag=${i}`)); [['fra', 'par'], ['par', 'ams'], ['fra', 'ams']].forEach(([a, b], i) => ev(`UI.via=null;openLinkModal('${a}','${b}');ACT.buildLink({tier:1});closeModal();S.links[S.links.length-1].tag=${i}`));
ev("var D=S.links.find(l=>l.tag===2);compute()"); ev("var D=S.links.find(l=>l.tag===2);compute()");
} }
const hops = (ev, mode) => ev(`trPaths('fra',${JSON.stringify(mode)}).path('ams').length`); const hops = (ev, mode) => ev(`trPaths('fra',${lit(mode)}).path('ams').length`);
test('a trace can follow the metrics, the lowest latency or the quietest links', () => { test('a trace can follow the metrics, the lowest latency or the quietest links', () => {
const { ev, errors } = load(); const { ev, errors } = load();

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// The NOC dashboard's list of cities where the player has no POP yet. // The NOC dashboard's list of cities where the player has no POP yet.
function game(t) { function game(t) {
@ -23,7 +24,7 @@ test('it lists exactly the cities you could still open, biggest first', (t) => {
assert.ok(!c.includes(ev('S.home')), 'not where you already are'); assert.ok(!c.includes(ev('S.home')), 'not where you already are');
const hidden = json(ev, 'CITIES.filter(C=>!cityOn(C.id)).map(C=>C.id)'); const hidden = json(ev, 'CITIES.filter(C=>!cityOn(C.id)).map(C=>C.id)');
assert.ok(hidden.every((x) => !c.includes(x)), 'a city not on the map is not listed'); assert.ok(hidden.every((x) => !c.includes(x)), 'a city not on the map is not listed');
const sizes = json(ev, `${JSON.stringify(c)}.map(eyeP)`); const sizes = json(ev, `${lit(c)}.map(eyeP)`);
assert.deepEqual(sizes, [...sizes].sort((a, b) => b - a)); assert.deepEqual(sizes, [...sizes].sort((a, b) => b - a));
assert.match(ev("$('popsSec').textContent"), new RegExp(`Cities without a POP \\(${want.length}\\)`)); assert.match(ev("$('popsSec').textContent"), new RegExp(`Cities without a POP \\(${want.length}\\)`));
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
@ -64,7 +65,7 @@ test('building a POP takes the city off the list; none left says so', (t) => {
test('sorts flip, each starts the useful way round, and bad keys are ignored', (t) => { test('sorts flip, each starts the useful way round, and bad keys are ignored', (t) => {
const { ev, errors } = game(t); const { ev, errors } = game(t);
const vals = (code) => { more(ev); return json(ev, `${JSON.stringify(shown(ev))}.map(c=>${code})`); }; const vals = (code) => { more(ev); return json(ev, `${lit(shown(ev))}.map(c=>${code})`); };
const asc = (a) => a.every((x, i) => !i || a[i - 1] <= x), desc = (a) => a.every((x, i) => !i || a[i - 1] >= x); const asc = (a) => a.every((x, i) => !i || a[i - 1] <= x), desc = (a) => a.every((x, i) => !i || a[i - 1] >= x);
ev("ACT.popsSort({k:'eye'})"); ev("ACT.popsSort({k:'eye'})");
assert.ok(asc(vals('eyeP(c)')), 'clicking the default sort flips it'); assert.ok(asc(vals('eyeP(c)')), 'clicking the default sort flips it');
@ -90,7 +91,7 @@ test('the region filter narrows the list, ignores nonsense, and an emptied regio
more(ev); more(ev);
const oc = shown(ev); const oc = shown(ev);
assert.ok(oc.length > 0); assert.ok(oc.length > 0);
assert.ok(ev(`${JSON.stringify(oc)}.every(c=>CITY[c].reg==='OC')`)); assert.ok(ev(`${lit(oc)}.every(c=>CITY[c].reg==='OC')`));
assert.equal(oc.length, ev("CITIES.filter(C=>cityOn(C.id)&&!S.pops[C.id]&&C.reg==='OC').length")); assert.equal(oc.length, ev("CITIES.filter(C=>cityOn(C.id)&&!S.pops[C.id]&&C.reg==='OC').length"));
ev("for(const C of CITIES)if(C.reg==='OC'&&cityOn(C.id))S.pops[C.id]={day:0,routers:1};UI._dh=null;renderDash()"); ev("for(const C of CITIES)if(C.reg==='OC'&&cityOn(C.id))S.pops[C.id]={day:0,routers:1};UI._dh=null;renderDash()");
assert.equal(shown(ev).length, 0); assert.equal(shown(ev).length, 0);

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
function setup(t) { function setup(t) {
const h = load(); const h = load();
@ -148,7 +149,7 @@ test('boxes follow the traffic each city really sends: Russia and China have the
// Goggle is throttled to half in Russia. // Goggle is throttled to half in Russia.
assert.ok(Math.abs(ev("cacheDem('mmk','ggl')/cacheDem('mmk','akm')") - ev('NSH_RU.ggl*0.5/NSH_RU.akm')) < 1e-9); assert.ok(Math.abs(ev("cacheDem('mmk','ggl')/cacheDem('mmk','akm')") - ev('NSH_RU.ggl*0.5/NSH_RU.akm')) < 1e-9);
// In China only the networks on its own list get boxes. // In China only the networks on its own list get boxes.
for (const id of nets('sha')) assert.ok(ev(`NSH_CN[${JSON.stringify(id)}]>0`), `${id} reaches Shanghai`); for (const id of nets('sha')) assert.ok(ev(`NSH_CN[${lit(id)}]>0`), `${id} reaches Shanghai`);
// Elsewhere nothing changes: the world share. // Elsewhere nothing changes: the world share.
assert.ok(Math.abs(ev("cacheDem('fra','nfx')") - ev('(R.cityDem.fra||0)*NSH.nfx')) < 1e-6); assert.ok(Math.abs(ev("cacheDem('fra','nfx')") - ev('(R.cityDem.fra||0)*NSH.nfx')) < 1e-6);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);

View file

@ -1,6 +1,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
function setup(t, opts) { function setup(t, opts) {
const h = load(opts); const h = load(opts);
@ -66,8 +67,8 @@ test('bulk peering covers rival IXs, respects policy and is idempotent', t => {
assert.ok(blocked.length > 0); assert.ok(blocked.length > 0);
const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), pnis = ev('JSON.stringify(S.pni)'); const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), pnis = ev('JSON.stringify(S.pni)');
ev('ACT.utilityPeers()'); ev('ACT.utilityPeers()');
for (const k of expected) assert.equal(ev(`S.peers[${JSON.stringify(k)}]`), true, k); for (const k of expected) assert.equal(ev(`S.peers[${lit(k)}]`), true, k);
for (const k of blocked) assert.equal(ev(`!!S.peers[${JSON.stringify(k)}]`), false, k); for (const k of blocked) assert.equal(ev(`!!S.peers[${lit(k)}]`), false, k);
assert.equal(ev('S.cash'), cash); assert.equal(ev('S.cash'), cash);
assert.equal(ev('JSON.stringify(S.ixp)'), ports); assert.equal(ev('JSON.stringify(S.ixp)'), ports);
assert.equal(ev('JSON.stringify(S.pni)'), pnis); assert.equal(ev('JSON.stringify(S.pni)'), pnis);

View file

@ -6,12 +6,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h; return h;
} }

View file

@ -9,6 +9,7 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
@ -33,7 +34,7 @@ const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2
function open(storage) { function open(storage) {
const h = load({ seed: 777, storage }); const h = load({ seed: 777, storage });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute(); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{}; window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{};
const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;`); const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;`);
h.ev(GL); h.ev(GL);

View file

@ -6,12 +6,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h; return h;
} }

View file

@ -7,12 +7,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h; return h;
} }

View file

@ -7,12 +7,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h; return h;
} }
@ -78,7 +79,7 @@ test('with WebGL the lines go to the card, the rest to the overlay, and the map
const u0 = uploads(); ev('draw(1016)'); assert.equal(uploads(), u0, 'a frame alone uploads no tube data'); const u0 = uploads(); ev('draw(1016)'); assert.equal(uploads(), u0, 'a frame alone uploads no tube data');
const id = ev(`(()=>{const l=S.links.find(l=>l.kind!=='vxc'&&!linkDown(l));l.cut=S.day+5;compute();draw(1032);return l.id;})()`); const id = ev(`(()=>{const l=S.links.find(l=>l.kind!=='vxc'&&!linkDown(l));l.cut=S.day+5;compute();draw(1032);return l.id;})()`);
assert.ok(uploads() > u0, 'a cut rebuilds the tubes'); assert.ok(uploads() > u0, 'a cut rebuilds the tubes');
assert.equal(ev(`linkLook(linkGroups().find(g=>g.some(x=>x.id===${JSON.stringify(id)})),S.day).dash`), 1, 'drawn dashed like a cut'); assert.equal(ev(`linkLook(linkGroups().find(g=>g.some(x=>x.id===${lit(id)})),S.day).dash`), 1, 'drawn dashed like a cut');
ev('mapGl(false);draw(1048)'); ev('mapGl(false);draw(1048)');
assert.equal(ev(`document.getElementById('mapgl').hidden`), true, 'switching back hides the layers'); assert.equal(ev(`document.getElementById('mapgl').hidden`), true, 'switching back hides the layers');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
@ -243,7 +244,7 @@ test('leaving a game hides the card’s layers, and the next game shows them aga
ev('ACT.toTitle();draw(1016)'); ev('ACT.toTitle();draw(1016)');
assert.deepEqual(shown(), [false, false, false], 'back to the title: the old network is not left behind it'); assert.deepEqual(shown(), [false, false, false], 'back to the title: the old network is not left behind it');
assert.ok(ev('ctx===CTX0')); assert.ok(ev('ctx===CTX0'));
ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;compute();draw(1032)`); ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;compute();draw(1032)`);
assert.deepEqual(shown(), [true, true, true], 'the next game is on the card again'); assert.deepEqual(shown(), [true, true, true], 'the next game is on the card again');
ev(`slotBroke(UI.slot||'x');draw(1048)`); ev(`slotBroke(UI.slot||'x');draw(1048)`);
assert.deepEqual(shown(), [false, false, false], 'a damaged save leaves the title with an empty map too'); assert.deepEqual(shown(), [false, false, false], 'a damaged save leaves the title with an empty map too');
@ -311,7 +312,7 @@ test('selecting a tube sends its halo to the card, not the network again', () =>
const FAKE_GL = (name) => `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};const c=document.getElementById('mapgl');c.getContext=(t)=>t!=='webgl2'?null:new Proxy({},{get(t,k){ const FAKE_GL = (name) => `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};const c=document.getElementById('mapgl');c.getContext=(t)=>t!=='webgl2'?null:new Proxy({},{get(t,k){
if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k; if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
if(k==='getExtension')return ()=>({UNMASKED_RENDERER_WEBGL:'REN'}); if(k==='getExtension')return ()=>({UNMASKED_RENDERER_WEBGL:'REN'});
if(k==='getParameter')return (p)=>p==='REN'?${JSON.stringify(name)}:p==='ACTIVE_UNIFORMS'?0:4096; if(k==='getParameter')return (p)=>p==='REN'?${lit(name)}:p==='ACTIVE_UNIFORMS'?0:4096;
if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true; if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true;
return ()=>({});}});})()`; return ()=>({});}});})()`;

View file

@ -8,6 +8,7 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
@ -33,9 +34,9 @@ const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2
function open(fail) { function open(fail) {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute(); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{}; window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{};
window.__FAIL=${JSON.stringify(fail)};`); window.__FAIL=${lit(fail)};`);
h.ev(GL); h.ev(GL);
return h; return h;
} }
@ -85,7 +86,7 @@ test('an ordinary frame never asks the card for its errors', () => {
const pan = JSON.parse(ev(`(()=>{let sent=0,reads=0,most=0,at=[];for(let i=0;i<120;i++){const s=__SUB,g=__GE;cam.x+=3;__T+=16;draw(__T); const pan = JSON.parse(ev(`(()=>{let sent=0,reads=0,most=0,at=[];for(let i=0;i<120;i++){const s=__SUB,g=__GE;cam.x+=3;__T+=16;draw(__T);
if(__SUB>s)sent++;if(__GE>g){reads++;at.push(i);}most=Math.max(most,__GE-g);}return JSON.stringify({sent,reads,most,at});})()`)); if(__SUB>s)sent++;if(__GE>g){reads++;at.push(i);}most=Math.max(most,__GE-g);}return JSON.stringify({sent,reads,most,at});})()`));
assert.ok(pan.sent > 5, 'frames send pictures'); assert.ok(pan.sent > 5, 'frames send pictures');
assert.ok(pan.reads >= 1 && pan.reads <= 2, `about two seconds of panning read the errors once or twice, not once per frame that sends (${JSON.stringify(pan)})`); assert.ok(pan.reads >= 1 && pan.reads <= 2, `about two seconds of panning read the errors once or twice, not once per frame that sends (${lit(pan)})`);
assert.ok(pan.most <= 4, 'one check reads at most four flags'); assert.ok(pan.most <= 4, 'one check reads at most four flags');
// The pan's last pictures are still to be checked: once, on the next frame a second on. Then a still map reads nothing. // The pan's last pictures are still to be checked: once, on the next frame a second on. Then a still map reads nothing.
ev('__GE=0;__T+=1100;draw(__T);'); ev('__GE=0;__T+=1100;draw(__T);');

View file

@ -6,12 +6,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h; return h;
} }

View file

@ -7,12 +7,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() { function open() {
const h = load({ seed: 777 }); const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute(); h.ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});`); window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});`);
return h; return h;
} }

View file

@ -8,6 +8,7 @@ const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { game } = require('../scripts/weekly-puzzle'); const { game } = require('../scripts/weekly-puzzle');
const AW = require('../scripts/weekly-architect'); const AW = require('../scripts/weekly-architect');
const { lit } = require('../scripts/lib/js-literal');
const DIR = path.join(__dirname, '..', 'site', 'architect', 'weekly'); const DIR = path.join(__dirname, '..', 'site', 'architect', 'weekly');
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'sot-arwk-')); const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'sot-arwk-'));
@ -33,7 +34,7 @@ test('a grow brief makes the reference make room: a bigger tube or a second one'
} }
const { ev } = load(); const { ev } = load();
const [j, b] = grows[0]; const [j, b] = grows[0];
ev(`UI.arWk={key:'${j.key}',def:arWkValid(${JSON.stringify(j)},'${j.key}'),at:Date.now()}`); ev(`UI.arWk={key:'${j.key}',def:arWkValid(${lit(j)},'${j.key}'),at:Date.now()}`);
const c = Object.keys(b.dem)[0]; const c = Object.keys(b.dem)[0];
assert.ok(ev(`UI.arWk.def.briefs.some(x=>x.t.includes(CITY['${c}'].name+' grows to'))`), 'the brief says so'); assert.ok(ev(`UI.arWk.def.briefs.some(x=>x.t.includes(CITY['${c}'].name+' grows to'))`), 'the brief says so');
}); });
@ -47,10 +48,10 @@ test('every published week is accepted and its reference still earns three stars
test('the game refuses a file that does not add up', () => { test('the game refuses a file that does not add up', () => {
const { ev } = load(); const { ev } = load();
const j = JSON.parse(fs.readFileSync(path.join(DIR, AW.list(DIR)[0] + '.json'), 'utf8')), k = j.key; const j = JSON.parse(fs.readFileSync(path.join(DIR, AW.list(DIR)[0] + '.json'), 'utf8')), k = j.key;
const ok = (o) => ev(`!!arWkValid(${JSON.stringify(o)},'${k}')`); const ok = (o) => ev(`!!arWkValid(${lit(o)},'${k}')`);
assert.equal(ok(j), true); assert.equal(ok(j), true);
const bad = (f) => { const o = JSON.parse(JSON.stringify(j)); f(o); return ok(o); }; const bad = (f) => { const o = JSON.parse(JSON.stringify(j)); f(o); return ok(o); };
assert.equal(ev(`!!arWkValid(${JSON.stringify(j)},'2030-W01')`), false, 'under another week'); assert.equal(ev(`!!arWkValid(${lit(j)},'2030-W01')`), false, 'under another week');
assert.equal(bad((o) => { o.extra = 1; }), false, 'an unknown field'); assert.equal(bad((o) => { o.extra = 1; }), false, 'an unknown field');
assert.equal(bad((o) => { o.hq = 'atlantis'; }), false, 'an unknown HQ'); assert.equal(bad((o) => { o.hq = 'atlantis'; }), false, 'an unknown HQ');
assert.equal(bad((o) => { o.name.l = 'common.play'; }), false, 'a label it may not name'); assert.equal(bad((o) => { o.name.l = 'common.play'; }), false, 'a label it may not name');
@ -64,7 +65,7 @@ test('the game refuses a file that does not add up', () => {
test('this week\'s run shows in Puzzles, plays like a handmade one and keeps its own stars', () => { test('this week\'s run shows in Puzzles, plays like a handmade one and keeps its own stars', () => {
const { ev, errors, dom } = load(); const { ev, errors, dom } = load();
const key = ev('pzWeekKey(new Date())'), j = AW.generate(game(), key, tmp()); const key = ev('pzWeekKey(new Date())'), j = AW.generate(game(), key, tmp());
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.puzzleMenu()'); ev('ACT.puzzleMenu()');
const row = dom.window.document.getElementById('arWk'); const row = dom.window.document.getElementById('arWk');
assert.ok(row && row.querySelector('[data-act=pzArStart]'), 'a row with a Play button'); assert.ok(row && row.querySelector('[data-act=pzArStart]'), 'a row with a Play button');

View file

@ -7,6 +7,7 @@ const os = require('node:os');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const G = require('../scripts/weekly-puzzle'); const G = require('../scripts/weekly-puzzle');
const { lit } = require('../scripts/lib/js-literal');
const DIR = path.join(__dirname, '..', 'site', 'puzzles', 'weekly'); const DIR = path.join(__dirname, '..', 'site', 'puzzles', 'weekly');
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-weekly-')); const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-weekly-'));
@ -151,13 +152,13 @@ test('--check regenerates a published week when new prices break its budget, and
test('stars belong to the revision of the week they were earned on', () => { test('stars belong to the revision of the week they were earned on', () => {
const { ev, errors } = load(); const { ev, errors } = load();
const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`); const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${lit(o)},'${k}')`);
assert.equal(ev(`pzWkValid(${JSON.stringify(j)},'${k}').rev`), 1, 'a first edition is rev 1'); assert.equal(ev(`pzWkValid(${lit(j)},'${k}').rev`), 1, 'a first edition is rev 1');
assert.ok(ok({ ...j, rev: 2 })); assert.ok(ok({ ...j, rev: 2 }));
for (const rev of [1, 0, '2', 2.5, 1000]) assert.equal(ok({ ...j, rev }), false, `rev ${rev}`); for (const rev of [1, 0, '2', 2.5, 1000]) assert.equal(ok({ ...j, rev }), false, `rev ${rev}`);
ev(`localStorage.setItem('sot-puzzles',JSON.stringify({wk:{'${k}':{st:3,sp:1},'2026-W01':{st:2,sp:5}}}))`); ev(`localStorage.setItem('sot-puzzles',JSON.stringify({wk:{'${k}':{st:3,sp:1},'2026-W01':{st:2,sp:5}}}))`);
assert.equal(ev(`pzWkRec(pzLoad(),pzWkValid(${JSON.stringify(j)},'${k}')).st`), 3, 'same week, same revision: the stars stand'); assert.equal(ev(`pzWkRec(pzLoad(),pzWkValid(${lit(j)},'${k}')).st`), 3, 'same week, same revision: the stars stand');
const d2 = `pzWkValid(${JSON.stringify({ ...j, rev: 2 })},'${k}')`; const d2 = `pzWkValid(${lit({ ...j, rev: 2 })},'${k}')`;
assert.equal(ev(`pzWkRec(pzLoad(),${d2})`), null, 'regenerated: that week starts again'); assert.equal(ev(`pzWkRec(pzLoad(),${d2})`), null, 'regenerated: that week starts again');
ev(`pzBegin(${d2});pzRecord({stars:1,spend:9})`); ev(`pzBegin(${d2});pzRecord({stars:1,spend:9})`);
const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')")); const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')"));
@ -193,8 +194,8 @@ test('the published puzzle is played when it is good, the seeded one when it is
["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'], ["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'],
["Promise.reject(new TypeError('offline'))", 'offline'], ["Promise.reject(new TypeError('offline'))", 'offline'],
["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'], ["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, cities: ['fra', 'nope', 'ams'] })})})`, 'an unknown city'], [`Promise.resolve({ok:true,json:()=>Promise.resolve(${lit({ ...good, cities: ['fra', 'nope', 'ams'] })})})`, 'an unknown city'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'], [`Promise.resolve({ok:true,json:()=>Promise.resolve(${lit({ ...good, key: '2020-W01' })})})`, 'another week'],
]) { ]) {
serve(how); serve(how);
await tick(); await tick();
@ -209,7 +210,7 @@ test('the published puzzle is played when it is good, the seeded one when it is
assert.match(ev("document.getElementById('pzWk').textContent"), /Loading this week/); assert.match(ev("document.getElementById('pzWk').textContent"), /Loading this week/);
assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), true); assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), true);
// The good one. // The good one.
serve(`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(good)})})`); serve(`Promise.resolve({ok:true,json:()=>Promise.resolve(${lit(good)})})`);
await tick(); await tick();
assert.equal(ev('UI.pzWk.st'), 'ok'); assert.equal(ev('UI.pzWk.st'), 'ok');
const row = ev("document.getElementById('pzWk').textContent"); const row = ev("document.getElementById('pzWk').textContent");
@ -228,7 +229,7 @@ test('the published puzzle is played when it is good, the seeded one when it is
const def = JSON.parse(ev('JSON.stringify(pzWkDef())')), sol = G.sized({ ev }, G.world(ev), G.shape(def), def).three.b; const def = JSON.parse(ev('JSON.stringify(pzWkDef())')), sol = G.sized({ ev }, G.world(ev), G.shape(def), def).three.b;
ev('pzBegin(pzWkDef())'); ev('pzBegin(pzWkDef())');
SV.judge(ev, sol.links); SV.judge(ev, sol.links);
ev(`pzsApplyRt(${JSON.stringify(sol.rt)});pzAfter()`); ev(`pzsApplyRt(${lit(sol.rt)});pzAfter()`);
assert.equal(ev('pzEval().stars'), 3); assert.equal(ev('pzEval().stars'), 3);
assert.match(ev('pzShareText(pzEval())'), new RegExp(`^Series of Tubes puzzle ${key} ⭐⭐⭐ \\$[\\d.]+[kM] · seriesoftub\\.es$`)); assert.match(ev('pzShareText(pzEval())'), new RegExp(`^Series of Tubes puzzle ${key} ⭐⭐⭐ \\$[\\d.]+[kM] · seriesoftub\\.es$`));
const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')")); const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')"));
@ -242,7 +243,7 @@ test('the published puzzle is played when it is good, the seeded one when it is
test('the file is checked field by field', () => { test('the file is checked field by field', () => {
const { ev, errors } = load(); const { ev, errors } = load();
const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`); const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${lit(o)},'${k}')`);
assert.ok(ok(j)); assert.ok(ok(j));
const no = (edit, why) => { const o = JSON.parse(JSON.stringify(j)); edit(o); assert.equal(ok(o), false, why); }; const no = (edit, why) => { const o = JSON.parse(JSON.stringify(j)); edit(o); assert.equal(ok(o), false, why); };
no((o) => { o.v = 3; }, 'a newer schema'); no((o) => { o.v = 3; }, 'a newer schema');
@ -270,7 +271,7 @@ test('the file is checked field by field', () => {
// Every label a theme may use exists in English, and every file names its text in the player's language. // Every label a theme may use exists in English, and every file names its text in the player's language.
assert.ok(ev("Object.values(PZ_WK_THEMES).every(T=>[T.t,...T.names,...T.jokes].every(l=>typeof EN[l]==='string'))")); assert.ok(ev("Object.values(PZ_WK_THEMES).every(T=>[T.t,...T.names,...T.jokes].every(l=>typeof EN[l]==='string'))"));
for (const f of committed()) { for (const f of committed()) {
const d = ev(`JSON.stringify(pzWkValid(${JSON.stringify(f)},'${f.key}'))`); const d = ev(`JSON.stringify(pzWkValid(${lit(f)},'${f.key}'))`);
assert.ok(d, f.key); assert.ok(d, f.key);
assert.doesNotMatch(ev(`(d=>pzTxt(d.wn)+' '+pzTxt(d.wj))(${d})`), /\{|puzzles_weekly\./, `${f.key}: filled in`); assert.doesNotMatch(ev(`(d=>pzTxt(d.wn)+' '+pzTxt(d.wj))(${d})`), /\{|puzzles_weekly\./, `${f.key}: filled in`);
} }
@ -282,7 +283,7 @@ test('weekly puzzle in every language and on a 360 px phone', async () => {
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
const { ev, errors } = load({ lang }); const { ev, errors } = load({ lang });
const key = ev('pzWeekKey(new Date())'); const key = ev('pzWeekKey(new Date())');
ev(`window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...f, key })})})`); ev(`window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${lit({ ...f, key })})})`);
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()"); ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()");
ev('ACT.puzzleMenu({})'); ev('ACT.puzzleMenu({})');
await tick(); await tick();

View file

@ -8,12 +8,13 @@ const os = require('node:os');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const G = require('../scripts/weekly-scenario'); const G = require('../scripts/weekly-scenario');
const { lit } = require('../scripts/lib/js-literal');
const DIR = path.join(__dirname, '..', 'site', 'scenarios', 'weekly'); const DIR = path.join(__dirname, '..', 'site', 'scenarios', 'weekly');
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-wkscn-')); const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-wkscn-'));
const committed = () => G.list(DIR).map((k) => JSON.parse(fs.readFileSync(path.join(DIR, k + '.json'), 'utf8'))); const committed = () => G.list(DIR).map((k) => JSON.parse(fs.readFileSync(path.join(DIR, k + '.json'), 'utf8')));
const tick = () => new Promise((r) => setTimeout(r, 30)); const tick = () => new Promise((r) => setTimeout(r, 30));
const serveFile = (ev, j) => ev(`UI.wsWk=null;window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(j)})})`); const serveFile = (ev, j) => ev(`UI.wsWk=null;window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${lit(j)})})`);
// One file per goal type, from the committed ones where a week has it: enough to check every card. // One file per goal type, from the committed ones where a week has it: enough to check every card.
const GOALS = { const GOALS = {
served: { theme: 'budget', goal: { t: 'served', p: { g: 200 } }, desc: { l: 'wkscn.desc_city_on_a_shoestring', p: { city: 'fra' } } }, served: { theme: 'budget', goal: { t: 'served', p: { g: 200 } }, desc: { l: 'wkscn.desc_city_on_a_shoestring', p: { city: 'fra' } } },
@ -55,7 +56,7 @@ test('every committed week verifies: not won on day 0, the reference wins on its
}); });
test('the file is checked field by field, and --check rejects a tampered one', () => { test('the file is checked field by field, and --check rejects a tampered one', () => {
const { ev, errors } = load(), j = committed()[0], ok = (x, key = j.key) => ev(`!!wsValid(${JSON.stringify(x)},'${key}')`); const { ev, errors } = load(), j = committed()[0], ok = (x, key = j.key) => ev(`!!wsValid(${lit(x)},'${key}')`);
assert.equal(ok(j), true); assert.equal(ok(j), true);
const bad = { const bad = {
'another week': [j, '2020-W01'], 'not a week': [{ ...j, key: '2026-W99' }, '2026-W99'], 'another week': [j, '2020-W01'], 'not a week': [{ ...j, key: '2026-W99' }, '2026-W99'],
@ -123,8 +124,8 @@ test('the published scenario is played when it is good, the in-browser weekly wh
["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'], ["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'],
["Promise.reject(new TypeError('offline'))", 'offline'], ["Promise.reject(new TypeError('offline'))", 'offline'],
["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'], ["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, city: 'nope' })})})`, 'an unknown city'], [`Promise.resolve({ok:true,json:()=>Promise.resolve(${lit({ ...good, city: 'nope' })})})`, 'an unknown city'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'], [`Promise.resolve({ok:true,json:()=>Promise.resolve(${lit({ ...good, key: '2020-W01' })})})`, 'another week'],
]) { ]) {
ev(`UI.wsWk=null;window.fetch=()=>${how}`); ev('ACT.scenarios({})'); await tick(); ev(`UI.wsWk=null;window.fetch=()=>${how}`); ev('ACT.scenarios({})'); await tick();
assert.equal(ev('wsDef()'), null, why); assert.equal(ev('wsDef()'), null, why);
@ -145,7 +146,7 @@ test('every goal type has a progress card, needs play, and wins, streaks and sha
const { ev, dom, errors } = load(), key = ev('pzWeekKey(new Date())'); const { ev, dom, errors } = load(), key = ev('pzWeekKey(new Date())');
for (const t of Object.keys(GOALS)) { for (const t of Object.keys(GOALS)) {
const f = fileFor(t, key); const f = fileFor(t, key);
assert.equal(ev(`wsBegin(${JSON.stringify(f)},'T')`), true, t); assert.equal(ev(`wsBegin(${lit(f)},'T')`), true, t);
ev('if(UI.pendGame)ACT.pitchSkip();closeModal();compute();renderAll()'); ev('if(UI.pendGame)ACT.pitchSkip();closeModal();compute();renderAll()');
assert.equal(ev('wsOk()'), false, `${t}: not won on day 0`); assert.equal(ev('wsOk()'), false, `${t}: not won on day 0`);
assert.ok(ev('scnProg().items.length') > 0, `${t}: a progress card`); assert.ok(ev('scnProg().items.length') > 0, `${t}: a progress card`);
@ -156,7 +157,7 @@ test('every goal type has a progress card, needs play, and wins, streaks and sha
} }
// A win: a POP goal met on day 1, recorded for the week, with a streak and the share line. // A win: a POP goal met on day 1, recorded for the week, with a streak and the share line.
ev("localStorage.removeItem('sot-wkscn')"); ev("localStorage.removeItem('sot-wkscn')");
ev(`wsBegin(${JSON.stringify(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`); ev(`wsBegin(${lit(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`);
// Waves take a few days to light (real lead times), so the goal is met once they are up. // Waves take a few days to light (real lead times), so the goal is met once they are up.
const build = "for(const c of ['ams','par']){UI.via=null;openLinkModal('fra',c);ACT.buildLink({tier:1});closeModal();}for(let i=0;i<90&&!S.scn.done;i++)dayTick()"; const build = "for(const c of ['ams','par']){UI.via=null;openLinkModal('fra',c);ACT.buildLink({tier:1});closeModal();}for(let i=0;i<90&&!S.scn.done;i++)dayTick()";
ev(build); ev(build);
@ -169,7 +170,7 @@ test('every goal type has a progress card, needs play, and wins, streaks and sha
assert.equal(rec.streak.n, 1); assert.equal(rec.streak.n, 1);
// Last week won too: the streak grows; a gap starts it again. // Last week won too: the streak grows; a gap starts it again.
ev(`localStorage.setItem('sot-wkscn',JSON.stringify({go:{},w:{},streak:{last:pzPrevKey('${key}'),n:3,best:3}}))`); ev(`localStorage.setItem('sot-wkscn',JSON.stringify({go:{},w:{},streak:{last:pzPrevKey('${key}'),n:3,best:3}}))`);
ev(`wsBegin(${JSON.stringify(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`); ev(`wsBegin(${lit(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`);
ev(build); ev(build);
assert.equal(JSON.parse(ev("localStorage.getItem('sot-wkscn')")).streak.n, 4); assert.equal(JSON.parse(ev("localStorage.getItem('sot-wkscn')")).streak.n, 4);
assert.equal(ev(`wsStreak(wsLoad(),pzKeyAdd('${key}',2))`), 0); assert.equal(ev(`wsStreak(wsLoad(),pzKeyAdd('${key}',2))`), 0);
@ -178,7 +179,7 @@ test('every goal type has a progress card, needs play, and wins, streaks and sha
test('saves keep the scenario, checked again on load; a tampered one plays on as the in-browser weekly', () => { test('saves keep the scenario, checked again on load; a tampered one plays on as the in-browser weekly', () => {
const { ev, errors } = load(), key = ev('pzWeekKey(new Date())'); const { ev, errors } = load(), key = ev('pzWeekKey(new Date())');
ev(`wsBegin(${JSON.stringify(fileFor('path', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal();S.scn.run=7`); ev(`wsBegin(${lit(fileFor('path', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal();S.scn.run=7`);
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
assert.equal(ev("S.scn.wk.goal.t+':'+S.scn.run+':'+S.scn.home"), 'path:7:fra'); assert.equal(ev("S.scn.wk.goal.t+':'+S.scn.run+':'+S.scn.home"), 'path:7:fra');
ev("S.scn.wk.goal={t:'win',p:{}};S.scn.run='x';S=migrate(JSON.parse(JSON.stringify(S)));compute();renderAll()"); ev("S.scn.wk.goal={t:'win',p:{}};S.scn.run='x';S=migrate(JSON.parse(JSON.stringify(S)));compute();renderAll()");

View file

@ -2,6 +2,7 @@
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const start = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;for(const g of GOALS)S.done[g.id]=0"); const start = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;for(const g of GOALS)S.done[g.id]=0");
@ -11,7 +12,7 @@ test('each network operators\' meeting only comes to a city where it really meet
// the conference calendar // the conference calendar
assert.deepEqual(JSON.parse(ev("JSON.stringify(CONFS.filter(cf=>!nogOk(cf.n,cf.c)).map(cf=>cf.n+'@'+cf.c))")), []); assert.deepEqual(JSON.parse(ev("JSON.stringify(CONFS.filter(cf=>!nogOk(cf.n,cf.c)).map(cf=>cf.n+'@'+cf.c))")), []);
// the rules themselves, on cities people know // the rules themselves, on cities people know
const ok = (n, c) => ev(`nogOk(${JSON.stringify(n)},${JSON.stringify(c)})`); const ok = (n, c) => ev(`nogOk(${lit(n)},${lit(c)})`);
for (const c of ['chi', 'ash', 'sea', 'hnl']) assert.ok(ok('NANOG 99', c), `NANOG in ${c}`); for (const c of ['chi', 'ash', 'sea', 'hnl']) assert.ok(ok('NANOG 99', c), `NANOG in ${c}`);
for (const c of ['lon', 'tor', 'mex']) assert.ok(!ok('NANOG 99', c), `no NANOG in ${c}`); for (const c of ['lon', 'tor', 'mex']) assert.ok(!ok('NANOG 99', c), `no NANOG in ${c}`);
for (const c of ['sin', 'tok', 'syd', 'akl', 'bom', 'suv']) assert.ok(ok('APRICOT 2027', c), `APRICOT in ${c}`); for (const c of ['sin', 'tok', 'syd', 'akl', 'bom', 'suv']) assert.ok(ok('APRICOT 2027', c), `APRICOT in ${c}`);

View file

@ -7,12 +7,13 @@ const assert = require('node:assert/strict');
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('./harness'); const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
test('only Firefox on Android gets the land as a software canvas', () => { test('only Firefox on Android gets the land as a software canvas', () => {
const { ev } = load({ seed: 777 }); const { ev } = load({ seed: 777 });
const soft = (ua) => ev(`softCanvas(${JSON.stringify(ua)})`); const soft = (ua) => ev(`softCanvas(${lit(ua)})`);
// Firefox on Android, phone and tablet. // Firefox on Android, phone and tablet.
assert.equal(soft('Mozilla/5.0 (Android 14; Mobile; rv:132.0) Gecko/132.0 Firefox/132.0'), true); assert.equal(soft('Mozilla/5.0 (Android 14; Mobile; rv:132.0) Gecko/132.0 Firefox/132.0'), true);
assert.equal(soft('Mozilla/5.0 (Android 13; Tablet; rv:128.0) Gecko/128.0 Firefox/128.0'), true); assert.equal(soft('Mozilla/5.0 (Android 13; Tablet; rv:128.0) Gecko/128.0 Firefox/128.0'), true);
@ -26,7 +27,7 @@ test('only Firefox on Android gets the land as a software canvas', () => {
test('elsewhere the land picture is an ordinary canvas, which the browser may keep on the graphics card', () => { test('elsewhere the land picture is an ordinary canvas, which the browser may keep on the graphics card', () => {
const { ev, errors } = load({ seed: 777 }); const { ev, errors } = load({ seed: 777 });
ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();mapGl(false,false); ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();mapGl(false,false);
window.__opts=[];const gc=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(t,o){__opts.push(o||null);return gc.call(this,t,o);}; window.__opts=[];const gc=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(t,o){__opts.push(o||null);return gc.call(this,t,o);};
WL.cv=null;WL.key=null;cam.z=1.6;worldLayer(cam.z);`); WL.cv=null;WL.key=null;cam.z=1.6;worldLayer(cam.z);`);
assert.equal(ev('SOFT_CANVAS'), false); assert.equal(ev('SOFT_CANVAS'), false);