@wildshard/engine 0.1.17 → 0.1.19

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 (343) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/budgets/shard-size-baseline.json +10 -4
  3. package/index.html +6 -4
  4. package/lint/engine-sides.json +21 -0
  5. package/lint/host-callback-syntax.mjs +2 -1
  6. package/lint/host-callbacks.mjs +3 -3
  7. package/lint/host-files.mjs +5 -4
  8. package/lint/no-base64.mjs +3 -1
  9. package/lint/ratchet.json +0 -68
  10. package/lint/ratchet.mjs +1 -4
  11. package/lint/shard-imports.mjs +6 -7
  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 +22 -23
  18. package/package.json +25 -16
  19. package/scripts/agent-sync.mjs +27 -8
  20. package/scripts/app-build/appCook.ts +8 -2
  21. package/scripts/app-build/catalogue.ts +10 -7
  22. package/scripts/app-build/gen.ts +22 -2
  23. package/scripts/app-build/isolation.d.mts +10 -0
  24. package/scripts/app-build/isolation.mjs +47 -0
  25. package/scripts/app-build/outputProducts.d.mts +3 -0
  26. package/scripts/app-build/outputProducts.mjs +35 -0
  27. package/scripts/app-build/previousDeploy.d.mts +2 -0
  28. package/scripts/app-build/previousDeploy.mjs +10 -1
  29. package/scripts/app-build/serviceWorker.ts +10 -3
  30. package/scripts/app-build/splitOutput.mjs +4 -2
  31. package/scripts/app-build/standaloneOutput.d.mts +1 -1
  32. package/scripts/app-build/standaloneOutput.mjs +5 -3
  33. package/scripts/app-build/titlePreloads.d.mts +8 -0
  34. package/scripts/app-build/titlePreloads.mjs +69 -0
  35. package/scripts/app-build/worldMapAtlas.ts +10 -6
  36. package/scripts/app-build-pipeline.mjs +34 -3
  37. package/scripts/built-product.mjs +1 -1
  38. package/scripts/cell-mem-bench.mjs +81 -23
  39. package/scripts/check-custom-sections-zero.mjs +1 -1
  40. package/scripts/check-devserver.mjs +3 -1
  41. package/scripts/check-models.mjs +2 -0
  42. package/scripts/check-paths.allow.json +0 -115
  43. package/scripts/check-paths.mjs +2 -2
  44. package/scripts/check-platform-ratchets.mjs +2 -3
  45. package/scripts/chromium-keychain-check.mjs +4 -2
  46. package/scripts/chromium-keychain.d.mts +1 -1
  47. package/scripts/chromium-keychain.mjs +3 -1
  48. package/scripts/ci-static.sh +1 -1
  49. package/scripts/committed-fast-checks.mjs +0 -2
  50. package/scripts/content-sw-proof.mjs +2 -1
  51. package/scripts/cook-worker.mjs +9 -3
  52. package/scripts/cook.mjs +20 -3
  53. package/scripts/devices.d.mts +4 -0
  54. package/scripts/devices.mjs +39 -0
  55. package/scripts/devserver-client.d.mts +4 -2
  56. package/scripts/devserver-client.mjs +25 -8
  57. package/scripts/docs-inputs-proof.mjs +6 -6
  58. package/scripts/doctor-proof.mjs +1 -1
  59. package/scripts/e2e-faults.mjs +159 -0
  60. package/scripts/e7-voice-staging-proof.mjs +1 -1
  61. package/scripts/gate-related-tests.mjs +1 -1
  62. package/scripts/git-source-view.mjs +1 -1
  63. package/scripts/goldens/capture.mjs +17 -5
  64. package/scripts/grid-crossing-nightly.mjs +59 -0
  65. package/scripts/grid-crossing-qa.mjs +44 -0
  66. package/scripts/grid-crossing-ratchet.d.mts +6 -0
  67. package/scripts/grid-crossing-ratchet.mjs +52 -0
  68. package/scripts/grid-crossing-report.mjs +122 -0
  69. package/scripts/grid-crossing-stages.mjs +47 -0
  70. package/scripts/grid-crossing-tour.mjs +277 -0
  71. package/scripts/grid-crossing-walk-proof.mjs +136 -18
  72. package/scripts/host-ruler/roots.mjs +2 -2
  73. package/scripts/host-ruler.d.mts +91 -0
  74. package/scripts/host-ruler.mjs +565 -0
  75. package/scripts/live-prepush.py +3 -5
  76. package/scripts/loading-flow/benchmax.mjs +3 -1
  77. package/scripts/look-loop/test_look_loop.py +1 -38
  78. package/scripts/memory-proof.mjs +213 -0
  79. package/scripts/mmo-bots.mjs +8 -2
  80. package/scripts/net-lag-proof.mjs +219 -0
  81. package/scripts/night-market-kit-budget.mjs +2 -2
  82. package/scripts/offline-proof-rules.d.mts +5 -3
  83. package/scripts/offline-proof-rules.mjs +34 -7
  84. package/scripts/offline-proof.mjs +88 -18
  85. package/scripts/{shard-platform-output.mjs → output-reader.mjs} +1 -1
  86. package/scripts/page-release/content.d.mts +9 -1
  87. package/scripts/page-release/content.mjs +131 -17
  88. package/scripts/page-release/flow.mjs +36 -10
  89. package/scripts/page-release/stamp-content.mjs +24 -0
  90. package/scripts/page-release.mjs +28 -6
  91. package/scripts/page-size.mjs +2 -1
  92. package/scripts/pin-packs.ts +1 -1
  93. package/scripts/pins.ts +4 -4
  94. package/scripts/precommit-checks.mjs +1 -7
  95. package/scripts/precommit-jobs.mjs +0 -1
  96. package/scripts/precommit-source.py +1 -9
  97. package/scripts/program-discovery.mjs +1 -1
  98. package/scripts/ring-cook.mjs +2 -1
  99. package/scripts/ring-step.ts +1 -1
  100. package/scripts/script-scenario-metrics.mjs +1 -1
  101. package/scripts/shard-output-content.d.mts +1 -1
  102. package/scripts/shard-output-content.mjs +2 -2
  103. package/scripts/shard-outputs.mjs +1 -1
  104. package/scripts/shard-public.mjs +1 -1
  105. package/scripts/shard-wire-meter.mjs +24 -9
  106. package/scripts/side-parity.mjs +4 -2
  107. package/scripts/standalone-smoke.mjs +8 -3
  108. package/scripts/tier-textures-proof.mjs +101 -0
  109. package/scripts/tier-textures.mjs +78 -0
  110. package/scripts/tile-bake-report.mjs +1 -1
  111. package/scripts/tile-bakes.mjs +1 -1
  112. package/scripts/title-assets.generated.json +2 -0
  113. package/scripts/tsconfig.json +1 -2
  114. package/scripts/vendor/basisu/LICENSE +201 -0
  115. package/scripts/vendor/basisu/basis_encoder.cjs +2 -0
  116. package/scripts/vendor/basisu/basis_encoder.wasm +0 -0
  117. package/scripts/vitest-push-guards.config.ts +1 -1
  118. package/scripts/vps/harden-apply.sh +4 -1
  119. package/scripts/vps/harden-prometheus.sh +176 -0
  120. package/scripts/vps/harden.sh +16 -0
  121. package/scripts/vps/rebuild.sh +18 -0
  122. package/scripts/vps/wildshard-config +84 -24
  123. package/scripts/worker-client-play.mjs +7 -2
  124. package/scripts/worker-client-proof.mjs +1 -1
  125. package/scripts/worker-client-slug.mjs +44 -0
  126. package/scripts/worktree-reap.mjs +5 -5
  127. package/src/.oxlintrc.json +3 -182
  128. package/src/client/app/entry.ts +47 -12
  129. package/src/client/engine/boot/bootCache.ts +2 -2
  130. package/src/client/engine/boot/bootTrace.ts +12 -4
  131. package/src/client/engine/boot/browserChunkRecovery.ts +4 -0
  132. package/src/client/engine/boot/clearDownloads.ts +5 -2
  133. package/src/client/engine/boot/contentRead.ts +11 -0
  134. package/src/client/engine/boot/gpuFiles.ts +4 -2
  135. package/src/client/engine/boot/lastEnd.ts +99 -12
  136. package/src/client/engine/boot/parsedPages.ts +127 -58
  137. package/src/client/engine/boot/texturePack.ts +2 -2
  138. package/src/client/engine/build.d.ts +2 -0
  139. package/src/client/engine/core/Game.ts +18 -0
  140. package/src/client/engine/core/bootstrap.ts +4 -1
  141. package/src/client/engine/debug/probe.ts +18 -1
  142. package/src/client/engine/fx/LightPool.ts +41 -1
  143. package/src/client/engine/net/netPlayer.ts +19 -2
  144. package/src/client/engine/net/otherPlayers.ts +55 -8
  145. package/src/client/engine/net/predictor.ts +33 -9
  146. package/src/client/engine/net/redial.ts +29 -6
  147. package/src/client/engine/pwa/cacheNames.ts +58 -1
  148. package/src/client/engine/pwa/sw.js +53 -14
  149. package/src/client/engine/render/dataLook.ts +152 -40
  150. package/src/client/engine/render/families/detail.ts +89 -0
  151. package/src/client/engine/render/families/pbr.ts +7 -1
  152. package/src/client/engine/render/look.ts +6 -0
  153. package/src/client/engine/render/lookLight.ts +103 -11
  154. package/src/client/engine/render/lookRender.ts +105 -0
  155. package/src/client/engine/render/precompile.ts +20 -14
  156. package/src/client/engine/saves/indexed.ts +2 -2
  157. package/src/client/engine/telemetry/browserErrors.ts +28 -4
  158. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  159. package/src/client/engine/telemetry/staleBuildReport.ts +22 -1
  160. package/src/client/engine/ui/debugOptions.ts +1 -1
  161. package/src/client/engine/ui/lookLightOption.ts +10 -6
  162. package/src/client/engine/ui/namePrompt.ts +7 -0
  163. package/src/client/game/boot/audio.generated.ts +114 -216
  164. package/src/client/game/boot/bytes.generated.ts +118 -238
  165. package/src/client/game/boot/placedSpawn.ts +35 -0
  166. package/src/client/game/boot/spawnDownload.ts +25 -6
  167. package/src/client/game/boot/versions.generated.ts +7 -7
  168. package/src/client/game/devScene/hook.ts +291 -0
  169. package/src/client/game/grid/area.ts +38 -0
  170. package/src/client/game/grid/cellLoading.ts +12 -2
  171. package/src/client/game/grid/live.ts +134 -12
  172. package/src/client/game/grid/liveSession.ts +47 -5
  173. package/src/client/game/grid/mapAtlas.ts +18 -4
  174. package/src/client/game/grid/menu.ts +4 -0
  175. package/src/client/game/grid/minimapBlend.ts +15 -5
  176. package/src/client/game/grid/neighbourPanels.ts +10 -1
  177. package/src/client/game/grid/oneWayIn.ts +5 -1
  178. package/src/client/game/grid/placedCards.ts +55 -0
  179. package/src/client/game/grid/placedCells.ts +233 -0
  180. package/src/client/game/grid/placedContent.ts +85 -0
  181. package/src/client/game/grid/prefetch.ts +9 -1
  182. package/src/client/game/grid/productInputs.ts +3 -1
  183. package/src/client/game/grid/productLeases.ts +4 -1
  184. package/src/client/game/grid/products.ts +8 -4
  185. package/src/client/game/grid/regionalRuntime.ts +6 -0
  186. package/src/client/game/grid/regionalWorld.ts +15 -2
  187. package/src/client/game/grid/roadCull.ts +44 -14
  188. package/src/client/game/grid/roadLook.ts +24 -15
  189. package/src/client/game/grid/roadLookPlatform.ts +4 -2
  190. package/src/client/game/grid/roadResources.ts +24 -0
  191. package/src/client/game/grid/roadSign.worker.ts +4 -3
  192. package/src/client/game/grid/roadSignPaint.ts +16 -5
  193. package/src/client/game/grid/roadSignPreparation.ts +4 -3
  194. package/src/client/game/grid/roadSignScale.ts +8 -0
  195. package/src/client/game/grid/roadTileBacking.ts +13 -3
  196. package/src/client/game/grid/roadTileCapture.worker.ts +3 -1
  197. package/src/client/game/grid/roadTileCaptureWorker.ts +2 -1
  198. package/src/client/game/grid/roadTileWrite.worker.ts +4 -2
  199. package/src/client/game/grid/roadTileWriter.ts +2 -1
  200. package/src/client/game/grid/screenReports.ts +39 -0
  201. package/src/client/game/grid/session.ts +29 -4
  202. package/src/client/game/grid/shardfileFar.ts +9 -3
  203. package/src/client/game/grid/softWallLook.ts +25 -8
  204. package/src/client/game/mainMenu.ts +6 -2
  205. package/src/client/game/plugin/context.ts +2 -1
  206. package/src/client/game/plugin/followedMovers.ts +7 -1
  207. package/src/client/game/quest/figures.ts +2 -0
  208. package/src/client/game/session/finish.ts +11 -1
  209. package/src/client/game/shard/titleList.ts +6 -2
  210. package/src/client/game/shardfile/assetCache.ts +4 -4
  211. package/src/client/game/shardfile/client.ts +4 -1
  212. package/src/client/game/shardfile/clientAssets.ts +9 -5
  213. package/src/client/game/shardfile/clientLibrary.ts +1 -1
  214. package/src/client/game/shardfile/clientWater.ts +51 -9
  215. package/src/client/game/shardfile/clientWorker.ts +21 -8
  216. package/src/client/game/shardfile/look.ts +8 -3
  217. package/src/client/game/shardfile/product.ts +34 -7
  218. package/src/client/game/shardfile/productChecks.ts +2 -2
  219. package/src/client/game/shardfile/productCost.ts +2 -2
  220. package/src/client/game/shardfile/readAsset.ts +2 -2
  221. package/src/client/game/shardfile/reflectingWater.ts +73 -0
  222. package/src/client/game/shardfile/seatGrace.ts +9 -0
  223. package/src/client/game/shardfile/skinPlayback.ts +1 -1
  224. package/src/client/game/systems/npc/figureRows.ts +9 -0
  225. package/src/client/game/titleDeck.ts +4 -3
  226. package/src/client/host/online/doctor.ts +2 -0
  227. package/src/client/host/online/linkScreens.ts +30 -4
  228. package/src/client/host/online/shell.ts +14 -0
  229. package/src/client/host/standalone/shell.ts +4 -0
  230. package/src/cook/game/astc6Encode.ts +55 -0
  231. package/src/cook/game/astc6Wasm.ts +176 -0
  232. package/src/cook/game/cookJob.ts +30 -6
  233. package/src/cook/game/cookWorker.ts +38 -11
  234. package/src/cook/game/entryTotals.ts +51 -24
  235. package/src/cook/game/shardCook.ts +67 -9
  236. package/src/cook/game/spawnParts.ts +33 -8
  237. package/src/cook/game/tierTextures.ts +349 -0
  238. package/src/e2e/smoke/game.ts +19 -14
  239. package/src/e2e/smoke/page-globals.d.ts +9 -8
  240. package/src/e2e/smoke/template2.spec.ts +8 -7
  241. package/src/server/engine/ai/bossContenders.ts +27 -3
  242. package/src/server/engine/ai/phases.ts +1 -1
  243. package/src/server/engine/entities/creatureRefill.ts +9 -2
  244. package/src/server/engine/net/ledgerBook.ts +2 -0
  245. package/src/server/engine/net/room.ts +15 -0
  246. package/src/server/engine/sim/respawn.ts +8 -0
  247. package/src/server/game/boss/arenaRoomEntry.ts +5 -1
  248. package/src/server/game/boss/arenaRoomNative.ts +2 -0
  249. package/src/server/game/boss/native.ts +2 -1
  250. package/src/server/game/boss/nativeWake.ts +9 -5
  251. package/src/server/game/boss/openArenaNative.ts +2 -2
  252. package/src/server/game/boss/openArenaRoom.ts +3 -1
  253. package/src/server/game/grid/room.ts +44 -3
  254. package/src/server/game/grid/simulation.ts +23 -0
  255. package/src/server/game/population/mixedRoster.ts +11 -3
  256. package/src/server/game/population/nativeBake.ts +8 -3
  257. package/src/server/game/population/nativeReturns.ts +6 -3
  258. package/src/server/game/population/roster.ts +5 -3
  259. package/src/server/game/quest/eliteDrops.ts +15 -4
  260. package/src/server/game/quest/nativeChapter.ts +1 -1
  261. package/src/server/game/quest/nativeComposition.ts +5 -1
  262. package/src/server/game/riding/nativeTaming.ts +10 -6
  263. package/src/server/game/riding/wildRefill.ts +3 -2
  264. package/src/server/game/shardfile/bossRow.ts +4 -2
  265. package/src/server/game/shardfile/homeKeeper.ts +4 -2
  266. package/src/server/host/bake/headlessWorker.ts +1 -1
  267. package/src/server/host/dedicated/cellHost.ts +98 -16
  268. package/src/server/host/dedicated/cellProtocol.ts +16 -1
  269. package/src/server/host/dedicated/cellWorker.ts +8 -5
  270. package/src/server/host/dedicated/dedicatedRoom.ts +16 -6
  271. package/src/server/host/dedicated/gridCells.ts +15 -6
  272. package/src/server/host/dedicated/loopLag.ts +21 -0
  273. package/src/server/host/dedicated/main.ts +13 -5
  274. package/src/server/host/dedicated/packReader.ts +3 -3
  275. package/src/server/host/dedicated/placementFile.ts +4 -19
  276. package/src/server/host/dedicated/roadRoom.ts +34 -4
  277. package/src/server/host/dedicated/serverMetrics.ts +126 -0
  278. package/src/server/host/dedicated/socketPump.ts +21 -4
  279. package/src/server/host/dedicated/socketTransport.ts +2 -1
  280. package/src/server/host/dedicated/workerTable.ts +15 -4
  281. package/src/server/host/dedicated/world.ts +95 -8
  282. package/src/server/host/headless.ts +1 -1
  283. package/src/server/host/headlessRuntime.ts +1 -1
  284. package/src/server/host/standalone/roadWorld.ts +15 -3
  285. package/src/server/host/standalone/serverHost.ts +4 -1
  286. package/src/server/host/standalone/serverProduct.ts +41 -11
  287. package/src/shared/engine/ai/BossBrain.ts +8 -0
  288. package/src/shared/engine/net/deviceWord.ts +138 -0
  289. package/src/shared/engine/net/socketFrames.ts +7 -4
  290. package/src/shared/game/boss/wake.ts +6 -0
  291. package/src/shared/game/devColliders.ts +47 -0
  292. package/src/shared/game/eliteSystem.ts +8 -0
  293. package/src/shared/game/grid/allocator.ts +3 -0
  294. package/src/shared/game/grid/catalogueSlot.ts +7 -0
  295. package/src/shared/game/grid/placementRows.ts +36 -0
  296. package/src/shared/game/plugin/bossRecord.ts +3 -2
  297. package/src/shared/game/shardfile/ktx2Targets.ts +23 -3
  298. package/src/shared/game/shardfile/outputDescriptor.ts +9 -5
  299. package/src/shared/game/shardfile/packReads.ts +28 -3
  300. package/src/shared/game/shardfile/serverPack.ts +9 -0
  301. package/src/shared/game/systems/looks/trampleField.ts +2 -0
  302. package/src/shared/host/formatJsonSchema.ts +2 -2
  303. package/src/tsconfig.json +1 -27
  304. package/lint/host-reviews.json +0 -14
  305. package/lint/listed-view-code.json +0 -13
  306. package/lint/platform-pending-users.json +0 -2520
  307. package/lint/platform-pending-users.md +0 -18
  308. package/scripts/cell-mem/metrics-preload.mjs +0 -65
  309. package/scripts/check-closed-components.d.mts +0 -7
  310. package/scripts/check-closed-components.mjs +0 -87
  311. package/scripts/g571-hosts.d.mts +0 -3
  312. package/scripts/g571-hosts.mjs +0 -54
  313. package/scripts/host-ruler/register-migrate.mjs +0 -242
  314. package/scripts/listed-view-code.d.mts +0 -7
  315. package/scripts/listed-view-code.mjs +0 -93
  316. package/scripts/look-loop/fit-lut.py +0 -142
  317. package/scripts/look-loop/palette-delta.py +0 -183
  318. package/scripts/look-loop/regions/driftwood-isle.json +0 -25
  319. package/scripts/look-loop/regions/far-reach.json +0 -225
  320. package/scripts/look-loop/regions/open-plot-night-market.json +0 -855
  321. package/scripts/look-loop/regions/pine-hollow.json +0 -22
  322. package/scripts/look-loop/regions/sunscar-dunes.json +0 -281
  323. package/scripts/platform-chargebacks.d.mts +0 -9
  324. package/scripts/platform-chargebacks.mjs +0 -135
  325. package/scripts/shard-component-spans.d.mts +0 -15
  326. package/scripts/shard-component-spans.mjs +0 -18
  327. package/scripts/shard-components.d.mts +0 -16
  328. package/scripts/shard-components.mjs +0 -363
  329. package/scripts/shard-platform-hosts.d.mts +0 -2
  330. package/scripts/shard-platform-hosts.mjs +0 -93
  331. package/scripts/shard-platform-sections.d.mts +0 -2
  332. package/scripts/shard-platform-sections.mjs +0 -9
  333. package/scripts/shard-platform.d.mts +0 -76
  334. package/scripts/shard-platform.mjs +0 -1072
  335. package/src/.oxfmtrc.json +0 -48
  336. package/src/scripts/ask-new.sh +0 -29
  337. package/src/scripts/asks.mjs +0 -142
  338. package/src/scripts/herdr-prompt.sh +0 -34
  339. package/src/scripts/herdr-question-open.sh +0 -67
  340. package/src/scripts/md-wrap.mjs +0 -229
  341. /package/scripts/{shard-platform-format.d.mts → node-format.d.mts} +0 -0
  342. /package/scripts/{shard-platform-format.mjs → node-format.mjs} +0 -0
  343. /package/scripts/{shard-platform-output.d.mts → output-reader.d.mts} +0 -0
