// What server-run play needs from the game before it is built (the server-sim design, track T1): new games in two // halves (beginState/beginHello/beginShow), the tutorial's state apart from its box (tutAdvance/coachDom), a toast on // screen without its log line (toastPop), the boot's one-shot notes in bootNotes(), the five acts that read a typed // field taking the text as an argument, srvOn() and its two checks in the loop, mpSanitize keeping sim, the quote checks, // and the multiplayer-only client folder left out of every other page. None of it changes play in any build. // T1_BASE= also compares the refactors with the page at that ref (before them): same state, same screen. const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const { load } = require('./harness'); const { assemble, assembleRef, simId, MP_ONLY, ROOT } = require('../scripts/lib/page'); const { lit } = require('../scripts/lib/js-literal'); const BASE = process.env.T1_BASE; let baseHtml = null; const baseFile = () => { if (!baseHtml) { baseHtml = path.join(os.tmpdir(), `tubes-t1-base-${process.pid}.html`); fs.writeFileSync(baseHtml, assembleRef(BASE)); } return baseHtml; }; // The pages to compare: this one, and the base page when T1_BASE is set. const pages = (opts = {}) => [load(opts), ...(BASE ? [load({ ...opts, file: baseFile() })] : [])]; const pin = 'Date.now=()=>1.7e12;'; // What the player sees: the toasts (without their birth time), the panel, the HUD, a window, the coach. (Without the // label ids the shipped base page writes into data-i18n attributes: the words are compared.) const screen = (ev) => ev(`JSON.stringify({toasts:$('toasts').innerHTML,panel:$('panel').innerHTML,hud:$('hud').innerHTML, modal:$('modal').hidden?'':$('modalCard').innerHTML,coach:$('coach').hidden?'':$('coach').innerHTML,glow:document.querySelectorAll('.coach-glow').length})`) .replace(/ data-born=\\"[^"\\]*\\"/g, '').replace(/ data-i18n[-a-z]*=\\"[^"\\]*\\"/g, ''); // The game as a reload makes it, keys in order: what "the same game as before" means across this change, which writes // the fields a reload fills in when it creates things (tests/canonical-state.test.js). // stamp: false leaves out when log lines were written and their ids (a boot runs before a test can pin the clock). const canon = (ev, stamp = true) => ev(`(()=>{const u=uidN,r=S.rng,k=v=>Array.isArray(v)?v.map(k):v&&typeof v==='object'?Object.keys(v).sort().reduce((o,x)=>(o[x]=k(v[x]),o),{}):v; try{const s=migrate(JSON.parse(JSON.stringify(S)));if(!${stamp})for(const e of s.log)delete e.at,delete e.id;return JSON.stringify(k(s));}finally{uidN=u;S.rng=r;}})()`); const M = { code: 'K7Q2XD', pid: 'abcd1234', asn: 201234, seed: 424242, preset: 'bgp', color: '#3a86ff', title: 'Friday' }; test('a new network in halves: the server path (beginState, compute, beginHello, then beginShow with srv) gives the page the same game and screen as beginGame', (t) => { const A = load(), B = load(); t.after(() => { A.dom.window.close(); B.dom.window.close(); }); for (const h of [A, B]) h.ev(pin + 'UI.pitched=true;UI.asnTxt="";'); A.ev(`beginGame('Packet Pals','fra',{mode:'normal',preset:'bgp',mp:${lit(M)}})`); // The server: the state, its marks, its routing and its welcome; no screen, no storage. const keys0 = B.ev('Object.keys(localStorage).sort().join()'), toasts0 = B.ev("$('toasts').children.length"), started0 = B.ev('UI.started'); B.ev(`beginState('Packet Pals','fra',{mode:'normal',preset:'bgp',mp:${lit(M)},asn:201234})`); assert.equal(B.ev('Object.keys(localStorage).sort().join()'), keys0, 'beginState stores nothing'); assert.equal(B.ev("$('toasts').children.length"), toasts0, 'and shows nothing'); assert.equal(B.ev('UI.started'), started0, 'nor starts the clock'); B.ev('S.mp.sim=1;S.tut=null;compute();beginHello();'); // The page: makes its slot for the network, then shows it, without routing it again, a second welcome or a tutorial. B.ev(`slotLeave();slotNew();window.__c=0;const c0=compute;compute=()=>{__c++;c0();};beginShow('fra',{mode:'normal',preset:'bgp',mp:${lit(M)},srv:true});compute=c0;`); assert.equal(B.ev('__c'), 0, 'the page does not route a server network'); const plain = (ev) => ev('JSON.stringify({...S,tut:undefined,mp:{...S.mp,sim:undefined}})'); assert.equal(plain(B.ev), plain(A.ev), 'the same game'); assert.equal(B.ev("S.log.filter(e=>/Welcome/.test(e.t)).length"), 1, 'one welcome in the log'); assert.equal(screen(B.ev), screen(A.ev), 'the same screen'); assert.equal(B.ev('S.mp.sim'), 1); assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []); }); test('a new game from the title still starts as it did: Normal, sandbox, a scenario', (t) => { for (const how of ["UI.preset='bgp';ACT.start({})", "ACT.modeSet({m:'sandbox'});ACT.start({})", 'ACT.startScn({id:SCN[0].id})']) { const P = pages(); t.after(() => P.forEach((h) => h.dom.window.close())); for (const h of P) h.ev(pin + `UI.pitched=true;${how};`); assert.ok(P[0].ev('!!S&&UI.started'), how); for (const h of P.slice(1)) { assert.equal(canon(h.ev), canon(P[0].ev), `${how}: the same game as before`); assert.equal(screen(h.ev), screen(P[0].ev), `${how}: the same screen as before`); } for (const h of P) assert.deepEqual(h.errors, []); } }); test('the coach: tutAdvance moves S.tut on and draws nothing, coachDom draws and changes nothing; renderCoach is the two', (t) => { const P = pages(); t.after(() => P.forEach((h) => h.dom.window.close())); const steps = ["ACT.launchBB({city:'fra'})", "ACT.buyTransit({city:'fra',net:'cog',tier:1})", "ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'})", 'for(let i=0;i<6;i++)dayTick();renderAll()', "ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0})", "for(let i=0;i<40&&!S.biz.length;i++){dayTick();if(S.offers[0])ACT.accept({id:S.offers[0].id});}renderAll()"]; for (const h of P) h.ev(pin + "window.__TUBES_TUT__=true;UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;UI.speed=0;S.cash=1e7;"); assert.equal(P[0].ev('S.tut'), 0, 'the tutorial started'); const coach = (ev) => ev("$('coach').hidden+'|'+$('coach').innerHTML+'|'+document.querySelectorAll('.coach-glow').length"); for (const s of steps) { for (const h of P) h.ev(s); const ev = P[0].ev; // The two halves on their own, on this page. const box = coach(ev), st = ev('JSON.stringify(S)'); ev('coachDom()'); assert.equal(ev('JSON.stringify(S)'), st, `${s}: coachDom changes no state`); const tut = ev('S.tut'); ev("window.__box=$('coach').innerHTML;tutAdvance()"); assert.equal(ev("$('coach').innerHTML===__box"), true, `${s}: tutAdvance draws nothing`); assert.equal(ev('S.tut'), tut, `${s}: renderAll already advanced it`); assert.equal(coach(ev), box); for (const h of P.slice(1)) { assert.equal(h.ev('S.tut'), tut, `${s}: the same step as before`); assert.equal(coach(h.ev), box, `${s}: the same coach as before`); } } assert.equal(P[0].ev('S.tut'), null, 'the tutorial ran to its end'); assert.match(P[0].ev('S.log[0].t+S.log[1].t+S.log[2].t'), /basics/, 'and said so'); for (const h of P) assert.deepEqual(h.errors, []); }); test('toastPop shows a toast without its log line; toast() is the log line and toastPop, quiet days included', (t) => { const { ev, errors, dom } = load(); t.after(() => dom.window.close()); ev(pin + "UI.pitched=true;ACT.start({});closeModal();$('toasts').innerHTML='';"); const n0 = ev('S.log.length'); ev("toastPop('Hi there','good',[{l:'Open',act:'leftTab',args:{t:'noc'}}])"); assert.equal(ev('S.log.length'), n0, 'no log line'); assert.match(ev("$('toasts').innerHTML"), /Hi<\/b> there.*data-act="leftTab"/); ev("toast('Logged too','good')"); assert.equal(ev('S.log.length'), n0 + 1); // Quiet notifications: what a day says (tick) pops up only for trouble and milestones. ev("$('toasts').innerHTML='';window.__q=PREFS.quiet;PREFS.quiet=true;toastPop('a day note','',[],true);toastPop('not a day','',[],false);toastPop('trouble','bad',[],true);PREFS.quiet=__q"); assert.equal(ev("$('toasts').children.length"), 2, 'the quiet day note stays in the log only'); assert.deepEqual(errors, []); }); // A save that has both boot notes to say: new networks on the map since it was saved, and Australia's prices. function notesSave() { const { ev, dom } = load(); try { ev(pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();ACT.buildPop({city:'syd'});for(let i=0;i<5;i++)dayTick();S.seen=S.seen.slice(3);delete S.auV;"); return ev('JSON.stringify(packSave(S))'); } finally { dom.window.close(); } } test('bootNotes: a reopened network says once that new networks are on the map and that Australia changed, as the boot always did', (t) => { const txt = notesSave(); const P = pages({ storage: { 'sot-save-v1': txt } }); t.after(() => P.forEach((h) => h.dom.window.close())); const ev = P[0].ev; assert.equal(ev('typeof bootNotes'), 'function'); assert.equal(ev('S.grace.told'), 1, 'the courtesy route was announced'); assert.equal(ev("'auNews' in S"), false, 'Australia was announced'); const said = ev("S.log.slice(0,3).map(e=>e.t).join(' | ')"); assert.match(said, /new networks/i); assert.match(said, /Australia/i); ev('bootNotes()'); assert.equal(ev("S.log.slice(0,3).map(e=>e.t).join(' | ')"), said, 'once only'); for (const h of P.slice(1)) { assert.equal(canon(h.ev, false), canon(ev, false), 'the same as before'); assert.equal(screen(h.ev), screen(ev)); } // Declared before the multiplayer client's folder, so that folder can rebind it. const { map } = assemble({ mp: true }); const where = map.find((m) => fs.readFileSync(path.join(ROOT, 'src', m.file), 'utf8').includes('function bootNotes(')); assert.ok(where && where.file < 'game/98-server-play/', `bootNotes() is in ${where && where.file}`); for (const h of P) assert.deepEqual(h.errors, []); }); test('the five acts that read a typed field take the text as an argument first: the same game either way', (t) => { const setup = pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();S.cash=1e8;S.lvl=4;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});" + "ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();S.te={on:true,day:0};compute();"; const script = 'prefer cog at fra'; const cases = [ ['renameGo', "ACT.rename();$('rnIn').value=' Tubular Bells ';ACT.renameGo({})", "closeModal();ACT.renameGo({name:' Tubular Bells '})", 'S.name'], ['metricSet', "ACT.setMetric({id:S.links[0].id,v:'custom'});UI.sel={type:'link',id:S.links[0].id};renderPanel();$('metIn').value='2.5';ACT.metricSet({id:S.links[0].id})", "ACT.setMetric({id:S.links[0].id,v:'custom'});ACT.metricSet({id:S.links[0].id,v:'2.5'})", 'JSON.stringify(S.pairMet)'], ['teDeploy', `ACT.teEdit();$('teSrc').value=${lit(script)};ACT.teDeploy({})`, `closeModal();ACT.teDeploy({script:${lit(script)}})`, 'JSON.stringify(S.te)'], ]; for (const [act, field, arg, pick] of cases) { const A = load(), B = load(); t.after(() => { A.dom.window.close(); B.dom.window.close(); }); A.ev(setup); B.ev(setup); A.ev(field); B.ev(arg); assert.equal(B.ev(pick), A.ev(pick), `${act}: what it changed`); assert.equal(B.ev('JSON.stringify(S)'), A.ev('JSON.stringify(S)'), `${act}: the whole game`); assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []); } { const D = load(); t.after(() => D.dom.window.close()); assert.equal(D.ev(setup + "ACT.rename();$('rnIn').value='Tubular Bells';ACT.renameGo({});S.name"), 'Tubular Bells'); } // teCheck: the same report from the argument as from the editor. { const A = load(), B = load(); t.after(() => { A.dom.window.close(); B.dom.window.close(); }); A.ev(setup + `ACT.teEdit();$('teSrc').value=${lit(script)};ACT.teCheck({})`); B.ev(setup + `closeModal();ACT.teCheck({script:${lit(script)}})`); assert.match(A.ev("$('modalCard').textContent"), /rule/); assert.equal(B.ev("$('modalCard').querySelector('pre').textContent"), A.ev("$('modalCard').querySelector('pre').textContent")); assert.equal(B.ev('JSON.stringify(S)'), A.ev('JSON.stringify(S)')); } // pieRename: the rocket company's name, in a sandbox (where anyone may found one). { const pie = pin + "UI.pitched=true;ACT.modeSet({m:'sandbox'});ACT.start({});closeModal();ACT.pieFound();closeModal();"; const A = load(), B = load(); t.after(() => { A.dom.window.close(); B.dom.window.close(); }); A.ev(pie); B.ev(pie); assert.ok(A.ev('!!(S.pie&&S.pie.co)'), 'a rocket company'); A.ev("UI.pieTab='co';ACT.pieOpen()"); assert.ok(A.ev("!!$('pieNm')"), 'the name field is on screen'); A.ev("$('pieNm').value=' Orbit Pie ';ACT.pieRename({})"); B.ev("closeModal();ACT.pieRename({name:' Orbit Pie '})"); assert.equal(A.ev('S.pie.co.name'), 'Orbit Pie'); assert.equal(B.ev('JSON.stringify(S)'), A.ev('JSON.stringify(S)')); assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []); } // Without the argument and without the field, nothing happens, as before. const C = load(); t.after(() => C.dom.window.close()); C.ev(setup + "closeModal();window.__s=JSON.stringify(S);ACT.renameGo({});ACT.metricSet({id:S.links[0].id});ACT.pieRename({});"); assert.equal(C.ev('JSON.stringify(S)===__s'), true); }); test('the field paths of the five acts play as before', { skip: !BASE && 'set T1_BASE to compare with the page before' }, (t) => { const setup = pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();S.cash=1e8;S.lvl=4;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});" + "ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();S.te={on:true,day:0};compute();" + "ACT.rename();$('rnIn').value='Tubular Bells';ACT.renameGo({});ACT.setMetric({id:S.links[0].id,v:'custom'});UI.sel={type:'link',id:S.links[0].id};renderPanel();$('metIn').value='2.5';ACT.metricSet({id:S.links[0].id});" + "ACT.teEdit();$('teSrc').value='prefer cog at fra';ACT.teCheck({});ACT.teDeploy({});"; const P = pages(); t.after(() => P.forEach((h) => h.dom.window.close())); for (const h of P) h.ev(setup); assert.equal(canon(P[1].ev), canon(P[0].ev)); }); test('srvOn(): false in every page this track ships; a server-play folder that says yes keeps the loop and the boot from running the network', (t) => { // The plain page and the MP page with only the folder's placeholder: the stub, and a network with sim plays locally. for (const opts of [{}, { mp: true }]) { const { ev, errors, dom } = load(opts); t.after(() => dom.window.close()); assert.equal(ev('srvOn()'), false); assert.deepEqual(errors, []); } // A page whose folder rebinds srvOn (as the real client will) and opens a server network's mirror. const src = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-srv-src-')); t.after(() => fs.rmSync(src, { recursive: true, force: true })); fs.cpSync(path.join(ROOT, 'src'), src, { recursive: true }); fs.writeFileSync(path.join(src, 'game', '98-server-play', '50-t1-test.js'), 'srvOn=()=>!!(S&&S.mp&&S.mp.sim===1);bootNotes=()=>{window.__notes=(window.__notes||0)+1;};\n'); const file = path.join(src, 'page.html'); fs.writeFileSync(file, assemble({ src, mp: true }).html.replace("/*__MP_API__*/''", "'/api/mp'")); const mk = load(); t.after(() => mk.dom.window.close()); mk.ev(pin + `UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${lit(M)}});S.mp.sim=1;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();`); const txt = mk.ev('JSON.stringify(packSave(S))'); const run = (ev) => { ev("closeModal();UI.speed=8;let t=performance.now();for(let i=0;i<40;i++){t+=200;frame(t);}"); return ev('S.day'); }; { const { ev, errors, dom } = load({ file, storage: { 'sot-save-v1': txt } }); t.after(() => dom.window.close()); assert.equal(ev('S.mp.sim'), 1, 'mpSanitize kept sim'); assert.equal(ev('srvOn()'), true); assert.equal(ev('R.served'), 0, 'the boot did not route it (the server does)'); assert.equal(ev('window.__notes'), 1, 'the boot called the rebound bootNotes'); const d0 = ev('S.day'); assert.equal(run(ev), d0, 'no day ran on this page'); assert.deepEqual(errors, []); } { // The same save in the page this track ships: a sim network nobody runs for it plays here, as phase 1 does. const { ev, errors, dom } = load({ storage: { 'sot-save-v1': txt } }); t.after(() => dom.window.close()); assert.ok(ev('R.served') > 0, 'routed at boot'); const d0 = ev('S.day'); assert.ok(run(ev) > d0, 'and days run'); assert.deepEqual(errors, []); } }); test('mpSanitize keeps sim:1 and nothing else in its place', (t) => { const { ev, errors, dom } = load(); t.after(() => dom.window.close()); ev(pin + `UI.pitched=true;ACT.start({});closeModal();S.mp=${lit({ ...M, seq: 3 })};`); const back = (sim) => JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.mp.sim=${lit(sim)};return JSON.stringify(migrate(s).mp);})()`)); assert.equal(back(1).sim, 1); for (const v of [2, '1', true, null, { x: 1 }]) assert.equal('sim' in back(v), false, JSON.stringify(v)); assert.equal('sim' in JSON.parse(ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(S))).mp)')), false, 'a phase-1 network has none'); assert.deepEqual(errors, []); }); test('quote checks: a bulk order whose total changed under its window is shown again, not bought', (t) => { const { ev, errors, dom } = load(); t.after(() => dom.window.close()); ev(pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();S.cash=1e9;S.lvl=6;for(const c of ['fra','ams','lon','par'])ACT.buildPop({city:c});compute();"); // pniAll: the sheet's button carries the total it shows. ev("ACT.pniAllOpen({net:null})"); const args = JSON.parse(ev(`$('modalCard').querySelector('[data-act="pniAll"]').dataset.args`)); assert.equal(args.q, ev(`pniBatch(null,${args.tier}).cost`), 'the button carries the quoted total'); const n0 = ev('S.pni.length'), c0 = ev('S.cash'); ev(`ACT.pniAll(${lit({ ...args, q: args.q + 1 })})`); assert.equal(ev('S.pni.length'), n0, 'a changed total buys nothing'); assert.equal(ev('S.cash'), c0); assert.match(ev("$('modalCard').textContent"), /quote changed/i, 'the sheet says why, with the new total'); ev(`ACT.pniAll(${lit(args)})`); assert.ok(ev('S.pni.length') > n0, 'the shown total buys'); // Without q (the agent, older callers): as before. ev("closeModal();ACT.buildPop({city:'nyc'});window.__n=S.pni.length;ACT.pniAll({net:null,tier:1})"); assert.ok(ev('S.pni.length') > ev('__n')); // A sheet whose batch was ordered meanwhile (another tap, the intern): shown again, not a silent nothing. ev("ACT.pniAllOpen({net:null})"); const gone = JSON.parse(ev(`$('modalCard').querySelector('[data-act="pniAll"]').dataset.args`)); ev(`closeModal();ACT.pniAll(${lit({ net: gone.net, tier: gone.tier })});window.__n=S.pni.length;ACT.pniAll(${lit(gone)})`); assert.equal(ev('S.pni.length'), ev('__n')); assert.match(ev("$('modal').hidden?'':$('modalCard').textContent"), /quote changed/i, 'an emptied plan says so'); // bstdApply: the build standard's "Bring everything up now" carries the plan it shows (its key) and its total. ev("closeModal();S.popStd=bstdPut({...bstd(),rt:2});ACT.bstdOpen()"); const b = JSON.parse(ev(`$('modalCard').querySelector('[data-act="bstdApply"]').dataset.args`)); assert.deepEqual(b, JSON.parse(ev('JSON.stringify({quote:bstdPlanKey(bstdPlan(false)),q:bstdQuote(false).cost})'))); const rts = "JSON.stringify(Object.values(S.pops).map(p=>p.routers))", r0 = ev(rts); ev(`ACT.bstdApply(${lit({ ...b, quote: b.quote + 'x' })})`); assert.equal(ev(rts), r0, 'another plan builds nothing'); assert.match(ev("$('modalCard').textContent"), /quote changed/i); ev(`closeModal();ACT.bstdApply(${lit({ ...b, q: Math.round(b.q * 0.9) })})`); assert.equal(ev(rts), r0, 'a total 10% away builds nothing'); assert.match(ev("$('modalCard').textContent"), /quote changed/i); // Hardware prices drift a little every day under the market rule: the same plan a day later still builds. ev(`closeModal();ACT.bstdApply(${lit({ ...b, q: b.q + 1 })})`); assert.notEqual(ev(rts), r0, 'the shown plan builds, at today\'s prices'); ev(`ACT.bstdApply(${lit(b)})`); assert.match(ev("$('modal').hidden?'':$('modalCard').textContent"), /quote changed/i, 'and once it is all done, the old sheet is shown again'); // The two that always checked: utilityKit (cost) and utilityCaches (quote). ev("closeModal();window.__s=JSON.stringify(S);ACT.utilityKit({city:'fra',cost:-1,modal:true});ACT.utilityCaches({city:'fra',quote:'nope',modal:true})"); assert.equal(ev('JSON.stringify(S)===__s'), true); // utilityKit takes a day's drift too (the kit's router is priced by the market), not a whole part of the kit. ev("closeModal();ACT.buildPop({city:'mad'});window.__k=utilityKit('mad').cost;ACT.utilityKit({city:'mad',cost:__k+GEN_COST})"); assert.equal(ev('S.pops.mad.gen'), false); ev('ACT.utilityKit({city:\'mad\',cost:__k+1})'); assert.equal(ev('S.pops.mad.gen&&S.pops.mad.site2&&S.pops.mad.routers===2'), true); assert.deepEqual(errors, []); }); test('quote checks hold on a server-run day: the build standard\'s plan a few days old still builds, while hardware prices drift', (t) => { // The review's case: routers on the big network, the market rule on; every day moves the total a little. const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); const { ev, errors, dom } = load({ seed: 77 }); t.after(() => dom.window.close()); ev(`${pin}S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.lvl=Math.max(S.lvl,6);S.rules=makeRules('oncall'); S.nextFail=S.nextEvent=1e9;S.day=400;S.cash=1e10;compute();S.popStd=bstdPut({...bstd(),rt:8});ACT.bstdOpen();`); assert.equal(ev("rule('market')"), true); const b = JSON.parse(ev(`$('modalCard').querySelector('[data-act="bstdApply"]').dataset.args`)); ev('closeModal();for(let i=0;i<3;i++){S.cash=1e10;dayTick();}'); assert.notEqual(ev('bstdQuote(false).cost'), b.q, 'the total moved'); assert.equal(ev('bstdPlanKey(bstdPlan(false))'), b.quote, 'the plan did not'); const r0 = ev("Object.values(S.pops).reduce((a,p)=>a+(p.routers||1),0)"); ev(`ACT.bstdApply(${lit(b)})`); assert.ok(ev("Object.values(S.pops).reduce((a,p)=>a+(p.routers||1),0)") > r0, 'and it builds'); assert.deepEqual(errors, []); }); test('the multiplayer client folder and its CSS are in an MP page only, and SIM_ID is its build id', (t) => { const plain = assemble(), mp = assemble({ mp: true }); const only = (f) => MP_ONLY.some((p) => (p.endsWith('/') ? f.startsWith(p) : f === p)); assert.deepEqual(plain.map.filter((m) => only(m.file)), [], 'the plain page has none of it'); const mine = mp.map.filter((m) => only(m.file)); assert.ok(mine.some((m) => m.file.startsWith('game/98-server-play/')) && mine.some((m) => m.file === 'styles/43-server-play.css'), 'the MP page has both'); // The MP page is the plain page plus exactly those files. const lines = mp.html.split('\n'), drop = new Set(); for (const m of mine) for (let i = m.from; i <= m.to; i++) drop.add(i); assert.equal(lines.filter((l, i) => !drop.has(i + 1)).join('\n'), plain.html); assert.equal(assemble({ dev: true }).map.filter((m) => only(m.file)).length, 0, 'nor the development page without mp'); // The build id: 12 hex digits of the MP page, a new one for any change. assert.match(simId(), /^[0-9a-f]{12}$/); assert.equal(simId(), simId(mp.html)); assert.notEqual(simId(mp.html + ' '), simId(mp.html)); assert.match(plain.html, /const SIM_ID=\/\*__SIM_ID__\*\/'';/, 'unstamped in the source'); const h = load({ mp: true }); t.after(() => h.dom.window.close()); assert.equal(h.ev('SIM_ID'), simId(), 'load({mp:true}) is a stamped MP page'); assert.equal(h.ev('MP_API'), '/api/mp'); assert.deepEqual(h.errors, []); }); test('the translation check reads the server-play client too: a label used only there counts as used', (t) => { const { page, sourceLabels } = require('../scripts/i18n-check'); const src = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-srv-i18n-')); t.after(() => fs.rmSync(src, { recursive: true, force: true })); fs.cpSync(path.join(ROOT, 'src'), src, { recursive: true }); fs.writeFileSync(path.join(src, 'game', '98-server-play', '50-t1-label.js'), "function srvProbe(){return tr('zzsrv.probe_label');}\n"); assert.equal(sourceLabels(page(src)).labels.has('zzsrv.probe_label'), true, 'the checked page has the MP-only folder'); assert.equal(assemble({ src }).html.includes('zzsrv.probe_label'), false, 'and the plain page still has none of it'); }); test('a new POP has its router in its state from the start: a reload keeps the one play had, even under a port it cannot take', (t) => { // Before canonical state a POP had no rgen until a reload inferred one from its ports: founding an exchange (a tier-2 // port, which foundIx does not check against the router) and reloading gave a free router upgrade. Play always read // the basic router (RG[p.rgen||0]); now the state says so, and a reload keeps it. const { ev, errors, dom } = load({ seed: 9 }); t.after(() => dom.window.close()); const out = JSON.parse(ev(`${pin}UI.pitched=true;ACT.start({});closeModal();S.cash=1e8;S.lvl=6;let c=null; for(const x of Object.keys(CITY)){if(S.pops[x]||!cityOn(x)||cnCity(x))continue;ACT.buildPop({city:x});closeModal();if(S.pops[x]&&!foundIxWhy(x)){c=x;break;}} ACT.foundIx({city:c});closeModal();const u=uidN,r=S.rng,back=migrate(JSON.parse(JSON.stringify(packSave(S))));uidN=u;S.rng=r; JSON.stringify({c,live:S.pops[c].rgen,ix:S.ixp[c],reload:back.pops[c].rgen,maxP:RG[0].maxP})`)); assert.ok(out.c, 'a city to found an exchange in'); assert.equal(out.live, 0, 'the basic router, written down'); assert.ok(out.ix > out.maxP, 'an exchange port above what that router takes (foundIx does not check it: its own owner\'s to decide)'); assert.equal(out.reload, 0, 'a reload keeps the router play had'); // An old save's POP without the field still gets the router its ports need. assert.equal(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));delete s.pops[${lit(out.c)}].rgen;const u=uidN,r=S.rng;try{return migrate(s).pops[${lit(out.c)}].rgen;}finally{uidN=u;S.rng=r;}})()`) > 0, true); assert.deepEqual(errors, []); });