@wildshard/engine 0.1.15 → 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 (262) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/index.html +157 -11
  3. package/lint/engine-sides.json +23 -0
  4. package/lint/host-callback-syntax.mjs +2 -1
  5. package/lint/host-callbacks.mjs +3 -3
  6. package/lint/host-files.mjs +5 -4
  7. package/lint/host-register.json +496 -0
  8. package/lint/no-base64.mjs +3 -1
  9. package/lint/ratchet.json +2 -2
  10. package/lint/shard-imports.d.mts +1 -0
  11. package/lint/shard-imports.mjs +60 -13
  12. package/lint/shard-source.d.mts +9 -0
  13. package/lint/shard-source.mjs +91 -0
  14. package/lint/shardfile-boundaries.mjs +10 -8
  15. package/lint/sim-closure.mjs +6 -3
  16. package/lint/wildshard-plugin.d.ts +4 -0
  17. package/lint/wildshard-plugin.js +44 -27
  18. package/package.json +24 -6
  19. package/scripts/app-build/buildIdentity.d.mts +3 -1
  20. package/scripts/app-build/buildIdentity.mjs +25 -5
  21. package/scripts/app-build/builtAt.d.mts +4 -0
  22. package/scripts/app-build/builtAt.mjs +21 -0
  23. package/scripts/app-build/outputProducts.d.mts +3 -0
  24. package/scripts/app-build/outputProducts.mjs +31 -0
  25. package/scripts/app-build/serviceWorker.ts +16 -2
  26. package/scripts/app-build/versionFiles.ts +2 -1
  27. package/scripts/app-build-pipeline.mjs +7 -1
  28. package/scripts/audio-download-proof.mjs +843 -0
  29. package/scripts/build-app.mjs +4 -0
  30. package/scripts/build-mirror.d.mts +2 -0
  31. package/scripts/build-mirror.mjs +5 -4
  32. package/scripts/built-product.mjs +3 -3
  33. package/scripts/cell-mem/metrics-preload.mjs +65 -0
  34. package/scripts/cell-mem-bench.mjs +130 -0
  35. package/scripts/check-chunks.mjs +2 -1
  36. package/scripts/check-devserver.mjs +1 -1
  37. package/scripts/chromium-keychain-check.mjs +4 -2
  38. package/scripts/chromium-keychain.mjs +3 -1
  39. package/scripts/cook.mjs +7 -3
  40. package/scripts/devices.d.mts +4 -0
  41. package/scripts/devices.mjs +39 -0
  42. package/scripts/devserver-client.d.mts +7 -0
  43. package/scripts/devserver-client.mjs +85 -0
  44. package/scripts/doctor-proof.mjs +1 -1
  45. package/scripts/e2e-faults.mjs +159 -0
  46. package/scripts/engine-ci-budget.ts +7 -1
  47. package/scripts/format-lock.mjs +20 -11
  48. package/scripts/generate-title-launch.mjs +3 -2
  49. package/scripts/grid-crossing-walk-proof.mjs +30 -11
  50. package/scripts/heavy-lane.py +25 -1
  51. package/scripts/host-ruler/register-migrate.mjs +242 -0
  52. package/scripts/host-ruler/register.d.mts +36 -0
  53. package/scripts/host-ruler/register.mjs +116 -0
  54. package/scripts/host-ruler/roots.d.mts +29 -0
  55. package/scripts/host-ruler/roots.mjs +333 -0
  56. package/scripts/host-ruler/server-roots.d.mts +23 -0
  57. package/scripts/host-ruler/server-roots.mjs +272 -0
  58. package/scripts/main-watch.d.mts +1 -1
  59. package/scripts/main-watch.mjs +10 -6
  60. package/scripts/map-hash.mjs +3 -6
  61. package/scripts/memory-proof.mjs +158 -0
  62. package/scripts/mmo-bots.mjs +2 -2
  63. package/scripts/offline-proof-rules.d.mts +5 -2
  64. package/scripts/offline-proof-rules.mjs +43 -6
  65. package/scripts/offline-proof.mjs +15 -6
  66. package/scripts/online-rig.mjs +4 -4
  67. package/scripts/page-release/flow.d.mts +1 -0
  68. package/scripts/page-release/flow.mjs +6 -2
  69. package/scripts/page-release.mjs +5 -1
  70. package/scripts/physics-route.json +0 -71
  71. package/scripts/pins-catalogue.ts +103 -0
  72. package/scripts/pins-reuse.mjs +3 -1
  73. package/scripts/pins.ts +22 -14
  74. package/scripts/preview-grid.ts +203 -0
  75. package/scripts/road-preload-proof.mjs +167 -0
  76. package/scripts/server-release/publish.mjs +2 -2
  77. package/scripts/server-release/served-slug.d.mts +2 -0
  78. package/scripts/server-release/served-slug.mjs +10 -0
  79. package/scripts/server-release/sign.d.mts +1 -0
  80. package/scripts/server-release/sign.mjs +3 -7
  81. package/scripts/shard-components.mjs +0 -2
  82. package/scripts/shard-outputs.d.mts +8 -0
  83. package/scripts/shard-outputs.mjs +45 -11
  84. package/scripts/side-parity.d.mts +2 -1
  85. package/scripts/side-parity.mjs +25 -4
  86. package/scripts/test-amber.d.mts +1 -0
  87. package/scripts/test-amber.mjs +10 -0
  88. package/scripts/test-products.json +3 -3
  89. package/scripts/tier-textures-proof.mjs +101 -0
  90. package/scripts/tier-textures.mjs +60 -0
  91. package/scripts/tracked-public.d.mts +1 -0
  92. package/scripts/tracked-public.mjs +17 -0
  93. package/scripts/tsconfig.json +1 -0
  94. package/scripts/vps/wildshard-config +79 -23
  95. package/scripts/worker-client-play.mjs +1 -0
  96. package/scripts/worker-client-proof.mjs +1 -1
  97. package/scripts/worker-client-slug.mjs +44 -0
  98. package/src/cli/engine.mjs +8 -0
  99. package/src/client/app/bootRoute.ts +4 -1
  100. package/src/client/app/dropModal.ts +15 -2
  101. package/src/client/app/entry.ts +96 -13
  102. package/src/client/app/slugPath.ts +5 -0
  103. package/src/client/engine/audio/Audio.ts +20 -2
  104. package/src/client/engine/boot/bakedTextures.ts +3 -2
  105. package/src/client/engine/boot/bootTrace.ts +6 -1
  106. package/src/client/engine/boot/bytes.ts +4 -3
  107. package/src/client/engine/boot/clearDownloads.ts +1 -1
  108. package/src/client/engine/boot/contentRead.ts +4 -0
  109. package/src/client/engine/boot/dropNotice.ts +20 -6
  110. package/src/client/engine/boot/gpuFiles.ts +25 -2
  111. package/src/client/engine/boot/lastEnd.ts +8 -2
  112. package/src/client/engine/boot/parsedPages.ts +127 -58
  113. package/src/client/engine/boot/shardPrefetch.ts +7 -1
  114. package/src/client/engine/boot/sw.ts +19 -0
  115. package/src/client/engine/build.d.ts +2 -0
  116. package/src/client/engine/core/Game.ts +29 -3
  117. package/src/client/engine/core/GpuRecovery.ts +7 -0
  118. package/src/client/engine/core/Volumetrics.ts +5 -0
  119. package/src/client/engine/core/assets.ts +27 -20
  120. package/src/client/engine/core/bootstrap.ts +5 -3
  121. package/src/client/engine/core/ktx2.ts +84 -11
  122. package/src/client/engine/debug/probe.ts +18 -1
  123. package/src/client/engine/explore/Compare.ts +2 -2
  124. package/src/client/engine/explore/TouchFly.ts +3 -5
  125. package/src/client/engine/fx/LightPool.ts +41 -1
  126. package/src/client/engine/input/dom.ts +12 -0
  127. package/src/client/engine/net/predictor.ts +6 -2
  128. package/src/client/engine/player/Player.ts +10 -2
  129. package/src/client/engine/player/TouchControls.ts +12 -4
  130. package/src/client/engine/pwa/sw.js +59 -11
  131. package/src/client/engine/render/drawCheck.ts +96 -0
  132. package/src/client/engine/render/precompile.ts +20 -14
  133. package/src/client/engine/saves/staleBuildNote.ts +46 -0
  134. package/src/client/engine/telemetry/browserErrors.ts +161 -21
  135. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  136. package/src/client/engine/telemetry/screenOutbox.ts +61 -0
  137. package/src/client/engine/telemetry/staleBuildReport.ts +12 -0
  138. package/src/client/engine/ui/DeathFade.ts +99 -11
  139. package/src/client/engine/ui/ErrorModal.ts +13 -6
  140. package/src/client/engine/ui/Feedback.ts +2 -1
  141. package/src/client/engine/ui/Loading.ts +10 -6
  142. package/src/client/engine/ui/Map.ts +2 -1
  143. package/src/client/engine/ui/WeaponStrip.ts +2 -1
  144. package/src/client/engine/ui/backGuard.ts +104 -0
  145. package/src/client/engine/ui/hudAdapters.ts +30 -4
  146. package/src/client/engine/ui/loading.css +17 -0
  147. package/src/client/engine/ui/namePrompt.ts +6 -5
  148. package/src/client/engine/ui/styles/combat.css +12 -0
  149. package/src/client/engine/ui/styles/namePrompt.css +4 -2
  150. package/src/client/game/boot/audio.generated.ts +0 -396
  151. package/src/client/game/boot/bytes.generated.ts +42 -71
  152. package/src/client/game/boot/versions.generated.ts +0 -13
  153. package/src/client/game/compendium/keepsakes.ts +16 -6
  154. package/src/client/game/grapple/tool.ts +10 -7
  155. package/src/client/game/grid/area.ts +38 -0
  156. package/src/client/game/grid/cellLoading.ts +23 -12
  157. package/src/client/game/grid/cellScreens.ts +39 -74
  158. package/src/client/game/grid/live.ts +28 -2
  159. package/src/client/game/grid/liveSession.ts +54 -10
  160. package/src/client/game/grid/menu.ts +4 -0
  161. package/src/client/game/grid/nearPlaceholderPlan.ts +8 -0
  162. package/src/client/game/grid/nearPlaceholderView.ts +9 -3
  163. package/src/client/game/grid/neighbourPanels.ts +10 -1
  164. package/src/client/game/grid/oneWayIn.ts +92 -27
  165. package/src/client/game/grid/pageEntry.ts +19 -0
  166. package/src/client/game/grid/pageShell.ts +1 -1
  167. package/src/client/game/grid/placedCards.ts +55 -0
  168. package/src/client/game/grid/placedCells.ts +131 -0
  169. package/src/client/game/grid/plotAudio.ts +114 -0
  170. package/src/client/game/grid/products.ts +55 -5
  171. package/src/client/game/grid/regionalRuntime.ts +6 -0
  172. package/src/client/game/grid/regionalWorld.ts +15 -2
  173. package/src/client/game/grid/roadCull.ts +44 -14
  174. package/src/client/game/grid/roadLookPlatform.ts +2 -2
  175. package/src/client/game/grid/roadTileBacking.ts +13 -3
  176. package/src/client/game/grid/session.ts +47 -22
  177. package/src/client/game/grid/shardfileFar.ts +9 -3
  178. package/src/client/game/grid/spawnGround.ts +68 -0
  179. package/src/client/game/grid/voidLook.ts +29 -23
  180. package/src/client/game/loot/runtime.ts +3 -1
  181. package/src/client/game/mainMenu.ts +14 -6
  182. package/src/client/game/riding/hud.ts +6 -4
  183. package/src/client/game/session/finish.ts +22 -4
  184. package/src/client/game/session/play.ts +8 -2
  185. package/src/client/game/session/session.ts +4 -1
  186. package/src/client/game/shard/titleList.ts +6 -2
  187. package/src/client/game/shardfile/clientWorker.ts +43 -13
  188. package/src/client/game/shardfile/serverRoute.ts +10 -22
  189. package/src/client/game/slugPage.css +11 -0
  190. package/src/client/game/slugPage.ts +84 -0
  191. package/src/client/game/systems/viewmodel/heldView.ts +6 -3
  192. package/src/client/game/titleDeck.ts +56 -32
  193. package/src/client/host/online/doctor.ts +7 -6
  194. package/src/client/host/online/linkScreens.ts +16 -0
  195. package/src/client/host/online/release.ts +51 -5
  196. package/src/client/host/online/shell.ts +62 -27
  197. package/src/client/host/standalone/shell.ts +7 -3
  198. package/src/cook/game/audioReport.ts +57 -0
  199. package/src/cook/game/entryTotals.ts +26 -6
  200. package/src/cook/game/installedRuntimeReads.ts +3 -0
  201. package/src/cook/game/shardCook.ts +38 -8
  202. package/src/cook/game/tierTextures.ts +276 -0
  203. package/src/e2e/smoke/game.ts +19 -14
  204. package/src/e2e/smoke/page-globals.d.ts +9 -8
  205. package/src/e2e/smoke/template2.spec.ts +8 -7
  206. package/src/server/engine/sim/respawn.ts +6 -1
  207. package/src/server/engine/sim.ts +3 -0
  208. package/src/server/game/grid/simulation.ts +35 -0
  209. package/src/server/game/loot/harvest.ts +2 -0
  210. package/src/server/game/loot/keepsakeProgression.ts +40 -0
  211. package/src/server/game/loot/playerOwned.ts +5 -1
  212. package/src/server/game/plugin/simulation.ts +4 -0
  213. package/src/server/game/population/nativeBake.ts +2 -1
  214. package/src/server/game/quest/chapterRecords.ts +2 -0
  215. package/src/server/game/quest/serverChapters.ts +4 -0
  216. package/src/server/game/quest/serverDoors.ts +11 -5
  217. package/src/server/game/roomRespawn.ts +4 -0
  218. package/src/server/game/shardfile/installedSides.ts +18 -0
  219. package/src/server/game/shardfile/nativeAssemblyHosts.ts +19 -10
  220. package/src/server/game/shardfile/nativeAssemblyInput.ts +1 -4
  221. package/src/server/host/bake/headlessWorker.ts +5 -1
  222. package/src/server/host/dedicated/cellHost.ts +98 -29
  223. package/src/server/host/dedicated/cellProtocol.ts +11 -1
  224. package/src/server/host/dedicated/cellWorker.ts +9 -3
  225. package/src/server/host/dedicated/crossing.ts +6 -2
  226. package/src/server/host/dedicated/dedicatedRoom.ts +21 -8
  227. package/src/server/host/dedicated/gridCells.ts +52 -9
  228. package/src/server/host/dedicated/main.ts +31 -12
  229. package/src/server/host/dedicated/placementFile.ts +56 -0
  230. package/src/server/host/dedicated/releaseFile.ts +17 -10
  231. package/src/server/host/dedicated/roadRoom.ts +21 -5
  232. package/src/server/host/dedicated/socketTransport.ts +2 -1
  233. package/src/server/host/dedicated/workerTable.ts +13 -1
  234. package/src/server/host/dedicated/world.ts +111 -10
  235. package/src/server/host/headlessRuntime.ts +10 -5
  236. package/src/server/host/installers.ts +62 -0
  237. package/src/server/host/openWorld.ts +59 -0
  238. package/src/server/host/ropeDecks.ts +2 -0
  239. package/src/server/host/standalone/cellWorld.ts +25 -19
  240. package/src/server/host/standalone/fallFloor.ts +2 -2
  241. package/src/server/host/standalone/gridServer.ts +7 -4
  242. package/src/server/host/standalone/roadWorld.ts +41 -4
  243. package/src/shared/engine/audio/bootAudio.ts +33 -0
  244. package/src/shared/engine/level/spec.ts +3 -3
  245. package/src/shared/engine/net/acts.ts +3 -0
  246. package/src/shared/engine/net/deviceWord.ts +138 -0
  247. package/src/shared/engine/net/socketFrames.ts +7 -4
  248. package/src/shared/engine/physics/query.ts +27 -0
  249. package/src/shared/engine/physics/terrain.ts +19 -28
  250. package/src/shared/engine/saves/saves.lock.json +15 -0
  251. package/src/shared/engine/sim/actRoutes.ts +2 -0
  252. package/src/shared/game/compendium/keepsakeProgression.ts +24 -0
  253. package/src/shared/game/grid/catalogue.ts +12 -5
  254. package/src/shared/game/grid/catalogueSlot.ts +18 -0
  255. package/src/shared/game/grid/farProxy.ts +6 -5
  256. package/src/shared/game/grid/pageMode.ts +1 -1
  257. package/src/shared/game/grid/placementRows.ts +33 -0
  258. package/src/shared/game/grid/roadLayout.ts +26 -3
  259. package/src/shared/game/grid/singleplayer.json +0 -13
  260. package/src/shared/game/grid/voidFloor.ts +122 -0
  261. package/src/shared/game/strings.ts +15 -0
  262. package/src/shared/host/standalone/netInput.ts +2 -1
