'use strict'; /* Client side of the end game and trade: pure helpers (endcore.js), the send-dialog options for landing sites and transports (milcore.js), * string coverage of the new screens, and no HTML injection sinks. Browser behaviour was looked at in headless Chromium, not here. */ const test = require('node:test'); const assert = require('node:assert'); const fs = require('fs'); const path = require('path'); const I = require('../public/js/i18n.js'); const D = require('../public/js/data.js'); const E = require('../public/js/endcore.js'); const M = require('../public/js/milcore.js'); for (const f of fs.readdirSync(path.join(__dirname, '..', 'public', 'js', 'strings')).sort()) if (f.endsWith('.js')) require('../public/js/strings/' + f); const ROOT = path.join(__dirname, '..', 'public', 'js'); const site = (o) => Object.assign({ id: 1, index: 0, x: 1, y: 2, holder: null, takenBy: null, takenAt: null, level: 0, maxLevel: 100, progress: 0, pool: { fiber: 0, hardware: 0, capital: 0 }, build: null, next: { toLevel: 1, cost: { fiber: 100, hardware: 100, capital: 100 }, durationMs: 1000 } }, o || {}); const holder = (id, tag) => ({ allianceId: id, tag, name: 'Alliance ' + tag }); test('leading: highest node level, then more sites, then the earlier takeover', () => { assert.strictEqual(E.leading([]), null); assert.strictEqual(E.leading([site(), site({ index: 1 })]), null, 'nobody holds a site'); const a = site({ index: 0, holder: holder(1, 'AAA'), level: 10, takenAt: 500 }); const b = site({ index: 1, holder: holder(2, 'BBB'), level: 12, takenAt: 900 }); assert.strictEqual(E.leading([a, b]).tag, 'BBB'); assert.strictEqual(E.leading([a, b]).siteIndex, 1); const a2 = site({ index: 2, holder: holder(1, 'AAA'), level: 12, takenAt: 700 }); assert.strictEqual(E.leading([a, b, a2]).tag, 'AAA', 'same level: two sites beat one'); assert.strictEqual(E.leading([a, b, a2]).sites, 2); const c = site({ index: 3, holder: holder(3, 'CCC'), level: 12, takenAt: 100 }); assert.strictEqual(E.leading([b, c]).tag, 'CCC', 'same level and sites: the earlier takeover'); }); test('buildProgress, missing and holderKind', () => { assert.strictEqual(E.buildProgress(site(), 5), null); const s = site({ build: { toLevel: 2, startedAt: 1000, dueAt: 3000 } }); assert.strictEqual(E.buildProgress(s, 2000), 0.5); assert.strictEqual(E.buildProgress(s, 9000), 1); assert.strictEqual(E.buildProgress(s, 0), 0); assert.deepStrictEqual(E.missing({ fiber: 100, hardware: 50, capital: 0 }, { fiber: 40, hardware: 50, capital: 9 }), { fiber: 60 }); assert.deepStrictEqual(E.missing({ fiber: 1 }, null), { fiber: 1 }); assert.strictEqual(E.holderKind(site(), 5), 'incumbent'); assert.strictEqual(E.holderKind(site({ holder: holder(5, 'X') }), 5), 'mine'); assert.strictEqual(E.holderKind(site({ holder: holder(6, 'Y') }), 5), 'rival'); assert.strictEqual(E.holderKind(site({ holder: holder(5, 'X') }), null), 'rival'); }); test('buildCheck explains why the node cannot be built, in the order the server checks it', () => { const rich = { fiber: 1e6, hardware: 1e6, capital: 1e6 }; const ok = site({ pool: rich }); const you = { holder: true, canBuild: true, canShip: true, canAttack: false }; assert.deepStrictEqual(E.buildCheck(ok, you, false), { ok: true, reason: null }); assert.strictEqual(E.buildCheck(ok, you, true).reason, 'ended'); assert.strictEqual(E.buildCheck(ok, { holder: true, canBuild: false }, false).reason, 'forbidden'); assert.strictEqual(E.buildCheck(ok, { holder: false, canBuild: false }, false).reason, 'forbidden'); assert.strictEqual(E.buildCheck(site({ pool: rich, next: null, level: 100 }), you, false).reason, 'max_level'); assert.strictEqual(E.buildCheck(site({ pool: rich, build: { toLevel: 2, startedAt: 0, dueAt: 9 } }), you, false).reason, 'already_queued'); assert.strictEqual(E.buildCheck(site(), you, false).reason, 'not_enough_resources'); }); test('phaseNow flips to backbone_open at opensAt even before the status is refetched; ended wins', () => { const st = { phase: 'running', opensAt: 1000, ageDays: 40, openDay: 100 }; assert.strictEqual(E.phaseNow(st, 999), 'running'); assert.strictEqual(E.phaseNow(st, 1000), 'backbone_open'); assert.strictEqual(E.phaseNow({ phase: 'ended', opensAt: 1 }, 0), 'ended'); assert.strictEqual(E.phaseNow(null, 0), 'running'); assert.strictEqual(E.openProgress(st), 0.4); assert.strictEqual(E.openProgress({ ageDays: 500, openDay: 100 }), 1); assert.strictEqual(E.sumCargo({ fiber: 3, capital: 4 }), 7); assert.strictEqual(E.topRows([1, 2, 3], 2).length, 2); }); test('moveOptions on a landing site: scan, attack (needs an alliance, not your own site)', () => { const tile = (b) => ({ type: 'backbone', backbone: Object.assign({ siteId: 1, index: 0, mine: false, canAttack: true }, b) }); const home = { port_scanner: 2, script_crew: 10 }; const types = (o) => o.map((x) => x.type + (x.ok ? '' : '!')); assert.deepStrictEqual(types(M.moveOptions({ tile: tile(), home, allianceId: 5 })), ['scan', 'attack']); const noAll = M.moveOptions({ tile: tile(), home, allianceId: null }); assert.deepStrictEqual(types(noAll), ['scan', 'attack!']); assert.strictEqual(noAll[1].reason, 'no_alliance'); const own = M.moveOptions({ tile: tile({ mine: true }), home, allianceId: 5 }); assert.strictEqual(own[1].reason, 'own_site'); assert.deepStrictEqual(types(M.moveOptions({ tile: tile(), home: {}, allianceId: 5 })), ['scan!', 'attack!']); assert.ok(!M.moveOptions({ tile: tile(), home, allianceId: 5 }).some((o) => ['raid', 'takeover', 'settle', 'reinforce', 'transport'].includes(o.type))); }); test('moveOptions transportOnly: any POP takes a transport (a rival\'s too), nothing else is offered, links decide ok', () => { const rival = { type: 'pop', town: { id: 9, mine: false, owner: { id: 2, protected: true } } }; const mine = { type: 'pop', town: { id: 3, mine: true, owner: { id: 1 } } }; const home = { script_crew: 10, port_scanner: 3 }; const o = M.moveOptions({ tile: rival, home, transport: { links: 2, active: 1 }, transportOnly: true }); assert.deepStrictEqual(o, [{ type: 'transport', ok: true, reason: null }]); assert.strictEqual(M.moveOptions({ tile: rival, home, transport: { links: 2, active: 2 }, transportOnly: true })[0].reason, 'links_busy'); assert.strictEqual(M.moveOptions({ tile: mine, home, transport: { links: 0, active: 0 }, transportOnly: true })[0].reason, 'no_link'); assert.deepStrictEqual(M.moveOptions({ tile: { type: 'land', settle: { possible: true } }, home, transportOnly: true }), [], 'empty land takes no transport'); // without the flag a rival POP still gets the hostile types only assert.ok(!M.moveOptions({ tile: rival, home, transport: { links: 2, active: 0 } }).some((x) => x.type === 'transport')); }); // ------------------------------------------------------------------ strings of the new screens const files = ['screens/trade.js', 'screens/world.js', 'screens/cargo-ui.js', 'screens/reports.js', 'screens/map.js', 'screens/send.js', 'screens/movements.js', 'alertkinds.js']; const SRC = files.map((f) => fs.readFileSync(path.join(ROOT, f), 'utf8')).join('\n'); test('every static string key the trade / world / report / map / send screens use exists in en and nb', () => { const used = new Set(); for (const m of SRC.matchAll(/\b(?:App\.)?t\('([a-zA-Z0-9_.]+)'/g)) if (!m[1].endsWith('.')) used.add(m[1]); for (const m of SRC.matchAll(/\bt\([^()']*\? '([a-z0-9_]+\.[a-zA-Z0-9_.]+)' : '([a-z0-9_]+\.[a-zA-Z0-9_.]+)'/g)) { used.add(m[1]); used.add(m[2]); } assert.ok(used.size > 150, 'found the keys (' + used.size + ')'); const missing = []; for (const l of I.LANGS) for (const k of used) if (!I.strings[l][k]) missing.push(l + ' ' + k); assert.deepStrictEqual(missing, []); }); test('dynamic string keys: tabs, statuses, roles, validation codes, ranking tabs, build refusals, send reasons', () => { const want = ['trd.tab.offers', 'trd.tab.new', 'trd.tab.mine', 'trd.tab.send', 'trd.role.poster', 'trd.role.acceptor', 'wld.rank.operators', 'wld.rank.alliances', 'wld.rank.attackers', 'wld.rank.defenders', 'wld.build.why.ended', 'wld.build.why.forbidden', 'send.reason.no_alliance', 'send.reason.own_site', 'send.invalid.no_alliance', 'send.invalid.own_site', 'send.invalid.landing_scan_or_attack_only', 'tile.backbone', 'report.type.landing', 'rep.attackerWon', 'rep.defenderWon', 'rep.tab.mine', 'rep.tab.alliance', 'rep.folder.empty', 'rep.share.done', 'rep.share.already', 'nav.trade', 'nav.world', 'screen.trade', 'screen.world'] .concat(['all', 'open', 'accepted', 'completed', 'cancelled', 'expired', 'void'].map((s) => 'trd.status.' + s)) .concat(['giveRes', 'wantRes', 'giveAmount', 'wantAmount', 'maxDistance', 'terms'].map((s) => 'trd.v.' + s)); for (const l of I.LANGS) for (const k of want) assert.ok(I.strings[l][k], l + ' ' + k); // trade_terms paths the rules can report all have a message const R = require('../public/js/rules.js'); for (const bad of [{ giveRes: 'x' }, { wantRes: 'x' }, { wantRes: 'fiber' }, { giveAmount: 0 }, { wantAmount: 0 }, { maxDistance: 0 }]) { const r = R.tradeTermsCheck(Object.assign({ giveRes: 'fiber', giveAmount: 100, wantRes: 'hardware', wantAmount: 100, maxDistance: 30 }, bad)); assert.ok(!r.ok); assert.ok(I.strings.en['trd.v.' + r.errors[0].path], 'message for ' + r.errors[0].path); } }); test('the new screens put no player-controlled text through HTML sinks', () => { const code = SRC.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, ''); assert.ok(!/innerHTML|insertAdjacentHTML|outerHTML|document\.write/.test(code), 'no HTML injection sinks'); }); test('every screen file of the new screens is loaded by index.html, strings before screens', () => { const html = fs.readFileSync(path.join(__dirname, '..', 'public', 'index.html'), 'utf8'); const order = (f) => html.indexOf('js/' + f + '"'); for (const f of ['strings/alerts.js', 'strings/trade.js', 'strings/world.js', 'endcore.js', 'alertkinds.js', 'screens/cargo-ui.js', 'screens/trade.js', 'screens/world.js']) assert.ok(order(f) > 0, f + ' is in index.html'); assert.ok(order('strings/world.js') < order('main.js'), 'strings before the shell'); assert.ok(order('endcore.js') < order('screens/world.js')); assert.ok(order('milstate.js') < order('alertkinds.js') && order('main.js') < order('alertkinds.js'), 'alert kinds need App and App.mil'); assert.ok(order('screens/cargo-ui.js') < order('screens/trade.js') && order('screens/cargo-ui.js') < order('screens/world.js')); }); test('icons used by the new screens exist in the sprite', () => { const sprite = fs.readFileSync(path.join(__dirname, '..', 'public', 'icons', 'sprite.svg'), 'utf8'); const have = new Set((sprite.match(/id="i-([a-z_-]+)"/g) || []).map((s) => s.slice(6, -1))); const used = new Set(); for (const f of ['screens/trade.js', 'screens/world.js']) for (const m of fs.readFileSync(path.join(ROOT, f), 'utf8').matchAll(/\bicon\('([a-z_-]+)'/g)) used.add(m[1]); used.delete('b-'); // icon('b-' + building): the building icons used.add('b-' + D.TRANSPORT.building); for (const i of used) assert.ok(have.has(i), 'icon ' + i); }); test('every browser script under public/js parses (a syntax error in one file kills every screen after it)', () => { const vm = require('vm'); const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : e.name.endsWith('.js') ? [path.join(dir, e.name)] : [])); const files = walk(ROOT); assert.ok(files.length > 30, 'found the scripts (' + files.length + ')'); for (const f of files) assert.doesNotThrow(() => new vm.Script(fs.readFileSync(f, 'utf8'), { filename: f }), f); });