@wildshard/engine 0.1.18 → 0.1.20

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 (334) 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 +18 -0
  5. package/lint/ratchet.json +0 -68
  6. package/lint/ratchet.mjs +1 -4
  7. package/package.json +19 -15
  8. package/scripts/agent-sync.mjs +27 -8
  9. package/scripts/app-build/appCook.ts +8 -2
  10. package/scripts/app-build/catalogue.ts +10 -7
  11. package/scripts/app-build/gen.ts +33 -2
  12. package/scripts/app-build/isolation.d.mts +10 -0
  13. package/scripts/app-build/isolation.mjs +47 -0
  14. package/scripts/app-build/outputProducts.mjs +4 -0
  15. package/scripts/app-build/previousDeploy.d.mts +2 -0
  16. package/scripts/app-build/previousDeploy.mjs +10 -1
  17. package/scripts/app-build/serviceWorker.ts +10 -3
  18. package/scripts/app-build/splitOutput.mjs +4 -2
  19. package/scripts/app-build/standaloneOutput.d.mts +1 -1
  20. package/scripts/app-build/standaloneOutput.mjs +5 -3
  21. package/scripts/app-build/titlePreloads.d.mts +8 -0
  22. package/scripts/app-build/titlePreloads.mjs +69 -0
  23. package/scripts/app-build/worldMapAtlas.ts +10 -6
  24. package/scripts/app-build-pipeline.mjs +31 -3
  25. package/scripts/built-product.mjs +1 -1
  26. package/scripts/cell-mem-bench.mjs +83 -23
  27. package/scripts/check-custom-sections-zero.mjs +1 -1
  28. package/scripts/check-devserver.mjs +2 -0
  29. package/scripts/check-models.mjs +2 -0
  30. package/scripts/check-paths.allow.json +0 -115
  31. package/scripts/check-paths.mjs +2 -2
  32. package/scripts/check-platform-ratchets.mjs +2 -3
  33. package/scripts/chromium-keychain.d.mts +1 -1
  34. package/scripts/ci-static.sh +1 -1
  35. package/scripts/committed-fast-checks.mjs +0 -2
  36. package/scripts/content-sw-proof.mjs +2 -1
  37. package/scripts/cook-worker.mjs +9 -3
  38. package/scripts/cook.mjs +18 -5
  39. package/scripts/docs-inputs-proof.mjs +6 -6
  40. package/scripts/e7-voice-staging-proof.mjs +1 -1
  41. package/scripts/gate-related-tests.mjs +1 -1
  42. package/scripts/git-source-view.mjs +1 -1
  43. package/scripts/goldens/capture.mjs +17 -5
  44. package/scripts/grid-crossing-nightly.mjs +59 -0
  45. package/scripts/grid-crossing-qa.mjs +44 -0
  46. package/scripts/grid-crossing-ratchet.d.mts +6 -0
  47. package/scripts/grid-crossing-ratchet.mjs +52 -0
  48. package/scripts/grid-crossing-report.mjs +122 -0
  49. package/scripts/grid-crossing-stages.mjs +47 -0
  50. package/scripts/grid-crossing-tour.mjs +284 -0
  51. package/scripts/grid-crossing-walk-proof.mjs +126 -17
  52. package/scripts/host-ruler/roots.mjs +2 -2
  53. package/scripts/host-ruler.d.mts +91 -0
  54. package/scripts/host-ruler.mjs +565 -0
  55. package/scripts/land.mjs +2 -1
  56. package/scripts/live-prepush.py +3 -5
  57. package/scripts/loading-flow/benchmax.mjs +37 -12
  58. package/scripts/loading-flow/deskbench.mjs +276 -0
  59. package/scripts/loading-flow/stalls.d.mts +17 -3
  60. package/scripts/loading-flow/stalls.mjs +82 -3
  61. package/scripts/look-loop/test_look_loop.py +1 -38
  62. package/scripts/memory-proof.mjs +61 -6
  63. package/scripts/mmo-bots.mjs +8 -2
  64. package/scripts/net-lag-proof.mjs +219 -0
  65. package/scripts/night-market-kit-budget.mjs +2 -2
  66. package/scripts/nightly-model.ts +9 -6
  67. package/scripts/offline-proof-rules.d.mts +2 -2
  68. package/scripts/offline-proof-rules.mjs +15 -4
  69. package/scripts/offline-proof.mjs +80 -13
  70. package/scripts/{shard-platform-output.mjs → output-reader.mjs} +1 -1
  71. package/scripts/page-release/content.d.mts +9 -1
  72. package/scripts/page-release/content.mjs +131 -17
  73. package/scripts/page-release/flow.mjs +36 -10
  74. package/scripts/page-release/stamp-content.mjs +24 -0
  75. package/scripts/page-release.mjs +28 -6
  76. package/scripts/page-size.mjs +2 -1
  77. package/scripts/parity/boot-smoke.mjs +13 -2
  78. package/scripts/pin-format.ts +5 -2
  79. package/scripts/pin-packs.ts +1 -1
  80. package/scripts/pins-reuse.d.mts +1 -0
  81. package/scripts/pins-reuse.mjs +22 -0
  82. package/scripts/pins.ts +4 -4
  83. package/scripts/precommit-checks.mjs +1 -7
  84. package/scripts/precommit-jobs.mjs +0 -1
  85. package/scripts/precommit-source.py +1 -9
  86. package/scripts/program-discovery.mjs +1 -1
  87. package/scripts/ring-cook.mjs +2 -1
  88. package/scripts/ring-step.ts +1 -1
  89. package/scripts/scratch-dir.mjs +95 -0
  90. package/scripts/scratch-sweep.mjs +182 -0
  91. package/scripts/script-scenario-metrics.mjs +1 -1
  92. package/scripts/shard-output-content.d.mts +1 -1
  93. package/scripts/shard-output-content.mjs +2 -2
  94. package/scripts/shard-outputs.mjs +1 -1
  95. package/scripts/shard-public.mjs +1 -1
  96. package/scripts/shard-wire-meter.mjs +24 -9
  97. package/scripts/side-parity.mjs +4 -2
  98. package/scripts/standalone-smoke.mjs +8 -3
  99. package/scripts/tier-textures.mjs +22 -4
  100. package/scripts/tile-bake-report.mjs +1 -1
  101. package/scripts/tile-bakes.mjs +1 -1
  102. package/scripts/title-assets.generated.json +2 -0
  103. package/scripts/tsconfig.json +2 -14
  104. package/scripts/vendor/basisu/LICENSE +201 -0
  105. package/scripts/vendor/basisu/basis_encoder.cjs +2 -0
  106. package/scripts/vendor/basisu/basis_encoder.wasm +0 -0
  107. package/scripts/vitest-push-guards.config.ts +1 -1
  108. package/scripts/vps/harden-apply.sh +4 -1
  109. package/scripts/vps/harden-prometheus.sh +179 -0
  110. package/scripts/vps/harden.sh +16 -0
  111. package/scripts/vps/rebuild.sh +18 -0
  112. package/scripts/vps/wildshard-config +6 -2
  113. package/scripts/worker-client-play.mjs +6 -2
  114. package/scripts/worktree-reap.mjs +59 -13
  115. package/scripts/worktree.mjs +19 -5
  116. package/src/.oxlintrc.json +3 -182
  117. package/src/client/app/entry.ts +10 -2
  118. package/src/client/engine/anim/rigParser.ts +2 -2
  119. package/src/client/engine/boot/bootCache.ts +2 -2
  120. package/src/client/engine/boot/bootTrace.ts +12 -4
  121. package/src/client/engine/boot/browserChunkRecovery.ts +4 -0
  122. package/src/client/engine/boot/clearDownloads.ts +5 -2
  123. package/src/client/engine/boot/contentRead.ts +11 -0
  124. package/src/client/engine/boot/gpuFiles.ts +4 -2
  125. package/src/client/engine/boot/lastEnd.ts +99 -12
  126. package/src/client/engine/boot/texturePack.ts +2 -2
  127. package/src/client/engine/core/Game.ts +63 -19
  128. package/src/client/engine/core/gpuOnly.ts +10 -0
  129. package/src/client/engine/core/renderBudget.ts +134 -0
  130. package/src/client/engine/net/netPlayer.ts +19 -2
  131. package/src/client/engine/net/otherPlayers.ts +55 -8
  132. package/src/client/engine/net/predictor.ts +33 -9
  133. package/src/client/engine/net/redial.ts +68 -10
  134. package/src/client/engine/pwa/cacheNames.ts +58 -1
  135. package/src/client/engine/pwa/sw.js +41 -11
  136. package/src/client/engine/render/dataLook.ts +219 -44
  137. package/src/client/engine/render/families/detail.ts +89 -0
  138. package/src/client/engine/render/families/pbr.ts +9 -1
  139. package/src/client/engine/render/families/registry.ts +11 -2
  140. package/src/client/engine/render/families/sceneSurface.ts +116 -0
  141. package/src/client/engine/render/look.ts +12 -0
  142. package/src/client/engine/render/lookLight.ts +103 -11
  143. package/src/client/engine/render/lookRender.ts +105 -0
  144. package/src/client/engine/render/precompile.ts +4 -2
  145. package/src/client/engine/render/tiers.ts +4 -1
  146. package/src/client/engine/saves/indexed.ts +2 -2
  147. package/src/client/engine/telemetry/browserErrors.ts +24 -3
  148. package/src/client/engine/telemetry/staleBuildReport.ts +22 -1
  149. package/src/client/engine/ui/debugOptions.ts +1 -1
  150. package/src/client/engine/ui/lookLightOption.ts +10 -6
  151. package/src/client/engine/ui/namePrompt.ts +7 -0
  152. package/src/client/engine/world/declaredProps.ts +5 -1
  153. package/src/client/engine/world/skyRig.ts +4 -1
  154. package/src/client/engine/world/terrainTileView.ts +64 -23
  155. package/src/client/game/boot/audio.generated.ts +114 -114
  156. package/src/client/game/boot/bytes.generated.ts +118 -220
  157. package/src/client/game/boot/placedSpawn.ts +35 -0
  158. package/src/client/game/boot/spawnDownload.ts +25 -6
  159. package/src/client/game/boot/versions.generated.ts +7 -5
  160. package/src/client/game/devScene/hook.ts +428 -0
  161. package/src/client/game/devScene/liveLook.ts +21 -0
  162. package/src/client/game/grid/cellLoading.ts +12 -2
  163. package/src/client/game/grid/live.ts +152 -19
  164. package/src/client/game/grid/liveSession.ts +53 -3
  165. package/src/client/game/grid/mapAtlas.ts +18 -4
  166. package/src/client/game/grid/minimapBlend.ts +15 -5
  167. package/src/client/game/grid/oneWayIn.ts +5 -1
  168. package/src/client/game/grid/pageEntry.ts +12 -1
  169. package/src/client/game/grid/placedCells.ts +114 -12
  170. package/src/client/game/grid/placedContent.ts +85 -0
  171. package/src/client/game/grid/prefetch.ts +9 -1
  172. package/src/client/game/grid/productInputs.ts +23 -10
  173. package/src/client/game/grid/productLeases.ts +4 -1
  174. package/src/client/game/grid/products.ts +8 -4
  175. package/src/client/game/grid/roadLook.ts +24 -15
  176. package/src/client/game/grid/roadLookPlatform.ts +4 -2
  177. package/src/client/game/grid/roadResources.ts +24 -0
  178. package/src/client/game/grid/roadSign.worker.ts +4 -3
  179. package/src/client/game/grid/roadSignPaint.ts +16 -5
  180. package/src/client/game/grid/roadSignPreparation.ts +4 -3
  181. package/src/client/game/grid/roadSignScale.ts +8 -0
  182. package/src/client/game/grid/roadTileCapture.worker.ts +3 -1
  183. package/src/client/game/grid/roadTileCaptureWorker.ts +2 -1
  184. package/src/client/game/grid/roadTileWrite.worker.ts +4 -2
  185. package/src/client/game/grid/roadTileWriter.ts +2 -1
  186. package/src/client/game/grid/screenReports.ts +39 -0
  187. package/src/client/game/grid/session.ts +32 -7
  188. package/src/client/game/grid/softWallLook.ts +25 -8
  189. package/src/client/game/mainMenu.ts +6 -2
  190. package/src/client/game/plugin/context.ts +2 -1
  191. package/src/client/game/plugin/followedMovers.ts +7 -1
  192. package/src/client/game/quest/figures.ts +2 -0
  193. package/src/client/game/session/finish.ts +9 -0
  194. package/src/client/game/shardfile/assetCache.ts +4 -4
  195. package/src/client/game/shardfile/client.ts +28 -8
  196. package/src/client/game/shardfile/clientAssets.ts +9 -5
  197. package/src/client/game/shardfile/clientLibrary.ts +1 -1
  198. package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
  199. package/src/client/game/shardfile/clientViews.ts +36 -8
  200. package/src/client/game/shardfile/clientWater.ts +51 -9
  201. package/src/client/game/shardfile/clientWorker.ts +19 -7
  202. package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
  203. package/src/client/game/shardfile/groundMerge.ts +57 -5
  204. package/src/client/game/shardfile/hybrid.ts +2 -0
  205. package/src/client/game/shardfile/look.ts +8 -3
  206. package/src/client/game/shardfile/product.ts +34 -7
  207. package/src/client/game/shardfile/productChecks.ts +2 -2
  208. package/src/client/game/shardfile/productCost.ts +2 -2
  209. package/src/client/game/shardfile/readAsset.ts +2 -2
  210. package/src/client/game/shardfile/reflectingWater.ts +73 -0
  211. package/src/client/game/shardfile/seatGrace.ts +9 -0
  212. package/src/client/game/shardfile/skinPlayback.ts +1 -1
  213. package/src/client/game/shardfile/slabLibrary.ts +115 -49
  214. package/src/client/game/shardfile/tileContent.ts +1 -1
  215. package/src/client/game/shardfile/tileDriver.ts +38 -11
  216. package/src/client/game/shardfile/wirePage.ts +7 -3
  217. package/src/client/game/shardfile/worldScenes.ts +17 -10
  218. package/src/client/game/systems/npc/figureRows.ts +9 -0
  219. package/src/client/host/online/doctor.ts +22 -7
  220. package/src/client/host/online/doctorView.ts +2 -0
  221. package/src/client/host/online/linkScreens.ts +109 -5
  222. package/src/client/host/online/shell.ts +13 -4
  223. package/src/client/host/standalone/shell.ts +40 -0
  224. package/src/cook/game/astc6Encode.ts +55 -0
  225. package/src/cook/game/astc6Wasm.ts +176 -0
  226. package/src/cook/game/cookJob.ts +30 -6
  227. package/src/cook/game/cookWorker.ts +38 -11
  228. package/src/cook/game/entryTotals.ts +51 -24
  229. package/src/cook/game/shardCook.ts +35 -7
  230. package/src/cook/game/spawnParts.ts +33 -8
  231. package/src/cook/game/tierTextures.ts +87 -14
  232. package/src/server/engine/ai/bossContenders.ts +27 -3
  233. package/src/server/engine/ai/phases.ts +1 -1
  234. package/src/server/engine/entities/creatureRefill.ts +9 -2
  235. package/src/server/engine/net/ledgerBook.ts +2 -0
  236. package/src/server/engine/net/room.ts +15 -0
  237. package/src/server/engine/sim/respawn.ts +8 -0
  238. package/src/server/game/boss/arenaRoomEntry.ts +5 -1
  239. package/src/server/game/boss/arenaRoomNative.ts +2 -0
  240. package/src/server/game/boss/native.ts +2 -1
  241. package/src/server/game/boss/nativeWake.ts +9 -5
  242. package/src/server/game/boss/openArenaNative.ts +2 -2
  243. package/src/server/game/boss/openArenaRoom.ts +3 -1
  244. package/src/server/game/grid/room.ts +44 -3
  245. package/src/server/game/grid/simulation.ts +23 -0
  246. package/src/server/game/population/mixedRoster.ts +11 -3
  247. package/src/server/game/population/nativeBake.ts +8 -3
  248. package/src/server/game/population/nativeReturns.ts +6 -3
  249. package/src/server/game/population/roster.ts +5 -3
  250. package/src/server/game/quest/eliteDrops.ts +18 -3
  251. package/src/server/game/quest/nativeChapter.ts +1 -1
  252. package/src/server/game/quest/nativeComposition.ts +5 -1
  253. package/src/server/game/riding/nativeTaming.ts +22 -7
  254. package/src/server/game/riding/wildRefill.ts +3 -2
  255. package/src/server/game/shardfile/bossRow.ts +4 -2
  256. package/src/server/game/shardfile/homeKeeper.ts +4 -2
  257. package/src/server/host/bake/headlessWorker.ts +1 -1
  258. package/src/server/host/dedicated/cellHost.ts +112 -18
  259. package/src/server/host/dedicated/cellProtocol.ts +18 -1
  260. package/src/server/host/dedicated/cellWorker.ts +8 -5
  261. package/src/server/host/dedicated/dedicatedRoom.ts +38 -11
  262. package/src/server/host/dedicated/gridCells.ts +15 -6
  263. package/src/server/host/dedicated/loopLag.ts +21 -0
  264. package/src/server/host/dedicated/main.ts +13 -5
  265. package/src/server/host/dedicated/packReader.ts +3 -3
  266. package/src/server/host/dedicated/placementFile.ts +3 -2
  267. package/src/server/host/dedicated/roadRoom.ts +34 -4
  268. package/src/server/host/dedicated/serverMetrics.ts +135 -0
  269. package/src/server/host/dedicated/socketPump.ts +21 -4
  270. package/src/server/host/dedicated/workerTable.ts +32 -14
  271. package/src/server/host/dedicated/world.ts +65 -7
  272. package/src/server/host/headless.ts +1 -1
  273. package/src/server/host/headlessRuntime.ts +1 -1
  274. package/src/server/host/standalone/roadWorld.ts +15 -3
  275. package/src/server/host/standalone/serverHost.ts +57 -8
  276. package/src/server/host/standalone/serverProduct.ts +48 -16
  277. package/src/server/host/standalone/serverRuntime.ts +1 -1
  278. package/src/shared/engine/ai/BossBrain.ts +8 -0
  279. package/src/shared/engine/core/framePacing.ts +12 -1
  280. package/src/shared/engine/physics/terrainTiles.ts +20 -4
  281. package/src/shared/game/boss/wake.ts +6 -0
  282. package/src/shared/game/devColliders.ts +107 -0
  283. package/src/shared/game/devGameplay.ts +41 -0
  284. package/src/shared/game/eliteSystem.ts +8 -0
  285. package/src/shared/game/grid/allocator.ts +3 -0
  286. package/src/shared/game/grid/placementRows.ts +5 -2
  287. package/src/shared/game/plugin/bossRecord.ts +3 -2
  288. package/src/shared/game/shardfile/ktx2Targets.ts +23 -3
  289. package/src/shared/game/shardfile/outputDescriptor.ts +9 -5
  290. package/src/shared/game/shardfile/packReads.ts +28 -3
  291. package/src/shared/game/shardfile/serverPack.ts +9 -0
  292. package/src/shared/game/systems/looks/trampleField.ts +2 -0
  293. package/src/shared/host/formatJsonSchema.ts +2 -2
  294. package/src/tsconfig.json +1 -27
  295. package/lint/host-reviews.json +0 -14
  296. package/lint/listed-view-code.json +0 -13
  297. package/lint/platform-pending-users.json +0 -2520
  298. package/lint/platform-pending-users.md +0 -18
  299. package/scripts/cell-mem/metrics-preload.mjs +0 -65
  300. package/scripts/check-closed-components.d.mts +0 -7
  301. package/scripts/check-closed-components.mjs +0 -87
  302. package/scripts/g571-hosts.d.mts +0 -3
  303. package/scripts/g571-hosts.mjs +0 -54
  304. package/scripts/host-ruler/register-migrate.mjs +0 -242
  305. package/scripts/listed-view-code.d.mts +0 -7
  306. package/scripts/listed-view-code.mjs +0 -93
  307. package/scripts/look-loop/fit-lut.py +0 -142
  308. package/scripts/look-loop/palette-delta.py +0 -183
  309. package/scripts/look-loop/regions/driftwood-isle.json +0 -25
  310. package/scripts/look-loop/regions/far-reach.json +0 -225
  311. package/scripts/look-loop/regions/open-plot-night-market.json +0 -855
  312. package/scripts/look-loop/regions/pine-hollow.json +0 -22
  313. package/scripts/look-loop/regions/sunscar-dunes.json +0 -281
  314. package/scripts/platform-chargebacks.d.mts +0 -9
  315. package/scripts/platform-chargebacks.mjs +0 -135
  316. package/scripts/shard-component-spans.d.mts +0 -15
  317. package/scripts/shard-component-spans.mjs +0 -18
  318. package/scripts/shard-components.d.mts +0 -16
  319. package/scripts/shard-components.mjs +0 -363
  320. package/scripts/shard-platform-hosts.d.mts +0 -2
  321. package/scripts/shard-platform-hosts.mjs +0 -93
  322. package/scripts/shard-platform-sections.d.mts +0 -2
  323. package/scripts/shard-platform-sections.mjs +0 -9
  324. package/scripts/shard-platform.d.mts +0 -76
  325. package/scripts/shard-platform.mjs +0 -1072
  326. package/src/.oxfmtrc.json +0 -48
  327. package/src/scripts/ask-new.sh +0 -29
  328. package/src/scripts/asks.mjs +0 -142
  329. package/src/scripts/herdr-prompt.sh +0 -34
  330. package/src/scripts/herdr-question-open.sh +0 -67
  331. package/src/scripts/md-wrap.mjs +0 -229
  332. /package/scripts/{shard-platform-format.d.mts → node-format.d.mts} +0 -0
  333. /package/scripts/{shard-platform-format.mjs → node-format.mjs} +0 -0
  334. /package/scripts/{shard-platform-output.d.mts → output-reader.d.mts} +0 -0