@@ -0,0 +1,47 @@
1
+ import { appendFileSync, existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ /**
5
+ * PAGE-SIZE PZ12 (J274, preview first): cross-origin isolation per channel. An isolated channel's page origin answers every
6
+ * path with COOP `same-origin` and COEP `require-corp` (its build appends one `/*` rule to `dist/_headers`), so the
7
+ * document, its module workers and the standalone server worker's script all carry them. The service worker answers a
8
+ * navigation with its baked document; it sends the same two headers, read from that rule, so a load it serves is isolated
9
+ * like one the network serves. Content on packs.wildshard.io passes: every read there is CORS, and PC1 sends CORP.
10
+ * Staging and production join as J274 rolls out: add them here.
11
+ */
12
+ export const ISOLATED_CHANNELS = new Set(['preview']);
13
+ export const ISOLATION_HEADERS = Object.freeze({ 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp' });
14
+ const MARK = '# PAGE-SIZE PZ12 (J274): this channel is cross-origin isolated';
15
+
16
+ /** @param {string | undefined} channel */
17
+ export const isolated = channel => channel !== undefined && ISOLATED_CHANNELS.has(channel);
18
+
19
+ /** The `_headers` text with the isolation rule appended (once) for an isolated channel; unchanged for any other.
20
+ * @param {string} text @param {string | undefined} channel */
21
+ export function withIsolationRule(text, channel) {
22
+ if (!isolated(channel) || text.includes(MARK)) return text;
23
+ const rule = Object.entries(ISOLATION_HEADERS).map(([name, value]) => ` ${name}: ${value}`).join('\n');
24
+ return `${text.endsWith('\n') ? text : `${text}\n`}\n${MARK}\n/*\n${rule}\n`;
25
+ }
26
+
27
+ /** Append the rule to a build's `_headers`. @param {string} outDir @param {string | undefined} channel @returns {boolean} isolated */
28
+ export function writeIsolationRule(outDir, channel) {
29
+ const file = join(outDir, '_headers'), text = existsSync(file) ? readFileSync(file, 'utf8') : '';
30
+ const next = withIsolationRule(text, channel);
31
+ if (next !== text) appendFileSync(file, next.slice(text.length));
32
+ return isolated(channel);
33
+ }
34
+
35
+ /** The COOP and COEP a `_headers` text sends on `/` (from its `/*` rules), lower-cased, for the service worker's document.
36
+ * @param {string} text @returns {Record<string, string>} */
37
+ export function documentIsolation(text) {
38
+ /** @type {Record<string, string>} */ const out = {};
39
+ let all = false;
40
+ for (const line of text.split('\n')) {
41
+ if (line.trim() === '' || line.trimStart().startsWith('#')) continue;
42
+ if (!/^\s/u.test(line)) { all = line.trim() === '/*'; continue; }
43
+ const match = /^\s+(Cross-Origin-(?:Opener|Embedder)-Policy):\s*(.+?)\s*$/iu.exec(line);
44
+ if (all && match?.[1] !== undefined && match[2] !== undefined) out[match[1].toLowerCase()] = match[2];
45
+ }
46
+ return out;
47
+ }
@@ -1,6 +1,9 @@
1
1
  /** The app publishes its data products, never their temporary TypeScript sources. */
2
2
  export function copyOutputProducts(root: string, outDir: string): void;
3
3
 
4
+ /** Refuse a public/ copy of a product mount whose bytes differ from the product's; returns the mounts checked. */
5
+ export function checkPublishedMounts(root: string): number;
6
+
4
7
  /** DL20: drop the loose files only a part needs to hold; a default manifest's files stay. */
5
8
  export function pruneLooseCopies(outDir: string): { files: number; bytes: number };
6
9
 
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
2
3
  import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
4
 
@@ -21,7 +22,41 @@ export function copyOutputProducts(root, outDir) {
21
22
  // C3: the mounts a page reads by this folder's URL: a discovery document and the art of a product that packs none.
22
23
  const own = resolve(source, 'mounts/shardfiles', entry.name);
23
24
  if (existsSync(own)) cpSync(own, resolve(shardfiles, entry.name), { recursive: true });
25
+ // S12d: the discovery document as the build's cook serves it (the phone tier's table), over the product's own.
26
+ const served = resolve(outDir, '.discovery', entry.name, 'discovery.json');
27
+ if (existsSync(served)) copyFileSync(served, resolve(shardfiles, entry.name, 'discovery.json'));
24
28
  }
29
+ rmSync(resolve(outDir, '.discovery'), { recursive: true, force: true });
30
+ }
31
+
32
+ /** A product's mounts serve from `public/` (`pins.ts install` publishes them), so a product dropped into `out/` by hand keeps
33
+ * whatever an older head left there. AUDIO AU7 re-encodes a recording under its old URL, so a new revision and its
34
+ * predecessor share URLs with different bytes: a preparation preview then serves the old head's audio, its manifests
35
+ * name the old hashes, and `wildshard prepare` records no audio in the new head's fence (meta QA 2026-11-13 row 34).
36
+ * Refuse a build whose `public/` copy of a product's mount differs from the product's own bytes; a missing copy is the
37
+ * cook's to refuse. Under 0.5 s over every pinned product.
38
+ * @param {string} root @returns {number} the mounts checked */
39
+ export function checkPublishedMounts(root) {
40
+ const products = resolve(root, 'out'), stale = [];
41
+ if (!existsSync(products)) return 0;
42
+ let checked = 0;
43
+ for (const entry of readdirSync(products, { withFileTypes: true })) {
44
+ const cook = resolve(products, entry.name, 'cook.json');
45
+ if (!entry.isDirectory() || entry.name.startsWith('.') || !existsSync(cook)) continue;
46
+ let parsed;
47
+ try { parsed = JSON.parse(readFileSync(cook, 'utf8')); } catch (error) { throw new Error(`out/${entry.name}/cook.json does not parse`, { cause: error }); }
48
+ const { mounts } = /** @type {{mounts?: {url: string, hash: string}[]}} */ (parsed);
49
+ for (const row of mounts ?? []) {
50
+ const copy = resolve(root, `public${row.url}`);
51
+ if (!/^\/(?:assets|programs)\/(?!.*(?:^|\/)\.\.(?:\/|$))/u.test(row.url) || !existsSync(copy)) continue;
52
+ checked++;
53
+ if (createHash('sha256').update(readFileSync(copy)).digest('hex') !== row.hash) stale.push(`${entry.name} ${row.url}`);
54
+ }
55
+ }
56
+ if (stale.length > 0) throw new Error(`public/ holds ${stale.length} ${stale.length === 1 ? 'mount' : 'mounts'} with other bytes than their product in out/ `
57
+ + `(${stale.slice(0, 3).join(', ')}): publish that product's mounts (node scripts/pins.ts install for a pin, or copy a candidate's `
58
+ + 'mounts/ into public/), or remove its out/ folder if nothing pins it any more, and build again');
59
+ return checked;
25
60
  }
26
61
 
27
62
  /** DL20: a level file leaves the deploy when a part holds it and nothing reads its URL directly. Every default manifest's file
@@ -12,6 +12,8 @@ export function carryPreviousDeploy(directory: string, options?: {
12
12
  readonly optional?: boolean;
13
13
  /** PZ5: this build reads its content from a content base: its graph names code only, marked, so it is carried as code only */
14
14
  readonly contentBase?: boolean;
15
+ /** PAGE-SIZE D1: what the kept builds may add to the page; a kept build past it is dropped whole, newest first */
16
+ readonly budget?: {readonly files: number; readonly bytes: number};
15
17
  }): Promise<{current: number; builds: number; carried: number; bytes: number}>;