@@ -4325,76 +4325,5 @@
4325
4325
  "timeout": 180,
4326
4326
  "notes": "OP20: provisional OP3 scaffold route, south entry along the avenue and full plaza perimeter on tile seams, then south approach. Continuous fixed-step walking; no hovering or per-waypoint teleport. Not yet walked or qualified against the future Opus theme geometry; its visual owner must adapt and run the maintained route before activation closeout."
4327
4327
  }
4328
- ],
4329
- "open-plot-showcase-template": [
4330
- {
4331
- "name": "road-avenue-plaza-scaffold",
4332
- "start": {
4333
- "x": 0,
4334
- "z": -245,
4335
- "y": 0.2,
4336
- "yaw": 3.141592653589793
4337
- },
4338
- "waypoints": [
4339
- {
4340
- "x": 0,
4341
- "z": -220
4342
- },
4343
- {
4344
- "x": 0,
4345
- "z": -187.5
4346
- },
4347
- {
4348
- "x": 0,
4349
- "z": -125
4350
- },
4351
- {
4352
- "x": 0,
4353
- "z": -62.5
4354
- },
4355
- {
4356
- "x": -62.5,
4357
- "z": -62.5
4358
- },
4359
- {
4360
- "x": -62.5,
4361
- "z": 0
4362
- },
4363
- {
4364
- "x": -62.5,
4365
- "z": 62.5
4366
- },
4367
- {
4368
- "x": 0,
4369
- "z": 62.5
4370
- },
4371
- {
4372
- "x": 62.5,
4373
- "z": 62.5
4374
- },
4375
- {
4376
- "x": 62.5,
4377
- "z": 0
4378
- },
4379
- {
4380
- "x": 62.5,
4381
- "z": -62.5
4382
- },
4383
- {
4384
- "x": 0,
4385
- "z": -62.5
4386
- },
4387
- {
4388
- "x": 0,
4389
- "z": -50
4390
- },
4391
- {
4392
- "x": 0,
4393
- "z": -62.5
4394
- }
4395
- ],
4396
- "timeout": 180,
4397
- "notes": "OP5: provisional OP3 scaffold route, south entry along the avenue and full plaza perimeter on tile seams, then south approach. Continuous fixed-step walking; no hovering or per-waypoint teleport. Not yet walked or qualified against the future Opus theme geometry; its visual owner must adapt and run the maintained route before activation closeout."
4398
- }
4399
4328
  ]