@@ -22,7 +22,9 @@ export const DOCTOR_CHECKS = [
22
22
  export type DoctorId = (typeof DOCTOR_CHECKS)[number]['id'];
23
23
  export type DoctorState = 'wait' | 'run' | 'pass' | 'warn' | 'fail' | 'skip';
24
24
  /** One check as the panel shows it. `value` is what was measured; `hint` says what to do when it is not a pass. */
25
- export interface DoctorRow { readonly id: DoctorId; readonly label: string; readonly state: DoctorState; readonly value: string; readonly hint: string; readonly ms: number }
25
+ export interface DoctorRow { readonly id: DoctorId; readonly label: string; readonly state: DoctorState; readonly value: string; readonly hint: string; readonly ms: number;
26
+ /** The failure-mode catalogue's id this row's warning stands for (meta MMO-FAILURE-MODES-PLAN; FM4b mode 42, `clock-skew`). */
27
+ readonly failmode?: string }
26
28
 
27
29
  /** What the page knows before any check: its own stamps (`stampBuildDocuments`). */
28
30
  export interface DoctorConfig {
@@ -56,14 +58,14 @@ async function limited<T>(scope: Scope, ms: number, work: (signal: AbortSignal)
56
58
  }
57
59
 
58
60
  /** A check's outcome before it is timed. */
59
- interface Outcome { readonly state: DoctorState; readonly value: string; readonly hint?: string }
61
+ interface Outcome { readonly state: DoctorState; readonly value: string; readonly hint?: string; readonly failmode?: string }
60
62
  const pass = (value: string): Outcome => ({ state: 'pass', value });
61
63
  const warn = (value: string, hint: string): Outcome => ({ state: 'warn', value, hint });
62
64
  const fail = (value: string, hint: string): Outcome => ({ state: 'fail', value, hint });
63
65
  const skip = (value: string): Outcome => ({ state: 'skip', value });
64
66
 
65
67
  /** What the earlier checks learned, for the later ones. */
66
- interface Learned { readonly scope: Scope; release?: ReleaseFile; socket?: string; serverOffset?: number; pageOffset?: number; serverBuild?: string; rtt: number[]; joined: boolean;
68
+ export interface Learned { readonly scope: Scope; release?: ReleaseFile; socket?: string; serverOffset?: number; pageOffset?: number; serverBuild?: string; rtt: number[]; joined: boolean;
67
69
  /** The release's build has no server book or part on the packs origin: the server cannot move to it. */
68
70
  packsMissing?: boolean }
69
71
 
@@ -173,6 +175,8 @@ async function checkServer(learned: Learned, ms: number): Promise<Outcome> {
173
175
  // D7: behind Cloudflare the rooms address keeps /health private (404, no CORS), so the opaque answer is all a page gets.
174
176
  return pass(`${new URL(url).host} reachable · health is private`);
175
177
  } catch {
178
+ // PZ12 (J274): an isolated page (COEP require-corp) is refused the opaque answer itself, so a failure proves nothing
179
+ if (globalThis.crossOriginIsolated) return warn(`${new URL(url).host}: health is private`, `This page is cross-origin isolated, so it cannot read ${new URL(url).host}'s private health answer. If play fails, tell Jake.`);
176
180
  return fail(`${new URL(url).host}: no answer`, `Server unreachable: ${new URL(url).host} is down, its TLS is failing, or the server is stopped. Tell Jake.`);
177
181
  }
178
182
  }
@@ -236,18 +240,29 @@ function checkJoin(config: DoctorConfig, learned: Learned, ms: number): Promise<
236
240
  });