16
18
  /** Whether an unreachable carried origin may mean no previous builds: a CI test build or the solo preview, never a
17
19
  * staging or production release (OFF-VERCEL OV6). */
@@ -169,7 +169,11 @@ export function channelOrigin(channel) {
169
169
  * A test build (`optional`) treats a 5xx or network failure fetching the origin's manifest as no previous builds.
170
170
  * PZ5: `contentBase` says this build reads its content from a content base: its graph names its code only and is marked,
171
171
  * and a marked kept graph carries its code only (`CHUNK`). An unmarked one keeps its content, since its tabs read the page.
172
- * @param {{previousDirectory?: string, previousOrigin?: string, live?: readonly string[], ours?: (build: string) => boolean, optional?: boolean, contentBase?: boolean}} [options]
172
+ * PAGE-SIZE D1: `budget` is what the kept builds may add to the page (D1's limits less this build's own page). Newest first, a
173
+ * kept build that would take the page past it is dropped whole, as a pruned build is: chunk recovery moves its tabs on. Without
174
+ * it, the first build that splits its content off carried four builds that hold theirs (preview, 2026-11-13: 178 MB) and the
175
+ * gate refused every build, so those never aged out.
176
+ * @param {{previousDirectory?: string, previousOrigin?: string, live?: readonly string[], ours?: (build: string) => boolean, optional?: boolean, contentBase?: boolean, budget?: {files: number, bytes: number}}} [options]
173
177
  */
174
178
  export async function carryPreviousDeploy(directory, options = {}) {
175
179
  const current = currentManifest(directory, options.contentBase === true);
@@ -217,6 +221,11 @@ export async function carryPreviousDeploy(directory, options = {}) {
217
221
  continue;
218
222
  }
219
223
  for (const row of graph.files) if (!held.has(row.path)) fresh.push(row);
224
+ const freshBytes = fresh.reduce((sum, row) => sum + row.bytes, 0), budget = options.budget;
225
+ if (budget !== undefined && (carried + fresh.length > budget.files || bytes + freshBytes > budget.bytes)) {
226
+ console.warn(`Dropped previous build ${graph.build}: its ${String(fresh.length)} files (${(freshBytes / 1e6).toFixed(1)} MB) would take the page past PAGE-SIZE D1 (room for ${String(Math.max(0, budget.files - carried))} files, ${(Math.max(0, budget.bytes - bytes) / 1e6).toFixed(1)} MB)`);
227
+ continue;
228
+ }
220
229
  try {
221
230
  await pool(fresh, async row => {
222
231
  const target = join(directory, row.path);
@@ -8,6 +8,7 @@ import { ASSET_CACHE_NAME } from '../../src/client/engine/pwa/cacheNames';
8
8
  import { serverPackBookPath } from '../../src/shared/game/shardfile/serverPack';
9
9
  import { packsBookPath } from '../../src/shared/game/shardfile/spawnManifest';
10
10
  import { titleAssetURLs } from '../title-assets.mjs';
11
+ import { documentIsolation } from './isolation.mjs';
11
12
  import { writtenBundle, type EmittedFile } from './writtenBundle';
12
13
 
13
14
  /** Update checks fetch this tiny bootstrap; the core URL names its exact bytes. */
@@ -56,7 +57,8 @@ function documentContentBase(html: string): string {
56
57
  interface Book { readonly url: string; readonly bytes: Uint8Array }
57
58
 
58
59
  /** The build owns names. No worker parses boot banks, packs or runtime product metadata. */
59
- export async function serviceWorkerCore(bundle: Readonly<Record<string, EmittedFile>>, root: string, buildId: string, serverBook?: Book, packsBook?: Book): Promise<{
60
+ export async function serviceWorkerCore(bundle: Readonly<Record<string, EmittedFile>>, root: string, buildId: string, serverBook?: Book, packsBook?: Book,
61
+ documentHeaders: Readonly<Record<string, string>> = {}): Promise<{
60
62
  core: string; build: string; assets: string; hashed: string[];
61
63
  }> {
62
64
  const document = bundle['index.html'];
@@ -87,6 +89,8 @@ export async function serviceWorkerCore(bundle: Readonly<Record<string, EmittedF
87
89
  // PZ10: with a content base, every content path (the books, the title art) is read from it, so the worker precaches it
88
90
  // there, into its cross-build content cache; the page keeps code and shell. With none, the lists are today's.
89
91
  const base = documentContentBase(html);
92
+ // PZ12: a change of the document's isolation is a new worker (empty on a channel that is not isolated: its id is unchanged)
93
+ if (Object.keys(documentHeaders).length > 0) digest.update(JSON.stringify(documentHeaders));
90
94
  // The build's server book with its code: a device that adopts a build and goes offline can still read a server class it holds.
91
95
  let files = [...hashed, ...portraits, ...serverBook === undefined ? [] : [serverBook.url]], shellList = shell.filter(url => !portraits.includes(url));
92
96
  let content: string[] = [];
@@ -102,7 +106,9 @@ export async function serviceWorkerCore(bundle: Readonly<Record<string, EmittedF
102
106
  .replace(/['"]__FILES__['"]/u, () => JSON.stringify(JSON.stringify(files)))
103
107
  .replace(/['"]__SHELL_FILES__['"]/u, () => JSON.stringify(JSON.stringify(shellList)))
104
108
  .replace(/['"]__CONTENT__['"]/u, () => JSON.stringify(JSON.stringify({ base, files: content })))
105
- .replace(/['"]__DOCUMENT__['"]/u, () => JSON.stringify(html));
109
+ .replace(/['"]__DOCUMENT__['"]/u, () => JSON.stringify(html))
110
+ // PZ12: the page origin's COOP and COEP on the baked document, so a load the worker serves is isolated like the network's
111
+ .replace(/['"]__DOCUMENT_HEADERS__['"]/u, () => JSON.stringify(JSON.stringify(documentHeaders)));
106
112
  return { core, build, assets: ASSET_CACHE_NAME, hashed };
107
113
  }
108
114
 
@@ -151,7 +157,8 @@ export async function writeServiceWorker(outDir: string, root: string): Promise<
151
157
  const file = [join(outDir, path), join(`${resolve(outDir)}-content`, path)].find(at => existsSync(at));
152
158
  return file === undefined ? undefined : { url: `/${path}`, bytes: readFileSync(file) };
153
159
  };
154
- const { core, build, hashed } = await serviceWorkerCore(splitBundle(outDir, writtenBundle(outDir, root)), root, buildId, book(serverPackBookPath(buildId)), book(packsBookPath(buildId))), scripts = workerScripts(core);
160
+ const headersFile = join(outDir, '_headers'), documentHeaders = existsSync(headersFile) ? documentIsolation(readFileSync(headersFile, 'utf8')) : {};
161
+ const { core, build, hashed } = await serviceWorkerCore(splitBundle(outDir, writtenBundle(outDir, root)), root, buildId, book(serverPackBookPath(buildId)), book(packsBookPath(buildId)), documentHeaders), scripts = workerScripts(core);
155
162
  mkdirSync(dirname(join(outDir, scripts.fileName)), { recursive: true });
156
163
  writeFileSync(join(outDir, scripts.fileName), core);
157
164
  writeFileSync(join(outDir, 'sw.js'), stampWorker(scripts.bootstrap, outDir));
@@ -9,7 +9,7 @@
9
9
  import {existsSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, writeFileSync} from 'node:fs';
10
10
  import {dirname, join, resolve} from 'node:path';
11
11
  import {pathToFileURL} from 'node:url';
12
- import {classify, shardNames} from '../page-size.mjs';
12
+ import {carriedPaths, classify, shardNames} from '../page-size.mjs';
13
13
 
14
14
  /** The content tree beside a page: `dist` → `dist-content`. @param {string} dist */
15
15
  export const contentDirOf = dist => `${resolve(dist)}-content`;
@@ -68,7 +68,9 @@ export function splitOutput(dist, content = contentDirOf(dist)) {
68
68
  const root = resolve(dist), target = resolve(content), mark = join(root, SPLITTING);
69
69
  disjoint(root, target);
70
70
  if (!existsSync(join(root, 'index.html'))) throw new Error(`splitOutput: ${root} holds no index.html; give a built page`);
71
- const shards = shardNames(root), rows = files(root).filter(row => row.path !== SPLITTING && isContent(row.path, shards));
71
+ // a kept build's content (MF2 carry, PZ5: an unmarked build reads it from the page) stays on the page until it ages out
72
+ const carried = carriedPaths(root)?.paths ?? new Set();
73
+ const shards = shardNames(root), rows = files(root).filter(row => row.path !== SPLITTING && !carried.has(row.path) && isContent(row.path, shards));
72
74
  if (rows.length > 0) {
73
75
  if (!existsSync(mark)) rmSync(target, {recursive: true, force: true});
74
76
  writeFileSync(mark, '');
@@ -1,4 +1,4 @@
1
1
  /** Where a build's emitted shell is served from. */
2
2
  export function standaloneDirectory(buildId: string): string;
3
3
  /** The standalone shell and its server worker, under the build's folder. */
4
- export function writeStandaloneOutput(outDir: string, buildId: string, root: string): Promise<void>;
4
+ export function writeStandaloneOutput(outDir: string, buildId: string, root: string, options?: { devserver?: boolean }): Promise<void>;
@@ -11,13 +11,15 @@ import { engineRelease } from '../changelog.mjs';
11
11
  * @param {string} buildId */
12
12
  export const standaloneDirectory = (buildId) => `${codeDirectory(buildId)}/standalone`;
13
13
 
14
- /** @param {string} outDir @param {string} buildId @param {string} root */
15
- export async function writeStandaloneOutput(outDir, buildId, root) {
14
+ /** @param {string} outDir @param {string} buildId @param {string} root @param {{ devserver?: boolean }} [options] */
15
+ export async function writeStandaloneOutput(outDir, buildId, root, options = {}) {
16
16
  const directory = standaloneDirectory(buildId);
17
17
  await build({
18
18
  configFile: false, root, logLevel: 'warn', publicDir: false, resolve: { alias: rapierAlias }, assetsInclude: ['**/*.bin', '**/*.wasm'],
19
19
  // SENTRY-TRIAGE S5: the shells report errors too, under the same wildshard@<version> release as the page
20
- define: { __TITLE_ASSET_URLS__: '{}', __BUILD_ID__: BUILD_ID_EXPRESSION, __ENGINE_RELEASE__: JSON.stringify(engineRelease(root)) }, worker: { format: 'es' },
20
+ // SHARD-SOURCE AP5: the shell and the server worker read `__DEVSERVER__` too (the dev hook's server half); a production
21
+ // build folds it to false here as the page bundle does (scripts/check-devserver.mjs refuses one left unsubstituted)
22
+ define: { __TITLE_ASSET_URLS__: '{}', __BUILD_ID__: BUILD_ID_EXPRESSION, __ENGINE_RELEASE__: JSON.stringify(engineRelease(root)), __DEVSERVER__: JSON.stringify(options.devserver === true) }, worker: { format: 'es' },
21
23
  build: {
22
24
  outDir: resolve(outDir), emptyOutDir: false, assetsDir: directory, target: 'es2022', sourcemap: false, reportCompressedSize: false,
23
25
  rolldownOptions: {
@@ -0,0 +1,8 @@
1
+ /** PZ18: the grid page entry, whose static closure the document preloads. */
2
+ export const TITLE_PRELOAD_ROOT: string;
3
+ /** The title root's static-closure chunks the document does not already preload or load as its module script. */
4
+ export function titlePreloadFiles(report: Record<string, { moduleIds: string[]; imports: string[] }>, html: string, root?: string): string[];
5
+ /** The document with a modulepreload link for each file after its last one (or before its first module script). */
6
+ export function withTitlePreloads(html: string, files: readonly string[]): string;
7
+ /** Adds the title closure's modulepreload links to the output's index.html; returns the files it preloads. */
8
+ export function writeTitlePreloads(outDir: string, report: Record<string, { moduleIds: string[]; imports: string[] }>): string[];
@@ -0,0 +1,69 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+
4
+ /**
5
+ * PZ18 (meta PAGE-SIZE, QA 11-13 row 29): the title's code comes in the first wave. The entry imports the grid's page
6
+ * entry (`src/client/game/grid/pageEntry.ts`) dynamically, so its static closure (the title-0 chunks) was only requested
7
+ * once the entry had run: two serial round trips after the module graph (preview, throttled: 1.07 to 1.29 s of a 1.53 s
8
+ * title). The built document now names every chunk of that closure as a `modulepreload` beside the entry's own, so the
9
+ * browser fetches them with the first wave. Splicing the links into preview's document moved the throttled title from
10
+ * 1.54-1.56 s to 1.26-1.39 s.
11
+ */
12
+ export const TITLE_PRELOAD_ROOT = 'src/client/game/grid/pageEntry.ts';
13
+
14
+ const clean = (/** @type {string} */ id) => id.replaceAll('\\', '/').split('?')[0];
15
+ const PRELOAD = /<link\b[^>]*\brel="modulepreload"[^>]*>/gu;
16
+ const HREF = /\bhref="\/([^"]+)"/u;
17
+ const MODULE_SCRIPT = /<script\b[^>]*\btype="module"[^>]*\bsrc="\/([^"]+)"[^>]*>/gu;
18
+
19
+ /**
20
+ * The chunks of the title root's static closure (its own chunks first, then each one's static imports) that the document
21
+ * neither preloads nor loads as its module script already. Empty when no chunk holds the root (a fixture build).
22
+ * @param {Record<string, {moduleIds: string[], imports: string[]}>} report `.vite/chunk-modules.json`
23
+ * @param {string} html the built document
24
+ * @param {string} [root]
25
+ * @returns {string[]} chunk files, relative to the output folder
26
+ */
27
+ export function titlePreloadFiles(report, html, root = TITLE_PRELOAD_ROOT) {
28
+ const loaded = new Set([...html.matchAll(PRELOAD)].map(match => HREF.exec(match[0])?.[1]).filter(file => file !== undefined));
29
+ for (const match of html.matchAll(MODULE_SCRIPT)) if (match[1] !== undefined) loaded.add(match[1]);
30
+ /** @type {string[]} */ const order = [];
31
+ const seen = new Set();
32
+ /** @param {string} file */
33
+ const visit = file => {
34
+ if (seen.has(file)) return;
35
+ seen.add(file); order.push(file);
36
+ const row = report[file];
37
+ if (row === undefined) throw new Error(`title preloads: no chunk report row for ${file}`);
38
+ for (const next of row.imports) visit(next);
39
+ };
40
+ for (const [file, row] of Object.entries(report)) if (row.moduleIds.some(id => clean(id) === root)) visit(file);
41
+ return order.filter(file => !loaded.has(file) && file.endsWith('.js'));
42
+ }
43
+
44
+ /**
45
+ * Add the title closure's `modulepreload` links to `index.html`, right after the document's last one (or before its first
46
+ * module script), in the same form the bundler writes its own.
47
+ * @param {string} html
48
+ * @param {readonly string[]} files
49
+ */
50
+ export function withTitlePreloads(html, files) {
51
+ if (files.length === 0) return html;
52
+ const links = files.map(file => `<link rel="modulepreload" crossorigin href="/${file}">`).join('\n');
53
+ const preloads = [...html.matchAll(PRELOAD)], last = preloads.at(-1);
54
+ if (last?.index !== undefined) { const at = last.index + last[0].length; return `${html.slice(0, at)}\n${links}${html.slice(at)}`; }
55
+ const script = /<script\b[^>]*\btype="module"/u.exec(html);
56
+ if (script === null) throw new Error('title preloads: the document has no module script');
57
+ return `${html.slice(0, script.index)}${links}\n${html.slice(script.index)}`;
58
+ }
59
+
60
+ /**
61
+ * @param {string} outDir
62
+ * @param {Record<string, {moduleIds: string[], imports: string[]}>} report
63
+ * @returns {string[]} the chunks it preloads
64
+ */
65
+ export function writeTitlePreloads(outDir, report) {
66
+ const path = resolve(outDir, 'index.html'), html = readFileSync(path, 'utf8'), files = titlePreloadFiles(report, html);
67
+ if (files.length > 0) writeFileSync(path, withTitlePreloads(html, files));
68
+ return files;
69
+ }
@@ -45,14 +45,18 @@ export async function bakeWorldMapAtlas(products: readonly string[], read: (slug
45
45
  }
46
46
 
47
47
  /** One up-front map asset from all grid placements, shared by public and Developer, over the built products (was
48
- * vite/worldMapAtlas.ts's config hook): scripts/build-app.mjs runs it after the generators. */
48
+ * vite/worldMapAtlas.ts's config hook): scripts/build-app.mjs runs it after the generators. The grid's cells and every
49
+ * built placement: a released page adds cells from the signed placement file (placedCells.ts), mostly listed shards
50
+ * (QA-FEEDBACK 2026-11-13 row 44: open-plot-thin-ice had no tile). A placement this build didn't make, or a shard carded
51
+ * from the API after it (SA46), gets no tile: the page draws that cell's own map instead (minimapBlend.ts fullMapOverlay). */
49
52
  export async function writeWorldMapAtlas(root: string): Promise<void> {
50
- const row = v.object({ slug: v.string() }), catalogue = v.parse(v.object({ grid: v.object({ cells: v.array(row) }) }),
51
- JSON.parse(readFileSync(Reflect.get(process.env, 'WILDSHARD_CATALOGUE') ?? resolve(root, 'src/shared/game/grid/singleplayer.json'), 'utf8'))).grid;
52
- const slugs = catalogue.cells.map(cell => cell.slug);
53
+ const row = v.object({ slug: v.string() }), catalogue = v.parse(v.object({ placements: v.exactOptional(v.array(row)), grid: v.object({ cells: v.array(row) }) }),
54
+ JSON.parse(readFileSync(Reflect.get(process.env, 'WILDSHARD_CATALOGUE') ?? resolve(root, 'src/shared/game/grid/singleplayer.json'), 'utf8')));
55
+ const cells = catalogue.grid.cells.map(cell => cell.slug), builtHere = (slug: string): boolean => existsSync(resolve(root, 'out', slug, 'shard.json'));
56
+ const slugs = [...cells, ...(catalogue.placements ?? []).map(placement => placement.slug).filter(builtHere)];
53
57
  // A filtered product build (build-shardfiles --shard) leaves only its own products, and the products copy
54
- // (outputProducts.mjs) publishes just those: the others draw the plot tile. A cold atlas, none built, still refuses.
55
- const built = new Set(slugs.filter(slug => existsSync(resolve(root, 'out', slug, 'shard.json'))));
58
+ // (outputProducts.mjs) publishes just those: the other cells draw the plot tile. A cold atlas, none built, still refuses.
59
+ const built = new Set(slugs.filter(builtHere));
56
60
  const atlas = await bakeWorldMapAtlas(slugs, slug => built.size === 0 || built.has(slug) ? productMapBytes(root, slug) : null);
57
61
  const fileName = `assets/world-map-${hash(atlas.bytes).slice(0, 16)}.webp`;
58
62
  mkdirSync(dirname(join(root, WORLD_MAP_ATLAS)), { recursive: true });
@@ -8,6 +8,8 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from
8
8
  import { dirname, resolve } from "node:path";
9
9
  import { bakeAssetTables, writeAssetTables } from "./app-build/assetTables.mjs";
10
10
  import { writeChunkReport } from "./app-build/chunkReport.mjs";
11
+ import { writeTitlePreloads } from "./app-build/titlePreloads.mjs";
12
+ import { writeIsolationRule } from "./app-build/isolation.mjs";
11
13
  import { bakeGridSeams, writeGridSeams } from "./app-build/gridSeams.mjs";
12
14
  import { checkNoTopLevelAwait } from "./app-build/noTopLevelAwait.mjs";
13
15
  import { checkImportMaps } from "./app-build/importMap.mjs";
@@ -15,6 +17,7 @@ import { nameChunksByFinalBytes } from "./app-build/finalChunkNames.mjs";
15
17
  import { writeTitleAssets } from "./title-assets.mjs";
16
18
  import {
17
19
  copyOutputProducts,
20
+ checkPublishedMounts,
18
21
  copyDeferredPublic,
19
22
  pruneLooseCopies,
20
23
  } from "./app-build/outputProducts.mjs";
@@ -22,6 +25,7 @@ import { buildLabelOf, stampBuildDocuments } from "./app-build/buildIdentity.mjs
22
25
  import { engineRelease } from "./changelog.mjs";
23
26
  import { homeIconChannel, writeHomeIcons } from "./app-build/homeIcons.mjs";
24
27
  import { carryPreviousDeploy, channelOrigin, previousDeployOptional } from "./app-build/previousDeploy.mjs";
28
+ import { PAGE_LIMITS, pageSize } from "./page-size.mjs";
25
29
  import { assertAssetLimits, describeAssetLimits } from "./app-build/assetLimits.mjs";
26
30
  import { buildValidationReceipts } from "./app-build/validationReceipts.mjs";
27
31
  import { shardfileValidationRevision } from "./shardfile-validation-revision.mjs";
@@ -29,6 +33,23 @@ import { checkBakedTextures } from "./app-build/bakedTextures.mjs";
29
33
 
30
34
  import { assertHeavyLease } from "./heavy-lane-lease.mjs";
31
35
 
36
+ /** PAGE-SIZE D1: what the kept builds may add, D1's limits less this build's own page (its content and maps go elsewhere).
37
+ * @param {string} outDir @returns {{files: number, bytes: number} | undefined} */
38
+ function carryBudget(outDir) {
39
+ if (!existsSync(resolve(outDir, "index.html"))) return undefined;
40
+ const report = pageSize(outDir), zero = { files: 0, bytes: 0 };
41
+ const off = ["maps", "shard content", "engine art"].map((kind) => report.kinds[kind] ?? zero);
42
+ const files = report.total.files - off.reduce((sum, row) => sum + row.files, 0), bytes = report.total.bytes - off.reduce((sum, row) => sum + row.bytes, 0);
43
+ return { files: Math.max(0, PAGE_LIMITS.files - files), bytes: Math.max(0, PAGE_LIMITS.bytes - bytes) };
44
+ }
45
+
46
+ /** SHARD-SOURCE AP5: the dev hook's version (`DEV_HOOK_VERSION` in src/client/game/devScene/hook.ts), for a devserver build's flags. */
47
+ function devHookVersion() {
48
+ const version = /export const DEV_HOOK_VERSION = (\d+);/u.exec(readFileSync(resolve(import.meta.dirname, "../src/client/game/devScene/hook.ts"), "utf8"))?.[1];
49
+ if (version === undefined) throw new Error("app-build: src/client/game/devScene/hook.ts names no DEV_HOOK_VERSION");
50
+ return Number(version);
51
+ }
52
+
32
53
  /** A refused child step; the CLI preserves its code, library callers can clean up. */
33
54
  export class AppBuildFailureError extends Error {
34
55
  /** @param {number} exitCode */
@@ -55,6 +76,8 @@ export function prepareAppBuild() {
55
76
  // C3: a tree with no shard source (the lifted engine) has no list or bake to run; it builds from a catalogue and its packs.
56
77
  const shardSource = existsSync("src/shards");
57
78
  checkBakedTextures(process.cwd(), resolve("public"));
79
+ // A shard-source tree rebuilds out/ from public/ below; only a tree that builds from placed products can hold a stale copy.
80
+ if (!shardSource) checkPublishedMounts(process.cwd());
58
81
  if (shardSource) {
59
82
  step(["scripts/gen-shards.mjs"]);
60
83
  for (const baker of ["bake-chunk", "bake-sky"]) {
@@ -138,7 +161,10 @@ export async function finishAppBuild({ outDir, buildId, mode, deferPublic }) {
138
161
  // vite/chunkReport.ts); then the boot module bank into index.html and each home's extra file table (was
139
162
  // vite/bootModules.ts), and the spawn parts' q11 Brotli bodies (DL15, cached by content).
140
163
  try {
141
- writeChunkReport(outDir, process.cwd());
164
+ const report = writeChunkReport(outDir, process.cwd());
165
+ // PZ18: the title's static closure is preloaded with the entry's own chunks, so the title costs no round trip after it
166
+ const preloads = writeTitlePreloads(outDir, report);
167
+ console.log(`title preloads: ${preloads.length} chunks (${preloads.map((file) => file.split("/").pop()).join(", ")})`);
142
168
  } catch (error) {
143
169
  console.error(error instanceof Error ? error.message : String(error));
144
170
  throw new AppBuildFailureError(1);
@@ -195,7 +221,7 @@ export async function finishAppBuild({ outDir, buildId, mode, deferPublic }) {
195
221
  // the standalone shell and its server worker under the build's folder, before the service worker, which precaches them (J130)
196
222
  await (
197
223
  await import("./app-build/standaloneOutput.mjs")
198
- ).writeStandaloneOutput(outDir, buildId, process.cwd());
224
+ ).writeStandaloneOutput(outDir, buildId, process.cwd(), { devserver: mode === "devserver" });
199
225
 
200
226
  // the crossroads phone rig beside the bundle (was vite/crossroadsRig.ts); before the worker, which counts its files
201
227
  step([
@@ -209,6 +235,8 @@ export async function finishAppBuild({ outDir, buildId, mode, deferPublic }) {
209
235
  // J217 (LD6b): chunks name each other through each document's import map; with every document and bundle written,
210
236
  // refuse a document without its map, or a request that resolves nowhere
211
237
  checkImportMaps(outDir);
238
+ // PZ12 (J274): an isolated channel's page origin sends COOP and COEP on every path; the worker reads the same rule
239
+ if (writeIsolationRule(outDir, process.env.WS_CHANNEL)) console.log(`cross-origin isolated: ${process.env.WS_CHANNEL}`);
212
240
  // the service worker over the bundle as written (was vite/pwa-plugin.ts): sw.js and its content-named core
213
241
  step([
214
242
  "--import",
@@ -224,7 +252,8 @@ export async function finishAppBuild({ outDir, buildId, mode, deferPublic }) {
224
252
  mkdirSync(outDir, { recursive: true });
225
253
  writeFileSync(
226
254
  resolve(outDir, "build-flags.json"),
227
- JSON.stringify({ devserver: mode === "devserver" }),
255
+ // SHARD-SOURCE AP5: a devserver client names its dev hook's version, which sharddev's `watch` checks against its own
256
+ JSON.stringify(mode === "devserver" ? { devserver: true, devHook: devHookVersion() } : { devserver: false }),
228
257
  );
229
258
 
230
259
  // the data products beside the app (was vite/outputProducts.ts)
@@ -262,6 +291,7 @@ export async function finishAppBuild({ outDir, buildId, mode, deferPublic }) {
262
291
  // PAGE-SIZE PZ5: a build that reads its content from a content base (WS_CONTENT_BASE, stamped by PZ8) names its code
263
292
  // only, so a later release carries its code only. A kept build without that mark still carries its content.
264
293
  const contentBase = (process.env.WS_CONTENT_BASE ?? "") !== "";
294
+ const budget = carryBudget(outDir);
265
295
  console.log(
266
296
  "Previous deploy chunks:",
267
297
  await carryPreviousDeploy(outDir, {
@@ -269,6 +299,7 @@ export async function finishAppBuild({ outDir, buildId, mode, deferPublic }) {
269
299
  ...(previousOrigin === undefined ? {} : { previousOrigin }),
270
300
  optional,
271
301
  contentBase,
302
+ ...(budget === undefined ? {} : { budget }),
272
303
  }),
273
304
  );
274
305
 
@@ -168,7 +168,7 @@ export function assertBuiltTestProducts(root, files, options = {}) {
168
168
  * @param {string} root @param {string} name @param {string} folder @param {string} expectedSourceHash */
169
169
  export async function publishProductMap(root, name, folder, expectedSourceHash) {
170
170
  if (!/^[a-z0-9_-]+$/u.test(name)) throw new Error('Invalid program-map product name');
171
- const { outputFormat } = await import('./shard-platform-format.mjs');
171
+ const { outputFormat } = await import('./node-format.mjs');
172
172
  const envelope = readFileSync(resolve(folder, 'shard.json'));
173
173
  const receipt = JSON.parse(readFileSync(resolve(folder, 'validation.json'), 'utf8'));
174
174
  if (receipt.indexHash !== createHash('sha256').update(envelope).digest('hex')) throw new Error(`${name}: generated map index receipt differs`);