Merge main and resolve optics PR changelog conflict

This commit is contained in:
LookedPath 2026-10-28 09:03:53 +00:00
commit 9a01b3d415
60 changed files with 1911 additions and 179 deletions

View file

@ -0,0 +1,56 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const choose = (ev, v) => ev(`(()=>{const s=document.getElementById('homeSel');s.value=${JSON.stringify(v)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`);
const onTiles = ev => JSON.parse(ev("JSON.stringify([...document.querySelectorAll('.starts .start.on')].map(b=>b.dataset.city||'own'))"));
test('the title screen offers five homes and a sixth tile for any city, grouped by continent', () => {
const { ev, errors } = load();
assert.equal(ev('S'), null, 'before any game exists');
assert.equal(ev("document.querySelectorAll('.starts .start').length"), 6);
const opts = JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#homeSel option')].map(o=>o.value).filter(Boolean))"));
assert.ok(opts.length > 150, `lots of cities (${opts.length})`);
assert.ok(opts.every(c => ev(`homeOk('${c}')`)), 'only cities that work as a home');
assert.ok(!opts.some(c => ev(`!!CITY['${c}'].cn||!!CITY['${c}'].off`)), 'no hidden or Chinese cities');
assert.ok(!opts.includes('stg'), 'no city without transit to buy');
assert.ok(ev("document.querySelectorAll('#homeSel optgroup').length") >= 5, 'grouped by continent');
assert.deepEqual(errors, []);
});
test('picking any city starts the network there, and the tiles follow the choice', () => {
const { ev, errors } = load();
choose(ev, 'lis');
assert.equal(ev('UI.startCity'), 'lis');
assert.deepEqual(onTiles(ev), ['own'], 'the sixth tile lights up');
assert.equal(ev("document.getElementById('homeWhat').textContent"), 'Lisbon · ' + ev("REG[CITY.lis.reg]"), 'and names the city in full');
ev("document.querySelector('.start[data-city=nyc]').click()");
assert.deepEqual(onTiles(ev), ['nyc'], 'a suggested tile takes over again');
assert.equal(ev("document.getElementById('homeSel').value"), '', 'and the dropdown resets');
assert.match(ev("document.getElementById('homeWhat').textContent"), /more cities/);
choose(ev, 'akl');
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
assert.equal(ev('S.home'), 'akl');
assert.ok(ev("!!S.pops.akl"), 'the first POP is in Auckland');
assert.ok(ev("NETS.some(n=>sellsAt(n,'akl'))"), 'with transit to buy');
assert.deepEqual(errors, []);
});
test('a home that cannot work is refused, and the game falls back to Frankfurt', () => {
const { ev, errors } = load();
ev("ACT.pickStart({city:'stg'});ACT.pickStart({city:'pek'});ACT.pickStart({city:'nowhere'})");
assert.equal(ev('UI.startCity'), 'fra');
ev("UI.startCity='pek';ACT.start({})");
assert.equal(ev('S.home'), 'fra');
assert.deepEqual(errors, []);
});
test('the sixth tile works on a phone and in every language', () => {
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
const { ev, errors } = load(lang === 'en' ? {} : { lang });
ev('window.innerWidth=360;showTitle()');
assert.equal(ev("document.querySelector('label.start.own b').textContent"), ev("tr('title.anywhere_else')"), lang);
if (lang !== 'en') assert.notEqual(ev("tr('title.anywhere_else')"), 'Anywhere else', `${lang}: translated`);
assert.deepEqual(errors, []);
}
});

70
tests/eyeballs.test.js Normal file
View file

