Server-run play, part 1: game prerequisites and shared contracts
Groundwork for running multiplayer games on the session server; nothing
of it is switched on yet, and the plain build is unchanged.
- A new network in two halves (beginState/beginShow), the coach split into
tutAdvance/coachDom, toastPop split out of toast, bootNotes() for the
once-per-load toasts, the five text actions take their text as an
argument, and srvOn() with its two checks in the loop.
- Live state is what a reload makes of it (migrate() is a no-op on it):
new POPs, ports, PNIs, customers, attacks, dark fiber and the intern's
notes are written in their saved shape; a 365-day test proves it.
- pniAll and bstdApply check the quote the sheet showed (bstdApply by its
plan, within 1% for the daily hardware drift; utilityKit too).
- assemble({mp}) leaves src/game/98-server-play/ and its CSS out of every
page but a multiplayer build's, which also gets a SIM_ID build id.
- Contracts for the server, protocol and browser parts: the action tables
and envelope check (scripts/lib/mp-sim-acts.js), event fixtures, a shape
checker, a fake engine, and load({mp:true}) in the test harness.
- route-fuzz judges both pages with one migrate(), so reload repairs of
the base no longer count as divergences.
This commit is contained in:
parent
e25f843526
commit
d1e127da67
60 changed files with 2200 additions and 105 deletions
|
|
@ -100,7 +100,8 @@
|
|||
if (k === 'fail') { S.nextFail = S.day + 1; return ''; }
|
||||
if (k === 'event') { S.nextEvent = S.day + 1; return ''; }
|
||||
if (k === 'cash') { S.cash += a; after(); return ''; }
|
||||
if (k === 'lvl') { S.lvl = Math.min(LEVELS.length, (S.lvl || 0) + 1); after(); return ''; }
|
||||
// One level up from the level the game reads (lvl(): S.lvl, or 1 when a page never wrote it down).
|
||||
if (k === 'lvl') { S.lvl = Math.min(LEVELS.length, (S.lvl || 1) + 1); after(); return ''; }
|
||||
// Events that move routes, as the game's own events set them.
|
||||
if (k === 'ev') {
|
||||
const n = NETS[a % NETS.length].id;
|
||||
|
|
@ -148,28 +149,49 @@
|
|||
|
||||
// ---------- digests ----------
|
||||
// Everything routing produced: R in full (with every link's R.ef), the flows (R.fl), and what the PNI lists read.
|
||||
// An attack's record names its attack by id (as rwPack does): the attack itself is game state, compared with S.
|
||||
const rj = (v) => JSON.stringify(v, (k, x) => (k === 'attack' && x && typeof x === 'object' ? x.id : x));
|
||||
const routing = () => {
|
||||
if (!R) return 'noR';
|
||||
const r = JSON.stringify(R), fl = R.fl ? JSON.stringify(R.fl) : '';
|
||||
const r = rj(R), fl = R.fl ? JSON.stringify(R.fl) : '';
|
||||
let pf = '';
|
||||
if (typeof pniFlows === 'function' && S && !pzOn()) for (const c of Object.keys(S.pops).slice(0, 4)) try { pf += c + JSON.stringify(pniFlows(c)); } catch (e) { pf += c + 'E' + e.message; }
|
||||
return r + '\n' + fl + '\n' + pf;
|
||||
};
|
||||
const parts = () => { const o = {}; if (!R) return o; for (const k of Object.keys(R)) o[k] = JSON.stringify(R[k]); o.fl = R.fl ? JSON.stringify(R.fl) : ''; return o; };
|
||||
const parts = () => { const o = {}; if (!R) return o; for (const k of Object.keys(R)) o[k] = rj(R[k]); o.fl = R.fl ? JSON.stringify(R.fl) : ''; return o; };
|
||||
// A field only this checkout's game has (a new feature's state, on S or on its customers and offers) cannot match main
|
||||
// yet: the driver passes those (drop) and they are left out; every field both games have must still match.
|
||||
// The intern's state two levels deep (ops.on.sales, ops.wk.rev): a standing order one game has and the other retired.
|
||||
const opsPaths = () => { const O = S.ops, out = []; if (!O || typeof O !== 'object') return out;
|
||||
// Compared as a reload makes it (migrate(), keys in order): the same game, whichever way each version writes the
|
||||
// fields it fills in anyway (main may create a record without the defaults a reload gives it, in another order).
|
||||
// One reload judges both: the driver passes the base page's live state (sLive) through this checkout's migrate()
|
||||
// (sDigest(drop, json)), so a repair only one version's reload makes (main's re-aimed an attack whose customer left
|
||||
// during the day) is no divergence. That reload runs with this page's own S in scope (sanitize reads S.rules through
|
||||
// rule()): pages in lockstep have the same, and a difference in the rules shows up in the fields they decide. A POP without a router model plays the basic one (RG[p.rgen||0]): that is written
|
||||
// down first, so the reload does not guess one from its ports (a free upgrade a page from before canonical state got).
|
||||
// Puzzles are never saved: as they are. The rules stay as they are too: both pages may have set them alike (noIp4),
|
||||
// and a base that does not know a rule would drop it on the way.
|
||||
const sortK = (v) => (Array.isArray(v) ? v.map(sortK) : v && typeof v === 'object' ? Object.keys(v).sort().reduce((o, k) => ((o[k] = sortK(v[k])), o), {}) : v);
|
||||
const sLive = () => JSON.stringify(S === undefined ? null : S);
|
||||
const sOf = (json) => { const live = JSON.parse(json); if (!live || !S || pzOn() || live.mode === 'puzzle') return live; const u0 = uidN, r0 = S.rng;
|
||||
try {
|
||||
for (const c of Object.keys(live.pops || {})) if (live.pops[c] && live.pops[c].rgen === undefined) live.pops[c].rgen = 0;
|
||||
const rules = live.rules === undefined ? undefined : JSON.parse(JSON.stringify(live.rules));
|
||||
const s = migrate(live); s.rules = rules; return sortK(s);
|
||||
} finally { uidN = u0; S.rng = r0; } };
|
||||
const sNow = () => sOf(sLive());
|
||||
const opsPaths = (s = sNow()) => { const O = s.ops, out = []; if (!O || typeof O !== 'object') return out;
|
||||
for (const k of Object.keys(O)) { out.push(k); const v = O[k]; if (v && typeof v === 'object' && !Array.isArray(v)) for (const j of Object.keys(v)) out.push(k + '.' + j); } return out; };
|
||||
const sKeys = () => ({ top: Object.keys(S), items: [...new Set([...(S.biz || []), ...(S.offers || [])].flatMap((x) => Object.keys(x)))], ops: opsPaths(), orders: typeof OPSK === 'object' ? Object.keys(OPSK) : [] });
|
||||
const opsDrop = (ops) => { const o = {}; for (const k of Object.keys(S.ops)) { if (ops.includes(k)) continue; const v = S.ops[k];
|
||||
const sKeys = () => { const s = sNow(); return { top: Object.keys(s), items: [...new Set([...(s.biz || []), ...(s.offers || [])].flatMap((x) => Object.keys(x)))], ops: opsPaths(s), orders: typeof OPSK === 'object' ? Object.keys(OPSK) : [] }; };
|
||||
const opsDrop = (s, ops) => { const o = {}; for (const k of Object.keys(s.ops)) { if (ops.includes(k)) continue; const v = s.ops[k];
|
||||
if (v && typeof v === 'object' && !Array.isArray(v)) { const w = {}; for (const j of Object.keys(v)) if (!ops.includes(k + '.' + j)) w[j] = v[j]; o[k] = w; } else o[k] = v; } return o; };
|
||||
const sDrop = (drop) => { if (!drop || (!drop.top.length && !drop.items.length && !(drop.ops || []).length)) return S; const o = {};
|
||||
for (const k of Object.keys(S)) if (!drop.top.includes(k)) o[k] = k === 'ops' && S.ops && (drop.ops || []).length ? opsDrop(drop.ops) : S[k];
|
||||
// json: a live state to judge (the other page's, from sLive); without it, this page's own.
|
||||
const sDrop = (drop, json) => { const s = json === undefined ? sNow() : sOf(json); if (!s || typeof s !== 'object' || !drop || (!drop.top.length && !drop.items.length && !(drop.ops || []).length)) return s; const o = {};
|
||||
for (const k of Object.keys(s)) if (!drop.top.includes(k)) o[k] = k === 'ops' && s.ops && (drop.ops || []).length ? opsDrop(s, drop.ops) : s[k];
|
||||
for (const k of ['biz', 'offers']) if (Array.isArray(o[k])) o[k] = o[k].map((x) => { const y = {}; for (const f of Object.keys(x)) if (!drop.items.includes(f)) y[f] = x[f]; return y; });
|
||||
return o; };
|
||||
const sDigest = (drop) => JSON.stringify(sDrop(drop));
|
||||
const sParts = (drop) => { const s = sDrop(drop), o = {}; for (const k of Object.keys(s)) o[k] = JSON.stringify(s[k]); return o; };
|
||||
const sDigest = (drop, json) => JSON.stringify(sDrop(drop, json));
|
||||
const sParts = (drop, json) => { const s = sDrop(drop, json), o = {}; if (s && typeof s === 'object') for (const k of Object.keys(s)) o[k] = JSON.stringify(s[k]); return o; };
|
||||
/* After a move: what the move routed (a), routing again from the same state (b: on this checkout's page the kept
|
||||
tables are used), and routing from that state with the cache off (c: RC.on=false where there is an RC). b and c
|
||||
route from the same previous R; c's R is kept, as a plain compute would. */
|
||||
|
|
@ -188,5 +210,5 @@
|
|||
// Scarce IPv4 off (#150, rule ip4), the same rules object with its keys in the same order on both pages: the driver calls
|
||||
// it only while the base has no such rule, so the pages play the same game until it lands.
|
||||
const noIp4 = () => { if (S && S.rules) { const { ip4, mods, ...r } = S.rules; S.rules = { ...r, ip4: false, mods }; } };
|
||||
window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen, noIp4 };
|
||||
window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sLive, sDigest, sParts, check, errs, modalOpen, noIp4 };
|
||||
})();
|
||||
|
|
|
|||
579
scripts/lib/mp-sim-acts.js
Normal file
579
scripts/lib/mp-sim-acts.js
Normal file
|
|
@ -0,0 +1,579 @@
|
|||
// What a page of a server-run network may ask the session server to do, as plain data, and the envelope check every
|
||||
// request body passes before anything reaches a game (docs: the server-sim design, sections 5.8-5.9 and 10).
|
||||
// Shared by the realm (scripts/lib/mp-sim-realm.js), the host (scripts/lib/mp-sim.js) and the page's own copies
|
||||
// (src/game/98-server-play/40-acts.js), which tests hold equal to these tables. Plain data only: no game code here,
|
||||
// and nothing here is ever evaluated.
|
||||
//
|
||||
// Every ACT is in exactly one of SEND, ASK, VOTE, LOCAL or PUZZLE (tests/mp-sim-contract.test.js names the act and this
|
||||
// file when one is not). SEND is the agent's API_CMD minus the pz* acts and teCheck, traceRun, closeModal, plus
|
||||
// connCancel, pieRename and tutSkip: a test derives it again, so nobody counts it by hand.
|
||||
'use strict';
|
||||
|
||||
// Acts that change the game: the page sends them, the server runs them as a click (ACT[act](args)).
|
||||
const SEND = [
|
||||
'accept',
|
||||
'ad',
|
||||
'addCh',
|
||||
'addGen',
|
||||
'addPair',
|
||||
'addRouter',
|
||||
'addSite',
|
||||
'applyCn',
|
||||
'bstdApply',
|
||||
'bstdSet',
|
||||
'buildLink',
|
||||
'buildPop',
|
||||
'buildScrub',
|
||||
'buyIx',
|
||||
'buyNni',
|
||||
'buySat',
|
||||
'buySpare',
|
||||
'buyTE',
|
||||
'buyTransit',
|
||||
'buyVxc',
|
||||
'cache',
|
||||
'cacheSite',
|
||||
'callBank',
|
||||
'cancelIx',
|
||||
'cancelPni',
|
||||
'cancelTransit',
|
||||
'cancelVxc',
|
||||
'charter',
|
||||
'cleanPipe',
|
||||
'confGo',
|
||||
'confSponsor',
|
||||
'connCancel',
|
||||
'coreLab',
|
||||
'coreSet',
|
||||
'coreUp',
|
||||
'crews',
|
||||
'ddosAuto',
|
||||
'ddosEngage',
|
||||
'ddosTest',
|
||||
'decline',
|
||||
'declineLoan',
|
||||
'decomGo',
|
||||
'demoAsk',
|
||||
'dkAccept',
|
||||
'dkHaggle',
|
||||
'dkOptOut',
|
||||
'dkStay',
|
||||
'dkWalk',
|
||||
'downIx',
|
||||
'downP',
|
||||
'downT',
|
||||
'dropBiz',
|
||||
'fixInc',
|
||||
'foundIx',
|
||||
'hackback',
|
||||
'hwLock',
|
||||
'ip4Back',
|
||||
'ip4Buy',
|
||||
'ip4Lease',
|
||||
'ip4Nat',
|
||||
'ip4Nat64',
|
||||
'ip4Out',
|
||||
'ip4Return',
|
||||
'ip4Sell',
|
||||
'ip6Go',
|
||||
'ip6Stop',
|
||||
'lagIx',
|
||||
'lagNni',
|
||||
'lagP',
|
||||
'lagT',
|
||||
'launchBB',
|
||||
'layShip',
|
||||
'listFiber',
|
||||
'metricMode',
|
||||
'metricSet',
|
||||
'mkBanana',
|
||||
'myIxUp',
|
||||
'opsCap',
|
||||
'opsFire',
|
||||
'opsFloor',
|
||||
'opsHire',
|
||||
'opsNewPop',
|
||||
'opsParam',
|
||||
'opsPop',
|
||||
'opsToggle',
|
||||
'opsTpl',
|
||||
'orderCable',
|
||||
'orderDf',
|
||||
'peer',
|
||||
'peerAll',
|
||||
'peerPol',
|
||||
'pieAnt',
|
||||
'pieBid',
|
||||
'pieDish',
|
||||
'pieExim',
|
||||
'pieFactory',
|
||||
'pieFound',
|
||||
'pieLaunch',
|
||||
'pieLic',
|
||||
'pieName',
|
||||
'piePad',
|
||||
'pieRd',
|
||||
'pieRename',
|
||||
'pieSafe',
|
||||
'pieSpatPick',
|
||||
'pni',
|
||||
'pniAll',
|
||||
'pniChase',
|
||||
'popStdClear',
|
||||
'popStdSet',
|
||||
'regen',
|
||||
'renameGo',
|
||||
'renewLet',
|
||||
'renewMatch',
|
||||
'renewMeet',
|
||||
'repayLoan',
|
||||
'rmCache',
|
||||
'rmCh',
|
||||
'rmLink',
|
||||
'rmNni',
|
||||
'rmRouter',
|
||||
'rmScrub',
|
||||
'rmSite',
|
||||
'rs',
|
||||
'rtbh',
|
||||
'sacrif',
|
||||
'salesAuto',
|
||||
'salesFire',
|
||||
'salesHire',
|
||||
'salesMin',
|
||||
'salesRen',
|
||||
'salesVp',
|
||||
'satSize',
|
||||
'scrubMode',
|
||||
'scrubUp',
|
||||
'seaRush',
|
||||
'seatBuy',
|
||||
'seatNo',
|
||||
'sellSpare',
|
||||
'setCarry',
|
||||
'setChCount',
|
||||
'setMetric',
|
||||
'setPref',
|
||||
'setRoute',
|
||||
'setStandby',
|
||||
'siteSet',
|
||||
'spares',
|
||||
'subUpgrade',
|
||||
'takeLoan',
|
||||
'teClear',
|
||||
'teDeploy',
|
||||
'teToggle',
|
||||
'teleBuild',
|
||||
'teleRm',
|
||||
'teleTrk',
|
||||
'togglePrem',
|
||||
'tutSkip',
|
||||
'unlistFiber',
|
||||
'unpeer',
|
||||
'unrtbh',
|
||||
'upLink',
|
||||
'upRouter',
|
||||
'upSys',
|
||||
'upVxc',
|
||||
'utilityCaches',
|
||||
'utilityKit',
|
||||
'utilityPeers',
|
||||
'utilityRouteServers',
|
||||
'xpBuild',
|
||||
'xpCh',
|
||||
];
|
||||
// What-ifs the server answers with the window they open, putting the game back as it was (5.9).
|
||||
const ASK = ['linkCheck', 'teCheck', 'teSlop'];
|
||||
// The clock's buttons: on a server network they are a vote for the session's speed (4.5).
|
||||
const VOTE = ['phonePlay', 'phoneSpeed', 'speed'];
|
||||
// The page runs these itself: views, drafts, settings, slots, session acts, teOpt.
|
||||
const LOCAL = [
|
||||
'addParallel',
|
||||
'animSet',
|
||||
'bank',
|
||||
'bankClose',
|
||||
'bstdOpen',
|
||||
'chaosSet',
|
||||
'chartToggle',
|
||||
'closeModal',
|
||||
'closePanel',
|
||||
'cnPrem',
|
||||
'connCity',
|
||||
'connF',
|
||||
'connFor',
|
||||
'connNet',
|
||||
'connOpen',
|
||||
'connSort',
|
||||
'cont',
|
||||
'custCity',
|
||||
'custF',
|
||||
'custGo',
|
||||
'custOpen',
|
||||
'custSort',
|
||||
'dash',
|
||||
'dashClose',
|
||||
'dashLink',
|
||||
'dashSort',
|
||||
'dashTab',
|
||||
'decomOpen',
|
||||
'decomToggle',
|
||||
'dfMode',
|
||||
'dfSrc',
|
||||
'dfSys',
|
||||
'exportSave',
|
||||
'findGo',
|
||||
'findOpen',
|
||||
'focusCity',
|
||||
'goConn',
|
||||
'goEgress',
|
||||
'help',
|
||||
'helpClose',
|
||||
'importGo',
|
||||
'importPick',
|
||||
'install',
|
||||
'ip4Open',
|
||||
'ip4Pick',
|
||||
'keepPlaying',
|
||||
'keys',
|
||||
'langSet',
|
||||
'leaseSwap',
|
||||
'leftTab',
|
||||
'listMore',
|
||||
'logAll',
|
||||
'logOpen',
|
||||
'mapSet',
|
||||
'meetGo',
|
||||
'menu',
|
||||
'modeSet',
|
||||
'models',
|
||||
'mpBack',
|
||||
'mpChat',
|
||||
'mpCopyLink',
|
||||
'mpDoor',
|
||||
'mpJoin',
|
||||
'mpKeep',
|
||||
'mpLeave',
|
||||
'mpLeaveAsk',
|
||||
'mpNewer',
|
||||
'mpOpen',
|
||||
'mpShare',
|
||||
'mpStart',
|
||||
'mute',
|
||||
'netFilter',
|
||||
'netFocus',
|
||||
'newgame',
|
||||
'nocWindow',
|
||||
'offerStep',
|
||||
'openVxc',
|
||||
'opsCity',
|
||||
'opsOpen',
|
||||
'ownCab',
|
||||
'phoneTab',
|
||||
'pickHome',
|
||||
'pickStart',
|
||||
'pieCity',
|
||||
'pieGlobeNight',
|
||||
'pieGovOpen',
|
||||
'pieHi',
|
||||
'pieIns',
|
||||
'pieLas',
|
||||
'pieOpen',
|
||||
'pieSpatOpen',
|
||||
'pieTab',
|
||||
'pitchSkip',
|
||||
'pniAllOpen',
|
||||
'pniAllSize',
|
||||
'pniFilter',
|
||||
'pniGrp',
|
||||
'pniSort',
|
||||
'popGo',
|
||||
'popStep',
|
||||
'popsReg',
|
||||
'popsSort',
|
||||
'prefSet',
|
||||
'presetSet',
|
||||
'puzzleDoor',
|
||||
'puzzleMenu',
|
||||
'randomName',
|
||||
'rename',
|
||||
'resetAsk',
|
||||
'route',
|
||||
'routingOpen',
|
||||
'salesOpen',
|
||||
'satOpen',
|
||||
'scenarios',
|
||||
'seaDesign',
|
||||
'seaPackage',
|
||||
'selLink',
|
||||
'settings',
|
||||
'settingsClose',
|
||||
'share',
|
||||
'shareDl',
|
||||
'shareGo',
|
||||
'slotBack',
|
||||
'slotDel',
|
||||
'slotDelGo',
|
||||
'slotExport',
|
||||
'slotMenu',
|
||||
'slotRetry',
|
||||
'slotSpace',
|
||||
'slotSwitch',
|
||||
'slotTake',
|
||||
'soundSet',
|
||||
'start',
|
||||
'startScn',
|
||||
'startWeekly',
|
||||
'tab',
|
||||
'tailTog',
|
||||
'teBack',
|
||||
'teClose',
|
||||
'teEdit',
|
||||
'teExample',
|
||||
'teHelp',
|
||||
'teOpt',
|
||||
'teRecipe',
|
||||
'themeSet',
|
||||
'toTitle',
|
||||
'toggleLeft',
|
||||
'trace',
|
||||
'traceCopy',
|
||||
'traceMode',
|
||||
'traceRun',
|
||||
'updateLater',
|
||||
'updateNow',
|
||||
'utilities',
|
||||
'utilityPick',
|
||||
'via',
|
||||
'vpSet',
|
||||
'whatsNewShow',
|
||||
'wsShare',
|
||||
'xpOpen',
|
||||
'zoomStep',
|
||||
];
|
||||
// Puzzles never run on the server: they stay on the device, like everything that starts with pz.
|
||||
const PUZZLE = [
|
||||
'pzAddPar',
|
||||
'pzArAll',
|
||||
'pzArGo',
|
||||
'pzArNext',
|
||||
'pzArSkip',
|
||||
'pzArStart',
|
||||
'pzCity',
|
||||
'pzDiv',
|
||||
'pzFinish',
|
||||
'pzLeave',
|
||||
'pzLink',
|
||||
'pzLinkTo',
|
||||
'pzLook',
|
||||
'pzMkSkip',
|
||||
'pzMonkey',
|
||||
'pzPop',
|
||||
'pzReset',
|
||||
'pzRetry',
|
||||
'pzRmLink',
|
||||
'pzRmPop',
|
||||
'pzRoute',
|
||||
'pzRtAdd',
|
||||
'pzRtModel',
|
||||
'pzRtRm',
|
||||
'pzShare',
|
||||
'pzStart',
|
||||
'pzTab',
|
||||
'pzTier',
|
||||
'pzUndo',
|
||||
'pzVia',
|
||||
'pzWeekly',
|
||||
];
|
||||
|
||||
/* Two-click buttons: the first click arms the button on the page (a view change), only the second is sent, with
|
||||
confirmed:true. 'arg': the act takes ok:1 and runs at once. Anything else: the key the first click writes to
|
||||
UI.confirm, as a template over the act's args ({id} is String(args.id)); the server sets UI.confirm to it and runs the
|
||||
act once. */
|
||||
const CONFIRM = {
|
||||
cancelIx: 'arg',
|
||||
cancelPni: 'arg',
|
||||
cancelTransit: 'arg',
|
||||
cancelVxc: '{id}',
|
||||
connCancel: 'cc:{k}:{id}',
|
||||
dkOptOut: 'dk{city}{n}',
|
||||
dropBiz: '{id}',
|
||||
ip4Sell: '{id}',
|
||||
opsFire: 'opsFire',
|
||||
repayLoan: '{id}',
|
||||
rmLink: '{id}',
|
||||
rmScrub: 'scrub:{city}',
|
||||
rmSite: 'site{city}',
|
||||
salesFire: 'salesFire',
|
||||
teleRm: 'tele:{city}',
|
||||
};
|
||||
// The UI.confirm key a preset act's first click writes (null for 'arg' acts and acts that do not confirm).
|
||||
const SRV_ARM = Object.fromEntries(Object.entries(CONFIRM).filter(([, v]) => v !== 'arg'));
|
||||
function armKey(act, args) {
|
||||
const t = Object.prototype.hasOwnProperty.call(SRV_ARM, act) ? SRV_ARM[act] : null;
|
||||
return t === null ? null : t.replace(/\{(\w+)\}/g, (m, k) => String(args && args[k] !== undefined ? args[k] : ''));
|
||||
}
|
||||
|
||||
/* The UI drafts an act reads, and the only UI keys a request may set (its ui object). Types are checked here; the realm
|
||||
checks the values against the game's catalogs (cities, CABLES, DF_SYS, SEA_DESIGNS, the route picker's values). */
|
||||
const DRAFTS = {
|
||||
buildLink: ['pending', 'route', 'via', 'cnPrem'],
|
||||
decomGo: ['decom'],
|
||||
orderCable: ['pending', 'seaDesign', 'seaterminal', 'seaengineering'],
|
||||
orderDf: ['pending', 'dfSrc', 'dfSys'],
|
||||
pieLaunch: ['pieIns', 'pieLas'],
|
||||
teDeploy: ['slop'],
|
||||
};
|
||||
// pair: {a, b}, two different city-like ids; id: a short id string; ids: an array of at most 200 of them (a Set in the game).
|
||||
const DRAFT_TYPES = {
|
||||
cnPrem: 'boolean',
|
||||
decom: 'ids',
|
||||
dfSrc: ['lease', 'build', 'cable'],
|
||||
dfSys: 'id',
|
||||
pending: 'pair',
|
||||
pieIns: 'boolean',
|
||||
pieLas: 'boolean',
|
||||
route: 'string',
|
||||
seaDesign: 'id',
|
||||
seaengineering: 'boolean',
|
||||
seaterminal: 'boolean',
|
||||
slop: 'boolean',
|
||||
via: 'string',
|
||||
};
|
||||
|
||||
// Args longer than the envelope's 64 characters: their own cap (the game cuts the texts shorter itself).
|
||||
const TEXT = {
|
||||
metricSet: { v: 16 },
|
||||
pieRename: { name: 64 },
|
||||
renameGo: { name: 64 },
|
||||
teCheck: { script: 4000 },
|
||||
teDeploy: { script: 4000 },
|
||||
utilityCaches: { quote: 1024 },
|
||||
};
|
||||
|
||||
/* Acts that charge a total the player saw in a window, planned again at the click: the arg that carries what the window
|
||||
showed. The game refuses a different one ("The quote changed"); the server also refuses a request without it.
|
||||
'quote' is the plan's key (a string), any other name the total (a number). pniAll: the exact total (fixed prices, so
|
||||
the total names the plan). bstdApply: the plan's key, plus its total q, which may drift 1% (hardware prices move
|
||||
daily under the market rule). utilityKit: the total, within 1%. utilityCaches: the list of boxes. */
|
||||
const QUOTE = {
|
||||
bstdApply: 'quote',
|
||||
pniAll: 'q',
|
||||
utilityCaches: 'quote',
|
||||
utilityKit: 'cost',
|
||||
};
|
||||
|
||||
const ID_RE = /^[a-z0-9]{8,16}$/, SIM_RE = /^[0-9a-f]{12}$/, KEY_RE = /^[A-Za-z][A-Za-z0-9]{0,15}$/, VIEW_RE = /^[a-z0-9]{1,16}$/, SHORT_RE = /^[A-Za-z0-9_.:|~-]{1,40}$/;
|
||||
const SPEEDS = [0, 0.5, 1, 2, 4, 8];
|
||||
// The viewport a request's ctx may set on the realm, in CSS pixels: checkEnvelope clamps ctx.w and ctx.h into it.
|
||||
const VIEW_MIN = 200, VIEW_MAX = 4000;
|
||||
const PREFS = ['pauseFurious', 'pauseIncident', 'warnUnhappy'];
|
||||
const SETS = { SEND: new Set(SEND), ASK: new Set(ASK), CONFIRM: new Set(Object.keys(CONFIRM)) };
|
||||
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
||||
const plain = (o) => !!o && typeof o === 'object' && !Array.isArray(o) && (Object.getPrototypeOf(o) === Object.prototype || Object.getPrototypeOf(o) === null);
|
||||
const prim = (v, cap) => v === null || typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && v.length <= cap);
|
||||
// Keys a request object may never carry, whatever the regex says.
|
||||
const BAD_KEY = new Set(['__proto__', 'constructor', 'prototype']);
|
||||
|
||||
function bad(error, code = 400, extra = {}) { return { ok: false, code, error, ...extra }; }
|
||||
|
||||
function checkArgs(act, args) {
|
||||
if (!plain(args)) return 'args must be an object';
|
||||
const keys = Object.keys(args);
|
||||
if (keys.length > 12) return 'too many args';
|
||||
const caps = own(TEXT, act) ? TEXT[act] : {};
|
||||
for (const k of keys) {
|
||||
if (!KEY_RE.test(k) || BAD_KEY.has(k)) return `bad arg name ${JSON.stringify(k).slice(0, 40)}`;
|
||||
const v = args[k], cap = own(caps, k) ? caps[k] : 64;
|
||||
if (Array.isArray(v)) { if (v.length > 64 || !v.every((x) => prim(x, 64))) return `bad arg ${k}`; continue; }
|
||||
if (!prim(v, cap)) return `bad arg ${k}`;
|
||||
}
|
||||
if (own(QUOTE, act)) { const q = args[QUOTE[act]]; if (QUOTE[act] === 'quote' ? typeof q !== 'string' : !(typeof q === 'number' && Number.isFinite(q))) return `${act} needs the quoted ${QUOTE[act]}`; }
|
||||
return null;
|
||||
}
|
||||
function checkDraft(k, v) {
|
||||
const t = DRAFT_TYPES[k];
|
||||
if (Array.isArray(t)) return t.includes(v);
|
||||
if (t === 'boolean') return typeof v === 'boolean';
|
||||
if (t === 'string') return typeof v === 'string' && v.length <= 64;
|
||||
if (t === 'id') return typeof v === 'string' && SHORT_RE.test(v);
|
||||
// Two different places: the game's own drag never opens a link from a city to itself.
|
||||
if (t === 'pair') return plain(v) && Object.keys(v).length === 2 && typeof v.a === 'string' && typeof v.b === 'string' && SHORT_RE.test(v.a) && SHORT_RE.test(v.b) && v.a !== v.b;
|
||||
if (t === 'ids') return Array.isArray(v) && v.length <= 200 && v.every((x) => typeof x === 'string' && SHORT_RE.test(x));
|
||||
return false;
|
||||
}
|
||||
function checkCtx(c) {
|
||||
if (!plain(c)) return 'ctx must be an object';
|
||||
for (const k of Object.keys(c)) {
|
||||
const v = c[k];
|
||||
if (k === 'sel') { if (v !== null && !(plain(v) && Object.keys(v).length === 2 && (v.type === 'city' || v.type === 'link') && typeof v.id === 'string' && SHORT_RE.test(v.id))) return 'bad ctx.sel'; }
|
||||
else if (k === 'tab' || k === 'left') { if (v !== null && !(typeof v === 'string' && VIEW_RE.test(v))) return `bad ctx.${k}`; }
|
||||
else if (k === 'modal' || k === 'coarse') { if (typeof v !== 'boolean') return `bad ctx.${k}`; }
|
||||
// The page sends its innerWidth/innerHeight as they are: a 5120-px monitor, or a desktop zoomed out, is wider than
|
||||
// anything the layout tells apart (isPhone() and the like only ask whether it is under about 760). Clamped, not refused.
|
||||
else if (k === 'w' || k === 'h') { if (!(typeof v === 'number' && Number.isFinite(v) && v > 0 && v <= 1e5)) return `bad ctx.${k}`; c[k] = Math.min(VIEW_MAX, Math.max(VIEW_MIN, v)); }
|
||||
else return `unknown ctx.${String(k).slice(0, 20)}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const bool = (v) => v === undefined || typeof v === 'boolean';
|
||||
|
||||
/* The envelope of one request body, before anything reaches a game. kind: 'act' | 'ask' | 'vote' | 'here' | 'prefs'.
|
||||
opts.sim: the server's build id; a request built by another one answers 409 {old:true}. Returns {ok:true} or
|
||||
{ok:false, code (400 or 409), error, old?}. Only shapes are checked here; what the ids name is the realm's to check.
|
||||
One repair, in place: ctx.w and ctx.h (any finite width up to 100000) are clamped into VIEW_MIN–VIEW_MAX, so the
|
||||
realm only ever sees a viewport in that range. */
|
||||
function checkEnvelope(kind, body, opts = {}) {
|
||||
if (!plain(body)) return bad('the body must be a JSON object');
|
||||
const keys = Object.keys(body);
|
||||
const only = (allowed) => { for (const k of keys) if (!allowed.includes(k)) return `unknown field ${JSON.stringify(k).slice(0, 40)}`; return null; };
|
||||
const simOk = () => {
|
||||
if (typeof body.sim !== 'string' || !SIM_RE.test(body.sim)) return bad('sim must be the page\'s build id');
|
||||
if (opts.sim && body.sim !== opts.sim) return bad('this page is from another build', 409, { old: true });
|
||||
return null;
|
||||
};
|
||||
if (kind === 'act' || kind === 'ask') {
|
||||
const e = only(kind === 'act' ? ['rid', 'dev', 'sim', 'act', 'args', 'ui', 'confirmed', 'ctx'] : ['rid', 'dev', 'sim', 'act', 'args', 'ctx']);
|
||||
if (e) return bad(e);
|
||||
if (typeof body.rid !== 'string' || !ID_RE.test(body.rid)) return bad('bad rid');
|
||||
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
|
||||
const s = simOk(); if (s) return s;
|
||||
if (typeof body.act !== 'string' || !(kind === 'act' ? SETS.SEND : SETS.ASK).has(body.act)) return bad(`${kind} ${JSON.stringify(String(body.act).slice(0, 40))} is not one the server runs`);
|
||||
const a = checkArgs(body.act, body.args === undefined ? {} : body.args); if (a) return bad(a);
|
||||
if (body.ui !== undefined) {
|
||||
if (kind !== 'act' || !plain(body.ui)) return bad('bad ui');
|
||||
const allowed = own(DRAFTS, body.act) ? DRAFTS[body.act] : [];
|
||||
for (const k of Object.keys(body.ui)) if (!allowed.includes(k) || !checkDraft(k, body.ui[k])) return bad(`bad ui.${String(k).slice(0, 20)}`);
|
||||
}
|
||||
if (body.confirmed !== undefined && (body.confirmed !== true || !SETS.CONFIRM.has(body.act))) return bad('confirmed only goes with a two-click act');
|
||||
if (body.ctx !== undefined) { const c = checkCtx(body.ctx); if (c) return bad(c); }
|
||||
return { ok: true };
|
||||
}
|
||||
if (kind === 'vote') {
|
||||
const e = only(['speed', 'sim']); if (e) return bad(e);
|
||||
const s = simOk(); if (s) return s;
|
||||
if (body.speed !== null && !SPEEDS.includes(body.speed)) return bad('bad speed');
|
||||
return { ok: true };
|
||||
}
|
||||
if (kind === 'here') {
|
||||
const e = only(['dev', 'hidden', 'hold', 'idle', 'away', 'view']); if (e) return bad(e);
|
||||
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
|
||||
if (!['hidden', 'hold', 'idle', 'away'].every((k) => bool(body[k]))) return bad('bad flag');
|
||||
if (body.view !== undefined) {
|
||||
const v = body.view;
|
||||
if (v !== null && !(plain(v) && Object.keys(v).every((k) => (k === 'link' || k === 'peer') && (v[k] === null || (typeof v[k] === 'string' && SHORT_RE.test(v[k])))))) return bad('bad view');
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
if (kind === 'prefs') {
|
||||
const e = only(['prefs', 'lang']); if (e) return bad(e);
|
||||
if (body.prefs !== undefined && !(plain(body.prefs) && Object.keys(body.prefs).every((k) => PREFS.includes(k) && typeof body.prefs[k] === 'boolean'))) return bad('bad prefs');
|
||||
if (body.lang !== undefined && !(typeof body.lang === 'string' && /^[a-z]{2}(-[A-Za-z]{2,4})?$/.test(body.lang))) return bad('bad lang');
|
||||
return { ok: true };
|
||||
}
|
||||
return bad(`unknown kind ${String(kind).slice(0, 20)}`);
|
||||
}
|
||||
|
||||
// Body size caps per kind, in bytes (section 10), for the host's readJson.
|
||||
const BODY_MAX = { act: 16384, ask: 8192, here: 2048, prefs: 1024, vote: 256 };
|
||||
|
||||
module.exports = { SEND, ASK, VOTE, LOCAL, PUZZLE, CONFIRM, SRV_ARM, armKey, DRAFTS, DRAFT_TYPES, TEXT, QUOTE, SPEEDS, PREFS, VIEW_MIN, VIEW_MAX, BODY_MAX, checkEnvelope };
|
||||
|
|
@ -8,9 +8,14 @@
|
|||
// MCP server's own page and the tests that ask for it. Everywhere else the line is dropped whole, so
|
||||
// the page players get is exactly what it would be without it (docs/adr/0004-dev-only-code.md).
|
||||
//
|
||||
// The server-run play of a multiplayer build (src/game/98-server-play/ and src/styles/43-server-play.css) is only in a
|
||||
// page assembled with mp: true, which MP_API=… npm run build asks for; every other page, the one players get on
|
||||
// GitHub Pages included, has none of it.
|
||||
//
|
||||
// node scripts/lib/page.js [-o FILE] the page as it ships (stdout by default)
|
||||
// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests use)
|
||||
// node scripts/lib/page.js --source --dev [-o FILE] the development page: with src/agent/ (what npm run dev serves)
|
||||
// node scripts/lib/page.js --mp [--source] [-o FILE] a multiplayer build's page: with the server-play client
|
||||
// node scripts/lib/page.js --ref origin/main -o FILE the page as it ships at a git ref
|
||||
//
|
||||
// --ref uses that commit's own assembler, so it keeps working when this file changes; refs from before
|
||||
|
|
@ -22,6 +27,9 @@ const { execFileSync } = require('node:child_process');
|
|||
|
||||
const ROOT = path.join(__dirname, '..', '..');
|
||||
const INCLUDE = /^<!-- @include(-dev)? ([\w./-]+) -->$/;
|
||||
// Parts of src/ only a multiplayer build's page has (paths as the line map names them; a trailing / is a folder).
|
||||
const MP_ONLY = ['game/98-server-play/', 'styles/43-server-play.css'];
|
||||
const mpOnly = (f) => MP_ONLY.some((p) => (p.endsWith('/') ? f.startsWith(p) : f === p));
|
||||
|
||||
// Every file under dir, as paths relative to dir with '/' separators, in a stable order
|
||||
// (plain code-unit comparison, so the order never depends on the machine's locale).
|
||||
|
|
@ -36,11 +44,11 @@ function listFiles(dir, rel = '') {
|
|||
return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
}
|
||||
|
||||
// The partials that make up one include, in order: [{file, text}].
|
||||
function partials(src, dir) {
|
||||
// The partials that make up one include, in order: [{file, text}]. Without mp, the multiplayer-only ones are left out.
|
||||
function partials(src, dir, mp = true) {
|
||||
const base = path.join(src, dir);
|
||||
if (!fs.existsSync(base)) throw new Error(`@include ${dir}: no such directory under ${path.relative(ROOT, src) || '.'}`);
|
||||
return listFiles(base).map((r) => {
|
||||
return listFiles(base).filter((r) => mp || !mpOnly(dir + '/' + r)).map((r) => {
|
||||
const file = path.join(base, r);
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
if (text.includes('\r')) throw new Error(`${path.relative(ROOT, file)}: use LF line endings`);
|
||||
|
|
@ -52,7 +60,8 @@ function partials(src, dir) {
|
|||
|
||||
// The assembled page as a string, plus a map of which output line came from which source file.
|
||||
// dev: also the @include-dev parts (the development page); without it, their lines are left out entirely.
|
||||
function assemble({ src = path.join(ROOT, 'src'), dev = false } = {}) {
|
||||
// mp: also the multiplayer-only parts (MP_ONLY); without it, those files are left out entirely.
|
||||
function assemble({ src = path.join(ROOT, 'src'), dev = false, mp = false } = {}) {
|
||||
const shell = fs.readFileSync(path.join(src, 'index.html'), 'utf8');
|
||||
const out = [], map = [];
|
||||
let line = 1;
|
||||
|
|
@ -65,7 +74,7 @@ function assemble({ src = path.join(ROOT, 'src'), dev = false } = {}) {
|
|||
return;
|
||||
}
|
||||
if (m[1] && !dev) return;
|
||||
for (const p of partials(src, m[2])) {
|
||||
for (const p of partials(src, m[2], mp)) {
|
||||
const n = p.text.split('\n').length - 1;
|
||||
map.push({ file: p.file, from: line, to: line + n - 1 });
|
||||
out.push(p.text);
|
||||
|
|
@ -95,10 +104,17 @@ function assembleRef(ref, cwd = ROOT) {
|
|||
}
|
||||
|
||||
// The page as it ships: assembled, with labels shrunk to short ids (compile-labels.js). Not version-stamped.
|
||||
// `dicts` ({lang: label-keyed dictionary}) come back with the same ids.
|
||||
function shipped(dicts = {}) {
|
||||
// `dicts` ({lang: label-keyed dictionary}) come back with the same ids. mp: a multiplayer build's page.
|
||||
function shipped(dicts = {}, { mp = false } = {}) {
|
||||
const D = require('./dict');
|
||||
return require('./compile-labels').compile(assemble().html, D.read('en').dict, dicts);
|
||||
return require('./compile-labels').compile(assemble({ mp }).html, D.read('en').dict, dicts);
|
||||
}
|
||||
|
||||
/* The build id of server-run play (SIM_ID): the first 12 hex digits of sha256 of the multiplayer page as assembled from
|
||||
src/, labels as written (game and server-play client together, so a change to either is a new id). The build stamps
|
||||
it into MP pages and version.json; the session server works it out from its own src/ and refuses pages of another. */
|
||||
function simId(html = assemble({ mp: true }).html) {
|
||||
return require('node:crypto').createHash('sha256').update(html).digest('hex').slice(0, 12);
|
||||
}
|
||||
|
||||
// The shipped page written to a file, for tools that need a path (perf in a real browser, base vs head).
|
||||
|
|
@ -107,12 +123,13 @@ function pageFile(file = path.join(os.tmpdir(), `tubes-page-${process.pid}.html`
|
|||
return file;
|
||||
}
|
||||
|
||||
module.exports = { assemble, assembleRef, shipped, pageFile, locate, listFiles, ROOT };
|
||||
module.exports = { assemble, assembleRef, shipped, simId, pageFile, locate, listFiles, MP_ONLY, ROOT };
|
||||
|
||||
if (require.main === module) {
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : null; };
|
||||
const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble({ dev: args.includes('--dev') }).html : shipped().html;
|
||||
const mp = args.includes('--mp');
|
||||
const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble({ dev: args.includes('--dev'), mp }).html : shipped({}, { mp }).html;
|
||||
const out = opt('-o');
|
||||
if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(out, html); }
|
||||
else process.stdout.write(html);
|
||||
|
|
|
|||
|
|
@ -82,8 +82,9 @@ function playGame(pages, seed, opts = {}) {
|
|||
// standing order only one of them has (one this checkout retired, or added).
|
||||
const [k1, k2] = both('sKeys'), drop = { top: k2.top.filter((k) => !k1.top.includes(k)), items: k2.items.filter((k) => !k1.items.includes(k)),
|
||||
ops: [...k1.ops.filter((k) => !k2.ops.includes(k)), ...k2.ops.filter((k) => !k1.ops.includes(k))] };
|
||||
const [s1, s2] = both('sDigest', drop);
|
||||
if (s1 !== s2) { fail(where + ': game state S', { diff: firstDiff(base.call('sParts', drop), head.call('sParts', drop)) }); return false; }
|
||||
// Both states as this checkout's reload makes them (see sLive in fuzz-page.js).
|
||||
const [j1, j2] = both('sLive'), s1 = head.call('sDigest', drop, j1), s2 = head.call('sDigest', drop, j2);
|
||||
if (s1 !== s2) { fail(where + ': game state S', { diff: firstDiff(head.call('sParts', drop, j1), head.call('sParts', drop, j2)) }); return false; }
|
||||
return true;
|
||||
};
|
||||
|
||||
|
|
@ -111,7 +112,11 @@ function playGame(pages, seed, opts = {}) {
|
|||
const screen = (w) => { const [a0, b0] = both('screen', w); baseActs = baseActs || new Set(base.call('acts'));
|
||||
if (!retired) { const [o1, o2] = both('sKeys'); retired = new Set(o1.orders.filter((k) => !o2.orders.includes(k))); }
|
||||
const a = Array.isArray(a0) ? a0.filter((x) => !(/^ops/.test(x.act) && retired.has(x.args && x.args.k))) : a0;
|
||||
const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act)) : b0; same('buttons of ' + JSON.stringify(w), a, b); return a || []; };
|
||||
// Args only this checkout's buttons carry (the total or plan a window shows: pniAll's q, bstdApply's quote) are left
|
||||
// out as well: the driver presses the base's button, which both pages take as before.
|
||||
const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act)).map((x, i) => { const y = Array.isArray(a) && a[i] && a[i].act === x.act ? a[i].args : null;
|
||||
return y && x.args && typeof x.args === 'object' && typeof y === 'object' ? { act: x.act, args: Object.fromEntries(Object.entries(x.args).filter(([k]) => k in y)) } : x; }) : b0;
|
||||
same('buttons of ' + JSON.stringify(w), a, b); return a || []; };
|
||||
const press = (b, where) => { acts[b.act] = (acts[b.act] || 0) + 1; const [e1, e2] = both('press', b); same('press ' + where, e1, e2); note(where + ' ' + b.act + JSON.stringify(b.args) + (e1 ? ' !' + e1 : '')); };
|
||||
// Answer whatever window opened, a few levels deep, then close it.
|
||||
const modal = (bias) => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue