@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
@@ -142,6 +142,21 @@ export class Audio extends PlayerVoices {
142
142
  scope.onDispose(() => { this.levelBankFns.delete(fn); });
143
143
  if (this.levelBank) fn(this.levelBank);
144
144
  }
145
+ /** Lend `bank` as the level bank while `scope` lives (AU20: an Open Plot cell's own bank on the grid page). When the scope
146
+ * ends, unless another bank was installed meanwhile, what the lend replaced comes back: the level bank, the sample maps
147
+ * and the music's title bank (a page with no level bank, or a bank with no title, keeps its own). */
148
+ lendLevelBank(bank: LevelAudioBank, scope: Scope): void {
149
+ if (scope.disposed) return;
150
+ const previous = this.levelBank, loops = this.loops, shots = this.shots, title = this.music?.residentBank();
151
+ this.useLevelBank(bank);
152
+ scope.onDispose(() => {
153
+ if (this.levelBank !== bank) return;
154
+ this.levelBank = previous;
155
+ if (bank.samples !== undefined) this.applySamples(loops, shots);
156
+ if (bank.title !== undefined && title !== undefined) this.music?.useBank(title);
157
+ if (previous !== undefined) for (const fn of this.levelBankFns) fn(previous);
158
+ });
159
+ }
145
160
  useLevelBank(bank: LevelAudioBank): void {
146
161
  this.levelBank = bank;
147
162
  if (bank.samples) this.useSamples(bank.samples);
@@ -268,9 +283,12 @@ export class Audio extends PlayerVoices {
268
283
  * set) where they sound; before the first gesture it only fills the maps, and resume() starts the bed from them */
269
284
  useSamples(bank: SfxBank): void {
270
285
  if (bank.set !== this.sfxSet) return; // another set was picked while this one decoded
271
- const hadBed = this.sampleBed, hadUnder = this.underSample, hadHum = this.hum?.sample === true;
272
- this.loops = new Map(bank.loops); this.shots = new Map(bank.shots);
273
286
  if (bank.credit !== undefined) setSfxCredit(this.sfxSet, bank.credit);
287
+ this.applySamples(new Map(bank.loops), new Map(bank.shots));
288
+ }
289
+ private applySamples(loops: Map<LoopName, SampleLoop>, shots: Map<string, { bufs: AudioBuffer[]; gain: number }>): void {
290
+ const hadBed = this.sampleBed, hadUnder = this.underSample, hadHum = this.hum?.sample === true;
291
+ this.loops = loops; this.shots = shots;
274
292
  if (!this.g) return;
275
293
  if (this.started && (hadBed || this.loops.has(this.bed))) { this.stopBed(); this.startBed(); }
276
294
  if (this.underGain && (hadUnder || this.loops.has('underwater'))) this.feedUnder();
@@ -17,7 +17,7 @@ import { bootFileList } from './filePolicy';
17
17
  import * as THREE from 'three';
18
18
  import { fetchImage, tierUrl, versionedUrl } from './bytes';
19
19
  import { TIER } from '../core/tier';
20
- import { ktx2Texture } from '../core/ktx2';
20
+ import { ktx2Texture, readHeldForm } from '../core/ktx2';
21
21
  import { activeLevel } from '../../../shared/engine/level/selection';
22
22
  import { levelBakedId } from '../../../shared/engine/level/spec';
23
23
  import { labelAsset, labelClone } from '../render/gpuLabels';
@@ -59,7 +59,8 @@ export async function preloadBakedTextures(): Promise<number> {
59
59
  } catch (e) { console.warn(`[baked] ${u}: ${(e as Error).message}`); }
60
60
  }), ...urls.map(async (u) => {
61
61
  // E157: the KTX2 stand-in when there is one (Y-flipped at encode, like fetchImage's bitmap)
62
- try { loaded.set(u, (await ktx2Texture(tierUrl(u))) ?? await fetchImage(u, Infinity, true)); }
62
+ // OF17: a form that fails to read gives way to the other when the cache holds it
63
+ try { const served = tierUrl(u); loaded.set(u, await readHeldForm(served, tex => ktx2Texture(served, Infinity, tex), instead => fetchImage(u, Infinity, true, false, instead))); }
63
64
  catch (e) { console.warn(`[baked] ${u}: ${(e as Error).message}`); }
64
65
  })]);
65
66
  return urls.length + common.length;
@@ -1,7 +1,8 @@
1
1
  import { pageScope } from '../../../shared/engine/app/resources';
2
2
  import { saveStorage } from '../saves/slots';
3
3
  /** A small durable breadcrumb for an enabled level boot. A terminated WebContent process cannot run a final handler. */
4
- import { deliverBrowserError } from '../telemetry/browserErrors';
4
+ import { deliverBrowserError, flushScreenReports, screenReportsEnabled } from '../telemetry/browserErrors';
5
+ import { reportStaleBuild } from '../telemetry/staleBuildReport';
5
6
  import type { ProgressView } from './plan';
6
7
  import { markDropStep } from './dropNotice';
7
8
 
@@ -205,6 +206,10 @@ export function createBootTrace(transports: BootTraceTransports = PAGE_TRANSPORT
205
206
  }
206
207
  }
207
208
  void flushBootReports();