@ -0,0 +1,70 @@
// More American eyeballs and a merger or two (#155), more Australian eyeballs (#154).
const test = require('node:test');
const assert = require('node:assert');
const { load } = require('./harness');
function start(ev) { ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); }
test('American eyeballs follow PeeringDB, and the ones with upstreams are reached through their Tier 1s (#155)', () => {
const { ev, errors } = load();
start(ev);
const asn = { att: 7018, tmo: 21928, cxc: 22773, pes: 6128, ftr: 5650, gfb: 16591, snc: 46375 };
for (const [id, a] of Object.entries(asn)) assert.equal(ev(`NET.${id}.asn`), a, id);
assert.equal(ev('NET.att.type'), 't1');
assert.ok(ev("NET.att.price>0&&NET.att.ix.length===0"), 'AT&Tease sells transit and never peers at an IX');
assert.ok(ev("NET.tmo.pol==='selective'&&NET.pes.pol==='open'&&NET.gfb.pol==='open'&&NET.snc.pol==='open'"));
assert.ok(ev("NET.gfb.ix.includes('kcy')"), 'GFibber gives the Kansas City exchange some eyeballs');
assert.ok(ev("NET.tmo.ix.includes('sju')"), 'Tee-Hee Mobile is on the Puerto Rico exchange');
assert.equal(ev("NET.cxc.ix.length"), 0, 'Coax: PNIs only');
assert.deepEqual(JSON.parse(ev('JSON.stringify(NET.cxc.up)')), ['spc']);
assert.deepEqual(JSON.parse(ev('JSON.stringify(NET.ftr.up)')), ['vzn']);
// with PNIs to every Tier 1 and no transit, the small ones with Tier 1 upstreams are still reachable
ev("S.transit=[];S.ixp={};S.pni=[];for(const n of t1Need())S.pni.push({id:n.id,net:n.id,city:'fra',tier:0});compute()");
assert.ok(ev("t1Need().every(n=>n.pops.includes('fra'))"), 'every Tier 1, AT&Tease included, is in Frankfurt');
for (const id of ['tmo', 'pes', 'gfb', 'snc']) assert.equal(ev(`!!R.reachable.${id}`), true, id);
assert.deepEqual(errors, []);
});
test('Coax gets Spectre-um’d a year in, and Final Frontear joins Very-Zone a year later (#155)', () => {
const { ev, errors } = load();
start(ev);
ev("ACT.buildPop({city:'chi'});ACT.buildPop({city:'nyc'});ACT.buyIx({city:'nyc',tier:1,signed:true})");
ev("S.pni.push({id:'p1',net:'cxc',city:'chi',tier:1,ready:0},{id:'p2',net:'ftr',city:'nyc',tier:1,ready:0});S.peers['ftr@nyc']=true;compute()");
assert.doesNotMatch(ev("peerOk('cxc','pni','chi').why||''"), /Spectre-um/, 'Coax still decides for itself');
ev('S.day=364;dayTick()');
assert.equal(ev("merged('cxc')"), true, 'the deal closed');
assert.equal(ev("S.pni.find(p=>p.id==='p1').net"), 'spc', 'the Coax PNI now belongs to Spectre-um');
assert.match(ev("peerOk('cxc','pni','chi').why"), /Spectre-um/);
assert.equal(ev("merged('ftr')"), false);
const before = ev("pniMo(S.pni.find(p=>p.id==='p2'),0)");
ev('S.day=729;dayTick()');
assert.equal(ev("merged('ftr')"), true);
assert.equal(ev("S.pni.find(p=>p.id==='p2').net"), 'vzn');
assert.equal(ev("S.peers['ftr@nyc']"), undefined, 'the IX session ended');
assert.ok(ev("pniMo(S.pni.find(p=>p.id==='p2'),0)") > before, 'your free peer just became a paid one');
// a PNI with the new owner in the same city absorbs the old one instead of doubling up
const { ev: ev2 } = load();
start(ev2);
ev2("ACT.buildPop({city:'chi'});S.pni.push({id:'a',net:'cxc',city:'chi',tier:1,ready:0},{id:'b',net:'spc',city:'chi',tier:1,ready:0});S.day=400;dayTick()");
assert.equal(ev2("S.pni.filter(p=>p.city==='chi').map(p=>p.net).join()"), 'spc');
// the inbox never brings requests from a brand that no longer exists, and saves keep the record
ev("const o=JSON.parse(JSON.stringify(S));S=migrate(o)");
assert.equal(ev("merged('cxc')&&merged('ftr')"), true);
ev("S.merged={cxc:'x',zzz:3};S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('S.merged'), undefined, 'junk in a save is dropped');
assert.deepEqual(errors, []);
});
test('Australian eyeballs: Neptoon on every exchange family, Lawn-tel in Hobart, Internope behind its parent (#154)', () => {
const { ev, errors } = load();
start(ev);
const asn = { npt: 151660, lnt: 134697, pnt: 10214, mag: 58511, inp: 4739 };
for (const [id, a] of Object.entries(asn)) assert.equal(ev(`NET.${id}.asn`), a, id);
for (const c of ['syd', 'mel', 'bne', 'per', 'adl']) assert.ok(ev(`ixMembers('${c}').includes('npt')`), `Neptoon on the ${c} exchange`);
assert.ok(ev("XIXM['syd~2'].members.includes('npt')&&XIXM['syd~2'].members.includes('mag')"), 'and on the Sydney challenger');
assert.ok(ev("ixMembers('hba').includes('lnt')&&NET.lnt.pol==='selective'"));
assert.ok(ev("NET.mag.price>0&&NET.mag.pops.includes('akl')&&NET.mag.pops.includes('lon')"), 'the magpie flies far');
assert.ok(ev("NET.inp.pol==='restrictive'&&NET.inp.ix.length===0&&NET.inp.up[0]==='tpr'"));
assert.ok(ev("NET.stb.pops.includes('lax')&&NET.stb.pops.includes('sea')"), 'Musklink is where most of its users are');
assert.deepEqual(errors, []);
});

View file

@ -32,6 +32,8 @@ function load(opts = {}) {
// A non-English game: jsdom does not fetch the dictionary script, so register it up front.
// (opts.dir: the folder the dictionary comes from, e.g. a build's _site/i18n.)
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(opts.dir || path.join(__dirname, '..', 'site', 'i18n'), opts.lang + '.js'), 'utf8')); }
// jsdom has no CompressionStream; {gzip:true} lends the page Node's, the same API browsers have (#176).
if (opts.gzip) for (const k of ['CompressionStream', 'DecompressionStream', 'TextEncoder', 'TextDecoder']) window[k] = globalThis[k];
window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} };
// A recording 2D context, so draw code really runs under test (jsdom has no canvas).
const fake = () => { const calls = { n: 0 };

View file

@ -108,9 +108,10 @@ test('the static markup is translated by label', () => {
assert.equal(ev("document.querySelector('[data-act=help]').getAttribute('aria-label')"), ev("tr('common.how_to_play')"));
});
test('the language buttons on the title screen work before any game exists', () => {
test('the language dropdown on the title screen works before any game exists', () => {
const { ev } = load();
ev("[...document.querySelectorAll('#modalCard [data-act=langSet]')].find(b=>b.textContent==='Italiano').click()");
assert.equal(ev('S'), null);
ev("const s=document.querySelector('#modalCard select#langTitle');s.value='it';s.dispatchEvent(new Event('change',{bubbles:true}))");
assert.equal(ev("localStorage.getItem('sot-lang')"), 'it');
});

View file

@ -0,0 +1,143 @@
// The Caribbean (#125), the south-west Indian Ocean (#152), Pitcairn (#124), and Alaska, northern British Columbia
// and Russia's Arctic and Pacific coasts (#145).
const test = require('node:test');
const assert = require('node:assert');
const { load } = require('./harness');
function start(ev) { ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0"); }
const lands = (ev, cid, a, b) => ev(`CABLE_PAIRS.some(p=>p.cid==='${cid}'&&[p.a,p.b].sort().join()==='${[a, b].sort().join()}')`);
const wave = (ev, a, b, via) => ev(`UI.via=${via ? `'${via}'` : 'null'};UI.route='same';openLinkModal('${a}','${b}');ACT.buildLink({tier:2});closeModal();S.links.length`);
test('the Caribbean: islands on their own landmass, real landings, exchanges only where one runs (#125)', () => {
const { ev, errors } = load();
start(ev);
const isl = ['sju', 'sdq', 'kin', 'hav', 'nas', 'pos', 'bgi', 'fdf', 'cur'];
for (const c of isl) {
assert.ok(ev(`CABLE_PAIRS.some(p=>p.a==='${c}'||p.b==='${c}')`), `${c} has a cable`);
assert.ok(ev(`isSub('${c}','mia')&&isSub('${c}','ccs')`), `${c} is an island`);
assert.ok(ev(`NETS.some(n=>n.price&&n.pops.includes('${c}'))`), `${c} has a transit seller`);
assert.ok(ev(`onLand(CITY.${c}.x,CITY.${c}.y)`), `${c} is drawn on land`);
}
// PR-IX, the Jamaica exchange, TTIX and AMS-IX Caribbean; none in Santo Domingo (they are in Santiago), Havana,
// Nassau, Bridgetown or Martinique
assert.deepEqual(isl.filter(c => ev(`!!CITY.${c}.ix`)), ['sju', 'kin', 'pos', 'cur']);
for (const c of ['sju', 'kin', 'pos', 'cur']) assert.ok(ev(`ixMembers('${c}').length`) >= 5, `${c} has members`);
// Cuba's only cable comes from Venezuela, nothing from Florida
assert.deepEqual(JSON.parse(ev("JSON.stringify([...new Set(CABLE_PAIRS.filter(p=>p.a==='hav'||p.b==='hav').map(p=>p.cid))])")), ['alba']);
assert.ok(lands(ev, 'alba', 'ccs', 'hav') && lands(ev, 'arcos', 'mia', 'nas') && lands(ev, 'arcos', 'sju', 'cur') && lands(ev, 'am2', 'pos', 'for'));
assert.ok(lands(ev, 'ecfs', 'fdf', 'bgi') && lands(ev, 'cfx', 'mia', 'kin') && lands(ev, 'ecl', 'cur', 'pos') && lands(ev, 'sam1', 'sju', 'sdq'));
// old pairs stay where they were, so saved links keep their cable
assert.equal(ev("CAB.sam1.pairs[0].slice(0,2).join()"), 'mia,for');
// a hop through the islands carries traffic: Miami to San Juan to Curaçao
for (const c of ['mia', 'sju', 'cur']) ev(`ACT.buildPop({city:'${c}'});S.pops.${c}.rgen=3`);
wave(ev, 'mia', 'sju', 'am2'); wave(ev, 'sju', 'cur', 'arcos');
ev('compute()');
assert.equal(ev("S.links.filter(l=>l.sub).length"), 2, 'two subsea waves');
ev('cam.z=0.5;draw(0);cam.z=5;cam.x=CITY.sju.x;cam.y=CITY.sju.y;draw(0)');
assert.deepEqual(errors, []);
});
test('the south-west Indian Ocean: Réunion on SAFE, Mauritius, Madagascar and the Seychelles (#152)', () => {
const { ev, errors } = load();
start(ev);
const isl = ['run', 'mru', 'tnr', 'sez'];
for (const c of isl) {
assert.ok(ev(`CABLE_PAIRS.some(p=>p.a==='${c}'||p.b==='${c}')`), `${c} has a cable`);
assert.ok(ev(`isSub('${c}','dur')&&isSub('${c}','mba')`), `${c} is an island`);
assert.ok(ev(`NETS.some(n=>n.price&&n.pops.includes('${c}'))`), `${c} has a transit seller`);
}
assert.ok(ev("isSub('run','mru')&&isSub('run','tnr')"));
// REUNIX, MIXP and MGIX run today; the Seychelles exchange is not on the books
assert.deepEqual(isl.filter(c => ev(`!!CITY.${c}.ix`)), ['run', 'mru', 'tnr']);
assert.equal(ev('CITY.run.ix'), 'Rougail SAUCIX');
assert.ok(ev("['zeo','srr','cnp'].every(id=>ixMembers('run').includes(id))"), 'Zealot, Signal Frequently Ruined and Canal Minus on REUNIX');
// SAFE gains its island landings and keeps its old pair
assert.equal(ev("CAB.safe.pairs[0].slice(0,2).join()"), 'cpt,bom');
assert.ok(lands(ev, 'safe', 'dur', 'run') && lands(ev, 'safe', 'run', 'mru') && lands(ev, 'lion', 'tnr', 'run') && lands(ev, 'metiss', 'dur', 'tnr'));
assert.ok(lands(ev, 'seas', 'sez', 'dar') && lands(ev, 'peace', 'sez', 'mba') && lands(ev, 'eassy', 'mpm', 'tnr'));
assert.ok(ev("NET.tng.pops.includes('run')&&NET.tng.pops.includes('tnr')"), 'Tangerine on the islands');
ev('cam.z=5;cam.x=CITY.run.x;cam.y=CITY.run.y;draw(0)');
assert.deepEqual(errors, []);
});
test('Pitcairn: no cable and no network, but you may land your own, and the UK pays while the islanders are online (#124)', () => {
const { ev, errors } = load();
start(ev);
assert.equal(ev("CABLE_PAIRS.some(p=>p.a==='pcn'||p.b==='pcn')"), false, 'no cable lands there');
assert.equal(ev("NETS.some(n=>n.type!=='cdn'&&n.pops.includes('pcn'))"), false, 'no provider but you');
assert.equal(ev("landing('pcn')"), true, 'a beach for your own cable');
assert.ok(ev("isFinite(ownCabKm('ppt','pcn'))&&ownCabKm('ppt','pcn')<4000"), 'a sea route from Tahiti');
// the grant needs a POP with broadband that is nearly fully served
ev("ACT.buildPop({city:'pcn'});compute()");
assert.equal(ev('R.rev.grant'), 0, 'no grant without broadband');
ev("ACT.launchBB({city:'pcn'});compute()");
const served = ev("sfOf(R,'pcn')");
assert.equal(ev('R.rev.grant'), served >= 0.9 ? ev('GRANT_MO') : 0);
// islanders served: the grant shows in the monthly revenue
ev("R.citySrv.pcn=R.cityDem.pcn");
assert.equal(ev("grantOn(R)"), true);
ev("S.pops.pcn.down=S.day+3");
assert.equal(ev("grantOn(R)"), false, 'not while the POP is down');
ev("S.pops.pcn.down=0;UI.sel={type:'city',id:'pcn'};renderPanel()");
assert.match(ev("document.body.innerHTML"), /UK grant/);
assert.deepEqual(errors, []);
});
test('Alaska and northern British Columbia: towns with no road in are islands, and the Arctic fiber breaks in the ice (#145)', () => {
const { ev, errors } = load();
start(ev);
for (const c of ['anc', 'jnu', 'ome', 'brw', 'dut', 'prr']) {
assert.ok(ev(`CABLE_PAIRS.some(p=>p.a==='${c}'||p.b==='${c}')`), `${c} has a cable`);
assert.ok(ev(`onLand(CITY.${c}.x,CITY.${c}.y)`), `${c} is drawn on land`);
}
assert.equal(ev("isSub('anc','sea')"), false, 'Anchorage has a road south');
assert.equal(ev("isSub('prr','van')"), false, 'so does Prince Rupert');
for (const c of ['jnu', 'ome', 'brw', 'dut']) assert.ok(ev(`isSub('${c}','anc')`), `${c}: no road in, only the sea`);
assert.ok(lands(ev, 'qtl', 'ome', 'brw') && lands(ev, 'qtl', 'brw', 'anc') && lands(ev, 'aleu', 'anc', 'dut') && lands(ev, 'topaz', 'van', 'tok'));
assert.equal(ev('CAB.qtl.fragile'), true, 'sea ice keeps the repair ships away');
assert.equal(ev('CITY.anc.ix.length>0'), true, 'Anchorage has its exchange');
assert.ok(ev("ixMembers('anc').includes('acs')"));
assert.ok(ev("NET.gci.price>0&&['ome','brw','dut','jnu'].every(c=>NET.gci.pops.includes(c))"), 'Glacier sells transit across Alaska');
ev('cam.z=4;cam.x=CITY.brw.x;cam.y=CITY.brw.y;draw(0)');
assert.deepEqual(errors, []);
});
test("Russia's Arctic and Pacific: government boxes, real cables only, beaches where Polar Express never arrived (#145)", () => {
const { ev, errors } = load();
start(ev);
const ru = ['mmk', 'dks', 'tik', 'pvs', 'dyr', 'pkc', 'gdx', 'uus', 'vvo'];
for (const c of ru) {
assert.ok(ev(`CITY.${c}.ru===true`), `${c} needs the government box`);
assert.ok(ev(`onLand(CITY.${c}.x,CITY.${c}.y)`), `${c} is drawn on land`);
assert.ok(ev(`NET.rtc.pops.includes('${c}')`), `${c} has Rostelecomedy`);
}
// Polar Express only got as far as Amderma: its towns have no cable, but a beach for your own
for (const c of ['mmk', 'dks', 'tik', 'pvs']) {
assert.equal(ev(`cablesFor('${c}','vvo').length+CABLE_PAIRS.filter(p=>p.a==='${c}'||p.b==='${c}').length`), 0, `${c}: no cable yet`);
assert.ok(ev(`landing('${c}')`), `${c}: you may land one`);
}
assert.ok(lands(ev, 'chuk', 'pkc', 'dyr') && lands(ev, 'skm', 'uus', 'pkc') && lands(ev, 'skm', 'uus', 'gdx') && lands(ev, 'rjcn', 'vvo', 'tok') && lands(ev, 'hscs', 'uus', 'tok'));
// nothing crosses the Bering Strait
assert.equal(ev("CABLE_PAIRS.some(p=>CITY[p.a].ru!==CITY[p.b].ru&&(CITY[p.a].cc==='US'||CITY[p.b].cc==='US'))"), false);
assert.equal(ev("isSub('dyr','anc')"), true);
// Kamchatka has no road to the rest of Russia; Magadan and Vladivostok do
assert.equal(ev("isSub('pkc','vvo')"), true);
assert.equal(ev("isSub('gdx','vvo')||isSub('mmk','mos')"), false);
assert.ok(ev("CITY.vvo.ix.length>0&&ixMembers('vvo').includes('mgf')&&ixMembers('vvo').includes('ert')"), 'the Vladivostok exchange');
// a sovereign-internet drill cuts the cable to Japan like any other border link
ev("ACT.buildPop({city:'vvo'});ACT.buildPop({city:'tok'});S.pops.vvo.rgen=3;S.pops.tok.rgen=3");
wave(ev, 'vvo', 'tok', 'rjcn');
ev("S.ev.runet=S.day+5;compute()");
assert.equal(ev("linkDown(S.links.find(l=>l.a==='vvo'||l.b==='vvo'))"), true);
ev('cam.z=4;cam.x=CITY.pkc.x;cam.y=CITY.pkc.y;draw(0)');
assert.deepEqual(errors, []);
});
test('saves with POPs in the new places survive a save and reload', () => {
const { ev, errors } = load();
start(ev);
for (const c of ['sju', 'run', 'anc', 'vvo', 'pcn']) ev(`ACT.buildPop({city:'${c}'})`);
ev("const o=JSON.parse(JSON.stringify(S));S=migrate(o);compute()");
assert.ok(ev("['sju','run','anc','vvo','pcn'].every(c=>!!S.pops[c])"));
assert.deepEqual(errors, []);
});

View file

@ -331,7 +331,8 @@ test('#40 overland between continents costs ten times subsea or more, and has no
const sub=waveMo(c.km,true,2)*CAB[c.cid].price*waveMarket(c.a,c.b,true).m;return [land/sub,!!(CITY[c.a].land2||CITY[c.b].land2)];}))`));
assert.ok(r.length >= 4, 'Europe–Asia cable routes exist to compare');
// Across a land bridge (Cairo, #47) the cable goes the long way round Arabia, so overland is "only" 4–9× dearer.
for (const [x, bridge] of r) assert.ok(x >= (bridge ? 4 : 10), `overland is at least ${bridge ? 4 : 10}× subsea (${x.toFixed(1)})`);
// EIG from Dubai now follows Arabia and the Suez Canal at sea, which makes it a little longer: 9.97× (#183).
for (const [x, bridge] of r) assert.ok(x >= (bridge ? 4 : 9.5), `overland is at least ${bridge ? 4 : 9.5}× subsea (${x.toFixed(1)})`);
assert.equal(ev("landX('mrs','hkg')"), true);
assert.equal(ev("landX('fra','mrs')"), false, 'inside Europe stays normal');
assert.equal(ev("landMult('fra','mrs')"), 1);
@ -815,16 +816,16 @@ test('cancelling from the Connections list confirms once, without forging the pa
test('diversity offers respect buildable cable routes, not current infrastructure', () => {
const { ev, dom, errors } = load();
base(ev);
assert.equal(ev("diversityPossible('cbo','den')"), false, 'both Colombo exits share SEE-ME-WAVE 4');
assert.equal(ev("diversityPossible('den','cbo')"), false, 'same in reverse');
assert.equal(ev("diversityPossible('jam','den')"), false, 'both St Helena exits share Equi-yes');
assert.equal(ev("diversityPossible('den','jam')"), false, 'same in reverse');
assert.equal(ev("diversityPossible('fra','den')"), true, 'expansion is allowed before links are built');
ev("S.ev.landban={city:'cbo',until:S.day+100}");
ev("S.ev.landban={city:'jam',until:S.day+100}");
ev('S.won=true');
assert.equal(ev("diversityPossible('cbo','den')"), true, 'Tier 1 can build an independent subsea cable');
ev("S.scn={rules:{banCities:['cbo']}}");
assert.equal(ev("diversityPossible('cbo','den')"), false, 'scenario city bans are respected');
assert.equal(ev("diversityPossible('jam','den')"), true, 'Tier 1 can build an independent subsea cable');
ev("S.scn={rules:{banCities:['jam']}}");
assert.equal(ev("diversityPossible('jam','den')"), false, 'scenario city bans are respected');
ev('S.scn=null;S.won=false');
assert.equal(ev("diversityPossible('cbo','den')"), false, 'cache follows the cable unlock');
assert.equal(ev("diversityPossible('jam','den')"), false, 'cache follows the cable unlock');
assert.deepEqual(errors, []);
dom.window.close();
});
@ -850,7 +851,7 @@ test('save migration checks diversity using the imported cable unlock', () => {
const { ev, dom, errors } = load();
base(ev);
ev(`window.__save=JSON.parse(JSON.stringify(S));__save.offers=[
{id:'bad',type:'hyper',city:'cbo',city2:'den',name:'x',bw:1600,rate:1,reqs:['diverse','netchill'],exp:40},
{id:'bad',type:'hyper',city:'jam',city2:'den',name:'x',bw:1600,rate:1,reqs:['diverse','netchill'],exp:40},
{id:'good',type:'hyper',city:'fra',city2:'den',name:'y',bw:1600,rate:1,reqs:['diverse'],exp:40}
];__save.biz=[{...__save.offers[0],id:'existing',mood:100,since:0}];S.won=true;__save.won=false`);
assert.deepEqual(JSON.parse(ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(__save))).offers.map(o=>o.reqs))')), [['netchill'], ['diverse']]);
@ -1083,9 +1084,9 @@ test('#88 no subsea cable longer than any optic can light, and a refund for call
test('#50 a city without a cable landing points to the nearest one', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'osl'});UI.pending=null;openLinkModal('osl','nyc')");
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'zrh'});UI.pending=null;openLinkModal('zrh','nyc')");
const t = ev("$('modalCard').textContent");
assert.match(t, /No subsea cable lands in Oslo\. The nearest landing station is Stavanger/);
assert.match(t, /No subsea cable lands in Zurich\. The nearest landing station is Milan/);
assert.doesNotMatch(t, /nowhere/);
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,39 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const pick = (ev, id) => JSON.parse(ev(`(()=>{const s=document.getElementById('${id}');return JSON.stringify(s&&{tag:s.tagName,value:s.value,chg:s.dataset.chg,
opts:[...s.options].map(o=>[o.value,o.textContent,o.lang]),label:(document.querySelector('label[for=${id}]')||{}).textContent});})()`));
test('language is one dropdown on the title screen and in Settings, in every language, with the current one selected', () => {
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
const { ev, errors } = load(lang === 'en' ? {} : { lang });
const langs = JSON.parse(ev('JSON.stringify(Object.entries(LANGS))'));
const title = pick(ev, 'langTitle');
assert.equal(title.tag, 'SELECT', `${lang}: title screen`);
assert.equal(title.value, lang);
assert.deepEqual(title.opts, langs.map(([v, l]) => [v, l, v]), `${lang}: every language, named in itself`);
assert.equal(title.label, ev("tr('common.language')"), `${lang}: labelled`);
assert.equal(ev("document.querySelectorAll('#modalCard [data-act=langSet]').length"), 0, `${lang}: no language buttons left`);
ev("ACT.start({});ACT.settings()");
const set = pick(ev, 'langSel');
assert.equal(set.value, lang, `${lang}: settings`);
assert.equal(set.label, ev("tr('common.language')"));
assert.deepEqual(errors, []);
}
});
test('changing the dropdown in Settings switches language and keeps the game', () => {
const { ev, errors } = load();
ev("ACT.start({});dayTick();ACT.settings();const s=document.getElementById('langSel');s.value='fr';s.dispatchEvent(new Event('change',{bubbles:true}))");
assert.equal(ev("localStorage.getItem('sot-lang')"), 'fr');
assert.ok(ev("localStorage.getItem('sot-save-v1')"), 'saved before reloading');
assert.deepEqual(errors, []);
});
test('the dropdown fits a phone', () => {
const { ev, errors } = load();
ev('window.innerWidth=360;showTitle()');
assert.ok(ev("document.getElementById('langTitle').classList.contains('pick')"));
assert.deepEqual(errors, []);
});

139
tests/link-metrics.test.js Normal file
View file

@ -0,0 +1,139 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Waves between Frankfurt and Amsterdam (tier 3 is 800G, tier 0 is 10G), transit in Amsterdam, eyeballs in Frankfurt.
function setup(ev, tiers = [3, 3]) {
ev("ACT.start({});S.cash=1e8;S.lvl=4;for(const g of GOALS)S.done[g.id]=0");
ev("ACT.buildPop({city:'ams'});for(const c in S.pops){S.pops[c].rgen=3;S.pops[c].routers=2}");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'ams',net:'lvl',tier:3})");
tiers.forEach((t, i) => ev(`UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:${t}});closeModal();S.links[S.links.length-1].tag=${i}`));
ev("var L=i=>S.links.find(l=>l.tag===i),L1=L(0),L2=L(1);compute()");
}
const load_ = (ev, x) => ev(`R.load[${x}.id]||0`);
const body = dom => dom.window.document.body.textContent;
test('#122 the routing metric belongs to the city pair', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.setMetric({id:L2.id,v:'avoid'})");
assert.equal(ev("S.pairMet['ams|fra']"), 'avoid');
ev("ACT.selLink({id:L1.id});renderAll()");
assert.ok(ev("[...document.querySelectorAll('[data-act=\"setMetric\"]')].some(b=>b.className.includes('pink')&&/Avoid/.test(b.textContent))"), 'the other link shows the same metric');
ev("ACT.setMetric({id:L1.id,v:'normal'})");
assert.equal(ev("'ams|fra' in S.pairMet"), false);
assert.deepEqual(errors, []);
});
test('#122 a link on standby idles while the others have room and takes over when they fail', () => {
const { ev, dom, errors } = load();
setup(ev);
const total = ev("R.served");
assert.ok(load_(ev, 'L1') > 0 && load_(ev, 'L2') > 0, 'active links share the load');
ev("ACT.setStandby({id:L2.id,on:1});compute()");
assert.equal(ev("L2.standby"), true);
assert.ok(load_(ev, 'L1') > 0);
assert.equal(load_(ev, 'L2'), 0, 'standby link idles');
assert.ok(Math.abs(ev("R.served") - total) < 1e-6, 'nothing is lost');
ev("ACT.selLink({id:L2.id});renderAll()");
assert.match(body(dom), /On standby: idle while the other links/);
ev("L1.cut=S.day+5;compute();renderAll()");
assert.ok(load_(ev, 'L2') > 0, 'standby link takes over when the active one is cut');
assert.match(body(dom), /On standby, but carrying the traffic/);
// Every link on standby: they share the traffic like active ones, and the note does not claim the others are down.
ev("L1.cut=0;ACT.setStandby({id:L1.id,on:1});compute();renderAll()");
assert.ok(load_(ev, 'L1') > 0 && load_(ev, 'L2') > 0);
assert.match(body(dom), /no active link between these cities is up/);
ev("ACT.setStandby({id:L2.id,on:0})");
assert.equal(ev("'standby' in L2"), false);
assert.deepEqual(errors, []);
});
test('#122 a standby link takes the overflow when the active links are full', () => {
const { ev, dom, errors } = load();
setup(ev, [0, 3]); // 10G active, 800G next to it
const total = ev("R.served");
ev("ACT.setStandby({id:L2.id,on:1});compute()");
const cap = ev("capOf(L1)");
assert.ok(Math.abs(load_(ev, 'L1') - cap) < 1e-6, 'the active link fills up first');
assert.ok(load_(ev, 'L2') > 0, 'the rest spills onto the standby link');
assert.ok(Math.abs(ev("R.served") - total) < 1e-6, 'standby capacity is never wasted');
ev("ACT.selLink({id:L2.id});renderAll()");
assert.match(body(dom), /taking the overflow/);
assert.deepEqual(errors, []);
});
test('#122 the order links are built in does not change where traffic goes', () => {
const tiers = [3, 0, 3], standby = [true, false, false], seen = new Set();
for (const order of [[0, 1, 2], [2, 1, 0], [1, 0, 2], [2, 0, 1]]) {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;S.lvl=4;for(const g of GOALS)S.done[g.id]=0");
ev("ACT.buildPop({city:'ams'});for(const c in S.pops){S.pops[c].rgen=3;S.pops[c].routers=2}");
ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'ams',net:'lvl',tier:3})");
for (const i of order) ev(`UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:${tiers[i]}});closeModal();const l=S.links[S.links.length-1];l.tag=${i};if(${standby[i]})ACT.setStandby({id:l.id,on:1})`);
ev("ACT.setMetric({id:S.links[0].id,v:'prefer'});compute()");
seen.add(ev("JSON.stringify([0,1,2].map(i=>Math.round((R.load[S.links.find(l=>l.tag===i).id]||0)*1e6)))"));
assert.deepEqual(errors, []);
}
assert.equal(seen.size, 1, [...seen].join(' vs '));
});
test('#122 a new link between the same cities adds capacity and keeps the pair metric', () => {
const { ev, errors } = load();
setup(ev, [0]);
ev("ACT.setMetric({id:L1.id,v:'avoid'});ACT.setStandby({id:L1.id,on:1});compute()");
const before = ev("R.served");
ev("UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:3});closeModal();compute()");
const nl = "S.links[S.links.length-1]";
assert.equal(ev(`'standby' in ${nl}`), false, 'a new link starts active');
assert.equal(ev("pairMet('ams|fra')"), 'avoid');
assert.ok(ev("R.served") > before, 'more capacity, more traffic');
// The metric leaves with the last link, so a fresh link later starts on normal.
for (const id of ev("S.links.map(l=>l.id)")) ev(`UI.confirm=null;ACT.rmLink({id:'${id}'});ACT.rmLink({id:'${id}'})`);
assert.equal(ev("'ams|fra' in S.pairMet"), false);
assert.deepEqual(errors, []);
});
test('#122 old saves keep routing as before: per-link metrics become the pair metric', () => {
const { ev, errors } = load();
setup(ev);
// Every link on avoid: the pair is on avoid.
ev("delete S.pairMet;L1.metric='avoid';L2.metric='avoid';S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev("S.pairMet['ams|fra']"), 'avoid');
assert.equal(ev("S.links.some(l=>'metric' in l)"), false);
// Mixed metrics routed at the lowest one, all links carrying: no standby, normal.
ev("S.pairMet={};S.links[0].metric='backup';S.links[1].standby='yes';S=migrate(JSON.parse(JSON.stringify(S)));compute()");
assert.equal(ev("'ams|fra' in S.pairMet"), false);
assert.equal(ev("S.links.some(l=>'standby' in l||'metric' in l)"), false);
assert.ok(ev("S.links.every(l=>R.load[l.id]>0)"));
// Junk in the new field is dropped.
ev("S.pairMet={'ams|fra':'warp','fra|lon':'avoid'};S=migrate(JSON.parse(JSON.stringify(S)))");
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pairMet)")), {});
assert.deepEqual(errors, []);
});
test('#122 traceroute shows an active link, not one on standby', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.setStandby({id:L1.id,on:1})");
assert.equal(ev("trPaths('ams').path('fra')[0].l.id===L2.id"), true);
ev("ACT.setStandby({id:L1.id,on:0});ACT.setStandby({id:L2.id,on:1})");
assert.equal(ev("trPaths('ams').path('fra')[0].l.id===L1.id"), true);
assert.deepEqual(errors, []);
});
test('#122 the standby button shows next to another link, on desktop and phone', () => {
const { ev, dom, errors } = load();
setup(ev);
for (const w of [1280, 390]) {
ev(`window.innerWidth=${w};ACT.selLink({id:L1.id});renderAll()`);
const b = dom.window.document.querySelector('[data-act="setStandby"]');
assert.ok(b, `standby button at ${w}px`);
assert.match(b.textContent, /Put this link on standby/);
}
ev("S.links=S.links.filter(l=>l!==L2);ACT.selLink({id:L1.id});renderAll()");
assert.equal(dom.window.document.querySelector('[data-act="setStandby"]'), null, 'nothing to stand by for');
ev("L1.standby=true;renderAll()");
assert.match(dom.window.document.querySelector('[data-act="setStandby"]').textContent, /Take it off standby/);
assert.deepEqual(errors, []);
});

61
tests/more-cables.test.js Normal file
View file

@ -0,0 +1,61 @@
// More real cables: the North Sea and the Baltic, the Indian Ocean and Asia-Pacific.
const test = require('node:test');
const assert = require('node:assert');
const { load } = require('./harness');
function start(ev) { ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0"); }
const lands = (ev, cid, a, b) => ev(`CABLE_PAIRS.some(p=>p.cid==='${cid}'&&[p.a,p.b].sort().join()==='${[a, b].sort().join()}')`);
test('the North Sea and the Baltic: new landings, real cables, and anchors on the Baltic ones', () => {
const { ev, errors } = load();
start(ev);
for (const c of ['krs', 'ebj', 'rix']) {
assert.ok(ev(`CABLE_PAIRS.some(p=>p.a==='${c}'||p.b==='${c}')`), `${c} has a cable`);
assert.ok(ev(`NETS.some(n=>n.price&&n.pops.includes('${c}'))`), `${c} has a transit seller`);
}
assert.ok(ev("CITY.rix.ix.length>0&&ixMembers('rix').includes('tet')"), 'Riga has its exchange');
assert.ok(lands(ev, 'havf', 'ebj', 'krs') && lands(ev, 'havf', 'nyc', 'ebj') && lands(ev, 'havsil', 'krs', 'ebj') && lands(ev, 'norfest', 'svg', 'krs'));
assert.ok(lands(ev, 'havh', 'dub', 'man') && lands(ev, 'clion', 'hel', 'ham') && lands(ev, 'e4', 'ber', 'cph') && lands(ev, 'lvse', 'rix', 'sto'));
// Tampnet: NorSea Com from Kårstø past the Draupner and Ekofisk platforms to Lowestoft, and Norfest down the coast
assert.ok(lands(ev, 'tampn', 'svg', 'lon') && lands(ev, 'norfest', 'krs', 'osl'));
// the Baltic cables are the ones the anchors find
for (const c of ['clion', 'balt', 'e4', 'elight', 'elisa', 'lvse', 'bcs']) assert.equal(ev(`CAB.${c}.anchor`), true, c);
assert.equal(ev('CAB.marea.anchor'), undefined);
// old pairs stay where they were, so saved links keep their cable
assert.equal(ev("CAB.havf.pairs.slice(0,2).map(p=>p.slice(0,2).join()).join(' ')"), 'nyc,cph dub,cph');
assert.equal(ev("CAB.clion.pairs[0].slice(0,2).join()"), 'hel,fra');
assert.deepEqual(errors, []);
});
test('the Indian Ocean and Asia-Pacific: the big real cables, Muscat, the Maldives and Fukuoka', () => {
const { ev, errors } = load();
start(ev);
for (const c of ['mct', 'mle', 'fuk']) {
assert.ok(ev(`CABLE_PAIRS.some(p=>p.a==='${c}'||p.b==='${c}')`), `${c} has a cable`);
assert.ok(ev(`NETS.some(n=>n.price&&n.pops.includes('${c}'))`), `${c} has a transit seller`);
}
assert.ok(ev("isSub('mle','cbo')&&!isSub('mct','dxb')&&!isSub('fuk','tok')"), 'the Maldives are islands, Muscat and Fukuoka are not');
for (const [cid, a, b] of [['sjc2', 'tpe', 'osa'], ['adc', 'sin', 'bkk'], ['apcn2', 'tpe', 'sha'], ['flag', 'bde', 'pmo'], ['smw5', 'khi', 'cbo'], ['unity', 'tok', 'lax'],
['tpe2', 'sea', 'sha'], ['mist', 'maa', 'kul'], ['iax', 'bom', 'mle'], ['kjcn', 'icn', 'fuk'], ['smw6', 'bom', 'mle'], ['twoaf', 'mct', 'khi'], ['ohman', 'per', 'mct'], ['bifrost', 'jkt', 'gum'], ['indigo', 'per', 'syd']]) {
assert.ok(lands(ev, cid, a, b), `${cid} ${a}-${b}`);
}
// every cable pair has a drawn route and a sane length
assert.equal(ev("CABLE_PAIRS.filter(p=>!(p.km>0&&p.km<25000)||p.pts.some(q=>!isFinite(q[0])||!isFinite(q[1]))).length"), 0);
// no route jumps across the whole map at the ±180° seam: waypoints keep continuous longitudes (#183)
assert.deepEqual(JSON.parse(ev("JSON.stringify(CABLE_PAIRS.filter(p=>p.pts.some((q,i)=>i&&Math.abs(q[0]-p.pts[i-1][0])>W/3)).map(p=>p.cid+':'+p.a+'-'+p.b))")), []);
assert.ok(ev("cablePair('fast','sea','osa').km") < 9500, 'FASTEST to Osaka crosses the Pacific, not the world');
// subsea cables stay at sea: a stretch over land with sea on both sides is the line cutting across a coast.
// Allowed: the Suez Canal and the Dardanelles (not water in the coastline), and Quintillion's overland Alaska leg.
const cross = JSON.parse(ev(`JSON.stringify((()=>{const big=COAST.filter(p=>ringArea(p)>=40).map(p=>{let a=1e9,b=-1e9,c=1e9,d=-1e9;for(const [x,y] of p){a=Math.min(a,x);b=Math.max(b,x);c=Math.min(c,y);d=Math.max(d,y);}return {p,a,b,c,d};});
const on=(x,y)=>{x=((x%W)+W)%W;return big.some(q=>x>=q.a&&x<=q.b&&y>=q.c&&y<=q.d&&inPoly(x,y,q.p));};const out=[];
for(const p of CABLE_PAIRS){if(p.cid==='qtl'&&[p.a,p.b].sort().join()==='anc,brw')continue;const s=[];
for(let i=1;i<p.pts.length;i++){const [x0,y0]=p.pts[i-1],[x1,y1]=p.pts[i];const n=Math.max(1,Math.ceil(Math.hypot(x1-x0,y1-y0)/1.5));for(let k=(i===1?0:1);k<=n;k++)s.push([x0+(x1-x0)*k/n,y0+(y1-y0)*k/n]);}
const L=s.map(q=>on(q[0],q[1]));let i=0;while(i<L.length){if(!L[i]){i++;continue;}let j=i;while(j+1<L.length&&L[j+1])j++;const km=(j-i+1)*p.km/s.length;if(i>0&&j<L.length-1&&km>160)out.push(p.cid+':'+p.a+'-'+p.b+' '+Math.round(km)+' km');i=j+1;}}
return out;})())`));
assert.deepEqual(cross, [], 'cables cutting across land');
// a hop on one of the new cables carries traffic
ev("for(const c of ['sin','hkg']){ACT.buildPop({city:c});S.pops[c].rgen=3;}UI.via='sjc2';UI.route='same';openLinkModal('sin','hkg');ACT.buildLink({tier:2});closeModal();compute()");
assert.ok(ev("S.links.some(l=>l.cable==='sjc2')"), 'a wave on SJC2');
ev('cam.z=0.5;draw(0);cam.z=4;cam.x=CITY.mle.x;cam.y=CITY.mle.y;draw(0)');
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,38 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('#186 a new network starts at half speed, even after a game at 8×', () => {
const { ev, dom, errors } = load();
ev("ACT.start({});ACT.speed({v:8})");
assert.equal(ev('UI.speed'), 8);
ev("ACT.newgame();ACT.start({})");
assert.equal(ev('UI.speed'), 0.5, 'normal game');
assert.ok(dom.window.document.getElementById('sp0.5').classList.contains('on'), 'the HUD shows ½×');
ev("ACT.speed({v:0});ACT.newgame();UI.mode='sandbox';ACT.start({})");
assert.equal(ev('UI.speed'), 0.5, 'sandbox, and a paused game does not stay paused');
ev("ACT.speed({v:4});ACT.startScn({id:SCN[0].id,sure:1})");
assert.equal(ev('UI.speed'), 0.5, 'scenario');
ev("ACT.speed({v:2});ACT.startWeekly({sure:1})");
assert.equal(ev('UI.speed'), 0.5, 'weekly challenge');
assert.deepEqual(errors, []);
});
test('#186 on a phone, play after pause resumes at half speed, not the old game\'s speed', () => {
const { ev, errors } = load();
ev("window.innerWidth=360;ACT.start({});ACT.phoneSpeed();ACT.phoneSpeed();ACT.phoneSpeed()");
assert.notEqual(ev('UI.lastSpeed'), 0.5);
ev("ACT.newgame();ACT.start({});if(UI.pendGame)ACT.pitchSkip();ACT.phonePlay();ACT.phonePlay()");
assert.ok(ev("UI.started&&!UI.pendGame"), "the new game is running");
assert.equal(ev('UI.speed'), 0.5);
assert.deepEqual(errors, []);
});
test('#186 a saved game still continues at the speed it was saved at', () => {
const a = load();
a.ev("ACT.start({});ACT.speed({v:4});save(true)");
const b = load({ storage: { 'sot-save-v1': a.ev("localStorage.getItem('sot-save-v1')") } });
assert.equal(b.ev('UI.speed'), 4);
assert.deepEqual(a.errors, []);
assert.deepEqual(b.errors, []);
});

View file

@ -358,7 +358,9 @@ test('Sparkly Seabone is a Tier 1 now, but old saves keep the five they played f
ev("ACT.start({})");
assert.equal(ev("NET.skl.type"), 't1');
assert.ok(ev("NET.skl.pops.includes('nyc')&&NET.skl.pops.includes('sao')&&NET.skl.pops.includes('pmo')"));
assert.equal(ev("t1Need().length"), 6, 'new games need all six');
assert.equal(ev("t1Need().length"), 7, 'new games need all seven, AT&Tease included (#155)');
ev("S.t1v=2");
assert.equal(ev("t1Need().length"), 6, 'saves from before AT&Tease keep six');
ev("delete S.t1v");
assert.equal(ev("t1Need().length"), 5, 'older saves keep five');
assert.deepEqual(errors, []);
@ -784,8 +786,9 @@ test('Atlantic islands and Halifax: real landings, real exchanges only, and isla
assert.equal(hop(['mia', 'pdl', 'lis']), 1600, 'Florida to Lisbon via the Azores');
assert.equal(direct('atn', 'lis'), 1200);
assert.equal(hop(['atn', 'bda', 'lis']), 1600);
assert.equal(direct('lis', 'lag'), 1200);
// Equi-yes follows the coast close enough to fit 1.6T on its own; the Canaries hop matches it
assert.equal(hop(['lis', 'tci', 'lag']), 1600, 'Lisbon to Lagos via the Canaries');
assert.ok(hop(['lis', 'tci', 'lag']) >= direct('lis', 'lag'));
assert.equal(direct('for', 'mad'), 1200);
assert.equal(hop(['for', 'rai', 'lis']), 1600, 'Brazil to Europe via Cape Verde');
assert.equal(hop(['nyc', 'hfx']), 3200);

29
tests/report-link.test.js Normal file
View file

@ -0,0 +1,29 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const ISSUES = 'https://github.com/fjaeckel/seriesoftubes/issues/new/choose';
test('bugs and ideas point to GitHub from the menu and How to play, and the chat no longer asks for bug reports', () => {
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
const { ev, errors } = load(lang === 'en' ? {} : { lang });
ev('ACT.start({})');
for (const [where, setup] of [['menu', 'ACT.menu()'], ['help', 'showHelp()']]) {
const cards = JSON.parse(ev(`(()=>{${setup};return JSON.stringify([...document.querySelectorAll('#modal a[href="${ISSUES}"]')].map(a=>[a.target,a.rel,a.textContent.trim()]));})()`));
assert.equal(cards.length, 1, `${lang}: one GitHub card in ${where}`);
assert.deepEqual(cards[0].slice(0, 2), ['_blank', 'noopener'], `${lang}: opens in a new tab`);
if (lang !== 'en') assert.doesNotMatch(cards[0][2], /Found a bug/, `${lang}: translated`);
const chat = ev(`[...document.querySelectorAll('#modal a.chat')].map(a=>a.textContent).join(' ')`);
assert.doesNotMatch(chat, /report bugs|segnala bug|reporte bugs|signale des bugs|informa de fallos/, `${lang}: the chat card is for chatting`);
}
assert.deepEqual(errors, []);
}
});
test('the GitHub card fits a phone', () => {
const { ev, errors } = load();
ev("ACT.start({});window.innerWidth=360;ACT.menu()");
assert.ok(ev('isPhone()'));
assert.ok(ev(`!!document.querySelector('#modal a.plug[href="${ISSUES}"] .go')`), 'same card layout as the chat card');
assert.deepEqual(errors, []);
});

123
tests/save-size.test.js Normal file
View file

@ -0,0 +1,123 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// 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;
P.setItem=function(k,v){if(k==='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', () => {
const { ev, dom, errors } = load();
ev("ACT.start({});UI.saveFail=null;" + refuse('QuotaExceededError'));
ev('save()');
const toasts = () => [...dom.window.document.querySelectorAll('.toast')].filter(t => /not being saved/.test(t.textContent));
assert.equal(toasts().length, 1, 'one warning');
assert.match(toasts()[0].textContent, /too big for this browser/);
assert.ok(toasts()[0].querySelector('[data-act=exportSave]'), 'with an Export button');
ev('UI.saveFail.at-=1e6;save();save(true)');
assert.equal(toasts().length, 1, 'not again for every retry');
ev('ACT.menu()');
const card = ev("document.getElementById('modalCard').innerHTML");
assert.match(card, /not being saved/);
assert.doesNotMatch(card, /saves itself every few seconds/, 'the menu no longer claims it saves');
// Once a save works again, the menu goes back to normal.
ev("__err=null;save(true);ACT.menu()");
assert.equal(ev('saveFailing()'), false);
assert.match(ev("document.getElementById('modalCard').innerHTML"), /saves itself every few seconds/);
assert.deepEqual(errors, []);
});
test('#176 storage that is blocked altogether gets its own advice', () => {
const { ev, dom, errors } = load();
ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';save()');
assert.match(dom.window.document.body.textContent, /private window/);
assert.deepEqual(errors, []);
});
// A network with plenty of alien waves and ordinary customers, the shape of big late-game saves.
const bigBiz = "ACT.start({});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});" +
"S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',own:true,km:450,sys:'roadm',ch:[],ready:0,mo:500,day:0,cut:0});" +
"for(let i=0;i<300;i++){const slots=1+i%4;S.biz.push({id:'w'+i,city:'fra',city2:'ams',reqs:[],latMax:null,route:'normal',name:'Carrier '+i,type:'wwave',bw:1,rate:4000,mood:100-i%9*1.37,since:i,sites:null,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots),pm:i%2?100:99,warned:i%5===0,warn60:false});}" +
"S.biz.push({id:'l2',city:'fra',city2:'ams',reqs:['diverse'],latMax:3.2,route:'fast',name:'Fast Co',type:'hft',bw:5,rate:900,mood:80,since:0,sites:null,slots:0,pm:81,warned:false,warn60:true});" +
"S.biz.push({id:'d1',city:'fra',city2:null,reqs:[],latMax:null,route:'normal',name:'Plain Co',type:'dia',bw:5,rate:600,mood:100,since:0,sites:null,slots:0});compute()";
const sorted = "JSON.stringify(S.biz.map(b=>Object.keys(b).sort().map(k=>[k,b[k]])))";
test('#176 saves leave customer defaults out, and loading puts them back exactly', () => {
const { ev, errors } = load();
ev(bigBiz);
const full = ev('JSON.stringify(S).length'), packed = ev('JSON.stringify(packSave(S)).length');
assert.ok(packed < full * 0.75, `the save is much smaller (${packed} vs ${full})`);
const before = ev(sorted);
ev("save(true);S=migrate(loadSave());compute()");
const after = JSON.parse(ev(sorted)), want = JSON.parse(before);
// Customers that never got warnings or a previous mood come back with the defaults; everything else is identical.
const norm = list => list.map(b => Object.fromEntries(b)).map(b => ({ pm: b.mood, warned: false, warn60: false, ...b }));
assert.deepEqual(norm(after), norm(want));
assert.equal(ev("S.biz.find(b=>b.id==='l2').route"), 'fast', 'a chosen route is kept');
assert.equal(ev("S.biz.find(b=>b.id==='w7').what"), ev("wwWhat(S.links.find(l=>l.id==='df1'),4)"), 'alien waves get their description back');
assert.match(ev("localStorage.getItem('sot-save-v1')"), /"Carrier 1"/);
assert.doesNotMatch(ev("localStorage.getItem('sot-save-v1')"), /alien wave on your/, 'descriptions are not stored');
assert.deepEqual(errors, []);
});
test('#176 an older, unpacked save still loads the same', () => {
const { ev, errors } = load();
ev(bigBiz);
const before = ev(sorted);
ev("S=migrate(JSON.parse(JSON.stringify(S)));compute()");
const norm = list => list.map(b => Object.fromEntries(b)).map(b => ({ pm: b.mood, warned: false, warn60: false, ...b }));
assert.deepEqual(norm(JSON.parse(ev(sorted))), norm(JSON.parse(before)));
assert.deepEqual(errors, []);
});
// Compressing runs in the background: wait for it, without depending on how long it takes.
const settle = async (ev, cond) => { for (let i = 0; i < 400 && !ev(cond); i++) await new Promise(r => setTimeout(r, 5)); assert.ok(ev(cond), cond); };
const huge = "for(let i=0;i<12000;i++){const slots=1+i%4;S.biz.push({id:'h'+i,city:'fra',city2:'ams',name:'Huge Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()";
test('#176 small saves stay plain JSON, written at once', () => {
const { ev, errors } = load({ gzip: true });
ev("ACT.start({});save(true)");
assert.equal(ev("localStorage.getItem('sot-save-v1')[0]"), '{');
assert.deepEqual(errors, []);
});
test('#176 a huge save is gzipped into storage and the next visit loads it', async () => {
const a = load({ gzip: true });
a.ev(bigBiz + ';' + huge);
assert.ok(a.ev('JSON.stringify(packSave(S)).length') >= a.ev('GZ_MIN'), 'big enough to compress');
a.ev('save(true)');
await settle(a.ev, "(localStorage.getItem('sot-save-v1')||'').startsWith(GZ)");
const raw = a.ev("localStorage.getItem('sot-save-v1')"), full = a.ev('JSON.stringify(packSave(S)).length');
assert.ok(raw.length < full / 4, `much smaller in storage (${raw.length} vs ${full})`);
const before = a.ev("JSON.stringify([S.name,S.day,S.biz.length,S.biz.find(b=>b.id==='h77').what])");
// The next visit: the page unpacks it before booting and continues the same network.
const b = load({ gzip: true, storage: { 'sot-save-v1': raw } });
await settle(b.ev, 'UI.started===true');
assert.equal(b.ev("JSON.stringify([S.name,S.day,S.biz.length,S.biz.find(b=>b.id==='h77').what])"), before);
assert.deepEqual(a.errors, []);
assert.deepEqual(b.errors, []);
});
test('#176 a newer save is never overwritten by an older one still compressing', async () => {
const { ev, errors } = load({ gzip: true });
ev(bigBiz + ';' + huge);
ev("save(true);S.name='Newer';save(true);S.name='Newest';save(true)");
await settle(ev, "!UI.gzBusy&&(localStorage.getItem('sot-save-v1')||'').startsWith(GZ)");
ev("gunzip(localStorage.getItem('sot-save-v1')).then(t=>window.__t=JSON.parse(t).name)");
await settle(ev, "!!window.__t");
assert.equal(ev('__t'), 'Newest');
// A new game started while a big save compresses: the old network does not come back.
ev("save(true);ACT.newgame();ACT.start({});window.__new=S.name");
await settle(ev, '!UI.gzBusy');
assert.equal(ev("JSON.parse(localStorage.getItem('sot-save-v1')).name"), ev('__new'), 'the new game stays saved');
assert.deepEqual(errors, []);
});
test('#176 a damaged compressed save is kept aside and the player is told', async () => {
const { ev, dom, errors } = load({ gzip: true, storage: { 'sot-save-v1': 'gz:bm90IGd6aXA=' } });
await settle(ev, "localStorage.getItem('sot-save-broken')!==null");
assert.match(dom.window.document.body.textContent, /could not be/);
assert.equal(ev("localStorage.getItem('sot-save-broken')"), 'gz:bm90IGd6aXA=');
assert.equal(ev("localStorage.getItem('sot-save-v1')"), null);
assert.deepEqual(errors, []);
});