@wildshard/engine 0.1.17 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +7 -0
  3. package/lint/host-callback-syntax.mjs +2 -1
  4. package/lint/host-callbacks.mjs +3 -3
  5. package/lint/host-files.mjs +5 -4
  6. package/lint/no-base64.mjs +3 -1
  7. package/lint/shard-imports.mjs +6 -7
  8. package/lint/shard-source.d.mts +9 -0
  9. package/lint/shard-source.mjs +91 -0
  10. package/lint/shardfile-boundaries.mjs +10 -8
  11. package/lint/sim-closure.mjs +6 -3
  12. package/lint/wildshard-plugin.d.ts +4 -0
  13. package/lint/wildshard-plugin.js +22 -23
  14. package/package.json +9 -2
  15. package/scripts/app-build/outputProducts.d.mts +3 -0
  16. package/scripts/app-build/outputProducts.mjs +31 -0
  17. package/scripts/app-build-pipeline.mjs +3 -0
  18. package/scripts/check-devserver.mjs +1 -1
  19. package/scripts/chromium-keychain-check.mjs +4 -2
  20. package/scripts/chromium-keychain.mjs +3 -1
  21. package/scripts/cook.mjs +7 -3
  22. package/scripts/devices.d.mts +4 -0
  23. package/scripts/devices.mjs +39 -0
  24. package/scripts/devserver-client.d.mts +4 -2
  25. package/scripts/devserver-client.mjs +25 -8
  26. package/scripts/doctor-proof.mjs +1 -1
  27. package/scripts/e2e-faults.mjs +159 -0
  28. package/scripts/grid-crossing-walk-proof.mjs +14 -3
  29. package/scripts/memory-proof.mjs +158 -0
  30. package/scripts/offline-proof-rules.d.mts +4 -2
  31. package/scripts/offline-proof-rules.mjs +21 -5
  32. package/scripts/offline-proof.mjs +15 -6
  33. package/scripts/tier-textures-proof.mjs +101 -0
  34. package/scripts/tier-textures.mjs +60 -0
  35. package/scripts/tsconfig.json +1 -0
  36. package/scripts/vps/wildshard-config +79 -23
  37. package/scripts/worker-client-play.mjs +1 -0
  38. package/scripts/worker-client-proof.mjs +1 -1
  39. package/scripts/worker-client-slug.mjs +44 -0
  40. package/src/client/app/entry.ts +37 -10
  41. package/src/client/engine/boot/parsedPages.ts +127 -58
  42. package/src/client/engine/build.d.ts +2 -0
  43. package/src/client/engine/core/Game.ts +18 -0
  44. package/src/client/engine/core/bootstrap.ts +4 -1
  45. package/src/client/engine/debug/probe.ts +18 -1
  46. package/src/client/engine/fx/LightPool.ts +41 -1
  47. package/src/client/engine/pwa/sw.js +12 -3
  48. package/src/client/engine/render/precompile.ts +20 -14
  49. package/src/client/engine/telemetry/browserErrors.ts +4 -1
  50. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  51. package/src/client/game/boot/audio.generated.ts +0 -102
  52. package/src/client/game/boot/bytes.generated.ts +42 -60
  53. package/src/client/game/boot/versions.generated.ts +0 -2
  54. package/src/client/game/grid/area.ts +38 -0
  55. package/src/client/game/grid/live.ts +28 -2
  56. package/src/client/game/grid/liveSession.ts +14 -3
  57. package/src/client/game/grid/menu.ts +4 -0
  58. package/src/client/game/grid/neighbourPanels.ts +10 -1
  59. package/src/client/game/grid/placedCards.ts +55 -0
  60. package/src/client/game/grid/placedCells.ts +131 -0
  61. package/src/client/game/grid/regionalRuntime.ts +6 -0
  62. package/src/client/game/grid/regionalWorld.ts +15 -2
  63. package/src/client/game/grid/roadCull.ts +44 -14
  64. package/src/client/game/grid/roadTileBacking.ts +13 -3
  65. package/src/client/game/grid/session.ts +9 -0
  66. package/src/client/game/grid/shardfileFar.ts +9 -3
  67. package/src/client/game/session/finish.ts +5 -1
  68. package/src/client/game/shard/titleList.ts +6 -2
  69. package/src/client/game/shardfile/clientWorker.ts +2 -1
  70. package/src/client/game/titleDeck.ts +4 -3
  71. package/src/client/host/online/shell.ts +14 -0
  72. package/src/cook/game/shardCook.ts +38 -8
  73. package/src/cook/game/tierTextures.ts +276 -0
  74. package/src/e2e/smoke/game.ts +19 -14
  75. package/src/e2e/smoke/page-globals.d.ts +9 -8
  76. package/src/e2e/smoke/template2.spec.ts +8 -7
  77. package/src/server/host/dedicated/placementFile.ts +1 -17
  78. package/src/server/host/dedicated/socketTransport.ts +2 -1
  79. package/src/server/host/dedicated/world.ts +30 -1
  80. package/src/shared/engine/net/deviceWord.ts +138 -0
  81. package/src/shared/engine/net/socketFrames.ts +7 -4
  82. package/src/shared/game/grid/catalogueSlot.ts +7 -0
  83. package/src/shared/game/grid/placementRows.ts +33 -0
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env node
2
+ // IOSMEM (meta PAGE-SIZE-PLAN): the iPhone page-memory proof for Driftwood Isle, after WILDSHARD-GAME-8G (Jake 2026-11-13:
3
+ // staging v0.1.16 restarted while Playing on Driftwood on his iPhone 17 Pro, the page killed for memory). One command reads
4
+ // the page's memory at boot (title), in Playing on Driftwood, and at Driftwood's west edge where Sunscar's cell prepares:
5
+ // the owner ledger (`__wildshard.memory()`, GPU and RAM bytes by owner and kind), three.js's counts, the texture form this
6
+ // device loads, the grid's resident cells and claims, the JS heap (Chromium) and, on Chromium, the renderer and GPU
7
+ // process footprints. Phone tier, iPhone 17 Pro viewport (402x874, 3x pixel density), headless.
8
+ // scripts/browser-lane.sh node scripts/memory-proof.mjs --base=<staging or loopback url> [--engine=chromium|webkit]
9
+ // [--out=tmp/<lane>/memory-proof] [--label=<name>] [--edge=0] [--budget-mb=<n>]
10
+ // --budget-mb fails the run (exit 1) when the ledger's GPU+RAM peak passes n MB: the gate a later lane can hold.
11
+ import { spawnSync } from 'node:child_process';
12
+ import { mkdirSync, writeFileSync } from 'node:fs';
13
+ import { join, resolve as absolute } from 'node:path';
14
+ import { chromium, webkit } from 'playwright';
15
+ import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
16
+ import { saveFixture } from './debug-settings.mjs';
17
+ import { pageMemoryAttributionExpression } from './memory-report-snapshot.mjs';
18
+
19
+ /** @type {Record<string, string>} */
20
+ const args = Object.fromEntries(process.argv.slice(2).map(arg => /^--([^=]+)(?:=(.*))?$/u.exec(arg)).filter(match => match !== null).map(match => [match[1], match.at(2) ?? '1']));
21
+ const base = (args.base ?? '').replace(/\/$/u, '');
22
+ if (!/^https:\/\/(staging|preview)\.wildshard\.io$|^http:\/\/(127\.0\.0\.1|localhost):\d+$/u.test(base)) throw new Error('--base takes staging, preview or a loopback page: never production (J205)');
23
+ const engineName = args.engine ?? 'chromium';
24
+ if (engineName !== 'chromium' && engineName !== 'webkit') throw new Error(`No engine ${engineName}`);
25
+ const label = args.label ?? `${engineName}-${new URL(base).host.replaceAll(/[^a-z0-9]+/giu, '-')}`;
26
+ const out = absolute(args.out ?? 'tmp/memory-proof');
27
+ const budgetMB = args['budget-mb'] === undefined ? null : Number(args['budget-mb']);
28
+ const edge = args.edge !== '0';
29
+ mkdirSync(out, { recursive: true });
30
+ const MB = 1048576;
31
+ /** @param {number} ms */
32
+ const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms); });
33
+
34
+ const FOOTPRINT = String.raw`
35
+ import ctypes, json, sys
36
+ class R(ctypes.Structure):
37
+ _fields_ = [('uuid', ctypes.c_ubyte * 16)] + [(n, ctypes.c_uint64) for n in ('user_time','system_time','pkg_idle_wkups','interrupt_wkups','pageins','wired_size','resident_size','phys_footprint','proc_start_abstime','proc_exit_abstime')]
38
+ lib = ctypes.CDLL('/usr/lib/libproc.dylib'); out = {}
39
+ for p in sys.argv[1:]:
40
+ u = R()
41
+ out[p] = u.phys_footprint if lib.proc_pid_rusage(int(p), 0, ctypes.byref(u)) == 0 else None
42
+ print(json.dumps(out))
43
+ `;
44
+
45
+ /** In-page reader: plain data only, never a resource getter that could rebuild a retired resource. */
46
+ const PAGE_READ = `(() => {
47
+ const api = window.__wildshard, mem = (() => { try { return ${pageMemoryAttributionExpression}; } catch (e) { return { error: String(e) }; } })();
48
+ const group = (rows, key) => { const m = new Map(); for (const r of rows) { const k = key(r); const v = m.get(k) ?? { bytes: 0, n: 0 }; v.bytes += r.bytes; v.n++; m.set(k, v); }
49
+ return [...m.entries()].map(([k, v]) => ({ k, mb: Math.round(v.bytes / 1048576 * 10) / 10, n: v.n })).sort((a, b) => b.mb - a.mb).slice(0, 25); };
50
+ const rows = Array.isArray(mem?.allocations) ? mem.allocations : [];
51
+ let grid = null; try { const g = api?.shard?.grid; if (g) { const st = g.state(), res = g.residency?.();
52
+ grid = { inside: st.inside, home: st.home, feet: st.feet, residentMB: st.residentMB, playingMB: st.playingMB, strips: st.strips,
53
+ cells: st.cells.map(c => ({ slug: c.slug, cell: c.cell, shows: c.shows, drawn: c.drawn })), rings: { far: st.rings.far, l1: st.rings.l1, l0: st.rings.l0, inFlight: st.rings.inFlight, queued: st.rings.queued },
54
+ near: st.near, claims: res ? res.claims.map(c => ({ id: c.id ?? c.instance ?? c.key, bytes: c.bytes, kind: c.kind ?? c.category })) : null, cost: res?.cost ?? null }; } } catch (e) { grid = { error: String(e).slice(0, 200) }; }
55
+ let three = null; try { const r = api.requireWorld().game.renderer; three = { textures: r.info.memory.textures, geometries: r.info.memory.geometries, programs: r.info.programs?.length ?? null, pixelRatio: r.getPixelRatio() }; } catch {}
56
+ let textures = null; try { const t = api.textures?.(); textures = t ? { mode: t.mode, why: t.why, families: t.probe?.families ?? null } : null; } catch (e) { textures = { error: String(e).slice(0, 120) }; }
57
+ let audio = null; try { audio = api.requireWorld().audio.census(); } catch {}
58
+ return { href: location.href, heapMB: performance.memory ? Math.round(performance.memory.usedJSHeapSize / 1048576) : null,
59
+ totalsMB: mem?.totals ? { gpu: Math.round(mem.totals.gpu / 1048576), ram: Math.round(mem.totals.ram / 1048576) } : null,
60
+ unattributedMB: mem?.unattributed ? { gpu: Math.round(mem.unattributed.gpu / 1048576), ram: Math.round(mem.unattributed.ram / 1048576) } : null,
61
+ byOwner: group(rows, r => r.domain + ' ' + r.owner), byKind: group(rows, r => r.domain + ' ' + r.kind), byAsset: group(rows, r => r.domain + ' ' + r.owner + ' ' + r.asset),
62
+ // PZ22: each texture of 1 MB or more, whole, so a texture form change is read per texture, not only in the total
63
+ texRows: rows.filter(r => r.domain === 'gpu' && r.kind === 'texture' && r.bytes >= 1048576).sort((a, b) => b.bytes - a.bytes).slice(0, 40).map(r => JSON.parse(JSON.stringify(r))),
64
+ three, textures, grid, audio };
65
+ })()`;
66
+
67
+ /** @type {Record<string, unknown>} */
68
+ const result = { lane: 'opus-iosmem', engine: engineName, base, label, at: new Date().toISOString(), phases: [], errors: [] };
69
+ const browser = await (engineName === 'webkit' ? webkit : chromium).launch({ headless: true,
70
+ args: engineName === 'chromium' ? [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist', '--enable-precise-memory-info'] : [] });
71
+ let code = 0;
72
+ try {
73
+ const context = await browser.newContext({ viewport: { width: 402, height: 874 }, deviceScaleFactor: 3, isMobile: engineName === 'chromium', hasTouch: true,
74
+ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0.1 Mobile/15E148 Safari/604.1' });
75
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
76
+ await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
77
+ await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: { tier: 'phone', volume: 0 } });
78
+ await context.route('**/api/errors', route => route.fulfill({ status: 204, body: '' }));
79
+ const page = await context.newPage(); page.setDefaultTimeout(240_000);
80
+ page.on('pageerror', error => { /** @type {string[]} */ (result.errors).push(error.message.slice(0, 240)); });
81
+ const cdp = engineName === 'chromium' ? await browser.newBrowserCDPSession() : null;
82
+ const pageCdp = engineName === 'chromium' ? await context.newCDPSession(page) : null;
83
+ const heapProfile = args['heap-profile'] !== undefined && pageCdp !== null;
84
+ /** Chromium only: the live JS heap after a full collection, so garbage awaiting GC is told apart from what is held. */
85
+ const heapAfterGc = async () => { if (pageCdp === null) return null; await pageCdp.send('HeapProfiler.collectGarbage'); return Math.round((await pageCdp.send('Runtime.getHeapUsage')).usedSize / MB); };
86
+ const footprint = async () => {
87
+ if (cdp === null) return null;
88
+ const info = await cdp.send('SystemInfo.getProcessInfo'), pids = info.processInfo.filter(row => row.type === 'renderer' || row.type === 'GPU');
89
+ const sizes = JSON.parse(spawnSync('python3', ['-c', FOOTPRINT, ...pids.map(row => String(row.id))], { encoding: 'utf8' }).stdout || '{}');
90
+ const mb = (/** @type {string} */ type) => Math.round(pids.filter(row => row.type === type).reduce((sum, row) => sum + (sizes[String(row.id)] ?? 0), 0) / MB);
91
+ return { rendererMB: mb('renderer'), gpuMB: mb('GPU') };
92
+ };
93
+ const phase = async (/** @type {string} */ name) => {
94
+ const row = { phase: name, ...await page.evaluate(PAGE_READ), process: await footprint(), heapAfterGcMB: await heapAfterGc() };
95
+ row.processAfterGc = pageCdp === null ? null : await footprint();
96
+ /** @type {unknown[]} */ (result.phases).push(row);
97
+ await page.screenshot({ path: join(out, `${label}-${name}.jpg`), type: 'jpeg', quality: 60 }).catch(() => undefined);
98
+ const t = row.totalsMB;
99
+ console.log(`${name}: ledger gpu ${t?.gpu ?? '?'} MB ram ${t?.ram ?? '?'} MB, heap ${row.heapMB ?? '-'} MB (after GC ${row.heapAfterGcMB ?? '-'}), process ${JSON.stringify(row.process)}, three ${JSON.stringify(row.three)}, tex ${row.textures?.mode ?? '?'}, cells ${row.grid?.cells?.map((/** @type {any} */ c) => `${c.slug}:${JSON.stringify(c.shows)}`).join(' ') ?? '-'}`);
100
+ for (const top of row.byOwner.slice(0, 8)) console.log(` ${top.k} ${top.mb} MB (${top.n})`);
101
+ return row;
102
+ };
103
+ await page.goto(`${base}/?mute=1&nolock=1`, { waitUntil: 'load' });
104
+ await page.locator('.ws-main-select').waitFor({ state: 'visible', timeout: 120_000 });
105
+ await sleep(3000);
106
+ await phase('boot');
107
+ await page.locator('.ws-main-select').click();
108
+ if (await page.locator('#ws-name-box input').waitFor({ timeout: 15_000 }).then(() => true).catch(() => false)) { await page.locator('#ws-name-box input').fill('memproof'); await page.locator('#ws-name-box button[type=submit]').click(); }
109
+ await page.locator('.ws-menu-card').first().waitFor({ state: 'visible', timeout: 30_000 });
110
+ const index = await page.evaluate(() => [...document.querySelectorAll('.ws-menu-card')].findIndex(row => (row.textContent ?? '').includes('Driftwood Isle')));
111
+ if (index < 0) throw new Error('No Driftwood Isle card');
112
+ await page.locator('.ws-menu-dots i').nth(index).click();
113
+ if (heapProfile) { await pageCdp.send('HeapProfiler.enable'); await pageCdp.send('HeapProfiler.startSampling', { samplingInterval: 65536, includeObjectsCollectedByMajorGC: args['heap-profile'] === 'alloc', includeObjectsCollectedByMinorGC: args['heap-profile'] === 'alloc' }); }
114
+ await page.locator('.ws-menu-play').click();
115
+ await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 240_000, polling: 250 });
116
+ await sleep(2000);
117
+ await page.getByText('DONE', { exact: true }).click({ timeout: 2000 }).catch(() => undefined);
118
+ await sleep(10_000);
119
+ await phase('playing');
120
+ // 40 s more without moving: a page that keeps growing while the player stands still is the leak, not the walk.
121
+ /** @type {unknown[]} */ const still = []; result.still = still;
122
+ for (let i = 0; i < 4; i++) { await sleep(10_000); const at = await page.evaluate(() => ({ heapMB: (() => { const memory = /** @type {any} */ (performance).memory; return memory ? Math.round(memory.usedJSHeapSize / 1048576) : null; })(), loading: /** @type {any} */ (window).__wildshard.shard.grid.state().cells.filter((/** @type {any} */ c) => c.shows === 'loading').length })); still.push({ s: (i + 1) * 10, ...at, process: await footprint() }); console.log(`still +${(i + 1) * 10}s ${JSON.stringify(still.at(-1))}`); }
123
+ await phase('still');
124
+ if (heapProfile) {
125
+ const { profile } = await pageCdp.send('HeapProfiler.stopSampling');
126
+ /** @type {Map<string, number>} */ const self = new Map(), total = new Map();
127
+ const walk = (/** @type {any} */ node, /** @type {string[]} */ stack) => {
128
+ const f = node.callFrame, key = `${f.functionName === '' ? '(anon)' : f.functionName} ${f.url.split('/').pop()}:${f.lineNumber + 1}:${f.columnNumber + 1}`;
129
+ self.set(key, (self.get(key) ?? 0) + node.selfSize);
130
+ const next = [...stack, key]; for (const k of new Set(next)) total.set(k, (total.get(k) ?? 0) + node.selfSize);
131
+ for (const child of node.children) walk(child, next);
132
+ };
133
+ walk(profile.head, []);
134
+ const top = (/** @type {Map<string, number>} */ m) => [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, 60).map(([k, b]) => ({ k, mb: Math.round(b / MB * 10) / 10 }));
135
+ result.heapSelf = top(self); result.heapTotal = top(total);
136
+ console.log('heap self (live sampled):'); for (const row of /** @type {any[]} */ (result.heapSelf).slice(0, 25)) console.log(` ${row.mb} MB ${row.k}`);
137
+ }
138
+ if (edge) {
139
+ // Driftwood's west entryway toward Sunscar (grid-crossing-walk-proof's approach), placed by the harness pose, then 20 s for the neighbour to prepare.
140
+ for (const [x, z] of [[-235, -194], [-235, 0], [-245, 0]]) {
141
+ // the online page's server owns the position: place tells it (probe.ts `told`)
142
+ await page.evaluate(([px, pz]) => { const p = /** @type {any} */ (window).__wildshard.world.player; p.spawn(px, pz, p.yaw, Math.max(p.position.y, 0.5)); p.link?.place?.(p.position.x, p.position.y, p.position.z, p.yaw); }, [x, z]);
143
+ await sleep(4000);
144
+ }
145
+ await sleep(16_000);
146
+ await phase('edge');
147
+ }
148
+ const peak = Math.max(...(/** @type {any[]} */ (result.phases)).map(row => (row.totalsMB?.gpu ?? 0) + (row.totalsMB?.ram ?? 0)));
149
+ result.peakLedgerMB = peak;
150
+ if (budgetMB !== null && peak > budgetMB) { code = 1; console.log(`FAIL ledger peak ${peak} MB > budget ${budgetMB} MB`); }
151
+ await context.close();
152
+ } catch (error) { code = 1; /** @type {string[]} */ (result.errors).push(String(error).slice(0, 400)); console.log(`FAIL ${String(error).slice(0, 400)}`); }
153
+ finally {
154
+ writeFileSync(join(out, `${label}.json`), `${JSON.stringify(result, null, 2)}\n`);
155
+ await browser.close();
156
+ }
157
+ console.log(`memory proof ${label}: ${code === 0 ? 'done' : 'FAIL'} → ${join(out, `${label}.json`)}`);
158
+ process.exit(code);
@@ -4,10 +4,12 @@ export interface RequestRow {
4
4
  }
5
5
  export interface ScreenSample { t: number; phase: string; step: string; card: boolean; title: boolean; player: boolean; failCard: string; text: string }
6
6
  export interface Failure { shard: string; rule: string; url?: string; detail?: string }
7
- export type Outcome = 'play' | 'seat-wait' | 'title' | 'stalled' | 'error' | 'no-resume';
7
+ export type Outcome = 'play' | 'seat-wait' | 'title' | 'stalled' | 'error' | 'no-resume' | 'outside-world';
8
8
  export const DECK_SHARDS: readonly { slug: string; card: string }[];
9
9
  export const OPEN_PLOTS: readonly string[];
10
10
  export const ALL_SHARDS: readonly string[];
11
+ export function gridPlaces(slug: string, catalogue: { grid?: { cells?: readonly { slug?: unknown }[] } }): boolean;
12
+ export function screenKey(screen: { phase: string; step: string; error: string; failCard: string; title: boolean; player: boolean; progress: string }): string;
11
13
  export const SOLO_ONLY: RegExp;
12
14
  export const CLIENT_MANIFEST: RegExp;
13
15
  export const GRID_LAYOUT: RegExp;
@@ -19,6 +21,6 @@ export function textureForm(path: string): { name: string; form: 'img' | 'ktx2'
19
21
  export function judge(run: {
20
22
  shard: string; channel: 'staging' | 'preview'; mode: string; entry: string; rows: readonly RequestRow[];
21
23
  samples: readonly ScreenSample[]; outcome: Outcome; warm?: ReadonlySet<string>; layout?: boolean; walkthrough?: boolean;
22
- requireWorld?: boolean; proofError?: string; leaks?: number;
24
+ requireWorld?: boolean; proofError?: string; leaks?: number; placed?: boolean;
23
25
  }): Failure[];
24
26
  export function servedCounts(rows: readonly RequestRow[]): Record<string, number>;
@@ -11,6 +11,10 @@ export const DECK_SHARDS = Object.freeze([
11
11
  ]);
12
12
  /** Open Plots have no deck card (the open-plots audit): a player reaches them by a deep link with Developer on, or a resume. */
13
13
  export const OPEN_PLOTS = Object.freeze(['open-plot-thin-ice', 'open-plot-night-market', 'open-plot-mosslight-ruins']);
14
+ /** OF3, OF5b: whether the grid catalogue (`src/shared/game/grid/singleplayer.json`, its `grid.cells`) places a shard, so a world
15
+ * build may enter it. Thin Ice is a draft with no cell: a world build answers "Not in this world yet" for it.
16
+ * @param {string} slug @param {{ grid?: { cells?: readonly { slug?: unknown }[] } }} catalogue */
17
+ export const gridPlaces = (slug, catalogue) => (catalogue.grid?.cells ?? []).some(cell => cell.slug === slug);
14
18
  /** Every shard the proof covers, in run order. */
15
19
  export const ALL_SHARDS = Object.freeze([...DECK_SHARDS.map(shard => shard.slug), ...OPEN_PLOTS]);
16
20
 
@@ -33,7 +37,15 @@ export const CRITICAL_PHASES = Object.freeze(['start', 'download', 'load', 'none
33
37
  * text: string }} ScreenSample */
34
38
  /** One reason a run is red.
35
39
  * @typedef {{ shard: string, rule: string, url?: string, detail?: string }} Failure */
36
- /** @typedef {'play' | 'seat-wait' | 'title' | 'stalled' | 'error' | 'no-resume'} Outcome */
40
+ /** @typedef {'play' | 'seat-wait' | 'title' | 'stalled' | 'error' | 'no-resume' | 'outside-world'} Outcome */
41
+
42
+ /** OF5b: what counts as the screen changing, for the seat wait (10 s still at LOAD `server`) and the stall (60 s still, the game's
43
+ * own stuck watch, `stuckStep.ts`). The card's
44
+ * own state and its progress counters, never its free text: the card's clock and time-left tick every frame, and on a shard whose
45
+ * HUD has no quest lines (Template, Brasscap, Pastel Plain, Ink & Cel, the Open Plots) they fall inside any text prefix, so the
46
+ * screen never held still and those shards ran to the time limit instead of reaching the seat wait (buddy-engine's run, OF5b).
47
+ * @param {{ phase: string, step: string, error: string, failCard: string, title: boolean, player: boolean, progress: string }} screen */
48
+ export const screenKey = screen => JSON.stringify([screen.phase, screen.step, screen.error, screen.failCard, screen.title, screen.player, screen.progress]);
37
49
 
38
50
  /** A request that may fail without the run going red (OF5: telemetry, `/version.json` and the release read). Telemetry is
39
51
  * `/api/telemetry` and the error report `/api/errors`; the release read is the CDN's `/releases/<channel>.json` or the proof's
@@ -65,7 +77,7 @@ const failed = row => (row.servedBy === 'failed' && row.fail !== 'net::ERR_ABORT
65
77
  * The red rules of one entry. `warm` is the paths the warm visit read (undefined for the warm visit itself).
66
78
  * @param {{ shard: string, channel: 'staging' | 'preview', mode: string, entry: string, rows: readonly RequestRow[],
67
79
  * samples: readonly ScreenSample[], outcome: Outcome, warm?: ReadonlySet<string>, layout?: boolean, walkthrough?: boolean,
68
- * requireWorld?: boolean, proofError?: string, leaks?: number }} run
80
+ * requireWorld?: boolean, proofError?: string, leaks?: number, placed?: boolean }} run
69
81
  * @returns {Failure[]}
70
82
  */
71
83
  export function judge(run) {
@@ -104,14 +116,18 @@ export function judge(run) {
104
116
  }
105
117
  if (run.outcome === 'no-resume') out.push({ shard, rule: 'no-resume', detail: 'reopening the page showed the title, not the shard' });
106
118
  if ((run.leaks ?? 0) > 0) out.push({ shard, rule: 'offline-leak', detail: `${String(run.leaks)} reads reached the server while offline (the URLs are in the run's screens log)` });
107
- if (run.requireWorld === true && run.outcome !== 'play') out.push({ shard, rule: 'not-in-world', detail: run.outcome });
119
+ if (run.requireWorld === true && run.outcome !== 'play' && !(run.outcome === 'outside-world' && run.placed === false)) out.push({ shard, rule: 'not-in-world', detail: run.outcome });
120
+ // OF3: a world build never enters a shard its grid doesn't place (a draft such as Thin Ice): the title's "Not in this world yet"
121
+ // is the right end there, and wrong for a placed shard or a build with no world (preview opens every shard).
122
+ if (run.outcome === 'outside-world' && !(channel === 'staging' && run.placed === false))
123
+ out.push({ shard, rule: 'outside-world', detail: channel === 'staging' ? 'the grid places this shard, yet the page said it is not in this world' : 'a build with no world opens every shard' });
108
124
  // 6. A load that never finished with nothing else to blame.
109
125
  if (run.outcome === 'stalled' && out.length === 0) {
110
126
  const last = samples.at(-1);
111
127
  out.push({ shard, rule: 'stalled', detail: `${last?.phase ?? '?'}/${last?.step ?? '?'}` });
112
128
  }
113
- // 7. OF20: an offline entry reads the grid layout from the cache, and reads it at all.
114
- if (run.layout === true) {
129
+ // 7. OF20: an offline entry reads the grid layout from the cache, and reads it at all (a shard the world doesn't open loads none).
130
+ if (run.layout === true && run.outcome !== 'outside-world') {
115
131
  const layout = rows.filter(row => row.origin === 'page' && GRID_LAYOUT.test(pathOf(row.url)));
116
132
  if (layout.length === 0) out.push({ shard, rule: 'grid-layout-not-read', detail: 'the entry read no grid layout (a one-shard route, or none)' });
117
133
  for (const row of layout) if (row.servedBy !== 'service-worker') out.push({ shard, rule: 'grid-layout-not-cached', url: row.url, detail: row.servedBy });
@@ -44,7 +44,7 @@ import { join, resolve as resolvePath } from 'node:path';
44
44
  import { chromium } from 'playwright';
45
45
  import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
46
46
  import { saveFixture } from './debug-settings.mjs';
47
- import { ALL_SHARDS, DECK_SHARDS, judge, OPEN_PLOTS, pathOf, servedCounts } from './offline-proof-rules.mjs';
47
+ import { ALL_SHARDS, DECK_SHARDS, gridPlaces, judge, OPEN_PLOTS, pathOf, screenKey, servedCounts } from './offline-proof-rules.mjs';
48
48
  import { CHANNELS, RELEASE_PUBLIC_KEY } from './page-release/flow.mjs';
49
49
 
50
50
  /** @typedef {import('./offline-proof-rules.mjs').RequestRow} RequestRow */
@@ -77,6 +77,9 @@ const report = argv.includes('--report');
77
77
  const out = resolvePath(ROOT, option('out') ?? join('tmp', 'offline-proof', new Date().toISOString().replaceAll(/[:.]/gu, '-')));
78
78
  mkdirSync(out, { recursive: true });
79
79
  const STAGING = CHANNELS.staging;
80
+ /** The grid catalogue: a world build enters only the shards it places (OF3). It is this checkout's, so it matches a build of this
81
+ * tree (the default, or a `--base` served from it), not a build of another commit. */
82
+ const CATALOGUE = JSON.parse(readFileSync(join(ROOT, 'src/shared/game/grid/singleplayer.json'), 'utf8'));
80
83
  /** The stand-in door's world word: every proof shard on staging's grid. */
81
84
  const WORLD_WORD = Buffer.concat([Buffer.from([9]), Buffer.from(JSON.stringify({ cells: 20, shards: [...ALL_SHARDS] }))]);
82
85
  const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1';
@@ -200,6 +203,8 @@ const readScreen = () => {
200
203
  card, title: title && !card, player: world?.player !== undefined && world.player !== null && !card,
201
204
  phase: card ? (on instanceof HTMLElement ? on.dataset.phase ?? 'none' : 'none') : title ? 'title' : 'page',
202
205
  step: load instanceof HTMLElement ? load.dataset.step ?? '' : '',
206
+ // OF5b: the card's progress counters, which hold still while it waits on the seat (its clock and time-left never do)
207
+ progress: load instanceof HTMLElement ? [load.dataset.setup, load.dataset.readBytes, load.dataset.streamedBytes, load.dataset.spawnFilesDone, load.dataset.serverFiles].join('|') : '',
203
208
  error: (document.querySelector('.ws-load-error')?.textContent ?? '').replaceAll(/\s+/gu, ' ').slice(0, 300),
204
209
  // oxlint-disable-next-line unicorn/prefer-dom-node-text-content -- the text a player sees, not hidden templates
205
210
  failCard: fail instanceof HTMLElement ? fail.innerText.replaceAll(/\s+/gu, ' ').slice(0, 300) : '',
@@ -303,7 +308,8 @@ async function enter(run) {
303
308
  try {
304
309
  const open = OPEN_PLOTS.includes(slug) && entry === 'deck' ? `/?chunk=${slug}&skipintro&mute=1` : '/?mute=1';
305
310
  // a deep link is the entry itself: its reads are the card's from the first one
306
- if (open !== '/?mute=1') phase = 'none';
311
+ let linked = open !== '/?mute=1';
312
+ if (linked) phase = 'none';
307
313
  const hitsBefore = stamperHits;
308
314
  proxyOffline = mode === 'offline' && channel === 'staging' && jobs === 1;
309
315
  leakFrom = () => stamperHits - hitsBefore;
@@ -321,7 +327,7 @@ async function enter(run) {
321
327
  if (index === -1) {
322
328
  // a shard this build's deck doesn't show (Pastel Plain, Ink & Cel): the deep link with Developer on, as for Open Plots
323
329
  consoleLines.push(`no deck card "${card}" (deck: ${names.join(', ')}): entered by ?chunk=`);
324
- phase = 'none';
330
+ phase = 'none'; linked = true;
325
331
  await page.goto(new URL(`/?chunk=${slug}&skipintro&mute=1`, ORIGINS[channel]).href, { waitUntil: 'commit', timeout: 60_000 });
326
332
  } else {
327
333
  await page.locator(`.ws-menu-dots i[data-i="${String(index)}"]`).click();
@@ -338,15 +344,18 @@ async function enter(run) {
338
344
  if (screen === undefined) continue;
339
345
  if (await page.locator('.ws-load-play').isVisible().catch(() => false)) await page.locator('.ws-load-play').click({ timeout: 3000 }).catch(() => undefined);
340
346
  cardSeen ||= screen.card;
341
- const now = JSON.stringify([screen.phase, screen.step, screen.error, screen.text.slice(0, 200)]);
347
+ const now = screenKey(screen);
342
348
  if (now !== key) { key = now; changed = Date.now(); }
343
349
  if (screen.player) { outcome = 'play'; break; }
344
350
  if (screen.error !== '') { outcome = 'error'; break; }
345
351
  if (cardSeen && screen.title) { outcome = 'title'; break; }
346
352
  if (!cardSeen && screen.title && entry === 'resume' && at() - tappedAt > 20_000) { outcome = 'no-resume'; break; }
353
+ // OF3: a world build's title after a link to a shard its grid doesn't place (judged against the catalogue)
354
+ // (a link's answer only: a closed deck card shows the same badge)
355
+ if (linked && !cardSeen && screen.title && /not in this world yet/iu.test(screen.text) && at() - tappedAt > 5000) { outcome = 'outside-world'; break; }
347
356
  // a staging-like page waits on the seat, which the stand-in door never gives
348
357
  if (channel === 'staging' && screen.phase === 'load' && screen.step === 'server' && Date.now() - changed > 10_000) { outcome = 'seat-wait'; break; }
349
- if (Date.now() - changed > (mode === 'slow' ? 90_000 : 45_000) || at() - tappedAt > limit) { outcome = 'stalled'; break; }
358
+ if (Date.now() - changed > (mode === 'slow' ? 90_000 : 60_000) || at() - tappedAt > limit) { outcome = 'stalled'; break; }
350
359
  }
351
360
  outcomeMs = at() - tappedAt;
352
361
  await shot(outcome);
@@ -442,7 +451,7 @@ function record(channel, mode, slug, entry, visit, warm, extra = {}) {
442
451
  const layout = channel === 'staging' && mode === 'offline' && (entry === 'deck' || extra.walkthrough === true);
443
452
  const failures = judge({ shard: slug, channel, mode, entry, rows: visit.rows, samples: visit.samples,
444
453
  outcome: visit.outcome, ...warm === undefined ? {} : { warm }, layout, proofError: visit.proofError, leaks: visit.leaks,
445
- requireWorld: requireWorld && !mode.startsWith('warm'), ...extra });
454
+ requireWorld: requireWorld && !mode.startsWith('warm'), placed: gridPlaces(slug, CATALOGUE), ...extra });
446
455
  if (channel === 'staging' && !visit.world) failures.unshift({ shard: slug, rule: 'proof-not-a-world-build', detail: 'the page had no __WS_WORLD__ stamp' });
447
456
  const result = { shard: slug, channel, mode, entry, outcome: visit.outcome, ms: visit.ms, lastCard: visit.lastCard, served: servedCounts(visit.rows),
448
457
  swSoloReads: visit.rows.filter(row => row.origin === 'sw' && /serverWorker|serverRuntime|\/assets\/spawn\/server\//u.test(row.url)).length,
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env node
2
+ // S12 (J330): does a shard page load and look the same with its phone textures cut to a tier size by the cook's mip trim
3
+ // (src/cook/game/tierTextures.ts)? Phone tier, iPhone 17 Pro viewport, headless. Every `.glb` and `.ktx2` the page reads
4
+ // is fetched from the served build and, with --max, answered with `tierGlb` / `trimKtx2` at that size, so the page reads
5
+ // exactly what a trim-only cook would ship. Reports the bytes those responses carried, the page's GPU ledger and three's
6
+ // texture count once the player stands in the world, and saves a screenshot to compare.
7
+ // scripts/browser-lane.sh node --import ./scripts/bake-loader.mjs scripts/tier-textures-proof.mjs --base=http://127.0.0.1:<port>
8
+ // [--engine=chromium|webkit] [--slug=pine-hollow] [--max=512] [--out=tmp/<lane>/tier-proof] [--label=<name>]
9
+ // Loopback only: never staging or production.
10
+ import { mkdirSync, writeFileSync } from 'node:fs';
11
+ import { join, resolve as absolute } from 'node:path';
12
+ import { chromium, webkit } from 'playwright';
13
+ import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
14
+ import { saveFixture } from './debug-settings.mjs';
15
+ import { pageMemoryAttributionExpression } from './memory-report-snapshot.mjs';
16
+
17
+ const { tierGlb, trimKtx2 } = await import('../src/cook/game/tierTextures.ts');
18
+
19
+ /** @type {Record<string, string>} */
20
+ const args = Object.fromEntries(process.argv.slice(2).map(arg => /^--([^=]+)(?:=(.*))?$/u.exec(arg)).filter(match => match !== null).map(match => [match[1], match.at(2) ?? '1']));
21
+ const base = (args.base ?? '').replace(/\/$/u, '');
22
+ if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/u.test(base)) throw new Error('--base takes a loopback build only');
23
+ const engineName = args.engine ?? 'chromium', slug = args.slug ?? 'pine-hollow', max = args.max === undefined ? 0 : Number(args.max);
24
+ if (engineName !== 'chromium' && engineName !== 'webkit') throw new Error(`No engine ${engineName}`);
25
+ const label = args.label ?? `${engineName}-${max === 0 ? 'master' : `max${max}`}`, out = absolute(args.out ?? 'tmp/tier-proof');
26
+ mkdirSync(out, { recursive: true });
27
+ const MB = 1e6;
28
+ /** @param {number} ms */
29
+ const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms); });
30
+
31
+ const READ = `(() => {
32
+ const api = window.__wildshard, mem = (() => { try { return ${pageMemoryAttributionExpression}; } catch (e) { return { error: String(e) }; } })();
33
+ const rows = Array.isArray(mem?.allocations) ? mem.allocations : [], kinds = {};
34
+ for (const r of rows) { const k = r.domain + ' ' + r.kind; kinds[k] = (kinds[k] ?? 0) + r.bytes; }
35
+ let three = null; try { const r = api.requireWorld().game.renderer; three = { textures: r.info.memory.textures, geometries: r.info.memory.geometries }; } catch {}
36
+ // Decoded texture bytes, once per texture the scene draws: a compressed texture's transcoded levels as uploaded, an
37
+ // image's RGBA8 levels (a third more for mips). What the GPU holds for the page's textures, not counting render targets.
38
+ let textureBytes = null; try {
39
+ const world = api.requireWorld(), scene = world.game?.scene ?? world.scene, seen = new Set(); let total = 0;
40
+ scene.traverse(object => { for (const material of [object.material ?? []].flat()) for (const value of Object.values(material)) {
41
+ if (value === null || typeof value !== 'object' || value.isTexture !== true || seen.has(value)) continue;
42
+ seen.add(value);
43
+ if (value.isCompressedTexture === true) total += (value.mipmaps ?? []).reduce((sum, level) => sum + (level.data?.byteLength ?? 0), 0);
44
+ else { const image = value.image; if (image?.width > 0) total += image.width * image.height * 4 * (value.generateMipmaps === false ? 1 : 4 / 3); }
45
+ } });
46
+ textureBytes = { total, textures: seen.size };
47
+ } catch (e) { textureBytes = { error: String(e).slice(0, 160) }; }
48
+ let mode = null; try { mode = api.textures?.()?.mode ?? null; } catch {}
49
+ return { totals: mem?.totals ?? null, kinds, three, mode, textureBytes };
50
+ })()`;
51
+
52
+ const result = { engine: engineName, base, slug, max, label, at: new Date().toISOString(), outcome: 'none', errors: /** @type {string[]} */ ([]),
53
+ glb: { files: 0, served: 0, read: 0 }, ktx2: { files: 0, served: 0, read: 0 }, page: /** @type {unknown} */ (null) };
54
+ const browser = await (engineName === 'webkit' ? webkit : chromium).launch({ headless: true,
55
+ args: engineName === 'chromium' ? [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] : [] });
56
+ let code = 0;
57
+ try {
58
+ const context = await browser.newContext({ viewport: { width: 402, height: 874 }, deviceScaleFactor: 3, isMobile: engineName === 'chromium', hasTouch: true,
59
+ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0.1 Mobile/15E148 Safari/604.1' });
60
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
61
+ await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: { tier: 'phone', volume: 0 } });
62
+ await context.route('**/api/errors', route => route.fulfill({ status: 204, body: '' }));
63
+ await context.route(/\.(?:glb|ktx2)(?:\?.*)?$/u, async route => {
64
+ const response = await route.fetch(), body = new Uint8Array(await response.body());
65
+ const glb = /\.glb(?:\?|$)/u.test(route.request().url()), row = glb ? result.glb : result.ktx2;
66
+ /** @type {Uint8Array} */
67
+ let read = body;
68
+ try { if (max !== 0 && response.status() === 200) read = glb ? tierGlb(body, max) : trimKtx2(body, max); }
69
+ catch (error) { result.errors.push(`trim ${route.request().url()}: ${String(error).slice(0, 160)}`); }
70
+ row.files++; row.served += body.length; row.read += read.length;
71
+ const headers = { ...response.headers() };
72
+ delete headers['content-length']; delete headers['content-encoding']; delete headers.etag;
73
+ await route.fulfill({ status: response.status(), headers, body: Buffer.from(read) });
74
+ });
75
+ const page = await context.newPage(); page.setDefaultTimeout(240_000);
76
+ page.on('pageerror', error => { result.errors.push(error.message.slice(0, 240)); });
77
+ await page.goto(`${base}/?chunk=${slug}&skipintro&mute=1&nolock=1`, { waitUntil: 'commit', timeout: 120_000 });
78
+ const started = Date.now();
79
+ for (;;) {
80
+ await sleep(500);
81
+ if (Date.now() - started > 240_000) { result.outcome = 'stalled'; break; }
82
+ if (await page.locator('.ws-load-play').isVisible().catch(() => false)) await page.locator('.ws-load-play').click({ timeout: 3000 }).catch(() => undefined);
83
+ const ready = await page.evaluate(() => {
84
+ const api = /** @type {any} */ (window).__wildshard; let world = null; try { world = api?.requireWorld?.() ?? null; } catch { /* not yet */ }
85
+ return world?.player !== undefined && world?.player !== null && document.getElementById('hud')?.classList.contains('intro') !== true;
86
+ }).catch(() => false);
87
+ if (ready) { result.outcome = 'play'; break; }
88
+ }
89
+ await sleep(12_000);
90
+ result.page = await page.evaluate(READ);
91
+ await page.screenshot({ path: join(out, `${label}.png`) }).catch(() => undefined);
92
+ if (result.outcome !== 'play') code = 1;
93
+ } catch (error) {
94
+ result.errors.push(String(error).slice(0, 400)); code = 1;
95
+ } finally {
96
+ await browser.close();
97
+ }
98
+ writeFileSync(join(out, `${label}.json`), `${JSON.stringify(result, null, 2)}\n`);
99
+ const page = /** @type {any} */ (result.page);
100
+ console.log(`${label}: ${result.outcome}, mode ${page?.mode ?? '?'}, glb ${result.glb.files} files ${(result.glb.served / MB).toFixed(2)} -> ${(result.glb.read / MB).toFixed(2)} MB, ktx2 ${result.ktx2.files} files ${(result.ktx2.served / MB).toFixed(2)} -> ${(result.ktx2.read / MB).toFixed(2)} MB, decoded textures ${((page?.textureBytes?.total ?? 0) / MB).toFixed(2)} MB in ${page?.textureBytes?.textures ?? page?.textureBytes?.error ?? '?'}, three textures ${page?.three?.textures ?? '?'}, errors ${result.errors.length}`);
101
+ process.exit(code);
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ // S12 (J330): a shard's phone textures cooked from its masters by mip trim, measured against what phones read today.
3
+ // node --import ./scripts/bake-loader.mjs scripts/tier-textures.mjs out/pine-hollow [--max=512] [--out=tmp/<lane>/phone]
4
+ // Reads an opened product dir (`out/<slug>`: discovery.json's KTX2 table and mounts/), no shardfile upload, no network.
5
+ // For every row of the shard's phone table it prints three columns: today's phone file (a hand-made 6×6 / 512 set or a
6
+ // GPU twin), the desktop master trimmed to --max by `trimKtx2`/`tierGlb` (what a trim-only cook would ship), and today's
7
+ // phone file trimmed to --max. Bytes are file bytes; GPU is `ktx2GpuBytes`, mips included. --out writes the trimmed
8
+ // phone files at their URL paths, for a browser to load.
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
10
+ import { dirname, join, resolve } from 'node:path';
11
+
12
+ const { glbImages, isKtx2, ktx2GpuBytes, tierGlb, trimKtx2 } = await import('../src/cook/game/tierTextures.ts');
13
+
14
+ const args = process.argv.slice(2), flag = (/** @type {string} */ name) => args.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3);
15
+ const product = args.find(arg => !arg.startsWith('--'));
16
+ if (product === undefined) throw new Error('usage: tier-textures <product-dir> [--max=512] [--out=dir]');
17
+ const max = Number(flag('max') ?? 512), out = flag('out');
18
+ const slug = product.replace(/\/$/u, '').split('/').pop() ?? '';
19
+ const discovery = JSON.parse(readFileSync(join(product, 'mounts/shardfiles', slug, 'discovery.json'), 'utf8'));
20
+ /** @type {{phone: Record<string, string>, desktop: Record<string, string>}} */
21
+ const table = discovery.native.ktx2.args[0].shard;
22
+ /** @param {string} url @returns {Uint8Array | undefined} */
23
+ const read = url => { const path = join(product, 'mounts', url); return existsSync(path) ? new Uint8Array(readFileSync(path)) : undefined; };
24
+ /** @param {string} url @param {Uint8Array} bytes @returns {Uint8Array} */
25
+ const trim = (url, bytes) => (url.endsWith('.glb') ? tierGlb(bytes, max) : trimKtx2(bytes, max));
26
+ /** @param {string} url @param {Uint8Array} bytes @returns {number} */
27
+ const gpu = (url, bytes) => {
28
+ if (url.endsWith('.ktx2')) return isKtx2(bytes) ? ktx2GpuBytes(bytes) : 0;
29
+ if (url.endsWith('.glb')) return glbImages(bytes).reduce((total, image) => total + (isKtx2(image.bytes) ? ktx2GpuBytes(image.bytes) : 0), 0);
30
+ return 0;
31
+ };
32
+ /** The desktop master of a phone source: the same source, or its name without the `.phone` / `-phone` mark. */
33
+ /** @param {string} source @returns {string | undefined} */
34
+ const master = source => table.desktop[source] ?? table.desktop[source.replace(/\.phone\./u, '.')] ?? table.desktop[source.replace(/-phone\./u, '.')];
35
+
36
+ /** @type {Record<string, [number, number]>} */
37
+ const sum = { today: [0, 0], master: [0, 0], cooked: [0, 0], trimmed: [0, 0] };
38
+ let rows = 0, missing = 0, mastered = 0;
39
+ for (const [source, phoneUrl] of Object.entries(table.phone)) {
40
+ if (!/\.(?:glb|ktx2)$/u.test(phoneUrl)) continue;
41
+ const phone = read(phoneUrl);
42
+ if (phone === undefined) { missing++; continue; }
43
+ rows++;
44
+ const masterUrl = master(source), masterBytes = masterUrl === undefined ? undefined : read(masterUrl);
45
+ const cooked = masterBytes === undefined || masterUrl === undefined ? trim(phoneUrl, phone) : trim(masterUrl, masterBytes);
46
+ if (masterBytes !== undefined) mastered++;
47
+ const trimmed = trim(phoneUrl, phone);
48
+ /** @param {string} key @param {string} url @param {Uint8Array} bytes */
49
+ const add = (key, url, bytes) => { const row = sum[key] ?? [0, 0]; row[0] += bytes.length; row[1] += gpu(url, bytes); sum[key] = row; };
50
+ add('today', phoneUrl, phone);
51
+ add('master', masterUrl ?? phoneUrl, masterBytes ?? phone);
52
+ add('cooked', masterUrl ?? phoneUrl, cooked);
53
+ add('trimmed', phoneUrl, trimmed);
54
+ if (out !== undefined) { const path = resolve(out, `.${phoneUrl}`); mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, trimmed); }
55
+ }
56
+ const mb = (/** @type {number} */ n) => (n / 1e6).toFixed(2);
57
+ console.log(`${slug} phone table: ${rows} KTX2/GLB rows (${mastered} with a desktop master, ${missing} not in the product), --max=${max}`);
58
+ for (const [key, label] of [['today', 'phone today'], ['master', 'desktop masters'], ['cooked', `masters trimmed to ${max}`], ['trimmed', `phone today trimmed to ${max}`]]) {
59
+ console.log(`${label.padEnd(28)} file ${mb(sum[key]?.[0] ?? 0).padStart(7)} MB GPU ${mb(sum[key]?.[1] ?? 0).padStart(7)} MB`);
60
+ }
@@ -567,6 +567,7 @@
567
567
  "worker-client-play.mjs",
568
568
  "worker-client-proof.mjs",
569
569
  "worker-client-saves.mjs",
570
+ "worker-client-slug.mjs",
570
571
  "**/*.test.*"
571
572
  ],
572
573
  "files": [