209
+ // SENTRY-TRIAGE S13: an error screen an earlier page opened and could not deliver goes now, off the boot's hot path (title too).
210
+ // STALE-BUILD SB6: a stale-build screen an earlier page showed (index.html's note) joins the outbox first.
211
+ // No DSN (dev, tests): nothing can be sent, so no timer joins the page's own (the sw tests count them).
212
+ if (typeof window !== 'undefined' && screenReportsEnabled()) pageScope.timeout(8000, () => { reportStaleBuild(); flushScreenReports(); });
208
213
  }
209
214
 
210
215
  /** Shown in the loader and the Loading & memory Debug row after a restart. */
@@ -23,7 +23,7 @@ import { pageScope } from '../../../shared/engine/app/resources';
23
23
  import { presenting } from '../../../shared/engine/core/framePacing';
24
24
  import { workSlice } from '../../../shared/engine/core/workSlice';
25
25
  import { demandTextureResponse } from './texturePack';
26
- import { readContent } from './contentRead';
26
+ import { readContent, type ContentReadOptions } from './contentRead';
27
27
  import { contentURL } from './contentBase';
28
28
 
29
29
  export type ChunkFiles = Readonly<Record<ByteKey, readonly string[]>>;
@@ -218,11 +218,12 @@ function installCounter(): void {
218
218
  * ImageBitmapLoader (then texture.flipY must be false); pass false for canvas work that keeps the
219
219
  * file's orientation.
220
220
  */
221
- export async function fetchImage(file: string, maxSize: typeof Infinity = Infinity, flip = true, exact = false): Promise<ImageBitmap | HTMLImageElement> {
221
+ export async function fetchImage(file: string, maxSize: typeof Infinity = Infinity, flip = true, exact = false, instead?: ContentReadOptions['instead']): Promise<ImageBitmap | HTMLImageElement> {
222
222
  const url = tierUrl(file);
223
223
  let type = '';
224
+ // `instead` (OF17, core/assets.ts loadTexture): a failed read may throw rather than wait on RETRY (contentRead.ts)
224
225
  const bytes = await readContent(url, 25_000_000, {fetch: (address, init) => fetch(address, init),
225
- response: response => {type = response.headers.get('content-type') ?? '';}});
226
+ response: response => {type = response.headers.get('content-type') ?? '';}, ...(instead === undefined ? {} : {instead})});
226
227
  const blob = new Blob([bytes], {type});
227
228
  if (typeof createImageBitmap === 'function') {
228
229
  try {
@@ -91,7 +91,7 @@ export async function clearDownloads(): Promise<ClearReport> {
91
91
  try {
92
92
  const slot = jsonSlot('ktx2set', 'device');
93
93
  const value = slot.read();
94
- markers = typeof value === 'object' && value !== null ? Object.keys(value).length : 0;
94
+ markers = typeof value === 'object' && value !== null ? Object.keys(value).filter(key => !key.endsWith('.read')).length : 0; // OF17's notes are not markers
95
95
  slot.write({});
96
96
  } catch { /* storage off: no markers were written either */ }
97
97
  // 5. the HTTP cache (Clear-Site-Data: "cache"): offline this fails, and the reload is cold for Cache Storage only
@@ -26,6 +26,9 @@ export interface ContentReadOptions {
26
26
  response?: (response: Response) => void;
27
27
  /** An optional file: a server that answers it is not there (404, the HTML fallback) throws at once instead of RETRY. */
28
28
  missingThrows?: boolean;
29
+ /** OF17: asked when the read has failed twice, before it waits on RETRY. True throws the error instead: the caller has
30
+ * another copy to read (a texture's other form, held in the cache). */
31
+ instead?: (error: ContentReadError) => Promise<boolean>;
29
32
  }
30
33
 
31
34
  function html(bytes: Uint8Array): boolean {
@@ -139,6 +142,7 @@ export async function readContent(url: string, maximum: number, options: Content
139
142
  if (error.missing && options.missingThrows === true) throw error;
140
143
  if (!retried) { retried = true; }
141
144
  else {
145
+ if (options.instead !== undefined && await options.instead(error)) throw error;
142
146
  // RL8 (Jake's phone, 2026-11-09: an old cached build sat at "0.00 MB of 28.4 MB"): a deploy keeps only the live
143
147
  // build's hashed files, so a missing first-party file on a build the server no longer serves can never arrive.
144
148
  // Instead of RETRY forever, the page reloads past its worker into the live build (once per build and tab).
@@ -70,7 +70,7 @@ export interface DropStore {
70
70
  write: (key: DropKey, value: Json) => void;
71
71
  clear: (key: DropKey) => void;
72
72
  }
73
- type DropKey = 'step' | 'stepOnce' | 'pending' | 'pendingOnce' | 'expect';
73
+ type DropKey = 'step' | 'stepOnce' | 'pending' | 'pendingOnce' | 'expect' | 'seen';
74
74
 
75
75
  /** the step a world page names once it is playing */
76
76
  export const PLAYING = 'Playing';
@@ -184,9 +184,9 @@ export class DropNotes {
184
184
  if (end.player === true) return null;
185
185
  const said = end.kind === 'fresh' ? '' : end.reason;
186
186
  if (pending !== null && time(pending, 'at') >= time(expected, 't')) {
187
- return { kind: 'error', what: text(pending, 'what'), reason: text(pending, 'reason'), step: text(pending, 'step'), world: text(pending, 'world'),
187
+ return this.once({ kind: 'error', what: text(pending, 'what'), reason: text(pending, 'reason'), step: text(pending, 'step'), world: text(pending, 'world'),
188
188
  name: text(pending, 'name'), message: text(pending, 'message'), code: text(pending, 'code'), stack: text(pending, 'stack'), end: said,
189
- trail: text(pending, 'trail'), routeStack: text(pending, 'routeStack'), at: time(pending, 'at'), build: text(pending, 'build') };
189
+ trail: text(pending, 'trail'), routeStack: text(pending, 'routeStack'), at: time(pending, 'at'), build: text(pending, 'build') });
190
190
  }
191
191
  // the first boot of a visit, and a title after a title: no world page came before it in this tab
192
192
  if (step === null) return null;
@@ -195,7 +195,7 @@ export class DropNotes {
195
195
  if (end.kind === 'intentional' && PLAYER_EXITS.some((exit) => end.reason.startsWith(exit))) return null;
196
196
  const name = first(step.name, step.world), trail = step.trail.join(' → ');
197
197
  const via = trail === '' ? '' : ` It was sent here by a redirect: ${trail} → ${name} at ${step.step}.`;
198
- return {
198
+ return this.once({
199
199
  kind: 'restart',
200
200
  what: unexpected ? 'The game restarted unexpectedly' : 'Unexpectedly back at the title',
201
201
  reason: unexpected ? `The page stopped${name === '' ? '' : ` while ${name} was loading or running`}, without an error the game could catch. On a phone this is most often the system closing the page to free memory.${via}`
@@ -203,7 +203,21 @@ export class DropNotes {
203
203
  : `The page left ${name === '' ? 'the world' : name} for the title without the game or you asking (a browser back or reload, or an unmarked navigation).${via}`,
204
204
  step: step.step, world: step.world, name: step.name, message: step.error, code: '', stack: step.errorStack, end: first(said, step.route),
205
205
  trail, routeStack: step.routeStack, at: step.t, build: step.build,
206
- };
206
+ });
207
+ }
208
+
209
+ /**
210
+ * A drop shows once (Jake, 2026-11-13 ~10:05: the 14:48 Driftwood drop came back word for word, same time, after other play).
211
+ * The device copies outlive a quiet take (another tab's copies are its own, so they stay), and a later page that died read the
212
+ * old Playing step back; the device's `seen` mark names the last drop shown, and the same drop (its world and time) never shows again.
213
+ */
214
+ private once(drop: Drop): Drop | null {
215
+ let seen: Json = null;
216
+ try { seen = this.store.read('seen'); } catch { /* storage blocked: show it */ }
217
+ if (drop.at === 0) return drop; // no time to know it by
218
+ if (time(seen, 'at') === drop.at && text(seen, 'world') === drop.world) return null;
219
+ try { this.store.write('seen', { at: drop.at, world: drop.world }); } catch { /* storage blocked */ }
220
+ return drop;
207
221
  }
208
222
 
209
223
  private step(device: boolean): DropStep | null {
@@ -231,7 +245,7 @@ export class DropNotes {
231
245
  const SLOT: Readonly<Record<DropKey, () => ReturnType<typeof jsonSlot>>> = {
232
246
  step: () => jsonSlot('drop.step', 'session'), stepOnce: () => jsonSlot('drop.step.once', 'device'),
233
247
  pending: () => jsonSlot('drop.pending', 'session'), pendingOnce: () => jsonSlot('drop.pending.once', 'device'),
234
- expect: () => jsonSlot('drop.expect', 'session'),
248
+ expect: () => jsonSlot('drop.expect', 'session'), seen: () => jsonSlot('drop.seen', 'device'),
235
249
  };
236
250
  const slotOf = (key: DropKey): ReturnType<typeof jsonSlot> => SLOT[key]();
237
251
  const PAGE_STORE: DropStore = {
@@ -29,6 +29,11 @@
29
29
  * A harness pin still wins; desktop is unchanged.
30
30
  * Whatever picks KTX2, the KTX2 capability probe (src/client/engine/render/ktx2Probe.ts) runs once first and turns it into Images
31
31
  * when this GPU samples mipmapped compressed textures wrong in every compressed format the transcoder could target.
32
+ * OF17 (one form per device and tier): a shard this device has read as KTX2 stays KTX2 on every page of this tier, where the
33
+ * page's own rule would pick images (a grid page's over-cap estimate counts its residents, a one-shard page's doesn't, so
34
+ * the two disagreed on Nine Dragon and the offline page asked for images it never cached). Only towards KTX2: it is never
35
+ * the bigger form. And when one form of a file fails to read and the cache holds the other, the loader reads the held
36
+ * one (core/ktx2.ts `readHeldForm`), so a form the warm visit never read can't park LOAD on RETRY.
32
37
  * Resolved once per SHARD BUILD, on the build's first question (`texMode()`), and never changed inside it: no swap in a
33
38
  * running resident. A grid page can build multiple residents, each with its own TexturePolicyBinding.
34
39
  * The harness pin applies to that page's build. The
@@ -80,6 +85,8 @@ interface TexturePolicyState {
80
85
  readonly level: string | undefined;
81
86
  readonly policy: { mode: TexMode; why: string } | undefined;
82
87
  resolved: { mode: TexMode; why: string } | null;
88
+ /** OF17: this build's KTX2 read is already in the device's memory */
89
+ kept?: boolean;
83
90
  }
84
91
  let pagePolicy: TexturePolicyState = { level: undefined, policy: undefined, resolved: null };
85
92
  const policyFrames: { state: TexturePolicyState }[] = [];
@@ -91,6 +98,11 @@ let autoReady: ((slug: string) => boolean) | null = null;
91
98
  /** shardPrefetch.ts: how Auto learns that a shard's KTX2 set is cached (the marker check) */
92
99
  export function setAutoKtx2Check(fn: (slug: string) => boolean): void { autoReady = fn; }
93
100
 
101
+ /** OF17: the device's memory of the shards it has read as KTX2 on this tier (shardPrefetch.ts keeps it with the markers) */
102
+ export interface DeviceTexForm { read: (slug: string) => boolean; keep: (slug: string) => void }
103
+ let deviceForm: DeviceTexForm | null = null;
104
+ export function setDeviceTexForm(memory: DeviceTexForm | null): void { deviceForm = memory; }
105
+
94
106
  /** G188's automatic tier policy: measured over-cap phone builds use KTX2 before the first visit, never desktop. */
95
107
  export function autoTexturePolicy(mode: TexMode | undefined, imagesFirstPlayingBytes?: number): { mode: TexMode; why: string } | undefined {
96
108
  if (imagesFirstPlayingBytes !== undefined && (!Number.isSafeInteger(imagesFirstPlayingBytes) || imagesFirstPlayingBytes < 0)) throw new RangeError('Invalid images-first playing estimate');
@@ -124,7 +136,7 @@ let resolving = false;
124
136
  * zeroes sRGB mips). No verdict (no page, or a measurement pin) changes nothing. The transcoder reads this same probe. */
125
137
  const noRawAstc = (probe: Ktx2Probe): boolean => probe.ran && probe.families.astc !== true;
126
138
  /** S4: an overlay's raw ASTC 6×6 files have no transcode, so a phone-tier GPU that can't sample ASTC loads images. */
127
- function rawAstcVeto(probe: Ktx2Probe): string | null {
139
+ export function rawAstcVeto(probe: Ktx2Probe): string | null {
128
140
  if (TIER !== 'phone' || !noRawAstc(probe) || ![...registered.phone].some(url => url.includes('/astc6/'))) return null;
129
141
  return 'this table names raw ASTC 6×6 and the GPU has no ASTC';
130
142
  }
@@ -147,6 +159,8 @@ export function texModeWhy(): { mode: TexMode; why: string } {
147
159
  // DL17 (G1000): textures are in their final format at control, so a shard with a KTX2 set boots with it from the first
148
160
  // visit (its stand-ins download with the boot) instead of drawing images and swapping on the next visit
149
161
  else state.resolved = autoReady?.(slug) === true ? { mode: 'ktx2', why: `auto: ${slug} has a KTX2 set (its final format from the first visit)` } : { mode: 'img', why: `auto: ${slug} has no KTX2 set for this tier` };
162
+ // OF17: a shard this device has read as KTX2 keeps that form on this page too (the grid's choice on a one-shard page)
163
+ if (state.resolved.mode === 'img' && deviceForm?.read(slug) === true) state.resolved = { mode: 'ktx2', why: `auto: this device read ${slug} as KTX2 (OF17)` };
150
164
  }
151
165
  // last, whatever picked KTX2 (a harness pin included): a GPU that samples the transcoder's only compressed targets
152
166
  // wrong when mipmapped loads images (render/ktx2Probe.ts — the iOS Simulator's zeroed sRGB ASTC / ETC2 mips; a
@@ -172,5 +186,14 @@ export function standIn(served: string, tex: TexMode): string | undefined {
172
186
  }
173
187
  /** the KTX2 stand-in of a file this tier fetches, when this page loads KTX2 */
174
188
  export function gpuFile(served: string): string | undefined {
175
- return standIn(served, texMode());
189
+ const file = standIn(served, texMode());
190
+ if (file !== undefined) keepKtx2Read();
191
+ return file;
192
+ }
193
+ /** OF17: this build reads a KTX2 stand-in under Auto: the device remembers the shard's form (once per build) */
194
+ function keepKtx2Read(): void {
195
+ const state = activePolicy();
196
+ if (state.kept === true || deviceForm === null || texturePin() !== 'auto') return;
197
+ state.kept = true;
198
+ deviceForm.keep(state.level ?? PAGE_LEVEL);
176
199
  }
@@ -300,13 +300,19 @@ export function holdLeaving(save: () => Promise<unknown>): () => void {
300
300
  saver = save;
301
301
  return () => { if (saver === save) saver = null; };
302
302
  }
303
+ let leaveFirst: (() => Promise<void>) | null = null;
304
+ /** A step a navigation the game chose waits for, beside the save (play's back guard steps off its history entry, ui/backGuard.ts). */
305
+ export function beforeLeaving(first: (() => Promise<void>) | null): void { leaveFirst = first; }
303
306
  /** Run a navigation the game chose, once what a held session has made is durable. With nothing held this is the navigation, now. */
304
307
  export function leaveSaved(go: () => void): void {
305
- if (saver === null) { go(); return; }
308
+ const first = leaveFirst;
309
+ leaveFirst = null;
310
+ if (saver === null && first === null) { go(); return; }
306
311
  const save = saver;
307
312
  saver = null; // a second tap goes the same way, and doesn't save or wait twice
308
- void atMostLeaveWait(save()).then(go);
313
+ void Promise.all([save === null ? undefined : atMostLeaveWait(save()), first?.()]).then(() => go());
309
314
  }
315
+
310
316
  export function lastEnd(): LastEnd { return page.lastEnd(); }
311
317
  export function lastRecordedEnd(): LastEnd | null { return page.lastRecordedEnd(); }
312
318
  export function lastEndLine(now: number = Date.now()): string { return page.lastEndLine(now); }
@@ -1,29 +1,89 @@
1
- /** Private worker transfer format: bounded JSON token pages, never a cloned
1
+ /** Private worker transfer format: binary tokens decoded in bounded steps, never a cloned
2
2
  * descriptor tree. Admission still runs on the completely reconstructed tree. */
3
- /** Native fatal UTF-8/JSON semantics, then bounded live-parser transfer pages. */
3
+ /** Native fatal UTF-8/JSON semantics, then the live parser's binary token transfer. */
4
4
  export function parseJsonPages(bytes: Uint8Array): Uint8Array {
5
5
  const value: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
6
6
  return encodeParsedPages(value);
7
7
  }
8
8
 
9
- type Token = readonly ['o' | 'a', number] | readonly ['s', string, boolean]
10
- | readonly ['n', string] | readonly ['v', boolean | null];
9
+ /* PZ23 (WILDSHARD-GAME-8G): binary tokens, so a number crosses as a float64 and the page thread makes no string for it
10
+ * (the JSON token pages before made a token array and two strings a number: ~400 bytes of garbage, ~211 MB in the
11
+ * first minute on Driftwood). Little-endian, after one version byte:
12
+ * OBJECT u32 count · ARRAY u32 count · NUMBER f64 · NULL · FALSE · TRUE
13
+ * UTF8 u8 last, u32 bytes, UTF-8 · UTF16 u8 last, u32 units, UTF-16 units (a string that is not well formed: a lone
14
+ * surrogate survives JSON.parse, never UTF-8). A string goes in parts of at most PART code units.
15
+ * REF u32 index: a short string sent before (at most SHORT code units: keys, names, kinds), the index-th such string in
16
+ * send order, so a repeated key costs the page thread no view and no decode. */
17
+ const VERSION = 0x57, OBJECT = 1, ARRAY = 2, UTF8 = 3, UTF16 = 4, NUMBER = 5, NULL = 6, FALSE = 7, TRUE = 8, REF = 9;
18
+ const SHORT = 64;
19
+ /** A string part's code units, and a decode step's bounds: at most STEP_TOKENS tokens or STEP_BYTES transfer bytes. */
20
+ const PART = 4096, STEP_TOKENS = 32, STEP_BYTES = 16_384;
11
21
 
12
- function* tokens(input: unknown): Generator<Token> {
13
- const pending: unknown[] = [input];
22
+ class Writer {
23
+ bytes = new Uint8Array(65_536);
24
+ view = new DataView(this.bytes.buffer);
25
+ at = 0;
26
+ private readonly encoder = new TextEncoder();
27
+ private readonly short = new Map<string, number>();
28
+ room(n: number): void {
29
+ if (this.at + n <= this.bytes.length) return;
30
+ let size = this.bytes.length * 2;
31
+ while (size < this.at + n) size *= 2;
32
+ const next = new Uint8Array(size); next.set(this.bytes.subarray(0, this.at));
33
+ this.bytes = next; this.view = new DataView(next.buffer);
34
+ }
35
+ tag(tag: number): void { this.room(1); this.bytes[this.at++] = tag; }
36
+ count(tag: number, n: number): void { this.room(5); this.bytes[this.at] = tag; this.view.setUint32(this.at + 1, n, true); this.at += 5; }
37
+ number(value: number): void { this.room(9); this.bytes[this.at] = NUMBER; this.view.setFloat64(this.at + 1, value, true); this.at += 9; }
38
+ string(value: string): void {
39
+ if (value.length <= SHORT) {
40
+ const index = this.short.get(value);
41
+ if (index !== undefined) { this.count(REF, index); return; }
42
+ this.short.set(value, this.short.size);
43
+ }
44
+ // in a Unicode-mode class a whole pair is one code point, so only a lone surrogate matches
45
+ const utf8 = !/[\uD800-\uDFFF]/u.test(value);
46
+ if (value.length === 0) { this.part(UTF8, 1, 0); return; }
47
+ for (let from = 0; from < value.length;) {
48
+ let to = Math.min(value.length, from + PART);
49
+ // never split a surrogate pair across UTF-8 parts
50
+ if (utf8 && to < value.length && (value.codePointAt(to - 1) ?? 0) > 0xffff) to--;
51
+ const last = to >= value.length ? 1 : 0;
52
+ if (utf8) {
53
+ this.room(6 + (to - from) * 3);
54
+ const { written } = this.encoder.encodeInto(value.slice(from, to), this.bytes.subarray(this.at + 6));
55
+ this.part(UTF8, last, written); this.at += written;
56
+ } else {
57
+ this.room(6 + (to - from) * 2);
58
+ this.part(UTF16, last, to - from);
59
+ // oxlint-disable-next-line unicorn/prefer-code-point -- UTF-16 units, not code points: a lone surrogate crosses as it is
60
+ for (let i = from; i < to; i++, this.at += 2) this.view.setUint16(this.at, value.charCodeAt(i), true);
61
+ }
62
+ from = to;
63
+ }
64
+ }
65
+ /** A string part's head; its body follows at `at`. */
66
+ private part(tag: number, last: number, length: number): void {
67
+ this.room(6); this.bytes[this.at] = tag; this.bytes[this.at + 1] = last; this.view.setUint32(this.at + 2, length, true); this.at += 6;
68
+ }
69
+ }
70
+
71
+ /** Called only on the worker's native JSON.parse result. */
72
+ export function encodeParsedPages(input: unknown): Uint8Array {
73
+ const out = new Writer(), pending: unknown[] = [input];
74
+ out.tag(VERSION);
14
75
  while (pending.length > 0) {
15
76
  const value = pending.pop();
16
- if (typeof value === 'string') {
17
- if (value.length === 0) yield ['s', '', true];
18
- for (let at = 0; at < value.length; at += 256) yield ['s', value.slice(at, at + 256), at + 256 >= value.length];
19
- } else if (typeof value === 'number') yield ['n', Object.is(value, -0) ? '-0' : String(value)];
20
- else if (value === null || typeof value === 'boolean') yield ['v', value];
77
+ if (typeof value === 'string') out.string(value);
78
+ else if (typeof value === 'number') out.number(value);
79
+ else if (value === null) out.tag(NULL);
80
+ else if (typeof value === 'boolean') out.tag(value ? TRUE : FALSE);
21
81
  else if (Array.isArray(value)) {
22
- yield ['a', value.length];
82
+ out.count(ARRAY, value.length);
23
83
  for (let at = value.length - 1; at >= 0; at--) pending.push(value[at]);
24
84
  } else if (typeof value === 'object') {
25
85
  const entries = Object.entries(value);
26
- yield ['o', entries.length];
86
+ out.count(OBJECT, entries.length);
27
87
  for (let at = entries.length - 1; at >= 0; at--) {
28
88
  const entry = entries[at];
29
89
  if (entry === undefined) throw new Error('Missing parsed entry');
@@ -31,38 +91,21 @@ function* tokens(input: unknown): Generator<Token> {
31
91
  }
32
92
  } else throw new TypeError('Invalid parsed value');
33
93
  }
94
+ return out.bytes.slice(0, out.at);
34
95
  }
35
96
 
36
- /** Called only on the worker's native JSON.parse result. */
37
- export function encodeParsedPages(value: unknown): Uint8Array {
38
- const encoder = new TextEncoder(), pages: Uint8Array[] = [];
39
- let page: string[] = [], characters = 0, bytes = 0;
40
- const flush = (): void => {
41
- if (page.length === 0) return;
42
- const encoded = encoder.encode(`[${page.join(',')}]`);
43
- pages.push(encoded); bytes += 4 + encoded.length; page = []; characters = 0;
44
- };
45
- for (const token of tokens(value)) {
46
- const text = JSON.stringify(token);
47
- if (page.length >= 32 || characters + text.length > 4096) flush();
48
- page.push(text); characters += text.length + 1;
49
- }
50
- flush();
51
- const output = new Uint8Array(bytes), view = new DataView(output.buffer);
52
- let at = 0;
53
- for (const part of pages) { view.setUint32(at, part.length, true); output.set(part, at + 4); at += 4 + part.length; }
54
- return output;
55
- }
56
-
57
- type Frame = {readonly value: unknown[]; remaining: number}
97
+ type Frame = {readonly value: unknown[]; remaining: number; next: number}
58
98
  | {readonly value: Record<string, unknown>; remaining: number; key: string | undefined};
59
99
 
60
- /** Yield between every bounded native decode/parse and tree-construction page.
100
+ /** Yield before every bounded decode step (at most 32 tokens or 16 KiB of transfer) and once at the end.
61
101
  * Nothing caller-visible is published until the entire transfer is checked. */
62
102
  export async function decodeParsedPages(bytes: Uint8Array, pause: () => Promise<void>): Promise<unknown> {
63
- const frames: Frame[] = [], decoder = new TextDecoder('utf-8', {fatal: true});
103
+ // ignoreBOM: each part is decoded alone, and a string may start with U+FEFF
104
+ const frames: Frame[] = [], decoder = new TextDecoder('utf-8', {fatal: true, ignoreBOM: true});
105
+ let slots = 0;
64
106
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
65
107
  let root: unknown, hasRoot = false, string: string | undefined;
108
+ const short: string[] = [];
66
109
  const put = (value: unknown): void => {
67
110
  const frame = frames.at(-1);
68
111
  if (frame === undefined) {
@@ -76,35 +119,61 @@ export async function decodeParsedPages(bytes: Uint8Array, pause: () => Promise<
76
119
  if (Object.hasOwn(frame.value, frame.key)) throw new Error('Duplicate parsed key');
77
120
  Object.defineProperty(frame.value, frame.key, {value, writable: true, enumerable: true, configurable: true});
78
121
  frame.key = undefined; frame.remaining--;
79
- } else { frame.value.push(value); frame.remaining--; }
122
+ } else { frame.value[frame.next++] = value; frame.remaining--; }
80
123
  };
81
124
  const complete = (): void => { while (frames.at(-1)?.remaining === 0) frames.pop(); };
82
- for (let at = 0; at < bytes.length;) {
125
+ const need = (at: number, n: number): void => { if (n > bytes.length - at) throw new Error('Incomplete parsed token'); };
126
+ if (bytes.length === 0 || bytes[0] !== VERSION) throw new Error('Invalid parsed transfer');
127
+ for (let at = 1; at < bytes.length;) {
83
128
  await pause();
84
- if (at + 4 > bytes.length) throw new Error('Incomplete parsed page');
85
- const length = view.getUint32(at, true); at += 4;
86
- if (length === 0 || length > 16_384 || length > bytes.length - at) throw new Error('Invalid parsed page');
87
- const page: unknown = JSON.parse(decoder.decode(bytes.subarray(at, at + length))); at += length;
88
- if (!Array.isArray(page) || page.length === 0 || page.length > 32) throw new Error('Invalid parsed tokens');
89
- for (const token of page) {
90
- if (!Array.isArray(token)) throw new Error('Invalid parsed token');
91
- const [kind, value, last] = token;
92
- if (kind === 's' && token.length === 3 && typeof value === 'string' && value.length <= 256 && typeof last === 'boolean') {
93
- string = (string ?? '') + value;
94
- if (last) { put(string); string = undefined; complete(); }
129
+ const stepEnd = at + STEP_BYTES;
130
+ for (let tokens = 0; tokens < STEP_TOKENS && at < bytes.length && at < stepEnd; tokens++) {
131
+ const tag = bytes[at++];
132
+ if (tag === UTF8 || tag === UTF16) {
133
+ need(at, 5);
134
+ const last = bytes[at], length = view.getUint32(at + 1, true); at += 5;
135
+ if ((last !== 0 && last !== 1) || length > (tag === UTF8 ? PART * 3 : PART)) throw new Error('Invalid parsed string');
136
+ const size = tag === UTF8 ? length : length * 2;
137
+ need(at, size);
138
+ let part = '';
139
+ if (tag === UTF8) part = decoder.decode(bytes.subarray(at, at + size));
140
+ // oxlint-disable-next-line unicorn/prefer-code-point -- UTF-16 units, not code points: a lone surrogate crosses as it is
141
+ else for (let i = 0; i < length; i++) part += String.fromCharCode(view.getUint16(at + i * 2, true));
142
+ at += size;
143
+ string = string === undefined ? part : string + part;
144
+ if (last === 1) { if (string.length <= SHORT) short.push(string); put(string); string = undefined; complete(); }
95
145
  continue;
96
146
  }
97
- if (string !== undefined || token.length !== 2) throw new Error('Incomplete parsed string');
98
- if ((kind === 'o' || kind === 'a') && typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) {
99
- if (kind === 'a') {
100
- const container: unknown[] = []; put(container);
101
- if (value > 0) frames.push({value: container, remaining: value});
147
+ if (string !== undefined) throw new Error('Incomplete parsed string');
148
+ if (tag === REF) {
149
+ need(at, 4);
150
+ const value = short[view.getUint32(at, true)]; at += 4;
151
+ if (value === undefined) throw new Error('Invalid parsed reference');
152
+ put(value); complete(); continue;
153
+ }
154
+ if (tag === OBJECT || tag === ARRAY) {
155
+ need(at, 4);
156
+ const count = view.getUint32(at, true); at += 4;
157
+ // every element or entry takes at least one more byte, so no count, nor all of them together, sizes past the transfer
158
+ slots += count;
159
+ if (count > bytes.length - at || slots > bytes.length) throw new Error('Invalid parsed count');
160
+ if (tag === ARRAY) {
161
+ // sized once: a pushed array regrows and leaves its old backing stores behind
162
+ // oxlint-disable-next-line unicorn/no-new-array -- a length: the decode fills every slot before anything is published
163
+ const container: unknown[] = new Array<unknown>(count); put(container);
164
+ if (count > 0) frames.push({value: container, remaining: count, next: 0});
102
165
  } else {
103
166
  const container: Record<string, unknown> = {}; put(container);
104
- if (value > 0) frames.push({value: container, remaining: value, key: undefined});
167
+ if (count > 0) frames.push({value: container, remaining: count, key: undefined});
105
168
  }
106
- } else if (kind === 'n' && typeof value === 'string' && (value === '-0' || String(Number(value)) === value)) put(Number(value));
107
- else if (kind === 'v' && (value === null || typeof value === 'boolean')) put(value);
169
+ } else if (tag === NUMBER) {
170
+ need(at, 8);
171
+ const value = view.getFloat64(at, true); at += 8;
172
+ if (Number.isNaN(value)) throw new Error('Invalid parsed number');
173
+ put(value);
174
+ } else if (tag === NULL) put(null);
175
+ else if (tag === FALSE) put(false);
176
+ else if (tag === TRUE) put(true);
108
177
  else throw new Error('Invalid parsed token');
109
178
  complete();
110
179
  }
@@ -39,7 +39,7 @@ import { bootCatalog, type BootLevel } from './catalog';
39
39
  import { bootFiles } from './extras';
40
40
  import { bootParts, packFor } from './pack';
41
41
  import { gpuUrl, versionedUrl } from './bytes';
42
- import { isRegisteredGpuFile, registerGpuFiles, setAutoKtx2Check, texMode, texModeWhy, texturePin, type TexMode } from './gpuFiles';
42
+ import { isRegisteredGpuFile, registerGpuFiles, setAutoKtx2Check, setDeviceTexForm, texMode, texModeWhy, texturePin, type TexMode } from './gpuFiles';
43
43
  import { BASIS_PATH } from '../core/ktx2';
44
44
  import { ktx2ProbeResult } from '../render/ktx2Probe';
45
45
  import { TIER } from '../core/tier';
@@ -110,6 +110,12 @@ function markKtx2(def: BootLevel, complete: boolean, hash: string): void {
110
110
  }
111
111
  // DL17: Auto boots a shard's KTX2 set from the first visit (no images-then-KTX2 swap); the marker still records the cached set
112
112
  setAutoKtx2Check((slug) => { const def = bootCatalog().find(slug); return def !== undefined && ktx2Set(def).length > 0; });
113
+ /** OF17: the device's note that it read `slug` as KTX2 on this tier, kept beside the set markers (Clear downloads drops both) */
114
+ export const ktx2ReadKey = (slug: string): string => `ktx2set:${slug}.${TIER}.read`;
115
+ setDeviceTexForm({
116
+ read: (slug) => { try { return savedStorage.getItem(ktx2ReadKey(slug)) !== null; } catch { return false; } },
117
+ keep: (slug) => { try { savedStorage.setItem(ktx2ReadKey(slug), '1'); } catch { /* private mode: each page keeps its own rule */ } },
118
+ });
113
119
 
114
120
  export interface PrefetchEnv {
115
121
  /** a service worker controls the page (its caches are where the files go) */
@@ -68,6 +68,8 @@ let watched: ServiceWorkerRegistration | null = null;
68
68
  let newestBuild: string | null = null;
69
69
  let discovery = 0;
70
70
  let controlEvent = false, controlFrames = false, controlReached = false, precacheTarget: ServiceWorkerRegistration | null = null, precacheAsked = false;
71
+ /** OF5a: the title settled (`ws:title-settled`), and whether its update precache was asked */
72
+ let titleSettled = false, updateAsked = false;
71
73
  // declared ahead of the functions that read it (they only run after registration; `boot()` is hoisted)
72
74
  const api: WsSw = { ready: boot(), enabled: swAllowed(), waiting: null, adopt, version };
73
75
 
@@ -351,6 +353,20 @@ function askPrecache(): void {
351
353
  if (!precacheAsked && installing !== null) pageScope.listen(installing, 'statechange', () => { ask(installing); });
352
354
  }
353
355
 
356
+ /** OFFLINE OF5a: a title page never reaches control, so a build update seen only on the title held none of its code, and the
357
+ * first offline launch failed on it. A settled title (mainMenu.ts) asks the active and the waiting worker for an update
358
+ * precache; each does it only on a device that holds an older build's generation (sw.js), so a first visit reads nothing. */
359
+ function askUpdatePrecache(): void {
360
+ const reg = precacheTarget;
361
+ if (!titleSettled || updateAsked || reg === null || controlReached || pageScope.disposed || pageScope.disposing) return;
362
+ for (const w of [reg.active, reg.waiting]) {
363
+ if (w === null || w.state !== 'activated' && w.state !== 'installed') continue;
364
+ // oxlint-disable-next-line unicorn/require-post-message-target-origin -- ServiceWorker.postMessage has no targetOrigin parameter.
365
+ try { w.postMessage({ type: 'PRECACHE', update: true }); } catch { /* a retired worker is asked on the next title */ }
366
+ }
367
+ updateAsked = true;
368
+ }
369
+
354
370
  async function register(s: ServiceWorkerContainer): Promise<void> {
355
371
  const url = import.meta.env.DEV ? '/sw.js?sw=1' : '/sw.js';
356
372
  let reg: ServiceWorkerRegistration;
@@ -374,6 +390,9 @@ async function register(s: ServiceWorkerContainer): Promise<void> {
374
390
  if (w !== null && w !== undefined) try { w.postMessage({ type: 'PAUSE' }); } catch { /* a retired worker has nothing to pause */ }
375
391
  }
376
392
  precacheTarget = reg; afterControl();
393
+ // OF5a: a title that settled before this registration landed (slow WebKit registration) marked the document; else it says so later
394
+ if (document.documentElement.dataset['wsTitleSettled'] === '1') { titleSettled = true; askUpdatePrecache(); }
395
+ else pageScope.listen(document, 'ws:title-settled', () => { titleSettled = true; askUpdatePrecache(); }, { once: true });
377
396
  // Standalone installs live for days: keep discovering updates so the pill can offer them.
378
397
  pageScope.listen(document, 'visibilitychange', () => {
379
398
  if (!document.hidden) void reg.update().catch(() => undefined);
@@ -1,2 +1,4 @@
1
1
  /** Vite's compiled author-dev mode. Production/native builds always substitute false. */
2
2
  declare const __DEVSERVER__: boolean;
3
+ /** SHARD-AUTHORING SA43: a `WILDSHARD_PREPARATION_ONLY` production build, the client `wildshard prepare` records in. */
4
+ declare const __PREPARATION_ONLY__: boolean;