237
241
  }
238
242
 
239
- function checkLatency(learned: Learned): Outcome {
243
+ /**
244
+ * FM4b mode 42 (`clock-skew`): the device's clock measured more than 30 s off the server's health `now` (or the page's `Date`
245
+ * header). The warning shows the measured offset and the automatic-clock fix; it never claims the offset caused a failed secure
246
+ * connection. An unmeasured clock is `clock unknown`, never a warning.
247
+ */
248
+ const clockSkew = (offsetMs: number, server: boolean): Outcome => ({ state: 'warn', value: '', failmode: 'clock-skew',
249
+ hint: `Check automatic date and time: this device's clock is ${(Math.abs(offsetMs) / 1000).toFixed(0)} s ${offsetMs >= 0 ? 'behind' : 'ahead of'} the ${server ? 'server' : 'page\'s host'}. Set date and time to automatic in its settings, then Run again.` });
250
+
251
+ /** The latency row, with the device clock's measured offset. Exported for its test. */
252
+ export function checkLatency(learned: Learned): Outcome {
240
253
  const offsetMs = learned.serverOffset ?? learned.pageOffset ?? null;
241
254
  const clock = offsetMs === null ? 'clock unknown' : `clock ${offsetMs >= 0 ? '+' : '−'}${(Math.abs(offsetMs) / 1000).toFixed(1)} s${learned.serverOffset === undefined ? ' vs page' : ''}`;
242
- const clockOff = offsetMs !== null && Math.abs(offsetMs) > CLOCK_OFF_MS;
255
+ const skewed = offsetMs !== null && Math.abs(offsetMs) > CLOCK_OFF_MS ? clockSkew(offsetMs, learned.serverOffset !== undefined) : null;
243
256
  if (learned.rtt.length === 0) {
257
+ // a clock that is off is worth saying even when the socket gave no pings to time
258
+ if (skewed !== null) return { ...skewed, value: `${learned.joined ? 'no pong' : 'needs the socket'} · ${clock}` };
244
259
  if (!learned.joined) return skip(`needs the socket · ${clock}`);
245
260
  return warn(`no pong · ${clock}`, 'The server answered the join but not the pings. Run the check again.');
246
261
  }
247
262
  const sorted = [...learned.rtt].sort((a, b) => a - b), median = sorted[Math.floor(sorted.length / 2)] ?? 0, min = sorted[0] ?? 0;
248
263
  const fmt = (ms: number): string => ms < 10 ? ms.toFixed(1) : String(Math.round(ms));
249
264
  const value = `${fmt(median)} ms (min ${fmt(min)}) · ${clock}`;
250
- if (clockOff) return warn(value, "This phone's clock is off. Set date and time to automatic in the phone's settings.");
265
+ if (skewed !== null) return { ...skewed, value };
251
266
  if (median > SLOW_MS) return warn(value, 'The link is slow. Play still works, but hits may feel late. Try Wi-Fi closer to the router, or mobile data.');
252
267
  return pass(value);
253
268
  }
@@ -300,7 +315,7 @@ export async function runDoctor(config: DoctorConfig, owner: Scope, show: (row:
300
315
  let outcome: Outcome;
301
316
  // A check's own limit is inside it; this one is the guard for a check that forgot.
302
317
  try { outcome = await limited(scope, ms * 2, () => work[id]()); } catch (error) { outcome = fail(errorText(error), 'This check did not finish. Run the checks again.'); }
303
- const row: DoctorRow = { id, label, state: outcome.state, value: outcome.value, hint: outcome.hint ?? '', ms: Math.round(diagnosticNow() - started) };
318
+ const row: DoctorRow = { id, label, state: outcome.state, value: outcome.value, hint: outcome.hint ?? '', ms: Math.round(diagnosticNow() - started), ...outcome.failmode === undefined ? {} : { failmode: outcome.failmode } };
304
319
  if (scope.disposed) break;
305
320
  rows.push(row); show(row);
306
321
  }
@@ -111,6 +111,8 @@ export function openDoctor(config: DoctorConfig, exit: DoctorExit | null, earlie
111
111
  const view = rows.get(row.id);
112
112
  if (view === undefined || scope.disposed) return;
113
113
  view.row.dataset['state'] = row.state; view.glyph.textContent = GLYPH[row.state];
114
+ // FM4b mode 42: a warning that stands for a catalogued failure carries its id (`clock-skew`), as the link's cards do
115
+ if (row.failmode === undefined) delete view.row.dataset['failmode']; else view.row.dataset['failmode'] = row.failmode;
114
116
  view.value.textContent = row.state === 'run' ? 'checking…' : row.value;
115
117
  view.hint.textContent = row.hint; view.ms.textContent = row.state === 'run' ? '' : `${String(row.ms)} ms`;
116
118
  };
@@ -5,8 +5,9 @@
5
5
  // turned the link away) and its **hold card** (the banner's sibling: what was tapped, the dial's live progress, what happens by itself).
6
6
  // The look is the Developer prototypes' (src/client/app/failScreens.ts, FM1b); each root carries the catalogue's `data-failmode` ids.
7
7
  import type { Scope } from '@wildshard/engine/app/scope';
8
- import type { LinkCause, LinkProgress, LinkState } from '@wildshard/engine/net/redial';
8
+ import type { LinkAway, LinkCause, LinkProgress, LinkState } from '@wildshard/engine/net/redial';
9
9
  import type { Countdown } from '@wildshard/engine/net/socketFrames';
10
+ import type { TransportStats } from '@wildshard/engine/net/transport';
10
11
  import { diagnosticNow } from '@wildshard/engine/core/clock';
11
12
  import { captureBrowserError } from '@wildshard/engine/telemetry/browserErrors';
12
13
 
@@ -24,6 +25,12 @@ function reportStop(screen: 'link-lost' | 'link-refused', detail: string, report
24
25
  const GIVE_UP_S = 120;
25
26
  /** The Reconnected notice stays this long. */
26
27
  const NOTICE_MS = 2500;
28
+ /** FM4b modes 21 and 22, sampled once a second while live: a pong RTT over this is slow; five in a row spanning this much are unstable. */
29
+ const SLOW_RTT_MS = 250, UNSTABLE_SPAN_MS = 250;
30
+ /** Mode 22: the share of frames the server says it skipped for this client (`lossPct`), not measured TCP loss. */
31
+ const UNSTABLE_LOSS_PCT = 5;
32
+ /** A quality chip shows after this many bad seconds in a row, clears after this many good ones, and shows at most once a minute. */
33
+ const QUALITY_SUSTAIN_S = 5, QUALITY_CLEAR_S = 10, QUALITY_GAP_S = 60;
27
34
  /** After Keep waiting, a blocked tap pulses the banner instead of opening the card again, for this long. */
28
35
  const QUIET_MS = 10_000;
29
36
 
@@ -88,6 +95,8 @@ export interface LinkScreenHooks {
88
95
  readonly doctor?: (from: string) => void;
89
96
  /** Reload this page into the world, taking the seat back (another tab, a turned-away link). */
90
97
  readonly reload: () => void;
98
+ /** FM4b modes 21 and 22: the link's measured pong RTT and the server's reported frame skips (`NetClient.stats`) */
99
+ readonly stats?: () => TransportStats | undefined;
91
100
  /** S13: where a failed link's stop card reports (the browser error tracker; a test observes its own) */
92
101
  readonly report?: typeof captureBrowserError;
93
102
  }
@@ -116,6 +125,8 @@ function bannerFor(state: LinkState, cause: LinkCause, dials: number): { ids: st
116
125
  if (cause === 'silent') return { ids: 'half-open', tone: 'warn', title: 'Reconnecting', line: dials > 0 ? `try ${String(dials + 1)}` : 'no word from the world' };
117
126
  return { ids: 'drop reset', tone: 'warn', title: 'Reconnecting', line: dials > 0 ? `try ${String(dials + 1)}` : 'one moment' };
118
127
  }
128
+ /** How long the page was away, in the card's words. */
129
+ const awayFor = (ms: number): string => ms < 90_000 ? `${String(Math.round(ms / 1000))} s` : `${String(Math.round(ms / 60_000))} min`;
119
130
  const blockedIds = (ids: string): string => ids.split(' ').map(id => `${id}-blocked`).join(' ');
120
131
 
121
132
  /** A card's frame: the scrim, the box, a tag and a title. The caller fills the rest. */
@@ -169,7 +180,7 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
169
180
  parent.append(banner, deploy);
170
181
 
171
182
  let state: LinkState = 'live', reason: string | undefined, wasDown = false, quietUntil = 0, deployLeft = 0, deployTicking = false;
172
- let open: { scope: Scope; root: HTMLElement; kind: 'hold' | 'stop'; paint: () => void; what?: string; chat?: boolean; key?: string } | null = null;
183
+ let open: { scope: Scope; root: HTMLElement; kind: 'hold' | 'stop' | 'offline' | 'away'; paint: () => void; what?: string; chat?: boolean; key?: string } | null = null;
173
184
  const held: { text: string; send: (text: string) => void; drop: () => void }[] = [];
174
185
  const down = (): boolean => state === 'reconnecting' || state === 'resuming';
175
186
 
@@ -180,10 +191,11 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
180
191
  // a card takes the pointer back from the game (desktop pointer lock), so its buttons can be clicked
181
192
  const freePointer = (): void => { if ('exitPointerLock' in document && document.pointerLockElement instanceof Element) document.exitPointerLock(); };
182
193
  const paintBanner = (): void => {
183
- const shown = down();
194
+ // offline (FM4b mode 2) or back from away (modes 4 and 45), the card is the screen: no banner under it
195
+ const shown = down() && hooks.why() !== 'offline' && hooks.progress().away === undefined;
184
196
  banner.hidden = !shown;
185
197
  // a link that is down takes the top band from the deploy countdown; the countdown comes back with the link
186
- deploy.hidden = shown || deployLeft <= 0;
198
+ deploy.hidden = down() || deployLeft <= 0;
187
199
  if (!shown) return;
188
200
  const said = bannerFor(state, hooks.why(), hooks.progress().dials);
189
201
  banner.dataset['failmode'] = said.ids; banner.dataset['tone'] = said.tone; banner.dataset['state'] = state;
@@ -201,7 +213,8 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
201
213
  };
202
214
  /** The hold card: the banner opened up, on a tap it can't carry. It repaints each second from the dial's progress. */
203
215
  const hold = (what: string, chat: boolean): void => {
204
- if (open?.kind === 'stop') return;
216
+ // the offline card already says why nothing goes out; a held chat line still waits for the link
217
+ if (open?.kind === 'stop' || open?.kind === 'offline' || open?.kind === 'away') return;
205
218
  remember(); open?.scope.dispose(); open = null;
206
219
  const own = scope.child('online.hold'), said = bannerFor(state, hooks.why(), hooks.progress().dials);
207
220
  const title = chat ? 'Your message will send when you\'re back' : state === 'resuming' ? 'Still reconnecting' : hooks.why() === 'restart' ? 'The world is restarting' : 'Not connected yet';
@@ -248,14 +261,105 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
248
261
  root.querySelector('button')?.focus();
249
262
  };
250
263
  const doctor = (from: string): { label: string; busy: string; act: () => void }[] => hooks.doctor === undefined ? [] : [{ label: 'Check connection', busy: 'Opening…', act: () => { hooks.doctor?.(from); } }];
264
+ /**
265
+ * FM4b mode 2 (`offline-play`): the device says it has no network. Play waits under the card, the dial waits for the network
266
+ * (Redial's `offline`), and the card closes by itself when the network is back (the banner takes over) or the link is.
267
+ * J229: no seat-hold or save time is claimed, only what this page measured.
268
+ */
269
+ const offlineCard = (): void => {
270
+ if (open?.kind === 'offline') return;
271
+ remember(); open?.scope.dispose(); open = null;
272
+ const own = scope.child('online.offline'), { root, box } = card(own, 'offline-play', 'warn', 'Connection dropped', 'You\'re offline');
273
+ box.append(make('p', 'ws-link-body', 'This device lost its internet connection. The world needs it to carry on.'));
274
+ const status = make('ul', 'ws-link-facts'), waiting = make('li');
275
+ status.setAttribute('role', 'status'); status.append(waiting);
276
+ const paint = (): void => { waiting.replaceChildren(ring(), `Down for ${String(Math.floor(hooks.progress().downMs / 1000))} s`); };
277
+ paint(); own.interval(1000, paint);
278
+ box.append(status, make('p', 'ws-link-auto', 'We\'ll connect again by ourselves as soon as the network is back. Nothing is sent while you\'re offline.'));
279
+ const actions = doctor('offline-play');
280
+ if (actions.length > 0) box.append(buttons(own, actions));
281
+ const details = make('details'); details.append(make('summary', '', 'Details'), make('p', '', 'navigator.onLine is false · dialling waits for "online"')); box.append(details);
282
+ parent.append(root); freePointer();
283
+ open = { scope: own, root, kind: 'offline', paint };
284
+ root.querySelector('button')?.focus();
285
+ };
286
+
287
+ /**
288
+ * FM4b modes 4 (`background-long`) and 45 (`sleep-wake`): the page was away for over 30 s (out of view, or its clock stopped ticking)
289
+ * and came back to a quiet link. The card says how long the page measured itself away and that the link is being checked; it closes
290
+ * by itself when the link is back. J229: no lost seat or last-save resume is claimed, since the page can't know the world's hold.
291
+ */
292
+ const awayCard = (away: LinkAway): void => {
293
+ if (open?.kind === 'away') { open.paint(); return; }
294
+ remember(); open?.scope.dispose(); open = null;
295
+ const asleep = away.how === 'asleep', own = scope.child('online.away');
296
+ const { root, box } = card(own, asleep ? 'background-long sleep-wake' : 'background-long', 'info', 'Away', 'Welcome back');
297
+ box.append(make('p', 'ws-link-body', `You were away for ${awayFor(away.ms)}, and the link to the world went quiet. We're checking your connection now.`));
298
+ const status = make('ul', 'ws-link-facts'), tries = make('li'), next = make('li');
299
+ status.setAttribute('role', 'status'); status.append(tries, next);
300
+ const paint = (): void => {
301
+ const { dials, nextDialMs } = hooks.progress();
302
+ tries.replaceChildren(ring(), dials > 0 ? `Try ${String(dials + 1)}` : 'Checking your connection');
303
+ next.textContent = nextDialMs !== null ? `Next dial in ${String(Math.ceil(nextDialMs / 1000))} s` : 'Dialling now';
304
+ };
305
+ paint(); own.interval(1000, paint);
306
+ box.append(status, make('p', 'ws-link-auto', 'This closes by itself when you\'re back in. Game taps wait here; we never send one late.'),
307
+ buttons(own, [{ label: 'Try now', primary: true, busy: 'Dialling…', act: () => { hooks.dialNow(); } }, ...doctor(asleep ? 'sleep-wake' : 'background-long')]));
308
+ const details = make('details');
309
+ details.append(make('summary', '', 'Details'), make('p', '', `${asleep ? 'no page clock tick' : 'hidden'} ${awayFor(away.ms)} · link quiet on return · redialling`));
310
+ box.append(details);
311
+ parent.append(root); freePointer();
312
+ open = { scope: own, root, kind: 'away', paint };
313
+ root.querySelector('button')?.focus();
314
+ };
251
315
 
316
+ /**
317
+ * FM4b modes 21 (`slow`) and 22 (`lossy`): a notice chip in the top band while the link is live and measurably slow or unstable.
318
+ * Only what the page measured: the pong RTT, the spread of the last five, the server's `lossPct`. Never a guessed cause or a made-up
319
+ * percentage. A chip waits while a banner is up (it is the bottom layer) and comes back, if still due, with the link.
320
+ */
321
+ const rtts: number[] = [];
322
+ let slowRun = 0, unstableRun = 0, goodRun = 0, sinceChip = QUALITY_GAP_S, qualityScope: Scope | null = null, qualityKind: 'slow' | 'lossy' | null = null, qualityLine: HTMLElement | null = null;
323
+ const hideQuality = (): void => { qualityScope?.dispose(); qualityScope = null; qualityKind = null; qualityLine = null; };
324
+ const showQuality = (kind: 'slow' | 'lossy', rtt: number): void => {
325
+ if (qualityKind !== kind) {
326
+ hideQuality(); unnotice();
327
+ const own = qualityScope = scope.child('online.quality'), chip = own.ownNode(make('div', 'ws-link ws-link-notice'));
328
+ chip.dataset['failmode'] = kind; chip.dataset['tone'] = 'warn'; chip.setAttribute('role', 'status');
329
+ qualityLine = make('span');
330
+ chip.append(make('b', '', kind === 'slow' ? 'Slow connection' : 'Unstable connection'), qualityLine);
331
+ parent.append(chip);
332
+ qualityKind = kind; sinceChip = 0;
333
+ }
334
+ if (qualityLine !== null) qualityLine.textContent = kind === 'slow' ? `${String(Math.round(rtt))} ms` : 'others may jump';
335
+ };
336
+ const sampleQuality = (): void => {
337
+ sinceChip++;
338
+ const stats = hooks.stats?.();
339
+ if (stats === undefined || state !== 'live') { hideQuality(); slowRun = unstableRun = goodRun = 0; rtts.length = 0; return; }
340
+ const rtt = stats.rttMs;
341
+ if (Number.isFinite(rtt) && rtt > 0) { rtts.push(rtt); if (rtts.length > 5) rtts.shift(); }
342
+ const slow = Number.isFinite(rtt) && rtt > SLOW_RTT_MS;
343
+ const unstable = (rtts.length === 5 && Math.max(...rtts) - Math.min(...rtts) >= UNSTABLE_SPAN_MS) || stats.lossPct >= UNSTABLE_LOSS_PCT;
344
+ slowRun = slow ? slowRun + 1 : 0; unstableRun = unstable ? unstableRun + 1 : 0; goodRun = slow || unstable ? 0 : goodRun + 1;
345
+ const due = slowRun >= QUALITY_SUSTAIN_S ? 'slow' : unstableRun >= QUALITY_SUSTAIN_S ? 'lossy' : null;
346
+ if (qualityKind !== null) { if (goodRun >= QUALITY_CLEAR_S) hideQuality(); else showQuality(due ?? qualityKind, rtt); return; }
347
+ if (due !== null && sinceChip >= QUALITY_GAP_S) showQuality(due, rtt);
348
+ };
349
+ scope.interval(1000, sampleQuality);
252
350
  const link = (next: LinkState, why?: string): void => {
253
351
  state = next; reason = why;
352
+ if (state !== 'live') hideQuality();
254
353
  paintBanner();
255
354
  // down again: the notice goes, and a stop card (lost, after Try again) gives way to the banner
256
355
  if (down()) {
257
356
  wasDown = true; unnotice();
258
357
  if (open?.kind === 'stop') close();
358
+ if (hooks.why() === 'offline') { offlineCard(); return; }
359
+ if (open?.kind === 'offline') close();
360
+ const away = hooks.progress().away;
361
+ if (away !== undefined) { awayCard(away); return; }
362
+ if (open?.kind === 'away') close();
259
363
  // a hold card follows its banner: a new cause (silent to restart) or 35 s down redraws it, else it just ticks
260
364
  if (open?.kind === 'hold' && open.key !== `${state}:${hooks.why()}` && open.what !== undefined) hold(open.what, open.chat === true); else open?.paint();
261
365
  return;
@@ -20,6 +20,7 @@ import { voiceUi } from './voiceUi';
20
20
  import { fetchSignedRelease, releaseToDial, type ReleaseKeep } from './release';
21
21
  import { newBuildPanel } from './reconnectStrip';
22
22
  import { linkScreens } from './linkScreens';
23
+ import { diagnosticNow } from '@wildshard/engine/core/clock';
23
24
 
24
25
  /** `ready` with this byte is a clean quit: the door drops the body at once instead of holding it (server `socketPump.ts` `LEAVE_FLAG`). */
25
26
  const LEAVE_FLAG = 1;
@@ -71,8 +72,8 @@ export interface OnlineShell {
71
72
  readonly booted: Promise<{ readonly tick: number; readonly restored: boolean }>;
72
73
  /** The page has loaded: the door may seat the body (E7.2's step 4). */
73
74
  ready: () => void;
74
- /** The page came back into view: check the link now. */
75
- visible: () => void;
75
+ /** The page came back into view after `hiddenMs` out of it (FM4b mode 4): check the link now. */
76
+ visible: (hiddenMs?: number) => void;
76
77
  retry: () => void;
77
78
  /** FM4: the dial's progress and why the link is down, for the screens that show them; dial now, from a hold card. */
78
79
  progress: () => LinkProgress;
@@ -153,7 +154,7 @@ export function connectOnline(config: OnlineConfig, view: OnlineView): OnlineShe
153
154
  client.hello(config.build, config.identity);
154
155
  const tickOf = (): number => client.latest?.tick ?? 0, idle = (): void => undefined;
155
156
  return { client, voice, redials: true, booted, ready: () => { loaded = true; unseated?.control('ready'); unseated = null; },
156
- visible: () => { redial.check(); }, retry: () => { redial.retry(); }, progress: () => redial.progress, why: () => redial.why, dialNow: () => { redial.dialNow(); },
157
+ visible: hiddenMs => { redial.check(hiddenMs); }, retry: () => { redial.retry(); }, progress: () => redial.progress, why: () => redial.why, dialNow: () => { redial.dialNow(); },
157
158
  pause: idle, resume: idle, hold: idle, bossGod: idle, hardHits: idle, place: idle, raise: idle,
158
159
  // The door hears a quit on any link of this build: seated, still admitted, or handed a held body back. A link that is down (a redial's
159
160
  // wait) gets a fresh one to say it on, so a held body goes too. No redial follows: the page is going.
@@ -312,6 +313,8 @@ export async function startOnline(config: StartOnline): Promise<OnlineShell> {
312
313
  // Play here / Play again reload into the world: the tap that brought the player here comes along (QA row 16)
313
314
  reload: () => { entering(link.loaded); void reloadByHand(); },
314
315
  progress: () => shellNow?.progress() ?? { dials: 0, nextDialMs: null, downMs: 0 }, why: () => shellNow?.why() ?? 'closed',
316
+ // FM4b modes 21 and 22: the Slow and Unstable chips read the link's own measurements
317
+ stats: () => shellNow?.client.stats,
315
318
  });
316
319
  // `reload` is the one ending a screen doesn't answer: the page reloads into the world's build, once (J174)
317
320
  const ended = async (): Promise<void> => { if (!await stale()) newBuildPanel(scope, stale, () => { entering(link.loaded); void reloadByHand(); }); };
@@ -342,6 +345,12 @@ export async function startOnline(config: StartOnline): Promise<OnlineShell> {
342
345
  const chat = chatLines(scope, shell.client, document.body, screens.holdChat);
343
346
  voiceUi(scope, new VoiceChat(scope, shell.voice), chat);
344
347
  scope.listen(window,'pagehide',()=>{shell.flushRecords();});
345
- scope.listen(document, 'visibilitychange', () => { if (document.visibilityState === 'visible') { shell.visible(); screens.visible(); } });
348
+ // FM4b mode 4: how long the page was out of view rides the check, so a long absence back to a quiet link opens Welcome back
349
+ let hiddenAt: number | null = document.visibilityState === 'hidden' ? diagnosticNow() : null;
350
+ scope.listen(document, 'visibilitychange', () => {
351
+ if (document.visibilityState !== 'visible') { hiddenAt ??= diagnosticNow(); return; }
352
+ const hiddenMs = hiddenAt === null ? 0 : diagnosticNow() - hiddenAt;
353
+ hiddenAt = null; shell.visible(hiddenMs); screens.visible();
354
+ });
346
355
  return { ...shell, dispose: () => { scope.dispose(); shell.dispose(); } };
347
356
  }
@@ -12,9 +12,17 @@ import type { SaveStorage } from '@wildshard/engine/saves/store';
12
12
  import { ServerMessageSchema, ShellMessageSchema, type ProbedRow, type ServerMessage, type ShellMessage } from '@wildshard/format/standaloneControl';
13
13
  import { answerHeldReads, type HeldRead } from '../../../shared/host/standalone/heldReads';
14
14
  import type { HarnessFlag, HarnessGod, HarnessHits, HarnessJoin, HarnessMove, HarnessPlace } from '../../../shared/host/standalone/harnessPlace';
15
+ import type { DevBox, DevCollidersMessage, DevGround, DevGroundMessage } from '@wildshard/engine/game/devColliders';
16
+ import { isDevRestart, type DevGameplay, type DevPlace, type DevRestarted, type DevRestartMessage } from '@wildshard/engine/game/devGameplay';
15
17
  import type { ServerWorkerStart } from '../../../server/host/standalone/serverRuntime';
16
18
  import { WorkerLoopback } from '../../../shared/host/standalone/workerLoopback';
17
19
 
20
+ declare global { interface Window {
21
+ /** SHARD-SOURCE AP18 (DEVSERVER): the dev hook's ground for the in-page server */ __workerClientDevGround?: (ground: DevGround) => void;
22
+ /** SHARD-SOURCE AP19 (DEVSERVER): the dev hook's soft restart of the in-page server, on a new link this page's client rejoins */
23
+ __workerClientDevRestart?: (gameplay: DevGameplay, at: DevPlace | null) => Promise<DevRestarted>;
24
+ } }
25
+
18
26
  /** What the server should run and where the page keeps saves. */
19
27
  export interface StandaloneConfig {
20
28
  readonly slug: string;
@@ -66,6 +74,10 @@ export interface StandaloneShell {
66
74
  raise: (flag: string) => void;
67
75
  /** A proof's second client, a real one on its own link: it stands at this point in this cell, and `move` puts its body elsewhere. */
68
76
  join: (id: string, x: number, y: number, z: number) => { readonly client: NetClient; readonly move: (x: number, y: number, z: number) => void };
77
+ /** SHARD-SOURCE AP5: a watched part's solid boxes for the server's world (DEVSERVER pages only; elsewhere it does nothing). */
78
+ devColliders: (name: string, boxes: readonly DevBox[]) => void;
79
+ /** SHARD-SOURCE AP19: restart the in-page server's world on new gameplay rows, its player at `at`; this client rejoins it (DEVSERVER pages only). */
80
+ devRestart: (gameplay: DevGameplay, at: DevPlace | null) => Promise<DevRestarted>;
69
81
  dispose: () => void;
70
82
  }
71
83
 
@@ -73,6 +85,8 @@ function applyWrite(storage: SaveStorage, key: string, value: string | null): bo
73
85
  try { if (value === null) storage.removeItem(key); else storage.setItem(key, value); return true; } catch { return false; }
74
86
  }
75
87
 
88
+ /** AP19: how long the page waits for the in-page server's answer to a soft restart before it counts as refused. */
89
+ const DEV_RESTART_TIMEOUT_MS = 20_000;
76
90
  const SaveDocument = v.object({ keys: v.record(v.string(), v.unknown()), reset: v.optional(v.number()) });
77
91
  /** Apply only entries the worker changed since its last document. The page owns discovery and cosmetic wear;
78
92
  * a server pack/pending-drop write must leave those newer entries standing. Resets still replace the document. */
@@ -126,6 +140,30 @@ export function connectStandalone(config: StandaloneConfig, control: MessagePort
126
140
  const visibility = (): void => { if (!held) post({ kind: document.visibilityState === 'hidden' ? 'pause' : 'resume' }); };
127
141
  const scope = new Scope('standalone.shell');
128
142
  if (typeof document !== 'undefined') scope.listen(document, 'visibilitychange', visibility);
143
+ // SHARD-SOURCE AP18: `wildshard watch`'s ground for this server, from the page's dev hook (DEVSERVER pages only)
144
+ if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && harness !== undefined && typeof window !== 'undefined')
145
+ scope.expose(window, '__workerClientDevGround', (ground: DevGround) => { harness.postMessage({ wildshardDevGround: ground } satisfies DevGroundMessage, []); });
146
+ // SHARD-SOURCE AP19: the soft restart. The server takes a new link with the restart; this page's client rejoins on it at once
147
+ // (its hello waits in the port until the new world listens), as an online page does when its server comes back.
148
+ // One at a time, and only a message the worker takes: anything else answers `ok: false` before the client leaves its link, so
149
+ // the page reloads instead of sitting on a link nothing serves. A worker that never answers counts as a refusal too.
150
+ let restarting = false;
151
+ const devRestart = (gameplay: DevGameplay, at: DevPlace | null): Promise<DevRestarted> => new Promise<DevRestarted>(resolve => {
152
+ if (!(typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__) || harness === undefined) { resolve({ ok: false, ms: 0, reason: 'not a DEVSERVER page with an in-page server' }); return; }
153
+ const message: DevRestartMessage = { wildshardDevRestart: gameplay, at };
154
+ if (!isDevRestart(message)) { resolve({ ok: false, ms: 0, reason: 'the worker takes only the dev gameplay sections and a finite place' }); return; }
155
+ if (restarting) { resolve({ ok: false, ms: 0, reason: 'a restart is already running' }); return; }
156
+ restarting = true;
157
+ const line = new MessageChannel(), reply = new MessageChannel(), waiting: { timer?: ReturnType<typeof scope.timeout> } = {};
158
+ const settle = (answer: DevRestarted): void => { if (!restarting) return; restarting = false; scope.cancelTimer(waiting.timer); reply.port1.close(); resolve(answer); };
159
+ waiting.timer = scope.timeout(DEV_RESTART_TIMEOUT_MS, () => { settle({ ok: false, ms: DEV_RESTART_TIMEOUT_MS, reason: 'the in-page server did not answer the restart' }); });
160
+ reply.port1.onmessage = (event: MessageEvent<DevRestarted>): void => { settle(event.data); };
161
+ const link = new WorkerLoopback(line.port1);
162
+ link.onClose(reason => { if (reason === 'reload') config.refused?.(); });
163
+ client.rejoin(link);
164
+ harness.postMessage(message, [line.port2, reply.port2]);
165
+ });
166
+ if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && harness !== undefined && typeof window !== 'undefined') scope.expose(window, '__workerClientDevRestart', devRestart);
129
167
  post({ kind: 'boot', slug: config.slug, base: config.base, build: config.serverBuild ?? config.build, savePrefix: config.savePrefix, saves: documents, ...(config.lone === true ? { lone: true } : {}) });
130
168
  return { client, transport, booted: bootPromise,
131
169
  ready: () => { post({ kind: 'ready' }); }, pause: () => { post({ kind: 'pause' }); }, resume: () => { post({ kind: 'resume' }); },
@@ -136,6 +174,8 @@ export function connectStandalone(config: StandaloneConfig, control: MessagePort
136
174
  hardHits: by => { harness?.postMessage({ hits: by } satisfies HarnessHits, []); },
137
175
  bossGod: () => { harness?.postMessage({ god: true } satisfies HarnessGod, []); },
138
176
  raise: flag => { harness?.postMessage({ flag } satisfies HarnessFlag, []); },
177
+ devColliders: (name, boxes) => { if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__) harness?.postMessage({ wildshardDevColliders: name, boxes } satisfies DevCollidersMessage, []); },
178
+ devRestart,
139
179
  join: (id, x, y, z) => {
140
180
  const line = new MessageChannel(), second = new NetClient(new WorkerLoopback(line.port1));
141
181
  harness?.postMessage({ join: id, x, y, z } satisfies HarnessJoin, [line.port2]);
@@ -0,0 +1,55 @@
1
+ /** S12c: the cook's ASTC 6×6 encoder (`Astc6Encode`), S4's hand-made phone sets done by the cook. S4 baked them with
2
+ * `basisu -ldr_6x6 -effort 4` from source images (sharddev `scripts/bake-astc6.mjs`); a cook has no source images, only
3
+ * the shard's UASTC masters, so it decodes the master (already trimmed to its tier size, every level the master's own)
4
+ * to RGBA with basisu's own transcoder (`-export_dds RGBA32`) and encodes those levels as 6×6 with S4's flags. That
5
+ * re-encodes lossy data, so goldens judge it (G998).
6
+ *
7
+ * Cached by input hash (C4): the key is the input bytes, the role, the flags and basisu's version, and a hit reads the
8
+ * file back without running basisu. `stats` counts both, so a warm recook can prove it encoded nothing. */
9
+ // oxlint-disable-next-line import/no-nodejs-modules -- The cook is a Node process (J28).
10
+ import {execFileSync} from 'node:child_process';
11
+ // oxlint-disable-next-line import/no-nodejs-modules -- The cook is a Node process (J28).
12
+ import {createHash} from 'node:crypto';
13
+ // oxlint-disable-next-line import/no-nodejs-modules -- The cook is a Node process (J28).
14
+ import {existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync} from 'node:fs';
15
+ // oxlint-disable-next-line import/no-nodejs-modules -- The cook is a Node process (J28).
16
+ import {join} from 'node:path';
17
+ import type {Astc6Encode, TextureRole} from './tierTextures';
18
+
19
+ /** S4's 6×6 classes (`bake-astc6.mjs` CLASS), effort 4 of 10. */
20
+ const ROLE_FLAGS: Readonly<Record<TextureRole, readonly string[]>> = {srgb: ['-srgb'], linear: ['-linear'], normal: ['-normal_map']};
21
+ const ENCODE_FLAGS = ['-ktx2', '-ldr_6x6', '-effort', '4'];
22
+
23
+ export interface Astc6Cache {
24
+ readonly encode: Astc6Encode;
25
+ readonly stats: {encoded: number; reused: number; failed: number};
26
+ }
27
+
28
+ /** A basisu-backed `Astc6Encode` caching its files in `cacheDir`. Throws at once when basisu isn't on the PATH. */
29
+ export function basisuAstc6(cacheDir: string, basisu = 'basisu'): Astc6Cache {
30
+ const version = /v[\d.]+/u.exec(execFileSync(basisu, ['-version'], {encoding: 'utf8'}))?.[0] ?? '?';
31
+ mkdirSync(cacheDir, {recursive: true});
32
+ const stats = {encoded: 0, reused: 0, failed: 0};
33
+ const encode: Astc6Encode = (ktx2, role) => {
34
+ const key = createHash('sha256').update(`astc6/1|${version}|${ENCODE_FLAGS.join(' ')}|${ROLE_FLAGS[role].join(' ')}|`).update(ktx2).digest('hex');
35
+ const cached = join(cacheDir, `${key}.ktx2`);
36
+ if (existsSync(cached)) { stats.reused++; return new Uint8Array(readFileSync(cached)); }
37
+ const work = mkdtempSync(join(cacheDir, 'work-'));
38
+ try {
39
+ const input = join(work, 'in.ktx2'), levels = join(work, 'in.dds'), output = join(work, 'out.ktx2');
40
+ writeFileSync(input, ktx2);
41
+ execFileSync(basisu, ['-export_dds', 'RGBA32', input, '-output_file', levels], {stdio: 'ignore'});
42
+ execFileSync(basisu, [...ENCODE_FLAGS, ...ROLE_FLAGS[role], levels, '-output_file', output], {stdio: 'ignore'});
43
+ const bytes = new Uint8Array(readFileSync(output));
44
+ renameSync(output, cached);
45
+ stats.encoded++;
46
+ return bytes;
47
+ } catch {
48
+ stats.failed++;
49
+ return undefined;
50
+ } finally {
51
+ rmSync(work, {recursive: true, force: true});
52
+ }
53
+ };
54
+ return {encode, stats};
55
+ }