castle-web-cli 0.4.237 → 0.4.239

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 (239) hide show
  1. package/dist/bundle.d.ts +24 -0
  2. package/dist/bundle.js +447 -4
  3. package/dist/bundleLatin1.d.ts +6 -0
  4. package/dist/bundleLatin1.js +333 -0
  5. package/dist/castle-host/host.d.ts +10 -1
  6. package/dist/castle-host/host.js +133 -9
  7. package/dist/castleJson.d.ts +2 -0
  8. package/dist/castleJson.js +1 -0
  9. package/dist/deckExports.d.ts +35 -0
  10. package/dist/deckExports.js +365 -0
  11. package/dist/importCheckHook.d.ts +1 -0
  12. package/dist/importCheckHook.js +1 -1
  13. package/dist/index.js +21 -0
  14. package/dist/init.js +2 -1
  15. package/dist/multiplayerDoc.d.ts +1 -1
  16. package/dist/multiplayerDoc.js +9 -0
  17. package/dist/platformDoc.js +2 -1
  18. package/dist/playPagePolicy.d.ts +1 -0
  19. package/dist/playPagePolicy.js +8 -3
  20. package/dist/roomLogs.d.ts +39 -0
  21. package/dist/roomLogs.js +166 -0
  22. package/dist/save-deck.js +4 -0
  23. package/kits/base/CLAUDE.md +1 -0
  24. package/kits/base/castle.json +1 -1
  25. package/kits/base/sdk/README.md +113 -2
  26. package/kits/base/sdk/castle.d.ts +6 -2
  27. package/kits/base/sdk/castle.js +2 -0
  28. package/kits/base/sdk/commands.d.ts +56 -1
  29. package/kits/base/sdk/commands.js +29 -1
  30. package/kits/base/sdk/hub.d.ts +17 -0
  31. package/kits/base/sdk/hub.js +33 -9
  32. package/kits/base/sdk/localCache.d.ts +27 -0
  33. package/kits/base/sdk/localCache.js +115 -0
  34. package/kits/base/sdk/localCacheStore.d.ts +15 -0
  35. package/kits/base/sdk/localCacheStore.js +358 -0
  36. package/kits/base/sdk/multiplayer.js +30 -0
  37. package/kits/base/sdk/rooms.d.ts +11 -0
  38. package/kits/base/sdk/rooms.js +22 -0
  39. package/kits/base/sdk/store.d.ts +8 -2
  40. package/kits/base/sdk/store.js +5 -1
  41. package/kits/base/sdk/transport.d.ts +1 -0
  42. package/kits/base/sdk/transport.js +4 -5
  43. package/kits/hub-game/CLAUDE.md +22 -2
  44. package/kits/hub-game/castle.json +8 -5
  45. package/kits/hub-game/code/client/act.js +66 -91
  46. package/kits/hub-game/code/client/actCore.js +134 -0
  47. package/kits/hub-game/code/client/car.js +35 -0
  48. package/kits/hub-game/code/client/chrome.js +208 -381
  49. package/kits/hub-game/code/client/crowdNames.js +2 -2
  50. package/kits/hub-game/code/client/emoteWheel.js +109 -0
  51. package/kits/hub-game/code/client/hats.js +2 -0
  52. package/kits/hub-game/code/client/hookLayer.js +99 -48
  53. package/kits/hub-game/code/client/hostGo.js +77 -0
  54. package/kits/hub-game/code/client/hubControls.js +125 -0
  55. package/kits/hub-game/code/client/hubEntry.js +187 -0
  56. package/kits/hub-game/code/client/hudSurface.js +148 -0
  57. package/kits/hub-game/code/client/hudTree.js +96 -0
  58. package/kits/hub-game/code/client/idle.js +59 -13
  59. package/kits/hub-game/code/client/invites.js +13 -4
  60. package/kits/hub-game/code/client/menuIcons.js +8 -0
  61. package/kits/hub-game/code/client/menuRows.js +8 -2
  62. package/kits/hub-game/code/client/noTrips.js +38 -0
  63. package/kits/hub-game/code/client/qualityEntry.js +6 -1
  64. package/kits/hub-game/code/client/rehello.js +3 -1
  65. package/kits/hub-game/code/client/riders.js +26 -0
  66. package/kits/hub-game/code/client/role.js +79 -0
  67. package/kits/hub-game/code/client/safeLayout.js +32 -3
  68. package/kits/hub-game/code/client/sound.js +10 -3
  69. package/kits/hub-game/code/client/soundscape.js +2 -2
  70. package/kits/hub-game/code/client/soundscapeAmbience.js +38 -8
  71. package/kits/hub-game/code/client/soundscapeBaked.js +24 -5
  72. package/kits/hub-game/code/client/soundscapeCues.js +2 -1
  73. package/kits/hub-game/code/client/state.js +19 -0
  74. package/kits/hub-game/code/client/stuck.js +2 -1
  75. package/kits/hub-game/code/client/talkSurface.js +178 -0
  76. package/kits/hub-game/code/client/talkTree.js +238 -0
  77. package/kits/hub-game/code/client/tiers.js +8 -5
  78. package/kits/hub-game/code/client/uiDom.js +600 -0
  79. package/kits/hub-game/code/client/uiTree.js +359 -0
  80. package/kits/hub-game/code/client/vehicle.js +156 -0
  81. package/kits/hub-game/code/client/wear.js +27 -5
  82. package/kits/hub-game/code/client/worldLabels.js +13 -3
  83. package/kits/hub-game/code/client/yours.js +10 -3
  84. package/kits/hub-game/code/server/actors.js +4 -3
  85. package/kits/hub-game/code/server/analytics.js +61 -18
  86. package/kits/hub-game/code/server/decor.js +56 -16
  87. package/kits/hub-game/code/server/doorAnalytics.js +2 -5
  88. package/kits/hub-game/code/server/hub.js +261 -46
  89. package/kits/hub-game/code/server/idle.js +118 -5
  90. package/kits/hub-game/code/server/loadAbandon.js +2 -5
  91. package/kits/hub-game/code/server/manifest.js +46 -4
  92. package/kits/hub-game/code/server/npcs.js +4 -2
  93. package/kits/hub-game/code/server/players.js +3 -0
  94. package/kits/hub-game/code/server/role.js +142 -0
  95. package/kits/hub-game/code/server/standing.js +6 -4
  96. package/kits/hub-game/code/server/trackQueue.js +29 -0
  97. package/kits/hub-game/code/server/vehicle.js +126 -0
  98. package/kits/hub-game/code/shared/car.js +52 -0
  99. package/kits/hub-game/code/shared/deckFlags.js +34 -0
  100. package/kits/hub-game/code/shared/deviceClass.js +39 -0
  101. package/kits/hub-game/code/shared/expression.js +9 -0
  102. package/kits/hub-game/code/systems/hub.js +281 -86
  103. package/kits/hub-game/docs/analytics.md +15 -3
  104. package/kits/hub-game/docs/contract.md +352 -14
  105. package/kits/hub-game/docs/vehicle-preset.md +132 -0
  106. package/kits/hub-game/models/hats/baker-cap.pxmodel +89 -0
  107. package/kits/hub-game/models/hats/chef-toque.pxmodel +60 -0
  108. package/kits/hub-game/models/hats/delivery-cap.pxmodel +105 -0
  109. package/kits/hub-game/models/hats/fire-helmet.pxmodel +87 -0
  110. package/kits/hub-game/models/hats/hard-hat.pxmodel +71 -0
  111. package/kits/hub-game/models/hats/nurse-cap.pxmodel +61 -0
  112. package/kits/hub-game/models/hats/police-cap.pxmodel +105 -0
  113. package/kits/hub-game/models/hats/teacher-beret.pxmodel +52 -0
  114. package/kits/hub-game/models/role/square/top-apron.pxmodel +109 -0
  115. package/kits/hub-game/models/role/square/top-cardigan.pxmodel +141 -0
  116. package/kits/hub-game/models/role/square/top-coat.pxmodel +157 -0
  117. package/kits/hub-game/models/role/square/top-scrubs.pxmodel +93 -0
  118. package/kits/hub-game/models/role/square/top-tabard.pxmodel +109 -0
  119. package/kits/hub-game/models/role/square/top-vest.pxmodel +109 -0
  120. package/kits/hub-game/models/role/tool-bag.pxmodel +75 -0
  121. package/kits/hub-game/models/role/tool-bell.pxmodel +71 -0
  122. package/kits/hub-game/models/role/tool-hose.pxmodel +60 -0
  123. package/kits/hub-game/models/role/tool-parcel.pxmodel +61 -0
  124. package/kits/hub-game/models/role/tool-torch.pxmodel +55 -0
  125. package/kits/hub-game/models/role/tool-tray.pxmodel +75 -0
  126. package/kits/hub-game/models/role/top-apron.pxmodel +70 -0
  127. package/kits/hub-game/models/role/top-cardigan.pxmodel +102 -0
  128. package/kits/hub-game/models/role/top-coat.pxmodel +79 -0
  129. package/kits/hub-game/models/role/top-scrubs.pxmodel +54 -0
  130. package/kits/hub-game/models/role/top-tabard.pxmodel +70 -0
  131. package/kits/hub-game/models/role/top-vest.pxmodel +70 -0
  132. package/kits/hub-game/package-lock.json +1 -1
  133. package/kits/hub-game/package.json +1 -1
  134. package/kits/hub-game/scripts/check.mjs +7 -4
  135. package/kits/hub-game/scripts/fixtures/car-vectors.json +279 -0
  136. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +2 -1
  137. package/kits/hub-game/scripts/fixtures/hud-surface.json +670 -0
  138. package/kits/hub-game/scripts/fixtures/talk-surface.json +3930 -0
  139. package/kits/hub-game/scripts/gen-hats.mjs +46 -2
  140. package/kits/hub-game/scripts/gen-role.mjs +80 -0
  141. package/kits/hub-game/scripts/test-act-core.mjs +167 -0
  142. package/kits/hub-game/scripts/test-actions-client.mjs +34 -0
  143. package/kits/hub-game/scripts/test-actors.mjs +48 -0
  144. package/kits/hub-game/scripts/test-analytics.mjs +100 -6
  145. package/kits/hub-game/scripts/test-apply-deck.mjs +122 -0
  146. package/kits/hub-game/scripts/test-back-visibility.mjs +3 -1
  147. package/kits/hub-game/scripts/test-ballot.mjs +2 -0
  148. package/kits/hub-game/scripts/test-car.mjs +43 -0
  149. package/kits/hub-game/scripts/test-decor-client.mjs +2 -1
  150. package/kits/hub-game/scripts/test-decor.mjs +77 -0
  151. package/kits/hub-game/scripts/test-device-class.mjs +83 -0
  152. package/kits/hub-game/scripts/test-door-analytics.mjs +1 -1
  153. package/kits/hub-game/scripts/test-emote-wheel.mjs +374 -0
  154. package/kits/hub-game/scripts/test-hats.mjs +5 -4
  155. package/kits/hub-game/scripts/test-host-go.mjs +265 -0
  156. package/kits/hub-game/scripts/test-hub-controls.mjs +108 -0
  157. package/kits/hub-game/scripts/test-hub-entry.mjs +531 -0
  158. package/kits/hub-game/scripts/test-hub-ops.mjs +103 -0
  159. package/kits/hub-game/scripts/test-hub-trip.mjs +20 -1
  160. package/kits/hub-game/scripts/test-hud-clear.mjs +12 -2
  161. package/kits/hub-game/scripts/test-hud-rate.mjs +6 -2
  162. package/kits/hub-game/scripts/test-hud-surface.mjs +272 -0
  163. package/kits/hub-game/scripts/test-idle.mjs +347 -1
  164. package/kits/hub-game/scripts/test-interest-cells.mjs +8 -1
  165. package/kits/hub-game/scripts/test-invites-client.mjs +42 -1
  166. package/kits/hub-game/scripts/test-load-abandon.mjs +2 -2
  167. package/kits/hub-game/scripts/test-manifest.mjs +30 -0
  168. package/kits/hub-game/scripts/test-menu-client.mjs +1 -1
  169. package/kits/hub-game/scripts/test-no-trips.mjs +42 -0
  170. package/kits/hub-game/scripts/test-placement-cache.mjs +1 -1
  171. package/kits/hub-game/scripts/test-quality.mjs +13 -0
  172. package/kits/hub-game/scripts/test-rehello.mjs +258 -3
  173. package/kits/hub-game/scripts/test-resume-pose-server.mjs +203 -0
  174. package/kits/hub-game/scripts/test-resync.mjs +196 -0
  175. package/kits/hub-game/scripts/test-role-client.mjs +427 -0
  176. package/kits/hub-game/scripts/test-role.mjs +350 -0
  177. package/kits/hub-game/scripts/test-safe-layout.mjs +50 -1
  178. package/kits/hub-game/scripts/test-soundscape.mjs +124 -7
  179. package/kits/hub-game/scripts/test-standing.mjs +15 -1
  180. package/kits/hub-game/scripts/test-talk-surface.mjs +296 -0
  181. package/kits/hub-game/scripts/test-tiers.mjs +13 -0
  182. package/kits/hub-game/scripts/test-track-queue.mjs +64 -0
  183. package/kits/hub-game/scripts/test-ui-dom-dom.mjs +96 -0
  184. package/kits/hub-game/scripts/test-ui-tree.mjs +711 -0
  185. package/kits/hub-game/scripts/test-vehicle-client.mjs +168 -0
  186. package/kits/hub-game/scripts/test-vehicle.mjs +135 -0
  187. package/kits/hub-game/scripts/test-world-labels.mjs +40 -0
  188. package/kits/hub-game/scripts/test-yours.mjs +33 -0
  189. package/kits/hub-game/tools/hubScene/export.mjs +613 -0
  190. package/kits/hub-game/tools/hubScene/hubdata.mjs +921 -0
  191. package/kits/hub-game/tools/hubScene/merge-root.mjs +39 -0
  192. package/kits/hub-game/tools/hubScene/nodeworld.mjs +227 -0
  193. package/kits/hub-game/tools/hubScene/test/export-fixture.mjs +810 -0
  194. package/kits/hub-game/tools/hubScene/test/fixture.json +637 -0
  195. package/kits/hub-game/tools/hubScene/test/paint-export.mjs +40 -0
  196. package/kits/hub-game/tools/hubScene/test/upload.test.mjs +655 -0
  197. package/kits/hub-game/tools/hubScene/upload.mjs +636 -0
  198. package/kits/hub-game/tools/hubScene/validate-manifest.mjs +301 -0
  199. package/kits/multiplayer-3d/castle.json +4 -4
  200. package/kits/multiplayer-3d/code/client/resumeGate.js +30 -2
  201. package/kits/multiplayer-3d/code/client/steer.js +3 -1
  202. package/kits/multiplayer-3d/code/systems/multiplayer.js +30 -2
  203. package/kits/multiplayer-3d/package-lock.json +1 -1
  204. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +74 -2
  205. package/kits/physics-3d/CLAUDE.md +1 -1
  206. package/kits/physics-3d/behaviors/Player.jsx +37 -27
  207. package/kits/physics-3d/castle.json +2 -2
  208. package/kits/physics-3d/docs/engine-geometry-memory.md +23 -0
  209. package/kits/physics-3d/engine3d/memoryprofile.js +17 -0
  210. package/kits/physics-3d/engine3d/playerRun.js +6 -1
  211. package/kits/physics-3d/engine3d/pxmodel.js +6 -1
  212. package/kits/physics-3d/engine3d/world3d.js +6 -3
  213. package/kits/physics-3d/package.json +1 -1
  214. package/kits/physics-3d/play/behaviors/Player.js +40 -28
  215. package/kits/physics-3d/scripts/test-memory-profile.mjs +237 -0
  216. package/kits/physics-3d/systems/physics3d.js +5 -2
  217. package/kits/real-time/castle.json +2 -2
  218. package/kits/real-time/code/client/messages.js +5 -0
  219. package/kits/real-time/code/server/session.js +28 -1
  220. package/kits/real-time/package-lock.json +1 -1
  221. package/package.json +5 -4
  222. package/vendor/three/LICENSE +21 -0
  223. package/vendor/three/build/three.core.js +58773 -0
  224. package/vendor/three/build/three.module.js +18251 -0
  225. package/vendor/three/examples/jsm/controls/OrbitControls.js +1860 -0
  226. package/vendor/three/examples/jsm/controls/TransformControls.js +1918 -0
  227. package/vendor/three/examples/jsm/exporters/GLTFExporter.js +3595 -0
  228. package/vendor/three/examples/jsm/geometries/RoundedBoxGeometry.js +216 -0
  229. package/vendor/three/examples/jsm/math/MeshSurfaceSampler.js +315 -0
  230. package/vendor/three/examples/jsm/postprocessing/EffectComposer.js +363 -0
  231. package/vendor/three/examples/jsm/postprocessing/MaskPass.js +195 -0
  232. package/vendor/three/examples/jsm/postprocessing/OutputPass.js +139 -0
  233. package/vendor/three/examples/jsm/postprocessing/Pass.js +191 -0
  234. package/vendor/three/examples/jsm/postprocessing/RenderPass.js +183 -0
  235. package/vendor/three/examples/jsm/postprocessing/ShaderPass.js +135 -0
  236. package/vendor/three/examples/jsm/shaders/CopyShader.js +52 -0
  237. package/vendor/three/examples/jsm/shaders/OutputShader.js +103 -0
  238. package/vendor/three/examples/jsm/utils/BufferGeometryUtils.js +1435 -0
  239. package/vendor/three/package.json +134 -0