4400
4329
  }
@@ -0,0 +1,103 @@
1
+ // SHARD-DELETE DEL9 (meta J310): nothing engine pins or releases names a shard the API deleted. A deleted slug leaves
2
+ // `GET /api/catalogue`, so every slug engine names has to be one that list holds:
3
+ // - `test/pins/shardfiles.json`, the pinned heads every build installs;
4
+ // - `E7_STAGING_SHARDS` and `E7_PRODUCTION_SHARDS`, the GitHub variables a server release reads (empty: the default pair);
5
+ // - the pinned catalogue document's shards, placements and grid cells.
6
+ // Names compare by the folder a slug serves under (`template` pins as `_template`), as the release and the grid name them.
7
+ //
8
+ // node scripts/pins-catalogue.ts check CI (job 1, before install): the pins and both release variables against the live
9
+ // GET /api/catalogue; the offline half is test/pins-catalogue.test.ts
10
+ // `pins.ts refresh` refuses the same way before it writes a pin. Node built-ins only, so CI runs it before `pnpm install`.
11
+ import { readFileSync } from 'node:fs';
12
+ import { resolve } from 'node:path';
13
+ import { pathToFileURL } from 'node:url';
14
+ import { DEFAULT_SERVER_SHARDS, servedSlug } from './server-release/served-slug.mjs';
15
+
16
+ const PINS = 'test/pins/shardfiles.json';
17
+
18
+ /** One slug engine names that the catalogue doesn't list, and what named it. */
19
+ export interface Unlisted { readonly slug: string; readonly source: string }
20
+
21
+ /** The slugs a `GET /api/catalogue` body lists. A body with no shards array throws: an empty list must never pass for one. */
22
+ export function catalogueSlugs(body: unknown): ReadonlySet<string> {
23
+ const shards = (body as { shards?: unknown } | null)?.shards;
24
+ if (!Array.isArray(shards)) throw new Error('GET /api/catalogue: expected { shards: [...] }');
25
+ return new Set(shards.map((row: unknown) => {
26
+ const slug = (row as { slug?: unknown } | null)?.slug;
27
+ if (typeof slug !== 'string' || slug === '') throw new Error('GET /api/catalogue: a shard row has no slug');
28
+ return servedSlug(slug);
29
+ }));
30
+ }
31
+
32
+ /** A release variable's slugs; unset or empty selects the release's default pair, as `publish.mjs` does. */
33
+ export function releaseNames(value: string | undefined): readonly string[] {
34
+ const names = value === undefined || value.trim() === '' ? DEFAULT_SERVER_SHARDS : value;
35
+ return names.split(',').map(name => name.trim()).filter(Boolean);
36
+ }
37
+
38
+ /** The slugs a pins file names. */
39
+ export function pinnedSlugs(pins: unknown): readonly string[] {
40
+ const shards = (pins as { shards?: unknown } | null)?.shards;
41
+ if (!Array.isArray(shards)) throw new Error('test/pins/shardfiles.json: expected { shards: [...] }');
42
+ return shards.map((row: unknown) => {
43
+ const slug = (row as { slug?: unknown } | null)?.slug;
44
+ if (typeof slug !== 'string' || slug === '') throw new Error('test/pins/shardfiles.json: a pin has no slug');
45
+ return slug;
46
+ });
47
+ }
48
+
49
+ /** The slugs a catalogue document (`GET /api/catalogue.json`) names in its shards, placements and grid cells. */
50
+ export function documentSlugs(document: unknown): readonly string[] {
51
+ const doc = document as { shards?: { slug: string }[]; placements?: { slug: string }[]; grid?: { cells?: { slug: string }[] } };
52
+ return [...doc.shards ?? [], ...doc.placements ?? [], ...doc.grid?.cells ?? []].map(row => row.slug);
53
+ }
54
+
55
+ /** Every named slug the catalogue doesn't list, once per source and slug, in the order named. */
56
+ export function unlistedSlugs(listed: ReadonlySet<string>, named: Readonly<Record<string, readonly string[]>>): readonly Unlisted[] {
57
+ const seen = new Set<string>();
58
+ return Object.entries(named).flatMap(([source, slugs]) => slugs.flatMap(slug => {
59
+ const key = `${source}\0${slug}`;
60
+ if (listed.has(servedSlug(slug)) || seen.has(key)) return [];
61
+ seen.add(key);
62
+ return [{ slug, source }];
63
+ }));
64
+ }
65
+
66
+ /** One line per unlisted slug, naming who still names it and what to do. An API document is the API's to fix, not engine's. */
67
+ export function unlistedMessage(rows: readonly Unlisted[]): string {
68
+ return rows.map(({ slug, source }) => {
69
+ const fix = source.startsWith('GET ') ? 'the API disagrees with itself; report it to api-server' : `drop it from ${source}`;
70
+ return `${source} names ${slug}, which GET /api/catalogue no longer lists (deleted, DEL9): ${fix}`;
71
+ }).join('\n');
72
+ }
73
+
74
+ /** What engine names that a release reads, beside the pins: the default pair and each E7 shards variable `env` sets to a list (an
75
+ * unset GitHub variable reaches a step as '', which is the default pair, already named). */
76
+ export function releaseNamed(env: NodeJS.ProcessEnv): Record<string, readonly string[]> {
77
+ const named: Record<string, readonly string[]> = { 'the default release shards (server-release/served-slug.mjs)': releaseNames(undefined) };
78
+ for (const name of ['E7_STAGING_SHARDS', 'E7_PRODUCTION_SHARDS']) if ((env[name] ?? '').trim() !== '') named[name] = releaseNames(env[name]);
79
+ return named;
80
+ }
81
+
82
+ /** CI's online half of DEL9: the pins and both release variables name only slugs the live `GET /api/catalogue` lists. A catalogue the
83
+ * API can't serve is a warning, not a red: an API outage isn't a deleted shard. */
84
+ async function check(): Promise<void> {
85
+ const { WILDSHARD_API: api = 'https://api.wildshard.io' } = process.env;
86
+ const catalogue = await fetch(`${api}/api/catalogue`, { signal: AbortSignal.timeout(30_000) })
87
+ .then(response => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json() as Promise<unknown>; })
88
+ .catch((error: unknown) => error instanceof Error ? error : new Error(String(error)));
89
+ let listed: ReadonlySet<string> | Error;
90
+ try { listed = catalogue instanceof Error ? catalogue : catalogueSlugs(catalogue); } catch (error) { listed = error instanceof Error ? error : new Error(String(error)); }
91
+ if (listed instanceof Error) { console.log(`::warning title=catalogue check skipped::GET /api/catalogue failed: ${listed.message}`); return; }
92
+ const named = releaseNamed(process.env);
93
+ const unlisted = unlistedSlugs(listed, { [PINS]: pinnedSlugs(JSON.parse(readFileSync(PINS, 'utf8'))), ...named });
94
+ // This reads the live API, not the commit: a shard deleted on the API reds every branch until engine drops it, so say so.
95
+ if (unlisted.length > 0) throw new Error(`${unlistedMessage(unlisted)}\nA shard was deleted on the API, not by this commit: drop it`
96
+ + ' (pins: node scripts/pins.ts refresh --drop <slug>; a release variable: gh variable set) and push the fix.');
97
+ console.log(`catalogue check: ${PINS}, ${Object.keys(named).join(', ')} name only slugs GET /api/catalogue lists`);
98
+ }
99
+
100
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
101
+ if (process.argv[2] === 'check') await check();
102
+ else throw new Error('usage: pins-catalogue.ts check');
103
+ }
@@ -39,7 +39,7 @@ const HEX=/^[a-f0-9]{64}$/u;
39
39
  * imports is here unless KEY_EXEMPT says why its bytes can't change out/ or public/ (pins-reuse.test.mjs checks). */