@@ -0,0 +1,613 @@
1
+ // The hub-game save-time exporter (castle.json `exports.hubScene`): a hub deck's folder to a
2
+ // HubSceneManifest v1.7 for the native hub engine, in Node, with no page and no sign-in.
3
+ //
4
+ // node export.mjs --deck <deckDir> --stage <emptyDir> --cache <cacheDir> [--prev <dir>] [--kits <dir>] [--force]
5
+ //
6
+ // `castle-web export` runs it with the same values in env (CASTLE_EXPORT_*). It writes the
7
+ // manifest folder into the fresh, empty stage the CLI made:
8
+ // <stage>/shared/<sha256>.glb|png|webp|mp3|wav|m4a hardlinks (or copies) of <cache>/shared/ entries
9
+ // <stage>/<hubId>/manifest.json
10
+ // <stage>/<hubId>/inputs.json the inputs the cache key is made from
11
+ // and the CLI alone moves the stage into <deck>/.castle/exports/hubScene/. It prints a JSON
12
+ // summary as its last stdout line; exits 1 on faults (validate-manifest.mjs), 2 on bad arguments.
13
+ //
14
+ // What it may touch, by construction:
15
+ // - CODE: kit modules only from the shipped kits folder the CLI names (CASTLE_EXPORT_SHIPPED_KITS;
16
+ // by hand --kits, or this file's own kits/ when it is not under an imports/ folder), and the
17
+ // `three` package. The loader refuses every other module by real path (nodeworld.mjs). The
18
+ // deck's imports/ is read as data only.
19
+ // - WRITES: the stage, and new entries in <cache>/shared/, created exclusively and never
20
+ // overwritten (an existing entry is verified by hash). Every entry a run uses has its mtime set
21
+ // to now. DELETES: after a good export, at most once a day (<cache>/.gc-at), the shared entries
22
+ // no run has used for GC_DAYS and temp files a crashed run left over a day ago (sweepCache).
23
+ // A deck's own output holds hardlinks, so it keeps what it was exported with.
24
+ // - CACHE KEY (source.inputKey): sha256 over the CLI version, every file of the shipped
25
+ // physics-2d, physics-3d and hub-game trees and this tools folder, the three version, and every
26
+ // data file read (scene, blueprints, models, castle.json, door candidates, sky art), misses
27
+ // included. A previous manifest (--prev, the deck's last output) whose key still holds is
28
+ // restaged as is (`cached: true`).
29
+ //
30
+ // The world is the kit's own (nodeworld.mjs: physics-3d world3d.syncActors) from the deck's scene
31
+ // (castle.json editor.defaultPlayFile, else scenes/main.scene). Each distinct model is its own
32
+ // content-addressed glb placed per actor, except the scenery the scene marks still, which is baked
33
+ // into the scene glb in chunks, and actors drawn by nothing, which get no node (hubdata.mjs
34
+ // mergeStatic). The avatar is the hub-game platform avatar
35
+ // (blueprints/avatar-0.scene) built in Node: a hub never draws a deck's own player blueprint
36
+ // (contract §11). A deck with hub.tiers gets the kit's Low picture as a profile beside High (and
37
+ // middle and weakest with Low's rules for a weakestTier deck). v1.4 adds what the kit's own client
38
+ // reads natively (a DOM-less host has no castle.json to glob): `deck`, the hub block's client
39
+ // flags (code/shared/deckFlags.js, applied by client/hookLayer.js applyDeck), and `interactables`,
40
+ // the HubNpc, HubAct and HubSeat actors the kit's talk and act find, plus the chat moderation
41
+ // opt-in marker (`hub-chat-moderation`, its HubChatModeration { v: 1 } alone, no Transform) when the
42
+ // scene has it, for the native chat's Report & block. v1.6 adds the deck's sound: each file its
43
+ // hub block names (root and places' `idle.sounds`, what sound.js plays through physics-2d
44
+ // initialMedia), content-addressed like a glb, under `audio` by its castle.json-relative path;
45
+ // `deck` keeps `soundscape` and the root and places' `idle` at their castle.json keys; and
46
+ // `interactables` adds the `jukebox` actor (Shape, Lookable, Transform) and every actor carrying a
47
+ // component the soundscape names (zones, steps.paths, ambience.spots), whole, with its Transform.
48
+ // v1.7 (format and version unchanged, as in v1.4/v1.6) always adds `avatarFits` (all styles and
49
+ // indexes after the client's fallback; earned arrays verbatim, hat fit and top), `wearModels`
50
+ // (untinted content-addressed glbs for every hat, earned and role model, square variants included)
51
+ // and `wearPieces` (anchors, constant scales, replaceable main colours and fit-dependent placement
52
+ // notes). Wear assets also live in `assets` so cache restaging and upload include them. Fits are
53
+ // measured over feet; wear.js places them relative to the avatar origin. Ring scale is its
54
+ // unchanged height scale, with horizontal stretching left to the fit; tops have no constant
55
+ // scale. The shipped avatar/role/earned/hats code and wear models are already in the kits hash.
56
+ // Not carried over from the page:
57
+ // district sleep and the weakest look, Shape art and ground textures, meshes hub-game's client
58
+ // adds at run time, the camera reference screenshot.
59
+ import crypto from 'node:crypto';
60
+ import fs from 'node:fs';
61
+ import { createRequire, register } from 'node:module';
62
+ import path from 'node:path';
63
+ import { pathToFileURL } from 'node:url';
64
+ // Nothing but node: builtins is imported statically: the helpers below come in through the
65
+ // loader guard, installed first, so they are real-path checked like the kits.
66
+
67
+ const EXPORTER = 'castle.hub-game tools/hubScene/export.mjs';
68
+ const AVATAR_BLUEPRINT = 'imports/castle.hub-game/blueprints/avatar-0.scene';
69
+ const AVATAR_ID = '__hub_avatar';
70
+ // Still scenery is baked into one node per this many metres square (hubdata.mjs mergeStatic).
71
+ const MERGE_CELL_M = 24;
72
+ const CODE_FILE = /\.(m?js|jsx|ts)$/;
73
+ // A shared cache entry no export has used for this long is removed (sweepCache).
74
+ const GC_DAYS = 30;
75
+ const DAY_MS = 24 * 60 * 60 * 1000;
76
+ const KEYED_KITS = ['physics-2d', 'physics-3d', 'hub-game'];
77
+ const TOOLS_DIR = import.meta.dirname;
78
+ // A hub id names a folder beside shared/ (and packs/) in a manifest root.
79
+ const HUB_ID = /^[A-Za-z0-9_-]{1,64}$/;
80
+ const RESERVED_IDS = new Set(['shared', 'packs']);
81
+ const isHubId = (id) => typeof id === 'string' && HUB_ID.test(id) && !RESERVED_IDS.has(id);
82
+ // The stand-ins for the two workspace packages the kits import and the world build never calls.
83
+ const SDK_NAMES = ['onSaveReloadState', 'takeReloadState', 'writeFile', 'onFilesChanged', 'Lifecycle', 'setup',
84
+ 'User', 'Multiplayer', 'onBeforeRestart', 'fileUrl', 'initCard', 'Avatar', 'deleteFile', 'experiment',
85
+ 'experimentsReady', 'flushSaves', 'hasPendingSave', 'Hub', 'onSaveState', 'openFile', 'renameFile'];
86
+ const SDK_STUB = [
87
+ 'const inert = new Proxy(function () {}, { get: (t, k) => (k === "then" ? undefined : inert), apply: () => undefined });',
88
+ 'export const IMPORTS_DIR = "imports"; export const IMPORTS_PREFIX = "imports/";',
89
+ 'export const isEdit = () => false;',
90
+ // sdk/src/files.ts, verbatim in behaviour: model and art refs resolve through these.
91
+ 'const strip = (p) => p.replace(/^\\.\\//, "");',
92
+ 'export const deckPrefixOf = (f) => { const m = /^(imports\\/[^/]+\\/)/.exec(f ?? ""); return m ? m[1] : ""; };',
93
+ 'export const isImportedFile = (f) => deckPrefixOf(f) !== "";',
94
+ 'export const resolveDeckFile = (ref, from = "") => { const p = strip(String(ref ?? "")); return p.startsWith("@imports/") ? "imports/" + p.slice(9) : deckPrefixOf(strip(from)) + p; };',
95
+ ...SDK_NAMES.map((n) => `export const ${n} = inert;`),
96
+ ].join('\n');
97
+ const FONTS_STUB = 'export const FACES = {}; export const faceInfo = () => null; export const installBore = () => {}; export const installDMSans = () => {};';
98
+
99
+ const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
100
+ const readJson = (file) => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } };
101
+
102
+ const args = process.argv.slice(2);
103
+ const opt = (name, env) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : process.env[env]; };
104
+ const DECK = opt('deck', 'CASTLE_EXPORT_DECK_DIR');
105
+ const STAGE = opt('stage', 'CASTLE_EXPORT_STAGE_DIR');
106
+ const CACHE = opt('cache', 'CASTLE_EXPORT_CACHE_DIR');
107
+ const PREV = opt('prev', 'CASTLE_EXPORT_PREV_DIR');
108
+ if (!DECK || !STAGE || !CACHE) {
109
+ console.error('usage: node export.mjs --deck <deckDir> --stage <emptyDir> --cache <cacheDir> [--prev <dir>] [--kits <dir>] [--force]');
110
+ process.exit(2);
111
+ }
112
+ const deckDir = path.resolve(DECK);
113
+ const stageDir = path.resolve(STAGE);
114
+ const cacheShared = path.join(path.resolve(CACHE), 'shared');
115
+ const t0 = performance.now();
116
+
117
+ const KITS_DIR = (() => {
118
+ const named = opt('kits', 'CASTLE_EXPORT_SHIPPED_KITS');
119
+ if (named) return path.resolve(named);
120
+ const own = path.resolve(TOOLS_DIR, '../../..');
121
+ if (path.basename(own) === 'kits' && !TOOLS_DIR.split(path.sep).includes('imports')) return own;
122
+ console.error('export.mjs is not running from a kits/ folder: name the kits to use with --kits <dir>');
123
+ process.exit(2);
124
+ })();
125
+ for (const kit of KEYED_KITS) if (!fs.existsSync(path.join(KITS_DIR, kit, 'castle.json'))) fail(`${KITS_DIR} has no ${kit} kit`);
126
+ let stageEntries = null;
127
+ try { stageEntries = fs.readdirSync(stageDir); } catch { stageEntries = null; }
128
+ if (!stageEntries || stageEntries.length) fail(`${stageDir} is not an empty folder`);
129
+ fs.mkdirSync(cacheShared, { recursive: true });
130
+ if (!fs.lstatSync(cacheShared).isDirectory()) fail(`${cacheShared} is not a folder`);
131
+
132
+ const castleJson = readJson(path.join(deckDir, 'castle.json'));
133
+ if (!castleJson) fail(`${deckDir} has no castle.json`);
134
+ // An unsaved deck has no id yet; its folder name stands in, so a local export still has a home.
135
+ const hubId = castleJson.deckId ?? path.basename(deckDir);
136
+ if (!isHubId(hubId)) fail(`hub id ${JSON.stringify(hubId)} is not an id ([A-Za-z0-9_-], at most 64, not shared or packs)`);
137
+ const scenePath = castleJson.editor?.defaultPlayFile ?? 'scenes/main.scene';
138
+
139
+ // three: the CLI's own copy (CASTLE_EXPORT_THREE_DIR, cli/vendor/three, which a published CLI
140
+ // carries), else, by hand in this repo, where the shipped kits resolve it. Never the deck's.
141
+ const VENDORED_THREE = opt('three', 'CASTLE_EXPORT_THREE_DIR') || null;
142
+ let threeRoot;
143
+ let threeParent = null;
144
+ if (VENDORED_THREE) {
145
+ threeRoot = path.resolve(VENDORED_THREE);
146
+ if (!fs.existsSync(path.join(threeRoot, 'build/three.module.js'))) fail(`${threeRoot} is not a three copy (no build/three.module.js)`);
147
+ } else {
148
+ // Only a development checkout's kits (this repo's kits/, outside any node_modules) resolve three
149
+ // themselves. Kits inside an installed package without the CLI's copy fail: walking up from
150
+ // them can reach the deck's own node_modules (a CLI installed in the deck).
151
+ if (fs.realpathSync(KITS_DIR).split(path.sep).includes('node_modules')) fail(`no CASTLE_EXPORT_THREE_DIR names the CLI's three, and the kits ${KITS_DIR} are an installed package's; reinstall the CLI`);
152
+ threeParent = path.join(KITS_DIR, 'package.json');
153
+ try { threeRoot = path.dirname(path.dirname(createRequire(threeParent).resolve('three'))); } catch { fail(`three is not installed for the shipped kits ${KITS_DIR}, and no CASTLE_EXPORT_THREE_DIR names the CLI's copy`); }
154
+ }
155
+ const realThree = fs.realpathSync(threeRoot);
156
+ const realDeck = fs.realpathSync(deckDir);
157
+ if (realThree === realDeck || realThree.startsWith(realDeck + path.sep)) fail(`three at ${threeRoot} is inside the deck; an exporter never loads the deck's code`);
158
+ const threeVersion = readJson(path.join(threeRoot, 'package.json'))?.version ?? 'unknown';
159
+ const kitsHash = codeHash();
160
+
161
+ // The guard, then everything else through it.
162
+ const realKits = fs.realpathSync(KITS_DIR);
163
+ if (!fs.realpathSync(TOOLS_DIR).startsWith(realKits + path.sep)) fail(`${TOOLS_DIR} is not inside the kits ${KITS_DIR}`);
164
+ register(`data:text/javascript,${encodeURIComponent(hooksSource(KITS_DIR, VENDORED_THREE ? threeRoot : null, threeParent, [realKits, realThree]))}`);
165
+ const { buildDeckWorld, deckFiles, loadEngine } = await import('./nodeworld.mjs');
166
+ const { assembleManifest, audioDeckFlags, collectAvatarWear, collectHubData, deckSoundPaths } = await import('./hubdata.mjs');
167
+ const { validateManifest } = await import('./validate-manifest.mjs');
168
+ const { deckFlags } = await import('../../code/shared/deckFlags.js');
169
+ const { actorReferences } = await import('../../code/shared/quality.js');
170
+
171
+ // A shared asset's uri is exactly this from a hub folder; anything else is not one of ours.
172
+ const SHARED_URI = /^\.\.\/shared\/([0-9a-f]{64})\.(glb|png|webp|mp3|ogg|wav|m4a)$/;
173
+ const sharedName = (a) => { const m = SHARED_URI.exec(a?.uri ?? ''); return m && m[1] === a.sha256 && m[2] === a.type ? `${m[1]}.${m[2]}` : null; };
174
+ const staged = new Set();
175
+ // The stage's copy of a cache entry: a hardlink, or a copy across filesystems.
176
+ const stageShared = (name) => {
177
+ if (staged.has(name)) return true;
178
+ fs.mkdirSync(path.join(stageDir, 'shared'), { recursive: true });
179
+ const from = path.join(cacheShared, name);
180
+ const to = path.join(stageDir, 'shared', name);
181
+ // Used now: a sweep in another run leaves it alone for GC_DAYS.
182
+ try { const now = new Date(); fs.utimesSync(from, now, now); } catch {}
183
+ try { fs.linkSync(from, to); } catch {
184
+ try { fs.copyFileSync(from, to, fs.constants.COPYFILE_EXCL); } catch (e) {
185
+ // Another run's sweep collected it between our look and the link: the caller recovers.
186
+ if (e.code === 'ENOENT') return false;
187
+ throw e;
188
+ }
189
+ }
190
+ staged.add(name);
191
+ return true;
192
+ };
193
+ // The input list the key is made from sits beside the manifest (INPUTS_FILE), not in it: the
194
+ // native engine parses every byte of manifest.json at load and never needs the list.
195
+ const INPUTS_FILE = 'inputs.json';
196
+ const writeManifest = (m, inputs) => {
197
+ fs.mkdirSync(path.join(stageDir, hubId));
198
+ fs.writeFileSync(path.join(stageDir, hubId, INPUTS_FILE), JSON.stringify({ inputKey: m.source.inputKey, inputs }), { flag: 'wx' });
199
+ fs.writeFileSync(path.join(stageDir, hubId, 'manifest.json'), JSON.stringify(m), { flag: 'wx' });
200
+ };
201
+
202
+ // The last export's inputs, every one with the same bytes (or still missing): restage it.
203
+ if (PREV && !args.includes('--force')) {
204
+ const prev = readJson(path.join(path.resolve(PREV), hubId, 'manifest.json'));
205
+ const prevInputs = readJson(path.join(path.resolve(PREV), hubId, INPUTS_FILE));
206
+ const names = Object.values(prev?.assets ?? {}).map(sharedName);
207
+ if (prev?.source?.kitsHash === kitsHash && prevInputs?.inputKey === prev.source.inputKey && Array.isArray(prevInputs.inputs)
208
+ && names.length && names.every(Boolean) && names.every((n) => cacheEntryOk(n))) {
209
+ // A sound file the hub block names is keyed as readDeckSounds sees it (soundInput), never read
210
+ // through a link; every other input by its bytes.
211
+ const sounds = new Set(deckSoundPaths(castleJson.hub ?? null).filter((f) => soundSegments(f)));
212
+ const now = prevInputs.inputs.map((i) => ({ path: i.path, sha256: sounds.has(i.path) ? soundInput(i.path).hash : hashOrNull(path.resolve(deckDir, i.path)) }));
213
+ if (inputKeyOf(now) === prev.source.inputKey) {
214
+ if (names.every((n) => stageShared(n))) {
215
+ writeManifest(prev, prevInputs.inputs);
216
+ const faults = validateManifest(prev, path.join(stageDir, hubId));
217
+ finish(prev, { cached: true, faults });
218
+ }
219
+ // An entry was collected under us: forget the partial restage and export afresh.
220
+ fs.rmSync(path.join(stageDir, 'shared'), { recursive: true, force: true });
221
+ staged.clear();
222
+ }
223
+ }
224
+ }
225
+
226
+ const engine = await loadEngine({ kitsDir: KITS_DIR });
227
+ const { files, reads, absent } = deckFiles(deckDir, KITS_DIR);
228
+ const extraInputs = new Map(); // deck-relative path -> sha256 | null
229
+ const noteInput = (abs) => { extraInputs.set(path.relative(deckDir, abs).split(path.sep).join('/'), hashOrNull(abs)); };
230
+ noteInput(path.join(deckDir, 'castle.json'));
231
+
232
+ const built = buildDeckWorld(engine, { files, scenePath, avatarBlueprint: AVATAR_BLUEPRINT, avatarId: AVATAR_ID });
233
+ // GLTFExporter dumps whole light objects when it drops the ambient/hemisphere lights.
234
+ const warn = console.warn;
235
+ console.warn = (...a) => warn(...a.filter((x) => typeof x === 'string'));
236
+ const hubCfg = castleJson.hub ?? null;
237
+ const r = await collectHubData({ exportAvatar: true, splitModels: true, arrivalActor: hubCfg?.arrival?.actor ?? null, avatarActorId: AVATAR_ID,
238
+ mergeStatic: { cellM: MERGE_CELL_M, exclude: quotedInCode() },
239
+ soundscape: hubCfg?.soundscape ?? null,
240
+ tierRules: { tiers: hubCfg?.tiers === true, weakest: hubCfg?.weakestTier === true, lowActorDistance: hubCfg?.lowActorDistance === true,
241
+ sceneryNearM: engine.tiers?.SCENERY_NEAR_M ?? 30, npcNearM: engine.tiers?.NPC_NEAR_M ?? 20 } });
242
+ console.warn = warn;
243
+ if (r.errors.length) fail(r.errors.join('; '));
244
+
245
+ // Content-addressed: a new cache entry is created exclusively and never replaced.
246
+ const putShared = (buf, ext) => {
247
+ const h = sha256(buf);
248
+ const name = `${h}.${ext}`;
249
+ // Written again when another run's sweep collects it between our write and the stage.
250
+ for (let attempt = 0; attempt < 3; attempt += 1) {
251
+ writeEntry(buf, name);
252
+ if (stageShared(name)) return { type: ext, uri: `../shared/${name}`, sha256: h, bytes: buf.length, shared: true };
253
+ }
254
+ return fail(`cache entry ${name} kept going away while staging`);
255
+ };
256
+ function writeEntry(buf, name) {
257
+ if (!cacheEntryOk(name)) {
258
+ const target = path.join(cacheShared, name);
259
+ if (fs.existsSync(target) || isSymlink(target)) fail(`cache entry ${target} does not hold its hash; not overwriting it`);
260
+ const tmp = path.join(cacheShared, `.tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`);
261
+ const fd = fs.openSync(tmp, 'wx');
262
+ try { fs.writeSync(fd, buf); } finally { fs.closeSync(fd); }
263
+ try { fs.linkSync(tmp, target); } catch (e) { if (e.code !== 'EEXIST') throw e; }
264
+ fs.unlinkSync(tmp);
265
+ if (!cacheEntryOk(name)) fail(`cache entry ${target} does not hold its hash`);
266
+ }
267
+ }
268
+
269
+ // The hub client's readability rings (hub-game padCues.js, padRings.js), for a scene that asks.
270
+ const sceneEngine = built.runtime.data?.engine ?? {};
271
+ const padCues = engine.padCues.padCuesEnabled(sceneEngine)
272
+ ? { context: sceneEngine.hubPadContext === true, ring: sceneEngine.hubPadRing === true, spawnRing: sceneEngine.hubSpawnRing === true,
273
+ activeRing: { inset: 0.05, width: 0.12, unlit: true, defaultColor: '#d9a441', yieldWithinM: 1.2 },
274
+ cues: engine.padCues.collectPadCues(built.actors.filter((a) => a.id !== AVATAR_ID)) }
275
+ : null;
276
+ let spawnRing = null;
277
+ if (sceneEngine.hubSpawnRing === true) {
278
+ const { THREE, GLTFExporter } = engine;
279
+ const ring = new THREE.Mesh(engine.padRings.ringGeometry(1.2, 0.12, 8), new THREE.MeshBasicMaterial({ color: '#7fc9b8', side: THREE.DoubleSide }));
280
+ ring.name = 'hub.spawnRing';
281
+ // Where the client puts it: the arrival's authored point (padCues.js padArrivalPoint), 0.03 m up.
282
+ const at = engine.padCues.padArrivalPoint(built.actors.filter((a) => a.id !== AVATAR_ID), hubCfg?.arrival);
283
+ spawnRing = { glb: Buffer.from(await new GLTFExporter().parseAsync(ring, { binary: true })), at: [at.x, at.y + 0.03, at.z] };
284
+ }
285
+
286
+ const deckSounds = readDeckSounds(hubCfg);
287
+ const modelFiles = ['hats', 'earned', 'role'].flatMap((dir) =>
288
+ fs.readdirSync(path.join(KITS_DIR, 'hub-game/models', dir), { recursive: true })
289
+ .filter((file) => file.endsWith('.pxmodel')).sort().map((file) => `models/${dir}/${file.split(path.sep).join('/')}`));
290
+ const wear = await collectAvatarWear({ files, modelFiles, putShared });
291
+ const { manifest } = assembleManifest(r, {
292
+ hubId,
293
+ wear,
294
+ padCues,
295
+ spawnRing,
296
+ source: { deckId: castleJson.deckId ?? null, url: castleJson.deckId ? `https://castle.xyz/d/${castleJson.deckId}` : null, exporter: EXPORTER,
297
+ access: 'deck folder, at save', pins: pinsOf(castleJson), kits: kitVersions(), scene: scenePath },
298
+ hubCfg: hubCfg ? { ...hubCfg, title: hubCfg.title ?? castleJson.title } : { title: castleJson.title ?? r.title },
299
+ deck: audioDeckFlags(hubCfg, deckFlags(hubCfg)),
300
+ audio: deckSounds.audio,
301
+ putShared,
302
+ avatar: null,
303
+ resolveDoor,
304
+ readArt(art) {
305
+ const file = path.resolve(deckDir, art);
306
+ if (path.relative(deckDir, file).startsWith('..')) return null;
307
+ noteInput(file);
308
+ return fs.existsSync(file) ? { buf: fs.readFileSync(file), ext: path.extname(art).slice(1).toLowerCase() } : null;
309
+ },
310
+ });
311
+
312
+ const inputs = new Map();
313
+ for (const [key, { file, sha256: h }] of reads) inputs.set(path.relative(deckDir, file ?? path.join(deckDir, key)).split(path.sep).join('/'), h);
314
+ for (const [p, h] of extraInputs) inputs.set(p, h);
315
+ // A deck file looked for first and found missing (the shipped kit's stood in) is an input too.
316
+ for (const file of absent) inputs.set(path.relative(deckDir, file).split(path.sep).join('/'), null);
317
+ const sortedInputs = [...inputs].map(([p, h]) => ({ path: p, sha256: h })).sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
318
+ manifest.source.notes = [...(manifest.source.notes ?? []), ...built.notes, ...deckSounds.notes];
319
+ manifest.source.kitsHash = kitsHash;
320
+ manifest.source.three = threeVersion;
321
+ manifest.source.inputKey = inputKeyOf(sortedInputs);
322
+ manifest.source.inputs = { file: INPUTS_FILE, count: sortedInputs.length };
323
+ writeManifest(manifest, sortedInputs);
324
+ finish(manifest, { cached: false, faults: validateManifest(manifest, path.join(stageDir, hubId)) });
325
+
326
+ // Every short string literal in the code files that address scene actors by id (call hide, show,
327
+ // tint, move, despawn or touch) among the deck's code/ and its hub-game's (the deck's pinned copy,
328
+ // else the shipped kit's, which the kits hash covers), plus the literal first argument of every
329
+ // actor call the publish check's actorReferences reads in any of them (a template `spawn` copies,
330
+ // which draws the template's own node; an actor `label`, `reset` or `getActor` names), an optional
331
+ // call (`hub.spawn?.('x')`, spaces allowed) included. An actor id quoted there may change at run
332
+ // time, so it is never merged. Each deck file read is an input. Not seen: an id built at run time
333
+ // (`lamp-${i}`), or quoted in a file that only hands it to another; the scene's
334
+ // engine.hubKeepNodes patterns cover those (hubdata.mjs mergeStatic).
335
+ function quotedInCode() {
336
+ const found = new Set();
337
+ const ADDRESSES = /\.(hide|show|tint|move|despawn|touch)\??\.?\(/;
338
+ const LITERAL = /(['"`])([^'"`\\\s$]{1,96})\1/g;
339
+ const scan = (dir, keyed) => {
340
+ // The folder itself is an input too (its listing): a code file added later re-exports.
341
+ if (keyed) noteInput(dir);
342
+ for (const rel of codeFilesUnder(dir)) {
343
+ const p = path.join(dir, rel);
344
+ if (keyed) noteInput(p);
345
+ const text = fs.readFileSync(p, 'utf8');
346
+ // `f?.(x)` read as `f(x)`: actorReferences' tokens skip whitespace but expect the bare call.
347
+ const { ids, templates } = actorReferences([text.replace(/\?\s*\.\s*\(/g, '(')]);
348
+ for (const id of [...ids, ...templates]) found.add(id);
349
+ if (!ADDRESSES.test(text)) continue;
350
+ for (const m of text.matchAll(LITERAL)) found.add(m[2]);
351
+ }
352
+ };
353
+ scan(path.join(deckDir, 'code'), true);
354
+ const pinned = path.join(deckDir, 'imports/castle.hub-game/code');
355
+ if (fs.existsSync(pinned)) scan(pinned, true);
356
+ else scan(path.join(KITS_DIR, 'hub-game/code'), false);
357
+ // Missing or not, the pinned folder is keyed: one appearing later re-exports.
358
+ noteInput(pinned);
359
+ return found;
360
+ }
361
+
362
+ // v1.6: the deck's sound files its hub block names (hubdata.mjs deckSoundPaths), read as the
363
+ // page's physics-2d initialMedia holds them (engine/files.js: the deck's own .mp3, .wav and .m4a
364
+ // files by deck-relative path, none under node_modules/, dist/, .castle/ or a dot folder). A file
365
+ // the page would not have (missing, another type, a path initialMedia never keys) plays nothing
366
+ // there either: it is left out, with a note. Each file looked for is an input, a missing one
367
+ // included. A symlink is never followed.
368
+ function readDeckSounds(block) {
369
+ const audio = []; const notes = [];
370
+ for (const file of deckSoundPaths(block)) {
371
+ const where = `sound ${JSON.stringify(file)}`;
372
+ if (!soundSegments(file)) { notes.push(`${where}: not a deck media path; left out`); continue; }
373
+ const ext = /\.(mp3|wav|m4a)$/.exec(file)?.[1];
374
+ if (!ext) { notes.push(`${where}: not an .mp3, .wav or .m4a the page bundles; left out`); continue; }
375
+ const { hash, buf, why } = soundInput(file);
376
+ extraInputs.set(file, hash);
377
+ if (!buf) { notes.push(`${where}: ${why}; left out`); continue; }
378
+ audio.push({ path: file, ext, buf });
379
+ }
380
+ return { audio, notes };
381
+ }
382
+
383
+ // A sound path's segments, or null when initialMedia could never key it (engine/files.js: no
384
+ // leading slash, no dot segment or dot folder, nothing under node_modules/ or dist/).
385
+ function soundSegments(file) {
386
+ if (typeof file !== 'string' || !file || file.includes('\\')) return null;
387
+ const segs = file.split('/');
388
+ if (segs.some((s) => !s || s.startsWith('.')) || ['node_modules', 'dist'].includes(segs[0])) return null;
389
+ return segs;
390
+ }
391
+
392
+ // What a sound path holds, as its cache input, looked at without following a link and read only
393
+ // when it is a regular file inside the deck: { hash: sha256 | marker | null, buf | null, why }.
394
+ // The marker names why a file is not exported, so a link or other file put in place of an
395
+ // exported sound (or the other way round) changes the key even when the bytes are the same.
396
+ function soundInput(file) {
397
+ const segs = soundSegments(file);
398
+ const abs = path.join(deckDir, ...segs);
399
+ // Every component, folders included, is looked at without following a link.
400
+ let st = null;
401
+ for (let i = 1; i <= segs.length; i += 1) {
402
+ const at = path.join(deckDir, ...segs.slice(0, i));
403
+ st = null;
404
+ try { st = fs.lstatSync(at); } catch {}
405
+ if (!st) return { hash: null, buf: null, why: 'missing' };
406
+ if (st.isSymbolicLink()) {
407
+ let target = '';
408
+ try { target = fs.readlinkSync(at); } catch {}
409
+ return { hash: `link:${i}:${sha256(target)}`, buf: null, why: 'a link, not followed' };
410
+ }
411
+ if (i < segs.length && !st.isDirectory()) return { hash: null, buf: null, why: 'missing' };
412
+ }
413
+ if (!st.isFile()) return { hash: 'not-a-file', buf: null, why: 'not a regular file' };
414
+ let real = null;
415
+ try { real = fs.realpathSync(abs); } catch {}
416
+ if (!real || !real.startsWith(realDeck + path.sep)) return { hash: 'outside-deck', buf: null, why: 'outside the deck' };
417
+ let buf;
418
+ try { buf = fs.readFileSync(abs); } catch { return { hash: null, buf: null, why: 'unreadable' }; }
419
+ const hash = sha256(buf);
420
+ return buf.length ? { hash, buf, why: null } : { hash, buf: null, why: 'empty' };
421
+ }
422
+
423
+ // `deck:<name>` resolves to a sibling deck folder: castle.json devDecks names it (Town's), else a
424
+ // folder `<name>` or `hub-<name>` beside this deck (experiments/hub-*). Its castle.json deckId is
425
+ // the target. Nothing else on disk can say where a door goes: the server's door table owns the
426
+ // rest, cabinets included (it names their classic deck), so those stay `unresolved`,
427
+ // `resolveAt: 'load'`: the native engine takes their targets from Ghost's door list
428
+ // (cauldronHubDoors) when it loads the hub, as the web host does.
429
+ function resolveDoor(d) {
430
+ if (d.kind === 'cabinet') return { type: 'unresolved', resolveAt: 'load', note: `door ${d.id}: cabinet: the server door table names the classic deck` };
431
+ const m = /^deck:(.+)$/.exec(d.to ?? '');
432
+ if (!m) return { type: 'unresolved', resolveAt: 'load', note: `door ${d.id}: ${JSON.stringify(d.to)} is not deck:<name>` };
433
+ const candidates = [castleJson.devDecks?.[m[1]], m[1], `hub-${m[1]}`].filter((x) => typeof x === 'string');
434
+ // Every candidate probed is an input, a missing one included (hash null): the preferred
435
+ // folder appearing later must change the key, not keep the old target cached.
436
+ for (const rel of candidates) {
437
+ const file = path.resolve(deckDir, rel.startsWith('.') ? rel : path.join('..', rel), 'castle.json');
438
+ noteInput(file);
439
+ const cj = fs.existsSync(file) ? readJson(file) : null;
440
+ if (typeof cj?.deckId === 'string' && isHubId(cj.deckId)) return { type: d.kind === 'layer' ? 'hub' : 'deck', deckId: cj.deckId, hubId: cj.deckId };
441
+ }
442
+ return { type: 'unresolved', resolveAt: 'load', note: `door ${d.id}: no sibling deck folder with a deckId for ${d.to}` };
443
+ }
444
+
445
+ // The loader guard: `@imports/castle.<kit>/` resolves into the shipped kits folder, `three` and its
446
+ // addons into the CLI's copy (vendoredThree) or from the kits (threeParent), and EVERY module
447
+ // that resolves to a file must, by its real path, lie under the shipped kits or that `three`;
448
+ // anything else (a deck's imports/ or node_modules, a symlink leading out of a kit) is refused.
449
+ // Only node: builtins and the two stubs are exempt.
450
+ function hooksSource(kitsDir, vendoredThree, threeParent, allowedRoots) {
451
+ return `
452
+ import { existsSync, realpathSync } from 'node:fs';
453
+ import { fileURLToPath, pathToFileURL } from 'node:url';
454
+ import path from 'node:path';
455
+ const KITS = ${JSON.stringify(pathToFileURL(kitsDir).href + '/')};
456
+ const ROOTS = ${JSON.stringify(allowedRoots)};
457
+ const VENDORED = ${JSON.stringify(vendoredThree ? pathToFileURL(vendoredThree).href + '/' : null)};
458
+ const THREE_PARENT = ${JSON.stringify(threeParent ? pathToFileURL(threeParent).href : null)};
459
+ const stub = (src) => ({ url: 'data:text/javascript,' + encodeURIComponent(src), shortCircuit: true });
460
+ const allowed = (url) => {
461
+ if (!url.startsWith('file:')) return url.startsWith('node:');
462
+ let real;
463
+ try { real = realpathSync(fileURLToPath(url)); } catch { return false; }
464
+ return ROOTS.some((root) => real === root || real.startsWith(root + path.sep));
465
+ };
466
+ export async function resolve(specifier, context, next) {
467
+ const parent = context.parentURL ?? '';
468
+ if (specifier === 'castle-web-sdk') return stub(${JSON.stringify(SDK_STUB)});
469
+ if (specifier === 'castle-web-fonts') return stub(${JSON.stringify(FONTS_STUB)});
470
+ const alias = /^@imports\\/castle\\.([a-z0-9-]+)\\//.exec(specifier);
471
+ if (alias) specifier = KITS + alias[1] + '/' + specifier.slice(alias[0].length);
472
+ let result;
473
+ if ((specifier.startsWith('.') || specifier.startsWith('file:')) && !/\\.(m?js|jsx|json)$/.test(specifier)) {
474
+ const base = new URL(specifier, parent).href;
475
+ for (const ext of ['.js', '.jsx']) if (existsSync(fileURLToPath(base + ext))) { result = await next(base + ext, context); break; }
476
+ }
477
+ if (!result && (specifier === 'three' || specifier.startsWith('three/'))) {
478
+ if (VENDORED) {
479
+ // The copy has no package exports to resolve through: the two forms the kits write, by hand.
480
+ const addon = /^three\\/(?:examples\\/jsm|addons)\\/(.+)$/.exec(specifier);
481
+ if (specifier !== 'three' && !addon) throw new Error('hubScene export: refused to load ' + specifier + ' (not in the three the CLI ships)');
482
+ result = await next(VENDORED + (addon ? 'examples/jsm/' + addon[1] : 'build/three.module.js'), context);
483
+ } else result = await next(specifier, { ...context, parentURL: THREE_PARENT });
484
+ }
485
+ result ??= await next(specifier, context);
486
+ if (!result.url.startsWith('data:') && !allowed(result.url)) throw new Error('hubScene export: refused to load ' + result.url + ' (outside the shipped kits and three)');
487
+ return result;
488
+ }`;
489
+ }
490
+
491
+ function pinsOf(cj) {
492
+ return Object.fromEntries(Object.entries(cj.imports ?? {}).map(([alias, pin]) => [alias, pin?.version ?? null]));
493
+ }
494
+
495
+ // The shipped kits the world was built with: what each says its version is.
496
+ function kitVersions() {
497
+ return Object.fromEntries(KEYED_KITS.map((kit) => {
498
+ const cj = readJson(path.join(KITS_DIR, kit, 'castle.json'));
499
+ const pkg = readJson(path.join(KITS_DIR, kit, 'package.json'));
500
+ return [`castle.${kit}`, { publishedVersion: cj?.publishedVersion ?? null, package: pkg?.version ?? null }];
501
+ }));
502
+ }
503
+
504
+ // A file's SHA-256; for a folder (a code folder quotedInCode scans), the hash of the code files it
505
+ // lists, so a file added or removed there changes the key; null when there is nothing.
506
+ function hashOrNull(file) {
507
+ try {
508
+ if (fs.lstatSync(file).isDirectory()) return `dir:${sha256(codeFilesUnder(file).join('\n'))}`;
509
+ // A FIFO or other non-file (one a sound path used to name, say) is never opened: it would block.
510
+ if (!fs.statSync(file).isFile()) return 'not-a-file';
511
+ return sha256(fs.readFileSync(file));
512
+ } catch { return null; }
513
+ }
514
+
515
+ // The code files under `dir` quotedInCode reads, as sorted paths relative to it.
516
+ function codeFilesUnder(dir, rel = '') {
517
+ const out = [];
518
+ let entries = [];
519
+ try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }); } catch { return out; }
520
+ for (const e of entries) {
521
+ const r = rel ? `${rel}/${e.name}` : e.name;
522
+ if (e.isDirectory()) { if (e.name !== 'node_modules') out.push(...codeFilesUnder(dir, r)); } else if (e.isFile() && CODE_FILE.test(e.name)) out.push(r);
523
+ }
524
+ return out.sort();
525
+ }
526
+
527
+ function isSymlink(file) {
528
+ try { return fs.lstatSync(file).isSymbolicLink(); } catch { return false; }
529
+ }
530
+
531
+ // A cache entry that is a regular file holding the bytes its name says.
532
+ function cacheEntryOk(name) {
533
+ const file = path.join(cacheShared, name);
534
+ try { if (!fs.lstatSync(file).isFile()) return false; } catch { return false; }
535
+ return hashOrNull(file) === name.slice(0, 64);
536
+ }
537
+
538
+ function inputKeyOf(list) {
539
+ const lines = list.map((i) => `${i.path} ${i.sha256 ?? 'missing'}`).sort();
540
+ return sha256(`${EXPORTER}\n${kitsHash}\n${lines.join('\n')}`);
541
+ }
542
+
543
+ // Every file the loader could reach: the whole shipped physics-2d, physics-3d and hub-game trees
544
+ // (node_modules aside; a symlink by its target text, never followed) and this tools folder, plus
545
+ // the CLI version and three's. Computed once per run.
546
+ function codeHash() {
547
+ const h = crypto.createHash('sha256');
548
+ h.update(`cli ${process.env.CASTLE_EXPORT_CLI_VERSION ?? 'by hand'}\nthree ${threeVersion}\n`);
549
+ const walk = (dir, label) => {
550
+ let entries = [];
551
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
552
+ for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
553
+ if (e.name === 'node_modules') continue;
554
+ const p = path.join(dir, e.name);
555
+ const rel = `${label}/${e.name}`;
556
+ if (e.isSymbolicLink()) h.update(`link ${rel} ${fs.readlinkSync(p)}\n`);
557
+ else if (e.isDirectory()) walk(p, rel);
558
+ else if (e.isFile()) h.update(`file ${rel} ${sha256(fs.readFileSync(p))}\n`);
559
+ }
560
+ };
561
+ for (const kit of KEYED_KITS) walk(path.join(KITS_DIR, kit), kit);
562
+ walk(TOOLS_DIR, 'tools');
563
+ return h.digest('hex');
564
+ }
565
+
566
+ // The cache's own garbage collection, after a good export, once a day at most (CASTLE_EXPORT_GC=1
567
+ // runs it now): shared entries untouched for GC_DAYS (a run touches every entry it uses) and
568
+ // temp files over a day old. Only regular files with the cache's own names are ever removed. No
569
+ // lock: a run that loses an entry to a sweep between looking and staging writes it again from the
570
+ // bytes it holds (putShared), or gives up a restage and exports afresh.
571
+ function sweepCache() {
572
+ const marker = path.join(path.resolve(CACHE), '.gc-at');
573
+ const now = Date.now();
574
+ try { if (process.env.CASTLE_EXPORT_GC !== '1' && now - fs.lstatSync(marker).mtimeMs < DAY_MS) return null; } catch {}
575
+ // A fresh file renamed over the marker: whatever is there, a symlink included, is replaced, never written through.
576
+ const tmpMarker = path.join(path.resolve(CACHE), `.gc-at.${process.pid}-${crypto.randomBytes(6).toString('hex')}`);
577
+ fs.writeFileSync(tmpMarker, new Date(now).toISOString(), { flag: 'wx' });
578
+ fs.renameSync(tmpMarker, marker);
579
+ let removed = 0; let bytes = 0;
580
+ for (const name of fs.readdirSync(cacheShared)) {
581
+ const entry = /^[0-9a-f]{64}\.(glb|png|webp|mp3|ogg|wav|m4a)$/.test(name) && !staged.has(name);
582
+ const temp = /^\.tmp-\d+-[0-9a-f]{12}$/.test(name);
583
+ if (!entry && !temp) continue;
584
+ const file = path.join(cacheShared, name);
585
+ let st;
586
+ try { st = fs.lstatSync(file); } catch { continue; }
587
+ if (!st.isFile() || now - st.mtimeMs < (entry ? GC_DAYS * DAY_MS : DAY_MS)) continue;
588
+ try { fs.unlinkSync(file); removed += 1; bytes += st.size; } catch {}
589
+ }
590
+ return { removed, bytes };
591
+ }
592
+
593
+ function finish(m, { cached, faults }) {
594
+ const gc = faults.length ? null : sweepCache();
595
+ const assetBytes = Object.fromEntries(Object.entries(m.assets).map(([id, a]) => [id, a.bytes]));
596
+ const props = m.layers.filter((l) => l.role === 'prop');
597
+ console.log(JSON.stringify({
598
+ hubId: m.hubId, title: m.title, cached, seconds: Math.round(performance.now() - t0) / 1000,
599
+ manifest: `${m.hubId}/manifest.json`, inputKey: m.source.inputKey, inputs: m.source.inputs.count,
600
+ assets: assetBytes, totalBytes: Object.values(assetBytes).reduce((a, b) => a + b, 0),
601
+ models: props.length, placements: props.reduce((n, l) => n + l.instances.length, 0),
602
+ stats: m.stats, spawns: m.spawns.length, doors: m.doors.length,
603
+ doorsResolved: m.doors.filter((d) => d.target?.type !== 'unresolved').length,
604
+ characters: m.characters.length, audio: Object.keys(m.audio ?? {}).length, interactables: m.interactables?.length ?? 0, deck: m.deck ? Object.keys(m.deck) : null, colliders: m.colliders.length, labels: m.labels.length,
605
+ sky: Boolean(m.sky), fog: m.fog?.type ?? null, avatar: Boolean(m.avatar), gc, faults,
606
+ }));
607
+ process.exit(faults.length ? 1 : 0);
608
+ }
609
+
610
+ function fail(message) {
611
+ console.error(message);
612
+ process.exit(1);
613
+ }