40
40
  export const KEY_SOURCES=Object.freeze(['scripts/pins.ts','scripts/pin-packs.ts','scripts/pin-assets.ts','scripts/pin-format.ts',
41
41
  'scripts/bake-loader.mjs','scripts/format-hook.mjs','scripts/shardfile-validation-revision.mjs','scripts/pins-reuse.mjs',
42
- PINS,'test/pins/assets.json']);
42
+ 'scripts/tracked-public.mjs',PINS,'test/pins/assets.json']);
43
43
  export const KEY_EXEMPT=Object.freeze({
44
44
  'scripts/pins-exclude.mjs':'writes Git\'s exclude file only',
45
45
  'scripts/apfs-clone.mjs':'clones bytes that are then hashed against the manifest',
@@ -47,6 +47,8 @@ export const KEY_EXEMPT=Object.freeze({
47
47
  'src/cook/game/shardCook.ts':'slice command only',
48
48
  'scripts/renderer-revision.mjs':'names a printed preparation label only (J262); no byte under out/',
49
49
  'src/shared/game/shardfile/ktx2Targets.ts':'hashed already: the validation revision in the key covers src/shared/game/shardfile (S11)',
50
+ 'scripts/pins-catalogue.ts':'refresh check only (DEL9): refuses before the pins are written; no byte under out/',
51
+ 'scripts/server-release/served-slug.mjs':'refresh check only (DEL9): names a slug\'s served folder for the catalogue compare',
50
52
  });
51
53
 
52
54
  /** @typedef {{version:number,key:string,products:Record<string,Record<string,string>>,mounts:Record<string,string>}} Manifest */
package/scripts/pins.ts CHANGED
@@ -2,7 +2,9 @@
2
2
  // J65: engine's products are pinned real shardfiles, not a shard build. `test/pins/shardfiles.json` names each one by the
3
3
  // hash `api.wildshard.io` serves, and `test/pins/catalogue.json` is the catalogue document those heads came from.
4
4
  //
5
- // node scripts/pins.ts refresh re-pin to the live heads (read only: GETs)
5
+ // node scripts/pins.ts refresh re-pin to the live heads (read only: GETs); refuses while a pin, the default
6
+ // release pair or a set E7_*_SHARDS names a slug GET /api/catalogue no longer
7
+ // lists (DEL9); `--drop <slug>` lets refresh drop a deleted pin
6
8
  // node scripts/pins.ts install [slug...] fetch, check, validate, then write out/<folder> and publish its mounts
7
9
  // node scripts/pins.ts install --ring 1 Ring 1: pinned Template 1 and Dunes, dependency Template 2, and server slices
8
10
  // node scripts/pins.ts install --from-format <slug> a frozen dependency product (blender-template, brasscap-mesa),
@@ -30,7 +32,6 @@
30
32
  // mirror serves it. Coverage rows 4 and 5.
31
33
  // oxlint-disable-next-line import/no-unassigned-import -- Its hooks are the point, and they must run first.
32
34
  import './bake-loader.mjs';
33
- import { execFileSync } from 'node:child_process';
34
35
  import { createHash } from 'node:crypto';
35
36
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
36
37
  import { homedir } from 'node:os';
@@ -42,6 +43,9 @@ import { dropManifest, folderName, insideTree, lockPins, mountPath, pinsKey, reu
42
43
  import type { PackedIndex } from './pin-packs.ts';
43
44
  import { fetchPinnedPublicAssets, pinnedPublicAssets } from './pin-assets.ts';
44
45
  import { assertKtx2TableTargets } from '../src/shared/game/shardfile/ktx2Targets.ts';
46
+ import { trackedPublic } from './tracked-public.mjs';
47
+ import { catalogueSlugs, documentSlugs, pinnedSlugs, releaseNamed, unlistedMessage, unlistedSlugs } from './pins-catalogue.ts';
48
+ import { servedSlug } from './server-release/served-slug.mjs';
45
49
 
46
50
  interface Pin { readonly slug: string; readonly revision: number; readonly hash: string; readonly bytes: number }
47
51
  interface PinFile { readonly api: string; readonly shards: readonly Pin[] }
@@ -102,9 +106,17 @@ async function getJson(path: string): Promise<unknown> {
102
106
  return response.json();
103
107
  }
104
108
 
105
- /** Re-pin to the catalogue's live heads. */
106
- async function refresh(): Promise<void> {
109
+ /** Re-pin to the catalogue's live heads. A slug the catalogue no longer lists (DEL9: deleted) is refused, never silently
110
+ * dropped: whatever names it (a ring, a release variable, a proof list) has to drop it first, then `--drop <slug>`. */
111
+ async function refresh(drop: readonly string[]): Promise<void> {
107
112
  const [catalogue, listed, document] = await Promise.all([getJson('/api/catalogue'), getJson('/api/shardfiles'), getJson('/api/catalogue.json?stage=live')]);
113
+ const pinned = existsSync(PINS) ? pinnedSlugs(readJson(PINS)) : [], liveSlugs = catalogueSlugs(catalogue);
114
+ const wrongDrop = drop.filter(slug => !pinned.includes(slug) || liveSlugs.has(servedSlug(slug)));
115
+ if (wrongDrop.length > 0) throw new Error(`pins refresh refused: --drop ${wrongDrop.join(',')} names no pin, or one GET /api/catalogue still lists`);
116
+ const held = pinned.filter(slug => !drop.includes(slug));
117
+ const unlisted = unlistedSlugs(liveSlugs, { [PINS]: held, 'GET /api/catalogue.json?stage=live': documentSlugs(document), ...releaseNamed(process.env) });
118
+ if (unlisted.length > 0) throw new Error(`pins refresh refused, nothing written:\n${unlistedMessage(unlisted)}\n`
119
+ + `A deleted pin: drop it from what names it, then run pins.ts refresh --drop <slug>.`);
108
120
  const { shards } = catalogue as { shards: readonly CatalogueRow[] }, rows = Array.isArray(listed) ? listed as readonly ListedRow[] : (listed as { shardfiles: readonly ListedRow[] }).shardfiles;
109
121
  const sizes = new Map(rows.map(row => [row.hash, row.bytes]));
110
122
  const pins = shards.flatMap(({ slug, live }): Pin[] => (live === undefined ? [] : [{ slug, revision: live.revision, hash: live.hash, bytes: sizes.get(live.hash) ?? 0 }]));
@@ -181,13 +193,6 @@ function preparationOf(files: ReadonlyMap<string, Uint8Array>, root: string): 'c
181
193
  return cook.renderer === ownRenderer ? 'current' : 'stale';
182
194
  }
183
195
 
184
- function tracked(): ReadonlySet<string> {
185
- try {
186
- return new Set(execFileSync('git', ['ls-files', '-z', 'public'], { encoding: 'utf8', maxBuffer: 1 << 28 }).split('\0'));
187
- } catch {
188
- return new Set();
189
- }
190
- }
191
196
 
192
197
  /** The public paths an installed product published: its files under mounts/assets|programs and its cook.json rows. */
193
198
  function mountsOf(folder: string): Set<string> {
@@ -261,7 +266,7 @@ async function installLocked(only: readonly string[], source: 'pins' | 'format'
261
266
  insideTree(root, dirname(path));
262
267
  rmSync(path, { force: true });
263
268
  }
264
- const shared = tracked(), published = new Map<string, string>(), publicUrls = new Set(publicAssets.map(asset => asset.url));
269
+ const shared = trackedPublic(), published = new Map<string, string>(), publicUrls = new Set(publicAssets.map(asset => asset.url));
265
270
  const publish = (url: string, body: Uint8Array): void => {
266
271
  if (!mountPath(url)) throw new Error(`A pin publishes ${url}, outside public/`);
267
272
  const hash = digest(body), held = published.get(url);
@@ -456,7 +461,10 @@ function status(): void {
456
461
  }
457
462
 
458
463
  const [command = 'status', ...rest] = process.argv.slice(2);
459
- if (command === 'refresh') await refresh();
464
+ if (command === 'refresh') {
465
+ if (rest.some((arg, at) => arg.startsWith('-') ? arg !== '--drop' : rest[at - 1] !== '--drop')) throw new Error('usage: pins.ts refresh [--drop slug[,slug]]...');
466
+ await refresh(rest.flatMap((arg, at) => rest[at - 1] === '--drop' ? arg.split(',') : []));
467
+ }
460
468
  else if (command === 'install' && rest[0] === '--ring') await installRing(rest[1] ?? '1');
461
469
  else if (command === 'install' && rest[0] === '--from-format') await install(rest.slice(1), 'format');
462
470
  else if (command === 'install') await install(rest);
@@ -465,4 +473,4 @@ else if (command === 'verify-slices') await slice(true);
465
473
  else if (command === 'install-saves') await installSaves(rest);
466
474
  else if (command === 'keep') await keep(rest[0] ?? 'tmp/pins-release');
467
475
  else if (command === 'status') status();
468
- else throw new Error('usage: pins.ts refresh | install [slug...] | install --ring 1 | install-saves [slug...] | slice | verify-slices | keep <dir> | status');
476
+ else throw new Error('usage: pins.ts refresh [--drop slug] | install [slug...] | install --ring 1 | install-saves [slug...] | slice | verify-slices | keep <dir> | status');
@@ -0,0 +1,203 @@
1
+ // SHARD-AUTHORING SA35 (meta J314, grill Q11; Jake, 2026-11-12: "every deploy of preview in the github actions for deploy borrows the grid
2
+ // placement from staging by asking the staging mmo in the github action"). Preview has no MMO: its page bakes `test/pins/catalogue.json`.
3
+ // The staging MMO's grid is its build's catalogue (the same pinned J305 cells) plus every cell the API placed since, which it reads from the
4
+ // API-signed placement file (SA33, SA33a) at PLACEMENT_URL. Its own `/health` is tailnet-only (D7) and names instances, not cells, so the
5
+ // workflow asks for the one file the MMO itself believes, checked under the same placement key, and bakes those cells into preview's page.
6
+ //
7
+ // node --import ./scripts/bake-loader.mjs scripts/preview-grid.ts <out.json> [--placements=<url>] [--last=<url>] [--key=<spki hex>]
8
+ // writes the catalogue preview builds (page-release.mjs --catalogue=<out.json>), signature checked by engine's own reader
9
+ // node scripts/preview-grid.ts --news [--placements=<url>] [--last=<url>] [--key=<spki hex>]
10
+ // before install (node built-ins only): `news=true` when staging's placed cells differ from the live preview's
11
+ //
12
+ // Staging's file missing (404): staging placed no cell, so the pinned grid. Unreadable, refused or a bad signature (the "staging MMO down"):
13
+ // the live preview's own borrowed cells stay, and the run says so with a warning. Neither readable: the pinned grid, also with a warning.
14
+ import { createPublicKey, verify } from 'node:crypto';
15
+ import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
16
+ import { dirname, resolve } from 'node:path';
17
+ import { pathToFileURL } from 'node:url';
18
+
19
+ /** Where the API writes staging's placement file (SA33a) and the box reads it (SA33's PLACEMENT_URL). */
20
+ export const STAGING_PLACEMENTS = 'https://packs.wildshard.io/releases/staging-placements.json';
21
+ /** The live preview's baked catalogue: the last grid, kept when staging can't be read. */
22
+ export const LIVE_PREVIEW_CATALOGUE = 'https://preview.wildshard.io/catalogue.json';
23
+ /** The API's placement key (SA33a, `~/.config/wildshard/placement-signing-key.pub.pem`), SPKI DER in hex: the box's PLACEMENT_PUBLIC_KEY. */
24
+ export const PLACEMENT_PUBLIC_KEY = '302a300506032b65700321004afd39342aac6a4de6066cb72e9df54cbd3d4eb522e5e6e175a17954ab98f25e';
25
+ const PIN = 'test/pins/catalogue.json';
26
+ const FETCH_MS = 20_000;
27
+ /** The format's 7 × 7 (shard-format `GRID_RADIUS`, SA29), as the MMO's `placeCell` bounds a spot. */
28
+ const GRID_RADIUS = 3;
29
+
30
+ /** One placed cell: the placement file's row and a grid catalogue's cell. */
31
+ export interface Cell { readonly instance: string; readonly slug: string; readonly cell: readonly [number, number] }
32
+ interface Catalogue {
33
+ readonly grid: { readonly cells: readonly Cell[] };
34
+ readonly shards: readonly { readonly slug: string }[];
35
+ readonly missing: readonly string[];
36
+ }
37
+ /** What asking staging gave: its placed cells (a verified file), none placed (404), or down (anything else). */
38
+ export type StagingAnswer = { readonly placed: readonly Cell[]; readonly serial: number } | { readonly none: string } | { readonly down: string };
39
+ /** The live preview's catalogue, or why it couldn't be read. */
40
+ export type LastAnswer = { readonly catalogue: unknown } | { readonly down: string };
41
+ export interface Borrowed {
42
+ /** The pinned catalogue with staging's placed cells after its own. */
43
+ readonly document: Catalogue;
44
+ readonly cells: readonly Cell[];
45
+ /** `staging` read and believed; `kept` the live preview's cells; `pinned` neither. */
46
+ readonly source: 'staging' | 'kept' | 'pinned';
47
+ readonly lines: readonly string[];
48
+ /** Set when the run kept an older grid or fell back to the pin: the workflow's warning. */
49
+ readonly warning?: string;
50
+ }
51
+
52
+ const bare = (slug: string): string => slug.replace(/^_/u, '');
53
+ const at = (cell: Cell): string => `(${String(cell.cell[0])},${String(cell.cell[1])})`;
54
+ const named = (cells: readonly Cell[]): string => cells.map(cell => `${cell.instance} (${cell.slug}) at ${at(cell)}`).join(', ');
55
+
56
+ /** A catalogue's cells the pin's grid doesn't hold: the cells a page borrowed. */
57
+ export function borrowedCells(pin: Catalogue, catalogue: unknown): readonly Cell[] {
58
+ const cells = (catalogue as { grid?: { cells?: unknown } } | null)?.grid?.cells;
59
+ if (!Array.isArray(cells)) throw new Error('a catalogue with no grid cells');
60
+ const pinned = new Set(pin.grid.cells.map(cell => cell.instance));
61
+ return (cells as Cell[]).filter(cell => !pinned.has(cell.instance)).map(({ instance, slug, cell }) => ({ instance, slug, cell: [cell[0], cell[1]] }));
62
+ }
63
+
64
+ /**
65
+ * The grid preview builds: the pin's cells, then the borrowed ones. A cell is refused, as the staging MMO's `placeCell` refuses it, when its
66
+ * spot is off the 7 × 7 or taken, its slug already has a cell, or its instance is taken; a cell the pin already places the same way is kept once.
67
+ */
68
+ export function borrowGrid(pin: Catalogue, staging: StagingAnswer, last: LastAnswer): Borrowed {
69
+ const lines: string[] = [];
70
+ let source: Borrowed['source'], wanted: readonly Cell[], warning: string | undefined;
71
+ if ('placed' in staging) {
72
+ source = 'staging'; wanted = staging.placed;
73
+ lines.push(`staging's placement file, serial ${String(staging.serial)}, signature good: ${String(wanted.length)} placed cell(s)`);
74
+ } else {
75
+ let kept: readonly Cell[] | undefined, why = '';
76
+ if ('catalogue' in last) try { kept = borrowedCells(pin, last.catalogue); } catch (error) { why = error instanceof Error ? error.message : String(error); }
77
+ else why = last.down;
78
+ if ('none' in staging && (kept === undefined || kept.length === 0)) {
79
+ source = 'staging'; wanted = [];
80
+ lines.push(`staging has placed no cell (${staging.none}): the pinned grid`);
81
+ } else {
82
+ // The API rewrites its file and never deletes it, so a missing file after a placement is a fault, like an unreadable one.
83
+ const fault = 'none' in staging ? `${staging.none}, though the live preview borrowed cells` : 'down' in staging ? staging.down : '';
84
+ if (kept === undefined) {
85
+ source = 'pinned'; wanted = [];
86
+ warning = `staging's grid unreadable (${fault}), and so is the live preview's (${why}): this preview has the pinned grid only`;
87
+ } else {
88
+ source = 'kept'; wanted = kept;
89
+ warning = `staging's grid unreadable (${fault}): kept the live preview's grid, ${String(kept.length)} borrowed cell(s)`;
90
+ }
91
+ lines.push(warning);
92
+ }
93
+ }
94
+ const cells: Cell[] = [], left: string[] = [], spots = new Map<string, string>(), slugs = new Map<string, string>(), instances = new Map<string, string>();
95
+ for (const cell of pin.grid.cells) { spots.set(cell.cell.join(','), cell.instance); slugs.set(bare(cell.slug), cell.instance); instances.set(cell.instance, cell.slug); }
96
+ for (const cell of wanted) {
97
+ const [x, z] = cell.cell, spot = `${String(x)},${String(z)}`;
98
+ if (instances.get(cell.instance) === cell.slug && spots.get(spot) === cell.instance) continue;
99
+ const refused = !Number.isInteger(x) || !Number.isInteger(z) || Math.abs(x) > GRID_RADIUS || Math.abs(z) > GRID_RADIUS ? 'off the 7 × 7'
100
+ : spots.has(spot) ? `on ${spots.get(spot) ?? ''}'s spot`
101
+ : slugs.has(bare(cell.slug)) || instances.has(cell.slug) ? `${cell.slug} already has a cell (${slugs.get(bare(cell.slug)) ?? cell.slug})`
102
+ : instances.has(cell.instance) || slugs.has(bare(cell.instance)) ? `${cell.instance} is taken` : '';
103
+ if (refused !== '') { left.push(`left out ${cell.instance} (${cell.slug}) at ${at(cell)}: ${refused}`); continue; }
104
+ spots.set(spot, cell.instance); slugs.set(bare(cell.slug), cell.instance); instances.set(cell.instance, cell.slug);
105
+ cells.push({ instance: cell.instance, slug: cell.slug, cell: [x, z] });
106
+ }
107
+ // A cell staging's MMO may play but preview can't place breaks "the same cell": warn, as for a fault.
108
+ lines.push(...left);
109
+ if (left.length > 0) warning = [warning, `${String(left.length)} staging cell(s) left out of preview's grid: ${left.join('; ')}`].filter(line => line !== undefined).join('; ');
110
+ // A borrowed slug this build has no head for is "placed, with no head at this stage" (shard-format's `missing`).
111
+ const heads = new Set(pin.shards.map(head => bare(head.slug))), missing = [...pin.missing];
112
+ for (const cell of cells) if (!heads.has(bare(cell.slug)) && !missing.includes(cell.slug)) missing.push(cell.slug);
113
+ lines.push(cells.length === 0 ? `preview's grid: the pinned ${String(pin.grid.cells.length)} cells, none borrowed`
114
+ : `preview's grid: the pinned ${String(pin.grid.cells.length)} cells and ${String(cells.length)} from staging: ${named(cells)}`);
115
+ return { document: { ...pin, grid: { ...pin.grid, cells: [...pin.grid.cells, ...cells] }, missing }, cells, source, lines, ...(warning === undefined ? {} : { warning }) };
116
+ }
117
+
118
+ /** Whether two borrowed sets place the same cells. */
119
+ export function sameCells(a: readonly Cell[], b: readonly Cell[]): boolean {
120
+ const key = (cells: readonly Cell[]): string => cells.map(cell => `${cell.instance}=${cell.slug}@${cell.cell.join(',')}`).sort().join(' ');
121
+ return key(a) === key(b);
122
+ }
123
+
124
+ /** A signed file's body under `key`, Node built-ins only (the `--news` pass, before install). Engine's `readSigned` is the write's check. */
125
+ function signedBody(text: string, key: string): unknown {
126
+ const signed = JSON.parse(text) as { body?: unknown; signature?: unknown };
127
+ if (typeof signed.body !== 'string' || typeof signed.signature !== 'string') throw new Error('not a signed file');
128
+ if (!verify(null, Buffer.from(signed.body), createPublicKey({ key: Buffer.from(key, 'hex'), format: 'der', type: 'spki' }), Buffer.from(signed.signature, 'hex'))) throw new Error('a bad signature');
129
+ // The shape engine's PlacementSchema checks, roughly: a body the write's reader refuses must not make news every hour.
130
+ const body = JSON.parse(signed.body) as { kind?: unknown; serial?: unknown; cells?: unknown };
131
+ const id = (value: unknown): boolean => typeof value === 'string' && /^_?[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(value) && value.length <= 64;
132
+ if (body.kind !== 'placement' || !Number.isInteger(body.serial) || !Array.isArray(body.cells) || body.cells.length > 49
133
+ || !body.cells.every((row: { instance?: unknown; slug?: unknown; cell?: unknown }) => id(row.instance) && id(row.slug) && Array.isArray(row.cell) && row.cell.length === 2 && row.cell.every(Number.isInteger))) throw new Error('not a placement file');
134
+ return body;
135
+ }
136
+
137
+ async function fetchText(url: string): Promise<{ status: number; text: string }> {
138
+ if (url.startsWith('file:')) {
139
+ try { return { status: 200, text: readFileSync(new URL(url), 'utf8') }; }
140
+ catch (error) { if ((error as { code?: string }).code === 'ENOENT') return { status: 404, text: '' }; throw error; }
141
+ }
142
+ const response = await fetch(`${url}${url.includes('?') ? '&' : '?'}t=${String(Date.now())}`, { cache: 'no-store', redirect: 'error', signal: AbortSignal.timeout(FETCH_MS) });
143
+ return { status: response.status, text: await response.text() };
144
+ }
145
+ const message = (error: unknown): string => (error instanceof Error ? error.message : String(error));
146
+
147
+ /** Ask staging: its placement file, read by `read` (engine's reader for the write, `signedBody` for news). */
148
+ export async function askStaging(url: string, read: (text: string) => Promise<{ readonly channel: string; readonly serial: number; readonly cells: readonly Cell[] }>): Promise<StagingAnswer> {
149
+ try {
150
+ const { status, text } = await fetchText(url);
151
+ if (status === 404) return { none: `no placement file at ${url}` };
152
+ if (status !== 200) return { down: `${url} answered ${String(status)}` };
153
+ const file = await read(text);
154
+ if (file.channel !== 'staging') return { down: `${url} is a ${file.channel} placement file` };
155
+ return { placed: file.cells, serial: file.serial };
156
+ } catch (error) { return { down: `${url}: ${message(error)}` }; }
157
+ }
158
+ export async function askLast(url: string): Promise<LastAnswer> {
159
+ try {
160
+ const { status, text } = await fetchText(url);
161
+ return status === 200 ? { catalogue: JSON.parse(text) as unknown } : { down: `${url} answered ${String(status)}` };
162
+ } catch (error) { return { down: `${url}: ${message(error)}` }; }
163
+ }
164
+
165
+ async function main(argv: readonly string[]): Promise<void> {
166
+ const flag = (name: string): string | undefined => argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3);
167
+ const placements = flag('placements') ?? STAGING_PLACEMENTS, lastUrl = flag('last') ?? LIVE_PREVIEW_CATALOGUE, key = flag('key') ?? PLACEMENT_PUBLIC_KEY;
168
+ const pin = JSON.parse(readFileSync(PIN, 'utf8')) as Catalogue, out = argv.find(arg => !arg.startsWith('--'));
169
+ const github = (file: string | undefined, text: string): void => { if (file !== undefined && file !== '') appendFileSync(file, text); };
170
+ const news = argv.includes('--news'), { GITHUB_OUTPUT, GITHUB_ACTIONS, GITHUB_STEP_SUMMARY } = process.env;
171
+ if (!news && out === undefined) throw new Error('usage: preview-grid.ts <out.json> | --news [--placements=<url>] [--last=<url>] [--key=<hex>]');
172
+ // The write believes only engine's own reader (`readPlacementFile`, the staging MMO's check); `--news` runs before install.
173
+ const read = news ? (text: string): Promise<{ channel: string; serial: number; cells: Cell[] }> => Promise.resolve(signedBody(text, key) as { channel: string; serial: number; cells: Cell[] })
174
+ : async (text: string): Promise<{ readonly channel: string; readonly serial: number; readonly cells: readonly Cell[] }> => {
175
+ const { readPlacementFile } = await import('../src/server/host/dedicated/placementFile.ts');
176
+ return readPlacementFile(text, key);
177
+ };
178
+ const [staging, last] = await Promise.all([askStaging(placements, read), askLast(lastUrl)]);
179
+ const borrowed = borrowGrid(pin, staging, last);
180
+ for (const line of borrowed.lines) console.log(`preview grid: ${line}`);
181
+ if (news) {
182
+ // A deploy is news when staging's cells differ from what the live preview shows; a kept grid is the live one, so no news.
183
+ let shown: readonly Cell[] | undefined;
184
+ try { if ('catalogue' in last) shown = borrowedCells(pin, last.catalogue); } catch { shown = undefined; }
185
+ // An unreadable live catalogue is news only when staging has a cell to show.
186
+ const fresh = borrowed.source === 'staging' && (shown === undefined ? borrowed.cells.length > 0 : !sameCells(shown, borrowed.cells));
187
+ console.log(fresh ? 'preview grid: staging\'s grid differs from the live preview\'s: deploy' : 'preview grid: the live preview already shows staging\'s grid');
188
+ github(GITHUB_OUTPUT, `news=${String(fresh)}\n`);
189
+ return;
190
+ }
191
+ const file = resolve(out ?? '');
192
+ mkdirSync(dirname(file), { recursive: true });
193
+ writeFileSync(file, `${JSON.stringify(borrowed.document)}\n`);
194
+ console.log(`preview grid: wrote ${file}`);
195
+ // A workflow command ends at a newline, and fetched error text can hold one: GitHub's own escapes.
196
+ const escaped = (text: string): string => text.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');
197
+ if (borrowed.warning !== undefined && GITHUB_ACTIONS === 'true') console.log(`::warning title=preview grid::${escaped(borrowed.warning)}`);
198
+ github(GITHUB_STEP_SUMMARY, `### Preview grid (SA35)\n\n${borrowed.lines.map(line => `- ${line}`).join('\n')}\n`);
199
+ }
200
+
201
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
202
+ try { await main(process.argv.slice(2)); } catch (error) { console.error(`preview grid: ${message(error)}`); process.exitCode = 1; }
203
+ }