castle-web-cli 0.4.228 → 0.4.230

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 (236) hide show
  1. package/dist/agent-prompts.d.ts +11 -3
  2. package/dist/agent-prompts.js +153 -53
  3. package/dist/agent.d.ts +2 -0
  4. package/dist/agent.js +43 -33
  5. package/dist/api.d.ts +47 -2
  6. package/dist/api.js +85 -16
  7. package/dist/castle-host/host.d.ts +91 -0
  8. package/dist/castle-host/host.js +779 -3
  9. package/dist/castleJson.d.ts +59 -0
  10. package/dist/castleJson.js +267 -3
  11. package/dist/check.js +27 -1
  12. package/dist/cloudGit.d.ts +20 -1
  13. package/dist/cloudGit.js +267 -10
  14. package/dist/contentPack.d.ts +49 -0
  15. package/dist/contentPack.js +273 -0
  16. package/dist/devExperiments.d.ts +21 -0
  17. package/dist/devExperiments.js +139 -0
  18. package/dist/devHub.d.ts +55 -0
  19. package/dist/devHub.js +187 -0
  20. package/dist/devSessionChild.js +3 -1
  21. package/dist/devSessionServer.d.ts +14 -1
  22. package/dist/devSessionServer.js +229 -44
  23. package/dist/experimentAssignment.d.ts +15 -0
  24. package/dist/experimentAssignment.js +41 -0
  25. package/dist/importCheckHook.d.ts +40 -0
  26. package/dist/importCheckHook.js +171 -0
  27. package/dist/importRegression.d.ts +15 -0
  28. package/dist/importRegression.js +100 -0
  29. package/dist/importTrust.d.ts +2 -0
  30. package/dist/importTrust.js +27 -0
  31. package/dist/importUpdateHook.d.ts +18 -0
  32. package/dist/importUpdateHook.js +31 -8
  33. package/dist/importUpdateHookRunner.js +19 -7
  34. package/dist/imports.d.ts +16 -0
  35. package/dist/imports.js +145 -33
  36. package/dist/index.js +8 -1
  37. package/dist/init.d.ts +3 -0
  38. package/dist/init.js +125 -8
  39. package/dist/install.js +4 -1
  40. package/dist/localPaths.js +4 -0
  41. package/dist/login.js +2 -2
  42. package/dist/platformDoc.js +3 -8
  43. package/dist/playPagePolicy.js +3 -1
  44. package/dist/remix.js +5 -0
  45. package/dist/routerTaskReport.d.ts +28 -0
  46. package/dist/routerTaskReport.js +56 -0
  47. package/dist/save-deck.d.ts +18 -0
  48. package/dist/save-deck.js +145 -6
  49. package/dist/serve.d.ts +8 -0
  50. package/dist/serve.js +94 -13
  51. package/dist/serverBundle.d.ts +1 -1
  52. package/dist/serverBundle.js +5 -1
  53. package/dist/sourceLineage.d.ts +42 -0
  54. package/dist/sourceLineage.js +380 -0
  55. package/dist/webSourceSync.d.ts +11 -0
  56. package/dist/webSourceSync.js +26 -9
  57. package/kits/base/CLAUDE.md +2 -3
  58. package/kits/base/castle.json +1 -1
  59. package/kits/base/sdk/README.md +301 -52
  60. package/kits/base/sdk/agent.js +4 -4
  61. package/kits/base/sdk/avatar.d.ts +12 -0
  62. package/kits/base/sdk/avatar.js +23 -0
  63. package/kits/base/sdk/castle.d.ts +6 -1
  64. package/kits/base/sdk/castle.js +3 -0
  65. package/kits/base/sdk/commands.d.ts +208 -0
  66. package/kits/base/sdk/commands.js +16 -0
  67. package/kits/base/sdk/context.d.ts +6 -0
  68. package/kits/base/sdk/experiments.d.ts +15 -0
  69. package/kits/base/sdk/experiments.js +83 -0
  70. package/kits/base/sdk/hub.d.ts +85 -0
  71. package/kits/base/sdk/hub.js +107 -0
  72. package/kits/base/sdk/multiplayer.d.ts +86 -6
  73. package/kits/base/sdk/multiplayer.js +157 -4
  74. package/kits/base/sdk/server/hub.d.ts +169 -0
  75. package/kits/base/sdk/server/hub.js +125 -0
  76. package/kits/base/sdk/server/platformHandle.d.ts +49 -2
  77. package/kits/base/sdk/server/storage.d.ts +55 -2
  78. package/kits/base/sdk/server/wrapper.d.ts +85 -6
  79. package/kits/base/sdk/server/wrapper.js +393 -30
  80. package/kits/base/sdk/transport.d.ts +2 -1
  81. package/kits/base/sdk/transport.js +13 -1
  82. package/kits/hub-game/.prettierrc +5 -0
  83. package/kits/hub-game/CLAUDE.md +146 -0
  84. package/kits/hub-game/blueprints/avatar-0.scene +28 -0
  85. package/kits/hub-game/blueprints/avatar-1.scene +28 -0
  86. package/kits/hub-game/blueprints/avatar-2.scene +28 -0
  87. package/kits/hub-game/blueprints/avatar-3.scene +28 -0
  88. package/kits/hub-game/blueprints/bean/avatar-0.scene +28 -0
  89. package/kits/hub-game/blueprints/bean/avatar-1.scene +28 -0
  90. package/kits/hub-game/blueprints/bean/avatar-2.scene +28 -0
  91. package/kits/hub-game/blueprints/bean/avatar-3.scene +28 -0
  92. package/kits/hub-game/blueprints/blocky/avatar-0.scene +28 -0
  93. package/kits/hub-game/blueprints/blocky/avatar-1.scene +28 -0
  94. package/kits/hub-game/blueprints/blocky/avatar-2.scene +28 -0
  95. package/kits/hub-game/blueprints/blocky/avatar-3.scene +28 -0
  96. package/kits/hub-game/blueprints/pixel/avatar-0.scene +28 -0
  97. package/kits/hub-game/blueprints/pixel/avatar-1.scene +28 -0
  98. package/kits/hub-game/blueprints/pixel/avatar-2.scene +28 -0
  99. package/kits/hub-game/blueprints/pixel/avatar-3.scene +28 -0
  100. package/kits/hub-game/castle.json +96 -0
  101. package/kits/hub-game/code/client/attention.js +133 -0
  102. package/kits/hub-game/code/client/avatar.js +288 -0
  103. package/kits/hub-game/code/client/cabinets.js +90 -0
  104. package/kits/hub-game/code/client/chat.js +135 -0
  105. package/kits/hub-game/code/client/chrome.js +1001 -0
  106. package/kits/hub-game/code/client/doorFrame.js +15 -0
  107. package/kits/hub-game/code/client/firstJoin.js +14 -0
  108. package/kits/hub-game/code/client/grab.js +241 -0
  109. package/kits/hub-game/code/client/hookLayer.js +230 -0
  110. package/kits/hub-game/code/client/idle.js +326 -0
  111. package/kits/hub-game/code/client/keys.js +48 -0
  112. package/kits/hub-game/code/client/pack.js +232 -0
  113. package/kits/hub-game/code/client/packFormat.js +397 -0
  114. package/kits/hub-game/code/client/say.js +127 -0
  115. package/kits/hub-game/code/client/sha256.js +80 -0
  116. package/kits/hub-game/code/client/sound.js +147 -0
  117. package/kits/hub-game/code/client/state.js +131 -0
  118. package/kits/hub-game/code/client/talk.js +259 -0
  119. package/kits/hub-game/code/client/together.js +365 -0
  120. package/kits/hub-game/code/client/wear.js +149 -0
  121. package/kits/hub-game/code/server/actors.js +627 -0
  122. package/kits/hub-game/code/server/blocks.js +103 -0
  123. package/kits/hub-game/code/server/cabinets.js +309 -0
  124. package/kits/hub-game/code/server/game.js +137 -0
  125. package/kits/hub-game/code/server/grab.js +247 -0
  126. package/kits/hub-game/code/server/history.js +96 -0
  127. package/kits/hub-game/code/server/hub.js +1904 -0
  128. package/kits/hub-game/code/server/idle.js +412 -0
  129. package/kits/hub-game/code/server/index.js +64 -0
  130. package/kits/hub-game/code/server/labels.js +59 -0
  131. package/kits/hub-game/code/server/manifest.js +527 -0
  132. package/kits/hub-game/code/server/npcs.js +745 -0
  133. package/kits/hub-game/code/server/party.js +381 -0
  134. package/kits/hub-game/code/server/place.js +43 -0
  135. package/kits/hub-game/code/server/say.js +83 -0
  136. package/kits/hub-game/code/server/wear.js +142 -0
  137. package/kits/hub-game/code/systems/hub.js +2230 -0
  138. package/kits/hub-game/docs/content-pack.md +151 -0
  139. package/kits/hub-game/docs/contract.md +1139 -0
  140. package/kits/hub-game/docs/style.md +137 -0
  141. package/kits/hub-game/drawings/blocky/castle-eye.sprite +58 -0
  142. package/kits/hub-game/drawings/blocky/dash.sprite +59 -0
  143. package/kits/hub-game/drawings/blocky/pom.sprite +59 -0
  144. package/kits/hub-game/drawings/blocky/tabby.sprite +59 -0
  145. package/kits/hub-game/drawings/pixel/castle-arm.sprite +13 -0
  146. package/kits/hub-game/drawings/pixel/castle-body.sprite +23 -0
  147. package/kits/hub-game/drawings/pixel/castle-leg.sprite +12 -0
  148. package/kits/hub-game/drawings/pixel/kai-arm.sprite +14 -0
  149. package/kits/hub-game/drawings/pixel/kai-head.sprite +24 -0
  150. package/kits/hub-game/drawings/pixel/kai-leg.sprite +15 -0
  151. package/kits/hub-game/drawings/pixel/kai-torso.sprite +18 -0
  152. package/kits/hub-game/drawings/pixel/mimi-arm.sprite +13 -0
  153. package/kits/hub-game/drawings/pixel/mimi-head.sprite +23 -0
  154. package/kits/hub-game/drawings/pixel/mimi-leg.sprite +15 -0
  155. package/kits/hub-game/drawings/pixel/mimi-torso.sprite +18 -0
  156. package/kits/hub-game/drawings/pixel/nox-arm.sprite +13 -0
  157. package/kits/hub-game/drawings/pixel/nox-head.sprite +21 -0
  158. package/kits/hub-game/drawings/pixel/nox-leg.sprite +14 -0
  159. package/kits/hub-game/drawings/pixel/nox-torso.sprite +18 -0
  160. package/kits/hub-game/eslint.config.js +20 -0
  161. package/kits/hub-game/fonts.generated.js +9 -0
  162. package/kits/hub-game/index.html +22 -0
  163. package/kits/hub-game/main.jsx +6 -0
  164. package/kits/hub-game/models/avatar-0.pxmodel +21 -0
  165. package/kits/hub-game/models/avatar-1.pxmodel +24 -0
  166. package/kits/hub-game/models/avatar-2.pxmodel +27 -0
  167. package/kits/hub-game/models/avatar-3.pxmodel +22 -0
  168. package/kits/hub-game/models/bean/avatar-0.pxmodel +19 -0
  169. package/kits/hub-game/models/bean/avatar-1.pxmodel +24 -0
  170. package/kits/hub-game/models/bean/avatar-2.pxmodel +22 -0
  171. package/kits/hub-game/models/bean/avatar-3.pxmodel +24 -0
  172. package/kits/hub-game/models/blocky/avatar-0.pxmodel +21 -0
  173. package/kits/hub-game/models/blocky/avatar-1.pxmodel +30 -0
  174. package/kits/hub-game/models/blocky/avatar-2.pxmodel +28 -0
  175. package/kits/hub-game/models/blocky/avatar-3.pxmodel +27 -0
  176. package/kits/hub-game/models/pixel/avatar-0.pxmodel +24 -0
  177. package/kits/hub-game/models/pixel/avatar-1.pxmodel +16 -0
  178. package/kits/hub-game/models/pixel/avatar-2.pxmodel +19 -0
  179. package/kits/hub-game/models/pixel/avatar-3.pxmodel +23 -0
  180. package/kits/hub-game/package-lock.json +365 -0
  181. package/kits/hub-game/package.json +32 -0
  182. package/kits/hub-game/scenes/main.scene +318 -0
  183. package/kits/hub-game/scripts/check.mjs +339 -0
  184. package/kits/hub-game/scripts/fixtures/sdk-stub.mjs +3 -0
  185. package/kits/hub-game/scripts/gen-avatars-bean.mjs +748 -0
  186. package/kits/hub-game/scripts/gen-avatars-blocky.mjs +607 -0
  187. package/kits/hub-game/scripts/gen-avatars-pixel.mjs +771 -0
  188. package/kits/hub-game/scripts/gen-avatars.mjs +621 -0
  189. package/kits/hub-game/scripts/pack.mjs +192 -0
  190. package/kits/hub-game/scripts/test-actors.mjs +666 -0
  191. package/kits/hub-game/scripts/test-attention.mjs +103 -0
  192. package/kits/hub-game/scripts/test-avatar.mjs +472 -0
  193. package/kits/hub-game/scripts/test-ban-join.mjs +194 -0
  194. package/kits/hub-game/scripts/test-blocks.mjs +351 -0
  195. package/kits/hub-game/scripts/test-chat.mjs +98 -0
  196. package/kits/hub-game/scripts/test-classic.mjs +590 -0
  197. package/kits/hub-game/scripts/test-door-jump.mjs +131 -0
  198. package/kits/hub-game/scripts/test-door.mjs +56 -0
  199. package/kits/hub-game/scripts/test-grab.mjs +331 -0
  200. package/kits/hub-game/scripts/test-hub-ops.mjs +835 -0
  201. package/kits/hub-game/scripts/test-hub-trip.mjs +1310 -0
  202. package/kits/hub-game/scripts/test-idle.mjs +518 -0
  203. package/kits/hub-game/scripts/test-interest.mjs +413 -0
  204. package/kits/hub-game/scripts/test-keys.mjs +50 -0
  205. package/kits/hub-game/scripts/test-manifest.mjs +224 -0
  206. package/kits/hub-game/scripts/test-no-forms.mjs +16 -0
  207. package/kits/hub-game/scripts/test-npcs.mjs +714 -0
  208. package/kits/hub-game/scripts/test-pack.mjs +424 -0
  209. package/kits/hub-game/scripts/test-party.mjs +286 -0
  210. package/kits/hub-game/scripts/test-say.mjs +149 -0
  211. package/kits/hub-game/scripts/test-together.mjs +183 -0
  212. package/kits/hub-game/theme.style +3 -0
  213. package/kits/multiplayer-3d/castle.json +5 -5
  214. package/kits/multiplayer-3d/code/client/avatars.js +101 -1
  215. package/kits/multiplayer-3d/code/server/players.js +4 -1
  216. package/kits/multiplayer-3d/code/server/sceneBodies.js +27 -6
  217. package/kits/multiplayer-3d/code/server/world.js +20 -7
  218. package/kits/multiplayer-3d/code/systems/multiplayer.js +222 -11
  219. package/kits/physics-2d/castle.json +2 -2
  220. package/kits/physics-2d/engine/art.js +13 -0
  221. package/kits/physics-2d/engine/assets.js +4 -2
  222. package/kits/physics-2d/engine/scene.js +25 -5
  223. package/kits/physics-3d/CLAUDE.md +6 -1
  224. package/kits/physics-3d/castle.json +3 -3
  225. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +32 -4
  226. package/kits/physics-3d/engine3d/artobjects.js +2 -2
  227. package/kits/physics-3d/engine3d/materials.js +29 -1
  228. package/kits/physics-3d/engine3d/world3d.js +65 -1
  229. package/kits/physics-3d/systems/physics3d.js +5 -2
  230. package/kits/real-time/castle.json +2 -2
  231. package/kits/real-time/code/client/connection.js +77 -7
  232. package/kits/real-time/code/client/gameHooks.js +63 -3
  233. package/kits/real-time/code/client/messages.js +7 -0
  234. package/kits/real-time/code/server/gameHooks.js +24 -0
  235. package/kits/real-time/code/server/session.js +390 -22
  236. package/package.json +2 -2
@@ -0,0 +1,1904 @@
1
+ // The hub layer every place's server runs (contract §4-§11): which place this
2
+ // session is, the avatar each player wears, arrival and exit, the declared HUD,
3
+ // actor visibility and labels, holding players still, and results. It wraps
4
+ // the deck's own hooks (`code/server/game.js`, or `places/<id>.js`) and hands
5
+ // each one `hub`, the place's context, which carries the session -- `step` can
6
+ // send without having captured anything first.
7
+ //
8
+ // It returns the multiplayer-3d hooks object `castle.real-time`'s session
9
+ // calls, so nothing below the kit changes for a hub game, plus
10
+ // `worldCharacters`: the session callbacks a place's NPCs answer in a world
11
+ // that carries shared characters (`npcs.js`).
12
+
13
+ import { readScene } from '@imports/castle.multiplayer-3d/code/server/sceneBodies.js';
14
+ import * as Actors from './actors.js';
15
+ import * as History from './history.js';
16
+ import * as Blocks from './blocks.js';
17
+ import * as Cabinets from './cabinets.js';
18
+ import * as Grab from './grab.js';
19
+ import * as Idle from './idle.js';
20
+ import * as Manifest from './manifest.js';
21
+ import { setLabel, wireLabel } from './labels.js';
22
+ import { makeNpcs } from './npcs.js';
23
+ import * as Party from './party.js';
24
+ import * as Place from './place.js';
25
+ import * as Say from './say.js';
26
+ import * as Wear from './wear.js';
27
+ import { doorPoint } from '../client/doorFrame.js';
28
+
29
+ // How many avatars the kit offers (`blueprints/avatar-<n>.scene`); contract §11.
30
+ export const AVATARS = 4;
31
+
32
+ // Players sent together by one `hub.go` arrive together: the first arrival of a
33
+ // group waits this long for the rest before the group is placed.
34
+ const GROUP_WAIT_MS = 1500;
35
+ // How far a held body may drift before it is clamped back.
36
+ const HOLD_SLACK = 0.05;
37
+
38
+ const DEG = Math.PI / 180;
39
+
40
+ const HUD_LIMITS = { title: 40, big: 12, text: 120 };
41
+
42
+ // Ghost forgets a gathering pad 30 s after its last update; refresh well inside it.
43
+ const PAD_REFRESH_MS = 20000;
44
+ // A door that stayed shut for a player is not tried again for them until they
45
+ // step off its pad (`hub.pad` says who stands there); a deck that never
46
+ // reports the pad gets this long instead.
47
+ const SHUT_HOLD_MS = 60000;
48
+ // How often a place re-reads its doors' boards.
49
+ const BOARD_EVERY_MS = 60000;
50
+ // The newest result of the game a player came back from counts as this trip's
51
+ // for this long: the longest visit (maxDurationSec 1800) and some slack.
52
+ const RESULT_FRESH_MS = 35 * 60 * 1000;
53
+ const MAX_BOARD_DOORS = 16;
54
+ // Cabinet boards in one read: each may be 44 KB, and a read answers in one
55
+ // frame of the host's channel (about 384 KB).
56
+ const CABINET_BOARDS_PER_READ = 6;
57
+ // Jump-to-door (the chrome's Doors list, in a town): how far in front of the
58
+ // door a player is put, how wide the spread across it, and how often one
59
+ // player may jump.
60
+ const JUMP_OUT = 7;
61
+ const JUMP_SPREAD = 2;
62
+ const JUMP_EVERY_MS = 1000;
63
+ // A player a client already sees counts as this much nearer when the nearest
64
+ // are picked, so two players at about the same distance do not swap in and
65
+ // out of its set every tick.
66
+ // Finding someone (the chrome's People list, in a town): how often one player
67
+ // may ask where others are, how many it may ask about at once, how near a
68
+ // door counts as "near" it, and how long a place's own words for a spot run.
69
+ const WHERE_EVERY_MS = 700;
70
+ const WHERE_MAX = 12;
71
+ const WHERE_NEAR_DOOR_M = 7;
72
+ const WHERE_TEXT_MAX = 40;
73
+ const KEEP_NEARER = 0.8;
74
+ // How often each client is sent other players' rows once the session filters
75
+ // by interest (HUB.md "Town sessions"), whatever the tick rate; a client's own
76
+ // corrections still go every tick.
77
+ const POSE_HZ = 10;
78
+ // How often a place with players in it logs its own process's load: CPU per
79
+ // tick and memory, read by the host's log stream (the only per-session
80
+ // numbers a production layer has).
81
+ const STATS_EVERY_MS = 30000;
82
+ const USER_ID = /^\d{1,20}$/;
83
+
84
+ // `layer(castleJson, deckHooks, placeHooks)`: the hooks object for one session
85
+ // process. `placeHooks` maps place id -> that place's own hooks module.
86
+ // A scene with no ground catches a fallen player this far down when its place
87
+ // names no `fallY`: above the world's floor (-30), below any pit worth having.
88
+ const NO_GROUND_FALL_Y = -20;
89
+
90
+ // `engine` is multiplayer-3d's world (`createBody`, `removeActor`), which
91
+ // builds and drops the bodies of actors a game spawns (`hub.spawn`).
92
+ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGround = () => null, devDecks = null, engine = null) {
93
+ const { errors, manifest } = Manifest.readManifest(castleJson, sceneExists);
94
+ if (!manifest) {
95
+ // A deck the check would refuse runs none of its game (contract §1): an
96
+ // empty room of its main scene, keeping nothing, its hooks never called
97
+ // -- so neither a client-named scene nor persistence comes back with them.
98
+ for (const error of errors) {
99
+ console.error(`[hub] ${error}`);
100
+ }
101
+ return { persist: false, sceneFor: () => undefined, worldCharacters: {} };
102
+ }
103
+ const h = newState(manifest);
104
+ h.devDecks = devDecks && typeof devDecks === 'object' ? devDecks : null;
105
+ h.engine = engine;
106
+ const tickRate = Number.isFinite(castleJson?.server?.tickRate) && castleJson.server.tickRate > 0 ? castleJson.server.tickRate : 20;
107
+ const poseEvery = Math.max(1, Math.round(tickRate / POSE_HZ));
108
+
109
+ return {
110
+ persist: false,
111
+ poseEvery,
112
+ poseIntervalMs: Math.round((poseEvery * 1000) / tickRate),
113
+
114
+ sceneFor(session) {
115
+ h.session = session;
116
+ const { id, source } = Place.resolvePlace(session, manifest);
117
+ h.placeId = id;
118
+ h.place = manifest.places[id];
119
+ h.hooks = placeHooks[id] ?? deckHooks;
120
+ h.noGround = sceneGround(h.place.scene)?.none === true;
121
+ h.fallY = h.place.fallY ?? (h.noGround ? NO_GROUND_FALL_Y : null);
122
+ console.log(`[hub] place ${id} (${source}): ${h.place.scene}`);
123
+ return h.place.scene;
124
+ },
125
+
126
+ ready(sim) {
127
+ h.sim = sim;
128
+ h.actors = readScene(sim.scenePath);
129
+ h.npcs.ready();
130
+ h.hooks.ready?.(h.ctx);
131
+ },
132
+
133
+ // Runs before the world exists too: a hello that lands first is kept and
134
+ // read when the player gets a body.
135
+ message(session, player, data) {
136
+ h.session ??= session;
137
+ if (data?.k === 'hub-hello') {
138
+ hello(h, player, data);
139
+ return;
140
+ }
141
+ if (data?.k === 'hub-shut') {
142
+ doorShut(h, player, data);
143
+ return;
144
+ }
145
+ if (data?.k === 'hub-door-jump') {
146
+ doorJump(h, player, data);
147
+ return;
148
+ }
149
+ if (data?.k === 'hub-where') {
150
+ whereAsk(h, player, data);
151
+ return;
152
+ }
153
+ if (data?.k === 'hub-goto') {
154
+ goTo(h, player, data);
155
+ return;
156
+ }
157
+ if (data?.k === 'hub-say') {
158
+ Say.message({ h, blockedPairs, jumpDoors: doors }, player, data);
159
+ return;
160
+ }
161
+ if (data?.k === 'hub-party') {
162
+ Party.message(partyDeps(h), player, data);
163
+ return;
164
+ }
165
+ if (data?.k === 'hub-dev-classic') {
166
+ // The dev serve's stand-in for ghost's classic boards (`cabinets.js`).
167
+ if (h.sim && isDevSession(h)) {
168
+ (data.on === false ? Cabinets.fixtureOff : Cabinets.fixtureOn)(h, doors(h));
169
+ }
170
+ return;
171
+ }
172
+ if (data?.k === 'hub-grab') {
173
+ Grab.message(h, player?.playerId, data);
174
+ return;
175
+ }
176
+ if (data?.k === 'hub-emote') {
177
+ Idle.emoteMessage(h, player?.playerId, data);
178
+ return;
179
+ }
180
+ if (data?.k === 'hub-sit') {
181
+ Idle.sitMessage(h, placeAt, player?.playerId, data);
182
+ return;
183
+ }
184
+ if (data?.k === 'hub-stand') {
185
+ Idle.standMessage(h, player?.playerId);
186
+ return;
187
+ }
188
+ if (h.sim && !h.npcs.message(player, data)) {
189
+ h.hooks.message?.(h.ctx, player, data);
190
+ }
191
+ },
192
+
193
+ // `handovers` is the session's list of ownership changes for the next
194
+ // broadcast; the handovers `hub.reset` made go into it (flushHandovers).
195
+ place(sim, handovers) {
196
+ h.sim = sim;
197
+ logStats(h);
198
+ const dt = h.lastPlaceAt === null ? 0 : Math.min(0.25, (sim.timeMs - h.lastPlaceAt) / 1000);
199
+ h.lastPlaceAt = sim.timeMs;
200
+ reconcile(h);
201
+ readResults(h);
202
+ arrivals(h);
203
+ enforceHolds(h);
204
+ Idle.tick(h);
205
+ enforceDuration(h);
206
+ catchFalls(h);
207
+ Grab.tick(h);
208
+ Actors.dropLostSpawns(h, h.engine);
209
+ Actors.driveMoves(h);
210
+ h.npcs.place(dt);
211
+ Actors.flushHandovers(h, handovers);
212
+ },
213
+
214
+ step(sim, handovers) {
215
+ const dt = h.lastStepAt === null ? 0 : (sim.timeMs - h.lastStepAt) / 1000;
216
+ h.lastStepAt = sim.timeMs;
217
+ h.hooks.step?.(h.ctx, dt);
218
+ Actors.flushTints(h);
219
+ sendHudOverrides(h);
220
+ Actors.applyTunes(h, h.engine?.maxSpeed?.() ?? 12);
221
+ sendLabelOverrides(h);
222
+ sendAvatarOverrides(h);
223
+ Party.tick(partyDeps(h));
224
+ Wear.sendOverrides(h, blockedPairs(h));
225
+ // Cabinet cards (v1.7): nothing in a place with no classic door.
226
+ Cabinets.send(h, (playerId) => namesOf(h, blockedPairs(h)?.get(playerId) ?? []));
227
+ Actors.flushHandovers(h, handovers);
228
+ },
229
+
230
+ // Each client is sent the place's nearest `nearestPlayers` others, not
231
+ // everyone (HUB.md "Town sessions"). Pads, holds and `hub.go` read the
232
+ // simulation, which still has every player.
233
+ // A pair a block hides from each other is taken out of both sets
234
+ // (`blocks.js`) before the nearest are picked, so a hidden player never
235
+ // takes one of a client's `nearestPlayers` places.
236
+ interest(sim, known) {
237
+ const pairs = blockedPairs(h);
238
+ const hidden = pairs ? (viewer, other) => Boolean(pairs.get(viewer)?.has(other)) : null;
239
+ return Blocks.withoutHidden(nearestPlayers(sim, known, h.place.nearestPlayers, hidden), pairs);
240
+ },
241
+
242
+ shutdown: () => shutdown(h),
243
+
244
+ join() {
245
+ return {
246
+ // `fallY` as this session catches it, so a falling client holds just
247
+ // under it rather than past the world's floor, where no pose is read.
248
+ hubPlace: { ...Manifest.publicPlace(h.placeId, h.place), fallY: h.fallY },
249
+ hubAv: avatars(h, blockedPairs(h)),
250
+ ...wearingForJoin(h),
251
+ hud: hudForAll(h),
252
+ hidden: [...h.hidden],
253
+ held: [...h.held.keys()],
254
+ labels: labelsForAll(h),
255
+ tints: Actors.tintsOf(h),
256
+ marks: Actors.marksOf(h),
257
+ hubDoors: doorList(h),
258
+ spawned: Actors.spawnedOf(h),
259
+ spawnTemplates: Actors.templatesOf(h),
260
+ // v1.6, only in a place that turns idle play on.
261
+ ...Idle.fields(h),
262
+ };
263
+ },
264
+
265
+ delta() {
266
+ const out = {};
267
+ latch(h, 'hubAv', avatars(h, blockedPairs(h)), out);
268
+ latchWearing(h, out);
269
+ latch(h, 'hud', hudForAll(h), out);
270
+ latch(h, 'hidden', [...h.hidden], out);
271
+ latch(h, 'held', [...h.held.keys()], out);
272
+ latch(h, 'labels', labelsForAll(h), out);
273
+ latch(h, 'tints', Actors.tintsOf(h), out);
274
+ latch(h, 'marks', Actors.marksOf(h), out);
275
+ latch(h, 'hubDoors', doorList(h), out);
276
+ latch(h, 'spawnTemplates', Actors.templatesOf(h), out);
277
+ latch(h, 'spawned', Actors.spawnedOf(h), out);
278
+ for (const [field, value] of Object.entries(Idle.fields(h))) {
279
+ latch(h, field, value, out);
280
+ }
281
+ return Object.keys(out).length ? out : null;
282
+ },
283
+
284
+ // Shared-character requests (a layer of the place, or a world) reach the
285
+ // place's NPCs; before the simulation is built there are none to answer,
286
+ // so they are refused.
287
+ worldCharacters: {
288
+ async onWorldCharacterTurn(session, turn) {
289
+ h.session ??= session;
290
+ if (!h.sim) {
291
+ turn.reject('HUB_NPC_NOT_READY');
292
+ return;
293
+ }
294
+ await h.npcs.onTurn(turn);
295
+ },
296
+ async onWorldCharacterCommand(session, request) {
297
+ h.session ??= session;
298
+ await h.npcs.onCommand(request);
299
+ },
300
+ async onWorldCharacterRead(session, request) {
301
+ h.session ??= session;
302
+ if (!h.sim) {
303
+ request.reject('HUB_NPC_NOT_READY');
304
+ return;
305
+ }
306
+ await h.npcs.onRead(request);
307
+ },
308
+ },
309
+ };
310
+ }
311
+
312
+ // playerId -> the Set of other players that client sees: all of them when
313
+ // they fit, otherwise the `n` nearest, each one it already sees counted
314
+ // `KEEP_NEARER` times its distance. `hidden(viewerId, otherId)`, when given,
315
+ // is true for a player that viewer must never see (a block): such a player is
316
+ // left out before the pick, so it takes none of the `n` places, and out of
317
+ // the everyone-fits set too.
318
+ export function nearestPlayers(sim, known, n, hidden = null) {
319
+ const ids = [...sim.players.keys()];
320
+ const sees = new Map();
321
+ const shown = (id, other) => other !== id && !hidden?.(id, other);
322
+ if (ids.length - 1 <= n) {
323
+ for (const id of ids) {
324
+ sees.set(id, new Set(ids.filter((other) => shown(id, other))));
325
+ }
326
+ return sees;
327
+ }
328
+ const at = ids.map((id) => sim.players.get(id).at);
329
+ for (let i = 0; i < ids.length; i += 1) {
330
+ const sent = known.get(ids[i]);
331
+ const scored = [];
332
+ for (let j = 0; j < ids.length; j += 1) {
333
+ if (!shown(ids[i], ids[j])) {
334
+ continue;
335
+ }
336
+ const dx = at[j].x - at[i].x;
337
+ const dy = at[j].y - at[i].y;
338
+ const dz = at[j].z - at[i].z;
339
+ const d = dx * dx + dy * dy + dz * dz;
340
+ scored.push([sent?.has(ids[j]) ? d * KEEP_NEARER * KEEP_NEARER : d, ids[j]]);
341
+ }
342
+ scored.sort((a, b) => a[0] - b[0]);
343
+ sees.set(ids[i], new Set(scored.slice(0, n).map(([, id]) => id)));
344
+ }
345
+ return sees;
346
+ }
347
+
348
+ // `[hub] stats {...}` every STATS_EVERY_MS while anyone is here: players,
349
+ // ticks, CPU milliseconds per tick and as a share of one core, RSS and heap.
350
+ function logStats(h) {
351
+ if (typeof process === 'undefined' || typeof process.cpuUsage !== 'function') {
352
+ return;
353
+ }
354
+ const now = Date.now();
355
+ const s = h.stats;
356
+ if (s.at === null) {
357
+ Object.assign(s, { at: now, cpu: process.cpuUsage(), ticks: 0 });
358
+ return;
359
+ }
360
+ s.ticks += 1;
361
+ if (now - s.at < STATS_EVERY_MS) {
362
+ return;
363
+ }
364
+ const cpu = process.cpuUsage(s.cpu);
365
+ const cpuMs = (cpu.user + cpu.system) / 1000;
366
+ const players = h.sim?.players.size ?? 0;
367
+ if (players > 0) {
368
+ const mem = process.memoryUsage();
369
+ const round = (v) => Math.round(v * 100) / 100;
370
+ console.log(
371
+ `[hub] stats ${JSON.stringify({
372
+ players,
373
+ ticks: s.ticks,
374
+ cpuMsPerTick: round(cpuMs / Math.max(1, s.ticks)),
375
+ cpuPercent: round((cpuMs / (now - s.at)) * 100),
376
+ rssMb: Math.round(mem.rss / 1048576),
377
+ heapMb: Math.round(mem.heapUsed / 1048576),
378
+ })}`,
379
+ );
380
+ }
381
+ Object.assign(s, { at: now, cpu: process.cpuUsage(), ticks: 0 });
382
+ }
383
+
384
+ function newState(manifest) {
385
+ const h = {
386
+ manifest,
387
+ placeId: Manifest.MAIN_PLACE,
388
+ place: manifest.places[Manifest.MAIN_PLACE],
389
+ hooks: {},
390
+ session: null,
391
+ sim: null,
392
+ actors: [],
393
+ lastStepAt: null,
394
+ lastPlaceAt: null,
395
+ // the height below which a player has fallen, or null (`catchFalls`)
396
+ fallY: null,
397
+ // playerId -> when they last jumped to a door or to a player
398
+ jumpAt: new Map(),
399
+ // playerId -> when they last asked where others are (`hub-where`)
400
+ whereAt: new Map(),
401
+ // `logStats`: when the window began, the CPU reading then, ticks since
402
+ stats: { at: null, cpu: null, ticks: 0 },
403
+ // playerId -> { avatar, clientAvatar, from, fromDeckId, party, carry, read,
404
+ // hello, arrived, arrivedAt, helloAt, result, ended }
405
+ players: new Map(),
406
+ // door id -> the gathering pad sent to ghost: { padId, json, at }
407
+ pads: new Map(),
408
+ // playerId -> { door, at }: the door that last stayed shut for them
409
+ shut: new Map(),
410
+ // door id -> who the deck last said stands on its pad (`hub.pad`)
411
+ padDoors: new Map(),
412
+ // door id -> its board from ghost, and when the boards were last read
413
+ boards: new Map(),
414
+ // `${actorId}|${doorId}` -> the door's object `doors()` hands out
415
+ doorObjects: new Map(),
416
+ boardsAt: 0,
417
+ // `${op}:${code}` refusals already logged
418
+ refusals: new Set(),
419
+ hud: null,
420
+ // playerId -> spec, and what was last sent of each
421
+ hudMe: new Map(),
422
+ sentHudMe: new Map(),
423
+ hidden: new Set(),
424
+ // playerId -> { at, facing }
425
+ held: new Map(),
426
+ // actorId -> { text, style, until }
427
+ labels: new Map(),
428
+ // playerId -> Map(actorId -> label): words over an actor for some players
429
+ // only (an NPC's reply to its admitted audience), and what was last sent
430
+ labelsMe: new Map(),
431
+ sentLabelsMe: new Map(),
432
+ // playerId -> JSON of the avatars last sent to that player alone
433
+ // (`sendAvatarOverrides`), and who a block hides from whom this tick
434
+ sentAvMe: new Map(),
435
+ blocked: { key: null, pairs: null },
436
+ // field -> JSON last sent, so a delta goes out only on change
437
+ sent: new Map(),
438
+ // moved and recoloured scene actors (`actors.js`)
439
+ ...Actors.newActorState(),
440
+ // held and thrown objects (`grab.js`, v1.3)
441
+ ...Grab.newGrabState(),
442
+ // what players wear on their avatars (`wear.js`, v1.4)
443
+ ...Wear.newWearState(),
444
+ // emotes, seats and sounds (`idle.js`, v1.6)
445
+ ...Idle.newIdleState(),
446
+ // arcade cabinets' cards (`cabinets.js`, v1.7)
447
+ ...Cabinets.newCabinetState(),
448
+ // parties in a town (`party.js`, v1.10)
449
+ ...Party.newPartyState(),
450
+ // quick reactions and phrases (`say.js`, v1.11)
451
+ ...Say.newSayState(),
452
+ };
453
+ h.ctx = makeContext(h);
454
+ h.npcLabel = (actorId, text, options) => setLabel(h, isSceneActor(h, actorId) ? actorId : null, text, options, true);
455
+ h.blockedPairs = () => blockedPairs(h);
456
+ h.npcs = makeNpcs(h);
457
+ return h;
458
+ }
459
+
460
+ // The `hub` every deck hook is handed.
461
+ function makeContext(h) {
462
+ return {
463
+ get session() {
464
+ return h.session;
465
+ },
466
+ get sim() {
467
+ return h.sim;
468
+ },
469
+ get place() {
470
+ return { id: h.placeId, title: h.place.title, scene: h.place.scene, manifest: h.place };
471
+ },
472
+ get now() {
473
+ return h.sim?.timeMs ?? 0;
474
+ },
475
+ players() {
476
+ const out = [];
477
+ for (const [playerId, body] of h.sim?.players ?? []) {
478
+ out.push({
479
+ playerId,
480
+ username: usernameOf(h, playerId),
481
+ userId: userIdOf(h, playerId),
482
+ at: { ...body.at },
483
+ arrivedAt: h.players.get(playerId)?.arrivedAt ?? null,
484
+ });
485
+ }
486
+ return out;
487
+ },
488
+ actorsWith(name) {
489
+ return h.actors.filter((actor) => actor.components[name]).map((actor) => Actors.describe(actor, name));
490
+ },
491
+ username: (playerId) => usernameOf(h, playerId),
492
+ placeAt: (playerId, at, facingDeg) => placeAt(h, playerId, at, facingDeg === undefined ? undefined : facingDeg * DEG),
493
+ hold(playerId, at, facingDeg) {
494
+ const body = h.sim?.players.get(playerId);
495
+ if (!body) {
496
+ return;
497
+ }
498
+ const point = at ? { ...at } : { ...body.at };
499
+ const facing = facingDeg === undefined ? body.facing : facingDeg * DEG;
500
+ h.held.set(playerId, { at: point, facing });
501
+ placeAt(h, playerId, point, facing);
502
+ },
503
+ release(playerId) {
504
+ h.held.delete(playerId);
505
+ },
506
+ setHud(spec, playerId) {
507
+ const clean = cleanHud(spec);
508
+ if (playerId === undefined) {
509
+ h.hud = clean;
510
+ } else if (clean) {
511
+ h.hudMe.set(playerId, clean);
512
+ } else {
513
+ h.hudMe.delete(playerId);
514
+ }
515
+ },
516
+ hide(actorId) {
517
+ if (!isSceneActor(h, actorId) || h.hidden.has(actorId)) {
518
+ return;
519
+ }
520
+ h.hidden.add(actorId);
521
+ h.sim?.bodies.get(actorId)?.setEnabled(false);
522
+ },
523
+ show(actorId) {
524
+ if (!h.hidden.delete(actorId)) {
525
+ return;
526
+ }
527
+ h.sim?.bodies.get(actorId)?.setEnabled(true);
528
+ },
529
+ move: (actorId, to, options) => Actors.move(h, actorId, to, options),
530
+ tint: (actorId, color) => Actors.tint(h, actorId, color),
531
+ mark: (playerId, spec) => Actors.mark(h, playerId, spec),
532
+ results: (playerId) => History.results(h, playerId),
533
+ wear: (playerId, spec) => wear(h, playerId, spec),
534
+ tune: (playerId, spec) => Actors.tune(h, playerId, spec),
535
+ spawn: (fromActorId, at) => Actors.spawn(h, fromActorId, at, h.engine),
536
+ pose: (actorId) => Actors.pose(h, actorId),
537
+ reset: (actorId, at) => Actors.reset(h, actorId, at, h.engine),
538
+ despawn: (actorId) => Actors.despawn(h, actorId, h.engine),
539
+ // `to` limits the words to those players; for them they replace the
540
+ // label everyone else sees until they expire or are cleared the same way.
541
+ label: (actorId, text, options) => setLabel(h, isSceneActor(h, actorId) ? actorId : null, text, options, false),
542
+ npc: (actorId) => h.npcs.handle(actorId),
543
+ npcs: () => h.npcs.list(),
544
+ result: (playerId, value) => report(h, playerId, value),
545
+ drop: (playerId) => Grab.drop(h, playerId),
546
+ emote: (playerId, id) => Idle.emote(h, playerId, id),
547
+ seat: (playerId) => Idle.seat(h, playerId),
548
+ sound: (actorId, file, options) => Idle.sound(h, actorId, file, options),
549
+ holding: (playerId) => Grab.holding(h, playerId),
550
+ end(playerIds) {
551
+ const ids = playerIds ?? [...(h.sim?.players.keys() ?? [])];
552
+ for (const playerId of ids) {
553
+ end(h, playerId, 'end');
554
+ }
555
+ },
556
+ go: (door, playerIds, options) => go(h, door, playerIds, options),
557
+ pad: (door, playerIds) => gather(h, door, playerIds),
558
+ coming: (door) => Party.coming(h, door),
559
+ board: (door) => h.boards.get(door) ?? null,
560
+ doors: () => doors(h),
561
+ send: (playerId, data) => h.session?.send(playerId, data),
562
+ broadcast: (data) => h.session?.broadcast(data),
563
+ };
564
+ }
565
+
566
+ // The host's hub ops (`session.hub`): present only in a session ghost pinned
567
+ // to a hub place, never on the dev serve, which keeps its named keys.
568
+ function platformHub(h) {
569
+ return h.session?.hub ?? null;
570
+ }
571
+
572
+ // A client's hello: the avatar it wears, the door it came through, how many
573
+ // came with it, and what it carries back from a game (a town reads that). Where
574
+ // the host has hub ops, the door is ghost's arrival and the result and avatar
575
+ // are read from ghost (`readResults`); the client's word is not used for them.
576
+ function hello(h, player, data) {
577
+ const clientAvatar = Number.isInteger(data.avatar) && data.avatar >= 0 && data.avatar < AVATARS ? data.avatar : 0;
578
+ const party = Number.isInteger(data.party) && data.party >= 1 && data.party <= 24 ? data.party : 1;
579
+ const known = h.players.get(player.playerId);
580
+ const hub = platformHub(h);
581
+ const arrival = hub ? hub.arrival(player.playerId) : null;
582
+ const from = hub ? arrival?.doorId ?? null : typeof data.from === 'string' && data.from.length <= 32 ? data.from : null;
583
+ // A later hello with the same choice keeps the platform avatar a read found;
584
+ // a new choice wins, and outdates any read in flight (`avatarRev`).
585
+ const same = known?.hello && known.clientAvatar === clientAvatar;
586
+ // A hello that is not an avatar change is a client that joined afresh: it
587
+ // holds none of the cabinet cards it was sent (v1.7).
588
+ if (data.again !== true) {
589
+ Cabinets.forget(h, player.playerId);
590
+ }
591
+ h.players.set(player.playerId, {
592
+ // Who this is, kept for `leave`: by then the session has forgotten them.
593
+ userId: userIdOf(h, player.playerId) ?? known?.userId ?? null,
594
+ username: usernameOf(h, player.playerId),
595
+ avatar: same ? known.avatar : clientAvatar,
596
+ clientAvatar,
597
+ avatarRev: same ? known.avatarRev : (known?.avatarRev ?? 0) + 1,
598
+ from,
599
+ fromDeckId: arrival?.fromDeckId ?? null,
600
+ // A jump to a friend says whom (the client's word: it decides only where
601
+ // the player appears, beside someone already in this session).
602
+ near: typeof data.near === 'string' && USER_ID.test(data.near) ? data.near : (known?.near ?? null),
603
+ party,
604
+ carry: hub ? known?.carry ?? null : cleanCarry(data.carry),
605
+ read: known?.read ?? (hub ? 'want' : 'done'),
606
+ hello: true,
607
+ // A second hello (the avatar changed) keeps the player's place in an
608
+ // arrival group.
609
+ helloAt: known?.hello ? known.helloAt : Date.now(),
610
+ arrived: known?.arrived ?? false,
611
+ arrivedAt: known?.arrivedAt ?? null,
612
+ result: known?.result ?? null,
613
+ // ghost's results of this player for `hub.results`, kept across hellos
614
+ history: known?.history ?? null,
615
+ historyFrom: known?.historyFrom ?? null,
616
+ ended: known?.ended ?? false,
617
+ });
618
+ }
619
+
620
+ // What a returning client says it brings back: the result its game sent it.
621
+ // It is the client's word, display-only; read only where the host has no hub
622
+ // ops (the dev serve). Elsewhere a town reads the result from ghost (§7).
623
+ function cleanCarry(carry) {
624
+ const r = carry?.result;
625
+ if (!r || typeof r !== 'object' || typeof r.title !== 'string' || !outcomeOrNone(r.outcome)) {
626
+ return null;
627
+ }
628
+ return {
629
+ result: {
630
+ title: r.title.slice(0, 40),
631
+ outcome: r.outcome ?? null,
632
+ score: typeof r.score === 'number' && Number.isFinite(r.score) ? r.score : null,
633
+ unit: ['ms', 's', 'points'].includes(r.unit) ? r.unit : null,
634
+ verified: false,
635
+ },
636
+ };
637
+ }
638
+
639
+ // An outcome, or none: a result may carry only a score (contract §7, v1.1).
640
+ function outcomeOrNone(outcome) {
641
+ return outcome === undefined || outcome === null || Manifest.OUTCOMES.includes(outcome);
642
+ }
643
+
644
+ // Forget players the session no longer has, telling the deck first: its
645
+ // `leave` hook runs while the player is still known, so it may report their
646
+ // result for the visit (the host takes one for a player who has just left)
647
+ // and save their progress under the user id it is handed (v1.2).
648
+ function reconcile(h) {
649
+ for (const playerId of [...h.players.keys()]) {
650
+ const inSession = h.session?.players.some((p) => p.playerId === playerId);
651
+ if (!h.sim.players.has(playerId) && !inSession) {
652
+ forget(h, playerId);
653
+ }
654
+ }
655
+ }
656
+
657
+ function forget(h, playerId) {
658
+ const entry = h.players.get(playerId);
659
+ if (entry?.arrived) {
660
+ // A place's hook that throws still lets the player go, once.
661
+ try {
662
+ h.hooks.leave?.(h.ctx, playerId, { userId: entry.userId ?? null, username: entry.username ?? 'player' });
663
+ } catch (err) {
664
+ console.warn(`[hub] leave hook failed: ${err?.message ?? err}`);
665
+ }
666
+ }
667
+ Party.forget(h, playerId);
668
+ Say.forget(h, playerId);
669
+ h.players.delete(playerId);
670
+ h.held.delete(playerId);
671
+ h.hudMe.delete(playerId);
672
+ h.sentHudMe.delete(playerId);
673
+ h.tunes.delete(playerId);
674
+ h.sentTunes.delete(playerId);
675
+ h.labelsMe.delete(playerId);
676
+ h.sentLabelsMe.delete(playerId);
677
+ h.sentAvMe.delete(playerId);
678
+ h.marks.delete(playerId);
679
+ Wear.forget(h, playerId);
680
+ h.shut.delete(playerId);
681
+ h.jumpAt.delete(playerId);
682
+ h.whereAt.delete(playerId);
683
+ Grab.forget(h, playerId);
684
+ Idle.forget(h, playerId);
685
+ Cabinets.forget(h, playerId);
686
+ h.npcs.leave(playerId);
687
+ }
688
+
689
+ // The session is stopping (its last player left, or Castle is replacing it):
690
+ // everyone still here leaves now, as `leave` would have told the deck on the
691
+ // next tick that never comes, and the deck's `shutdown` hook gets a moment
692
+ // to finish what it is writing (v1.2): inside the host's own shutdown grace,
693
+ // after which it stops taking storage writes.
694
+ const SHUTDOWN_DRAIN_MS = 1500;
695
+
696
+ async function shutdown(h) {
697
+ if (!h.sim) {
698
+ return;
699
+ }
700
+ for (const playerId of [...h.players.keys()]) {
701
+ forget(h, playerId);
702
+ }
703
+ let timer = null;
704
+ await Promise.race([
705
+ Promise.resolve()
706
+ .then(() => h.hooks.shutdown?.(h.ctx))
707
+ .catch((err) => console.warn(`[hub] shutdown hook failed: ${err?.message ?? err}`)),
708
+ new Promise((resolve) => {
709
+ timer = setTimeout(resolve, SHUTDOWN_DRAIN_MS);
710
+ }),
711
+ ]);
712
+ clearTimeout(timer);
713
+ }
714
+
715
+ // Players with a body who said hello and have not arrived, placed as groups
716
+ // at the arrival (contract §5). A group is everyone who said hello inside one
717
+ // window; it is placed when it has as many as its members said were coming,
718
+ // or when the window closes.
719
+ function arrivals(h) {
720
+ const waiting = [];
721
+ for (const [playerId, entry] of h.players) {
722
+ if (entry.hello && !entry.arrived && h.sim.players.has(playerId)) {
723
+ waiting.push([playerId, entry]);
724
+ }
725
+ }
726
+ if (!waiting.length) {
727
+ return;
728
+ }
729
+ const first = Math.min(...waiting.map(([, e]) => e.helloAt));
730
+ const expected = Math.max(...waiting.map(([, e]) => e.party));
731
+ // A group also waits, inside the same window, for ghost's read of what its
732
+ // players bring back.
733
+ const reading = waiting.some(([, e]) => e.read !== 'done');
734
+ if ((waiting.length < expected || reading) && Date.now() - first < GROUP_WAIT_MS) {
735
+ // Whoever is in waits where they are, held, until the group is placed.
736
+ for (const [playerId] of waiting) {
737
+ if (!h.held.has(playerId)) {
738
+ const body = h.sim.players.get(playerId);
739
+ h.held.set(playerId, { at: { ...body.at }, facing: body.facing, waiting: true });
740
+ }
741
+ }
742
+ return;
743
+ }
744
+ const group = waiting.map(([playerId, entry]) => {
745
+ entry.arrived = true;
746
+ entry.arrivedAt = h.sim.timeMs;
747
+ if (h.held.get(playerId)?.waiting) {
748
+ h.held.delete(playerId);
749
+ }
750
+ return {
751
+ playerId,
752
+ username: usernameOf(h, playerId),
753
+ userId: entry.userId,
754
+ from: entry.from,
755
+ fromDeckId: entry.fromDeckId,
756
+ near: entry.near ?? null,
757
+ carry: entry.carry,
758
+ };
759
+ });
760
+ placeGroup(h, group.map((g) => g.playerId));
761
+ placeNearFriends(h, group);
762
+ h.hooks.arrive?.(h.ctx, group);
763
+ for (const { playerId } of group) {
764
+ const body = h.sim.players.get(playerId);
765
+ if (body) {
766
+ h.session?.send(playerId, { k: 'hub-arrived', facing: body.facing });
767
+ }
768
+ }
769
+ }
770
+
771
+ // A row at the arrival actor, facing the way the manifest says.
772
+ function placeGroup(h, playerIds) {
773
+ const arrival = h.place.arrival;
774
+ const actor = arrival.actor
775
+ ? h.actors.find((a) => a.id === arrival.actor)
776
+ : h.actors.find((a) => a.components.Player);
777
+ const t = actor?.components.Transform ?? h.sim.spawn ?? { x: 0, y: 1, z: 0 };
778
+ let facing;
779
+ if (typeof arrival.face === 'number') {
780
+ facing = arrival.face * DEG;
781
+ } else if (arrival.face === 'center') {
782
+ facing = Math.atan2(-t.x, -t.z);
783
+ } else {
784
+ facing = (t.rotationY ?? 0) * DEG;
785
+ }
786
+ // Facing f looks along (sin f, cos f); the row runs across it.
787
+ const across = { x: Math.cos(facing), z: -Math.sin(facing) };
788
+ const n = playerIds.length;
789
+ playerIds.forEach((playerId, i) => {
790
+ const offset = (i - (n - 1) / 2) * arrival.spread;
791
+ placeAt(h, playerId, { x: t.x + across.x * offset, y: Math.max(t.y ?? 1, 1.2), z: t.z + across.z * offset }, facing);
792
+ });
793
+ }
794
+
795
+ // A player who jumped to a friend stands beside them, facing them, when the
796
+ // friend is in this session, a block hides neither from the other, and a spot
797
+ // beside them is clear (no solid actor there; on a scene with no ground, a
798
+ // solid underfoot); otherwise where the group was placed. Several jumping to
799
+ // one friend take the spots in turn.
800
+ const NEAR_STEP_M = 1.6;
801
+ // A standing player, for the clearance test: radius and half height.
802
+ const BODY_RADIUS_M = 0.45;
803
+ const BODY_HALF_M = 0.9;
804
+
805
+ function placeNearFriends(h, group) {
806
+ const used = new Map();
807
+ for (const { playerId, near } of group) {
808
+ if (!near) {
809
+ continue;
810
+ }
811
+ const friendId = [...h.players.entries()].find(
812
+ ([id, entry]) => id !== playerId && entry.userId === near && entry.arrived && h.sim.players.has(id),
813
+ )?.[0];
814
+ if (friendId) {
815
+ placeBeside(h, playerId, friendId, used);
816
+ }
817
+ }
818
+ }
819
+
820
+ // Put a player beside another, facing them: true when a clear spot was found.
821
+ // `used` (other player id -> spots taken) lets several arriving at once take
822
+ // the spots in turn. Never across a block.
823
+ function placeBeside(h, playerId, otherId, used = new Map()) {
824
+ const other = h.sim.players.get(otherId);
825
+ if (!other?.at || blockedPairs(h)?.get(playerId)?.has(otherId)) {
826
+ return false;
827
+ }
828
+ const f = other.facing ?? 0;
829
+ // Facing f looks along (sin f, cos f): right, left, behind, ahead, then
830
+ // the same a step further out.
831
+ const dirs = [
832
+ [Math.cos(f), -Math.sin(f)],
833
+ [-Math.cos(f), Math.sin(f)],
834
+ [-Math.sin(f), -Math.cos(f)],
835
+ [Math.sin(f), Math.cos(f)],
836
+ ];
837
+ const taken = used.get(otherId) ?? [];
838
+ for (const step of [1, 1.5]) {
839
+ const spot = dirs
840
+ .map(([dx, dz]) => ({ x: other.at.x + dx * NEAR_STEP_M * step, y: other.at.y, z: other.at.z + dz * NEAR_STEP_M * step }))
841
+ .find((at) => !taken.some((t) => Math.hypot(t.x - at.x, t.z - at.z) < 2 * BODY_RADIUS_M) && spotClear(h, at));
842
+ if (spot) {
843
+ taken.push(spot);
844
+ used.set(otherId, taken);
845
+ placeAt(h, playerId, spot, Math.atan2(other.at.x - spot.x, other.at.z - spot.z));
846
+ return true;
847
+ }
848
+ }
849
+ return false;
850
+ }
851
+
852
+ // Whether a standing body fits at `at`: no solid scene actor overlaps it, and
853
+ // on a scene with no ground (`fallY`) a solid's top is under its feet.
854
+ function spotClear(h, at) {
855
+ let supported = h.noGround !== true;
856
+ for (const actor of h.actors) {
857
+ const c = actor.components;
858
+ const t = c.Transform;
859
+ const shape = c.Shape;
860
+ // Solid as physics reads it: a Solid component or a solid Shape.
861
+ if (!(c.Solid || shape?.solid === true) || !t || !shape) {
862
+ continue;
863
+ }
864
+ const half = shape.kind === 'sphere' ? (shape.radius ?? 0.5) : (shape.height ?? 1) / 2;
865
+ const top = (t.y ?? 0) + half;
866
+ const bottom = (t.y ?? 0) - half;
867
+ const inside = footprintHas(shape, t, at, BODY_RADIUS_M);
868
+ if (inside && top > at.y - BODY_HALF_M + 0.05 && bottom < at.y + BODY_HALF_M) {
869
+ return false;
870
+ }
871
+ if (!supported && footprintHas(shape, t, at, 0) && Math.abs(top - (at.y - BODY_HALF_M)) < 0.6) {
872
+ supported = true;
873
+ }
874
+ }
875
+ return supported;
876
+ }
877
+
878
+ // Whether a point lies within a shape's footprint, grown by `pad`.
879
+ function footprintHas(shape, t, at, pad) {
880
+ const dx = at.x - t.x;
881
+ const dz = at.z - t.z;
882
+ if (shape.kind === 'box') {
883
+ const r = ((t.rotationY ?? 0) * Math.PI) / 180;
884
+ const lx = dx * Math.cos(r) - dz * Math.sin(r);
885
+ const lz = dx * Math.sin(r) + dz * Math.cos(r);
886
+ return Math.abs(lx) <= (shape.width ?? 1) / 2 + pad && Math.abs(lz) <= (shape.depth ?? 1) / 2 + pad;
887
+ }
888
+ return Math.hypot(dx, dz) <= (shape.radius ?? 0.5) + pad;
889
+ }
890
+
891
+ // Move a body. One placed before the joiner's WORLD snapshot is where that
892
+ // snapshot starts them; a later one reaches the client as a clamp.
893
+ function placeAt(h, playerId, at, facing) {
894
+ const body = h.sim?.players.get(playerId);
895
+ if (!body || !at || ![at.x, at.y, at.z].every(Number.isFinite)) {
896
+ return;
897
+ }
898
+ body.at = { x: at.x, y: at.y, z: at.z };
899
+ if (facing !== undefined && Number.isFinite(facing)) {
900
+ body.facing = facing;
901
+ }
902
+ body.clamped = true;
903
+ body.body.setTranslation(body.at, true);
904
+ }
905
+
906
+ // A held body that drifted is put back, every tick it drifts (contract §8).
907
+ function enforceHolds(h) {
908
+ for (const [playerId, hold] of h.held) {
909
+ const body = h.sim.players.get(playerId);
910
+ if (!body) {
911
+ continue;
912
+ }
913
+ const drifted =
914
+ Math.hypot(body.at.x - hold.at.x, body.at.z - hold.at.z) > HOLD_SLACK || Math.abs(body.at.y - hold.at.y) > 0.5;
915
+ if (drifted) {
916
+ placeAt(h, playerId, hold.at, hold.facing);
917
+ } else if (body.facing !== hold.facing) {
918
+ // A move report carries facing even when the body stayed put.
919
+ body.facing = hold.facing;
920
+ }
921
+ }
922
+ }
923
+
924
+ // A player who fell below the place's `fallY` (contract §5, v1.1): the game's
925
+ // `fall` hook may put them somewhere; if it leaves them down there, the kit
926
+ // puts them back at the arrival.
927
+ function catchFalls(h) {
928
+ if (h.fallY === null) {
929
+ return;
930
+ }
931
+ for (const [playerId, entry] of h.players) {
932
+ const body = h.sim.players.get(playerId);
933
+ if (!body || !entry.arrived || entry.ended || h.held.has(playerId) || body.at.y >= h.fallY) {
934
+ continue;
935
+ }
936
+ h.hooks.fall?.(h.ctx, playerId);
937
+ if (h.sim.players.get(playerId)?.at.y < h.fallY && !h.held.has(playerId)) {
938
+ placeGroup(h, [playerId]);
939
+ }
940
+ }
941
+ }
942
+
943
+ // Nobody stays past the place's maximum visit (contract §5).
944
+ function enforceDuration(h) {
945
+ if (h.place.maxDurationSec === null) {
946
+ return;
947
+ }
948
+ const limit = h.place.maxDurationSec * 1000;
949
+ for (const [playerId, entry] of h.players) {
950
+ if (entry.arrived && !entry.ended && h.sim.timeMs - entry.arrivedAt >= limit) {
951
+ console.log(`[hub] ${usernameOf(h, playerId)} reached maxDurationSec`);
952
+ end(h, playerId, 'time');
953
+ }
954
+ }
955
+ }
956
+
957
+ // The player's result for this visit, at most once (contract §7).
958
+ function report(h, playerId, value) {
959
+ const entry = h.players.get(playerId);
960
+ if (!entry) {
961
+ console.warn(`[hub] result for ${playerId}, who is not here`);
962
+ return false;
963
+ }
964
+ if (entry.result) {
965
+ console.warn(`[hub] a second result for ${usernameOf(h, playerId)} was refused`);
966
+ return false;
967
+ }
968
+ const { error, result } = Manifest.checkResult(h.place, value);
969
+ if (error) {
970
+ console.warn(`[hub] result refused: ${error}`);
971
+ return false;
972
+ }
973
+ entry.result = result;
974
+ const shown = {
975
+ title: h.place.title,
976
+ ...result,
977
+ unit: h.place.result.score?.unit ?? null,
978
+ better: h.place.result.score?.better ?? null,
979
+ };
980
+ // Where the host has hub ops the result is kept: checked again against the
981
+ // published shape and recorded by ghost for a signed-in player.
982
+ const hub = platformHub(h);
983
+ if (hub) {
984
+ hub
985
+ .reportResult(playerId, result)
986
+ .then((receipt) => {
987
+ if (!receipt?.recorded) {
988
+ console.log(`[hub] result for ${usernameOf(h, playerId)} not recorded: ${receipt?.reason ?? 'unknown'}`);
989
+ }
990
+ })
991
+ .catch((err) => refused(h, 'result', err));
992
+ }
993
+ h.session?.send(playerId, { k: 'hub-result', result: shown });
994
+ return true;
995
+ }
996
+
997
+ function end(h, playerId, why) {
998
+ const entry = h.players.get(playerId);
999
+ if (entry) {
1000
+ entry.ended = true;
1001
+ }
1002
+ h.held.delete(playerId);
1003
+ h.session?.send(playerId, { k: 'hub-end', why });
1004
+ }
1005
+
1006
+ // This place's doors (contract §4): in dev, the `HubDoor` scene actors whose
1007
+ // `to` is a place the deck declares, with what the destination's manifest says
1008
+ // about who may go through. The door table replaces the scene actors.
1009
+ // The doors a player in this place may jump to: a town's (a place with no
1010
+ // `result`) that are not hidden, as `[{ id, title }]`; a game has none.
1011
+ // Recomputed each time, so a door the place hides, or one whose destination
1012
+ // changes, leaves or changes the list (`latch` sends only a change).
1013
+ function jumpDoors(h) {
1014
+ if (h.place.result) {
1015
+ return [];
1016
+ }
1017
+ // A cabinet is not a door to walk up to from across the square (v1.7).
1018
+ return doors(h).filter((door) => !h.hidden.has(door.actor) && !Cabinets.isCabinetDoor(door.props) && !door.classic);
1019
+ }
1020
+
1021
+ // The Doors list's rows. An event gate leads to a game another door already
1022
+ // leads to, so it is listed only while its event is open, and as the event
1023
+ // (two rows reading "King of the Hill" was one too many).
1024
+ function doorList(h) {
1025
+ const out = [];
1026
+ for (const door of jumpDoors(h)) {
1027
+ const event = h.boards.get(door.id)?.event;
1028
+ if (event && !event.open) {
1029
+ continue;
1030
+ }
1031
+ const row = { id: door.id, title: event ? `Event · ${door.title}`.slice(0, 48) : door.title };
1032
+ // What a player picking a door wants to know: today's featured door (it
1033
+ // is listed first), one that takes a single player, how many it needs.
1034
+ if (h.boards.get(door.id)?.featured === true) {
1035
+ row.featured = true;
1036
+ }
1037
+ if (door.maxPlayers === 1) {
1038
+ row.solo = true;
1039
+ } else if (door.minPlayers > 1) {
1040
+ row.need = door.minPlayers;
1041
+ }
1042
+ out.push(row);
1043
+ }
1044
+ // A stable sort: the featured doors first, each group in the place's order.
1045
+ return out.sort((a, b) => Number(b.featured === true) - Number(a.featured === true));
1046
+ }
1047
+
1048
+ // Put a player on the pad of a door of this town (in front of a door with no
1049
+ // pad), facing the door, from the chrome's Doors list. A held player, a game, or a door the place does not have is
1050
+ // ignored, and one player jumps at most once a second.
1051
+ function doorJump(h, player, data) {
1052
+ const door = h.sim ? jumpDoors(h).find((d) => d.id === data?.door) : null;
1053
+ const now = Date.now();
1054
+ // A sitter who jumps gets up first (v1.6); a player the place holds does not jump.
1055
+ if (door && now - (h.jumpAt.get(player.playerId) ?? 0) >= JUMP_EVERY_MS) {
1056
+ Idle.stand(h, player.playerId);
1057
+ }
1058
+ if (!door || h.held.has(player.playerId) || now - (h.jumpAt.get(player.playerId) ?? 0) < JUMP_EVERY_MS) {
1059
+ return;
1060
+ }
1061
+ h.jumpAt.set(player.playerId, now);
1062
+ // Onto the door's pad where it has one (v1.10), a little off its middle so
1063
+ // two who jump there do not land in one spot; else in front of the door.
1064
+ const at = Party.padPoint(h, door, Math.floor(Math.random() * 6)) ?? frontOf(door);
1065
+ const facing = ((door.t.rotationY ?? 0) + 180) * DEG;
1066
+ placeAt(h, player.playerId, { x: at.x, y: 1.2, z: at.z }, facing);
1067
+ h.session?.send(player.playerId, { k: 'hub-jumped', facing });
1068
+ }
1069
+
1070
+ // A spot in front of a door, for a jump to a door with no pad.
1071
+ function frontOf(door) {
1072
+ const t = door.t;
1073
+ return doorPoint({ x: t.x, z: t.z, rotationY: t.rotationY ?? 0 }, (Math.random() - 0.5) * JUMP_SPREAD, JUMP_OUT);
1074
+ }
1075
+
1076
+ // What `party.js` uses of this layer.
1077
+ function partyDeps(h) {
1078
+ return { h, blockedPairs, usernameOf, placeAt, stand: Idle.stand, jumpDoors, front: frontOf };
1079
+ }
1080
+
1081
+ // Where the players a client asks about are (the chrome's People list and its
1082
+ // pointer to a friend, in a town): each one's spot on the ground and the
1083
+ // place's words for it. Only players in this session a block does not hide
1084
+ // from the asker; a game answers nothing.
1085
+ function whereAsk(h, player, data) {
1086
+ const playerId = player?.playerId;
1087
+ const now = Date.now();
1088
+ if (!h.sim || h.place.result || !playerId || !Array.isArray(data?.ids) || now - (h.whereAt.get(playerId) ?? 0) < WHERE_EVERY_MS) {
1089
+ return;
1090
+ }
1091
+ h.whereAt.set(playerId, now);
1092
+ const hidden = blockedPairs(h)?.get(playerId);
1093
+ const at = {};
1094
+ for (const id of data.ids.slice(0, WHERE_MAX)) {
1095
+ const body = typeof id === 'string' && id !== playerId ? h.sim.players.get(id) : null;
1096
+ if (!body?.at || !h.players.get(id)?.arrived || hidden?.has(id)) {
1097
+ continue;
1098
+ }
1099
+ at[id] = { x: Math.round(body.at.x * 10) / 10, z: Math.round(body.at.z * 10) / 10, ...whereIs(h, body.at) };
1100
+ }
1101
+ h.session?.send(playerId, { k: 'hub-where', at });
1102
+ }
1103
+
1104
+ // The place's words for a spot, `{ where, door }`: on a door's pad (`door`
1105
+ // names it, `on` true), else beside a door (`door` again), else what the
1106
+ // place's `where` hook calls it, else nothing.
1107
+ function whereIs(h, at) {
1108
+ const list = jumpDoors(h);
1109
+ for (const actor of h.actors) {
1110
+ const pad = actor.components.HubPad;
1111
+ const t = actor.components.Transform;
1112
+ const door = pad && t ? list.find((d) => d.id === pad.door) : null;
1113
+ if (door && !h.hidden.has(actor.id) && Math.hypot(at.x - t.x, at.z - t.z) <= (pad.radius ?? actor.components.Shape?.radius ?? 2.3)) {
1114
+ return { where: `on the ${door.title} pad`, door: door.id, on: true };
1115
+ }
1116
+ }
1117
+ let best = null;
1118
+ for (const door of list) {
1119
+ const d = Math.hypot(at.x - door.t.x, at.z - door.t.z);
1120
+ if (d <= WHERE_NEAR_DOOR_M && (!best || d < best.d)) {
1121
+ best = { d, door };
1122
+ }
1123
+ }
1124
+ if (best) {
1125
+ return { where: `near ${best.door.title}`, door: best.door.id };
1126
+ }
1127
+ let words = null;
1128
+ try {
1129
+ words = h.hooks.where?.(h.ctx, { x: at.x, y: at.y, z: at.z });
1130
+ } catch (err) {
1131
+ console.warn(`[hub] where hook failed: ${err?.message ?? err}`);
1132
+ }
1133
+ return { where: typeof words === 'string' && words.trim() ? words.trim().slice(0, WHERE_TEXT_MAX) : null, door: null };
1134
+ }
1135
+
1136
+ // Put a player beside another player of this town, facing them, from the
1137
+ // chrome's People list (Join). The same limits as a jump to a door: a town
1138
+ // only, never a held player, once a second; and never across a block.
1139
+ function goTo(h, player, data) {
1140
+ const playerId = player?.playerId;
1141
+ const otherId = data?.player;
1142
+ const now = Date.now();
1143
+ if (
1144
+ !h.sim || h.place.result || !playerId || typeof otherId !== 'string' || otherId === playerId ||
1145
+ !h.players.get(playerId)?.arrived || !h.players.get(otherId)?.arrived || !h.sim.players.has(otherId) ||
1146
+ now - (h.jumpAt.get(playerId) ?? 0) < JUMP_EVERY_MS ||
1147
+ // Before anything of this player's changes: a blocked player is as absent
1148
+ // as one who is not here.
1149
+ blockedPairs(h)?.get(playerId)?.has(otherId)
1150
+ ) {
1151
+ return;
1152
+ }
1153
+ // A sitter who jumps gets up first (v1.6); a player the place holds does not jump.
1154
+ Idle.stand(h, playerId);
1155
+ if (h.held.has(playerId) || !placeBeside(h, playerId, otherId)) {
1156
+ return;
1157
+ }
1158
+ h.jumpAt.set(playerId, now);
1159
+ h.session?.send(playerId, { k: 'hub-jumped', facing: h.sim.players.get(playerId).facing, to: otherId });
1160
+ }
1161
+
1162
+ function doors(h) {
1163
+ const out = [];
1164
+ for (const actor of h.actors) {
1165
+ const props = actor.components.HubDoor;
1166
+ const deck = props ? otherDeck(props.to) : null;
1167
+ const dest = deck ? deckDoorPlace(h, props, deck) : props ? h.manifest.places[props.to] : null;
1168
+ if (!dest || typeof props.id !== 'string') {
1169
+ continue;
1170
+ }
1171
+ // One object per door for the place's life, refreshed in place: a deck that
1172
+ // kept the list from `ready()` sees ghost's board once it is read.
1173
+ const key = `${actor.id}|${props.id}`;
1174
+ const door = h.doorObjects.get(key) ?? {};
1175
+ h.doorObjects.set(key, door);
1176
+ Object.assign(door, {
1177
+ id: props.id,
1178
+ to: props.to,
1179
+ actor: actor.id,
1180
+ t: actor.components.Transform,
1181
+ props,
1182
+ title: dest.title,
1183
+ minPlayers: dest.minPlayers,
1184
+ maxPlayers: dest.maxPlayers,
1185
+ lateJoin: dest.lateJoin,
1186
+ // v1.7: the door leads to a classic deck (ghost's board says so).
1187
+ classic: Cabinets.isClassic(h, props.id),
1188
+ });
1189
+ out.push(door);
1190
+ }
1191
+ return out;
1192
+ }
1193
+
1194
+ // A door's `to` naming another deck rather than a place of this one:
1195
+ // `deck:<name>`, a deck the dev serve was told about (castle.json `devDecks`).
1196
+ // Its content arrives as a content pack (docs/content-pack.md); with the door
1197
+ // table, the row names the deck and ghost the release.
1198
+ const OTHER_DECK = /^deck:([A-Za-z0-9_-]{1,40})$/;
1199
+
1200
+ function otherDeck(to) {
1201
+ return typeof to === 'string' ? (OTHER_DECK.exec(to)?.[1] ?? null) : null;
1202
+ }
1203
+
1204
+ // What this place knows of another deck's main place before going: on the dev
1205
+ // serve, the destination's own manifest (its castle.json, handed to this
1206
+ // bundle by the serve), so the door repeats none of it. With the door table,
1207
+ // ghost's board for the door (`readResults`): the destination's title and the
1208
+ // door row's group, so production doors repeat none of it either. Failing
1209
+ // both (before the first read, or a field the row leaves unsaid), the door's
1210
+ // props.
1211
+ function deckDoorPlace(h, props, deck) {
1212
+ const json = h.devDecks && Object.hasOwn(h.devDecks, deck) ? h.devDecks[deck] : null;
1213
+ const main = json ? Manifest.readManifest(json, () => true).manifest?.places[Manifest.MAIN_PLACE] : null;
1214
+ if (main) {
1215
+ return { title: main.title, minPlayers: main.minPlayers, maxPlayers: main.maxPlayers, lateJoin: main.lateJoin, scene: null };
1216
+ }
1217
+ const board = typeof props.id === 'string' ? (h.boards.get(props.id) ?? null) : null;
1218
+ const int = (v, d) => (Number.isInteger(v) && v >= 1 && v <= 24 ? v : d);
1219
+ const maxPlayers = int(board?.maxPlayers, int(props.maxPlayers, 8));
1220
+ // A cabinet's board is titled with its classic deck, which may have no name.
1221
+ const named = board?.classic ? Cabinets.deckTitle(board.title) : board?.title;
1222
+ const title = typeof named === 'string' && named ? named : props.title;
1223
+ return {
1224
+ title: typeof title === 'string' && title ? title.slice(0, 40) : deck,
1225
+ minPlayers: Math.min(int(board?.minPlayers, int(props.minPlayers, 1)), maxPlayers),
1226
+ maxPlayers,
1227
+ lateJoin: typeof board?.lateJoin === 'boolean' ? board.lateJoin : props.lateJoin === true,
1228
+ scene: null,
1229
+ };
1230
+ }
1231
+
1232
+ // Send players through one of this place's doors (contract §4), into a new
1233
+ // instance or, with `instance`, one this place sent players to before (a late
1234
+ // join). In dev the destination is a named session whose key names the place;
1235
+ // the door table makes this a host command and the instance ghost's.
1236
+ function go(h, door, playerIds, { instance } = {}) {
1237
+ const going = (playerIds ?? []).filter((playerId) => !isShut(h, playerId, door));
1238
+ if (going.length < (playerIds ?? []).length) {
1239
+ if (!going.length) {
1240
+ return null;
1241
+ }
1242
+ playerIds = going;
1243
+ }
1244
+ const hub = platformHub(h);
1245
+ if (Cabinets.isClassic(h, door)) {
1246
+ return goClassic(h, hub, door, playerIds);
1247
+ }
1248
+ if (hub && isLayerDoor(h, door)) {
1249
+ return goLayer(h, door, playerIds);
1250
+ }
1251
+ if (hub) {
1252
+ return firePad(h, hub, door, playerIds);
1253
+ }
1254
+ // Only the dev serve can place a session at a place from its key. Anywhere
1255
+ // else the destination's server would build the main place while the
1256
+ // client loaded another, so a door stays shut until the host places
1257
+ // sessions through the door table.
1258
+ const sessionId = String(h.session?.sessionId ?? '');
1259
+ if (!isDevSession(h)) {
1260
+ console.warn(`[hub] door ${door} stays shut: doors need the door table outside castle-web serve`);
1261
+ return null;
1262
+ }
1263
+ const found = doors(h).find((d) => d.id === door);
1264
+ if (!found) {
1265
+ console.warn(`[hub] no door "${door}" to a place this deck has`);
1266
+ return null;
1267
+ }
1268
+ // Another deck's door goes to its main place, in a session running that
1269
+ // deck's server; the client mounts its content pack. A place of this deck
1270
+ // stays in this deck's namespace: on the serve, a deck reached through a
1271
+ // door runs under `deck:<name>/`, and a key without it would start the
1272
+ // town's server.
1273
+ const deck = otherDeck(found.to);
1274
+ const to = deck ? 'main' : found.to;
1275
+ const here = /^dev:(deck:[A-Za-z0-9_-]{1,40}\/)/.exec(sessionId)?.[1] ?? '';
1276
+ const prefix = deck ? `deck:${deck}/` : here;
1277
+ const key =
1278
+ typeof instance === 'string' && instance.startsWith(`${prefix}hub.${to}.`) ? instance : prefix + Place.devKey(to);
1279
+ for (const playerId of playerIds) {
1280
+ h.session?.send(playerId, {
1281
+ k: 'hub-go',
1282
+ door,
1283
+ key,
1284
+ place: to,
1285
+ deck,
1286
+ scene: deck ? null : h.manifest.places[to].scene,
1287
+ title: found.title,
1288
+ party: playerIds.length,
1289
+ });
1290
+ }
1291
+ console.log(`[hub] door ${door}: ${playerIds.length} to ${key}`);
1292
+ return key;
1293
+ }
1294
+
1295
+ // The dev serve's sessions: `dev`, or a named key under `dev:`.
1296
+ function isDevSession(h) {
1297
+ const sessionId = String(h.session?.sessionId ?? '');
1298
+ return sessionId === 'dev' || sessionId.startsWith('dev:');
1299
+ }
1300
+
1301
+ // A door the place marks `"kind": "layer"` in its `HubDoor` (v1.11) leads to a
1302
+ // place ghost puts on public layers, like a town, rather than in an instance
1303
+ // per pad: a village, a district, another town. Ghost holds no pad for it.
1304
+ const LAYER = 'layer';
1305
+
1306
+ function isLayerDoor(h, door) {
1307
+ return doors(h).find((d) => d.id === door)?.props?.kind === LAYER;
1308
+ }
1309
+
1310
+ // `hub.go` on a layer door (v1.11): no pad fires. Each signed-in player named
1311
+ // is told to go; their client asks the host (`Hub.go`), and ghost steers them
1312
+ // to a layer of the destination with their party and friends. Returns the
1313
+ // door id, or null when nobody went.
1314
+ function goLayer(h, door, playerIds) {
1315
+ const found = doors(h).find((d) => d.id === door);
1316
+ const going = [...membersOf(h, playerIds).values()];
1317
+ if (!going.length) {
1318
+ console.warn(`[hub] door ${door}: only signed-in players go through a door`);
1319
+ return null;
1320
+ }
1321
+ for (const playerId of going) {
1322
+ h.session?.send(playerId, {
1323
+ k: 'hub-go',
1324
+ door,
1325
+ key: null,
1326
+ place: null,
1327
+ scene: null,
1328
+ title: found.title,
1329
+ party: going.length,
1330
+ });
1331
+ }
1332
+ console.log(`[hub] door ${door}: ${going.length} to a layer`);
1333
+ return door;
1334
+ }
1335
+
1336
+ // `hub.go` on a door to a classic deck (a cabinet, v1.7): no pad fires and no
1337
+ // session is placed -- ghost would refuse a pad on such a door. Each player is
1338
+ // told to go, alone; their client asks the host, which plays the classic deck
1339
+ // itself, and waits under the cover until Back. Where the host runs the hub
1340
+ // only signed-in players go, as through any door. On the dev serve (the
1341
+ // fixture) the client has no host to ask and is told so (`dev`). Returns the
1342
+ // door id, or null when nobody went.
1343
+ function goClassic(h, hub, door, playerIds) {
1344
+ const found = doors(h).find((d) => d.id === door);
1345
+ if (!found) {
1346
+ console.warn(`[hub] no door "${door}" in this place`);
1347
+ return null;
1348
+ }
1349
+ const going = hub ? [...membersOf(h, playerIds).values()] : (playerIds ?? []);
1350
+ if (!going.length) {
1351
+ console.warn(`[hub] door ${door}: only signed-in players go through a door`);
1352
+ return null;
1353
+ }
1354
+ for (const playerId of going) {
1355
+ h.session?.send(playerId, {
1356
+ k: 'hub-go',
1357
+ door,
1358
+ classic: true,
1359
+ key: null,
1360
+ place: null,
1361
+ scene: null,
1362
+ title: found.title,
1363
+ party: 1,
1364
+ ...(hub ? {} : { dev: true }),
1365
+ });
1366
+ }
1367
+ console.log(`[hub] door ${door}: ${going.length} to a classic deck`);
1368
+ return door;
1369
+ }
1370
+
1371
+ // Signed-in players' user ids, which is all ghost holds a pad by:
1372
+ // userId -> playerId.
1373
+ function membersOf(h, playerIds) {
1374
+ const out = new Map();
1375
+ for (const playerId of playerIds ?? []) {
1376
+ const p = h.session?.players.find((q) => q.playerId === playerId);
1377
+ if (p && !p.isAnonymous && USER_ID.test(String(p.userId))) {
1378
+ out.set(String(p.userId), playerId);
1379
+ }
1380
+ }
1381
+ return out;
1382
+ }
1383
+
1384
+ function newPadId(door) {
1385
+ return `${door.slice(0, 40)}.${Math.random().toString(36).slice(2, 10)}`;
1386
+ }
1387
+
1388
+ // `hub.pad(door, playerIds)`, called as often as the deck likes (each step):
1389
+ // who stands on a pad door's pad, told to ghost when it changes and refreshed
1390
+ // before ghost forgets it. Nothing on the dev serve.
1391
+ function gather(h, door, playerIds) {
1392
+ if (typeof door !== 'string') {
1393
+ return;
1394
+ }
1395
+ const on = new Set(playerIds ?? []);
1396
+ h.padDoors.set(door, on);
1397
+ for (const [playerId, entry] of h.shut) {
1398
+ if (entry.door === door && !on.has(playerId)) {
1399
+ // Stepped off: the door may be tried again.
1400
+ unshut(h, playerId);
1401
+ }
1402
+ }
1403
+ const hub = platformHub(h);
1404
+ // Ghost holds no pad for a cabinet (v1.7): it is not a pad door.
1405
+ if (!hub || Cabinets.isClassic(h, door) || Cabinets.cabinetDoorIds(h).has(door) || isLayerDoor(h, door)) {
1406
+ return;
1407
+ }
1408
+ const users = membersOf(h, [...on].filter((playerId) => !isShut(h, playerId, door)));
1409
+ const members = [...users.keys()].sort();
1410
+ let pad = h.pads.get(door);
1411
+ if (pad?.firing) {
1412
+ // Until ghost answers the fire, this pad's group is ghost's to fix.
1413
+ return;
1414
+ }
1415
+ if (!pad) {
1416
+ if (!members.length) {
1417
+ return;
1418
+ }
1419
+ pad = { padId: newPadId(door), json: null, at: 0, firing: false, fireSent: false };
1420
+ h.pads.set(door, pad);
1421
+ }
1422
+ const json = JSON.stringify(members);
1423
+ const now = Date.now();
1424
+ if (json === pad.json && now - pad.at < PAD_REFRESH_MS) {
1425
+ return;
1426
+ }
1427
+ pad.json = json;
1428
+ pad.at = now;
1429
+ if (!members.length && !pad.fireSent) {
1430
+ // An empty pad is left for ghost to forget; the next gathering is new. One
1431
+ // whose fire went unanswered is kept: ghost may have fired it, and only
1432
+ // its own id can say so without firing a second pad.
1433
+ h.pads.delete(door);
1434
+ }
1435
+ hub
1436
+ .updatePad({ doorId: door, padId: pad.padId, memberUserIds: members })
1437
+ .then((answer) => {
1438
+ // Ghost fired this pad on a fire whose answer was lost.
1439
+ if (answer?.status === 'fired') {
1440
+ padFired(h, door, pad, users, answer.members);
1441
+ }
1442
+ })
1443
+ .catch((err) => refused(h, 'pad', err));
1444
+ }
1445
+
1446
+ // The client's word that a door this place sent it through stayed shut (its
1447
+ // trip failed and the player is still here): that player is left out of the
1448
+ // door's pad and of `hub.go` until they step off the pad, so a pad they stand
1449
+ // on does not fire the shut door again every countdown. The door's label says
1450
+ // so, to them alone.
1451
+ function doorShut(h, player, data) {
1452
+ const playerId = player?.playerId;
1453
+ const found = doors(h).find((d) => d.id === data?.door);
1454
+ if (!playerId || !found) {
1455
+ return;
1456
+ }
1457
+ unshut(h, playerId);
1458
+ if (h.padDoors.has(found.id) && !h.padDoors.get(found.id).has(playerId)) {
1459
+ // Already stepped off while the trip was failing.
1460
+ return;
1461
+ }
1462
+ h.shut.set(playerId, { door: found.id, at: Date.now(), actor: found.actor });
1463
+ // A sign: the player reads it from the pad, a pad's length from the door.
1464
+ setLabel(h, found.actor, 'Door shut — step off to retry', { to: [playerId], style: 'sign' }, false);
1465
+ }
1466
+
1467
+ function isShut(h, playerId, door) {
1468
+ const entry = h.shut.get(playerId);
1469
+ if (!entry || entry.door !== door) {
1470
+ return false;
1471
+ }
1472
+ if (h.padDoors.has(door) || Date.now() - entry.at < SHUT_HOLD_MS) {
1473
+ return true;
1474
+ }
1475
+ unshut(h, playerId);
1476
+ return false;
1477
+ }
1478
+
1479
+ function unshut(h, playerId) {
1480
+ const entry = h.shut.get(playerId);
1481
+ if (entry) {
1482
+ h.shut.delete(playerId);
1483
+ setLabel(h, entry.actor, null, { to: [playerId] }, false);
1484
+ }
1485
+ }
1486
+
1487
+ // `hub.go` where the host has hub ops: the pad door fires and ghost places the
1488
+ // group (a late join included, by the door's own rule); each member is told to
1489
+ // go through. Returns the pad's id.
1490
+ function firePad(h, hub, door, playerIds) {
1491
+ if (!doors(h).some((d) => d.id === door)) {
1492
+ console.warn(`[hub] no door "${door}" in this place`);
1493
+ return null;
1494
+ }
1495
+ const members = membersOf(h, playerIds);
1496
+ if (!members.size) {
1497
+ console.warn(`[hub] door ${door}: only signed-in players go through a door`);
1498
+ return null;
1499
+ }
1500
+ // The pad keeps its id until ghost answers the fire, so a retried go (or a
1501
+ // gathering update) after a lost answer names the same pad, which ghost
1502
+ // answers with the group it already fixed rather than firing a second one.
1503
+ const pad = h.pads.get(door) ?? { padId: newPadId(door), json: null, at: 0 };
1504
+ pad.firing = true;
1505
+ pad.fireSent = true;
1506
+ h.pads.set(door, pad);
1507
+ hub
1508
+ .updatePad({ doorId: door, padId: pad.padId, memberUserIds: [...members.keys()], fire: true })
1509
+ .then((answer) => {
1510
+ if (answer?.status === 'fired') {
1511
+ padFired(h, door, pad, members, answer.members);
1512
+ }
1513
+ })
1514
+ .catch((err) => refused(h, 'go', err))
1515
+ .finally(() => {
1516
+ pad.firing = false;
1517
+ });
1518
+ return pad.padId;
1519
+ }
1520
+
1521
+ // Ghost fixed a pad's group: each member here is told to go through, and the
1522
+ // next gathering on this door is a new pad. Once per pad.
1523
+ function padFired(h, door, pad, users, fired) {
1524
+ if (pad.done) {
1525
+ return;
1526
+ }
1527
+ pad.done = true;
1528
+ if (h.pads.get(door) === pad) {
1529
+ h.pads.delete(door);
1530
+ }
1531
+ const found = doors(h).find((d) => d.id === door);
1532
+ const group = Array.isArray(fired) ? fired : [];
1533
+ // The group is ghost's; anyone of it still here goes, on the pad now or not.
1534
+ const here = membersOf(h, h.session?.players.map((p) => p.playerId));
1535
+ for (const userId of group) {
1536
+ const playerId = users.get(userId) ?? here.get(userId);
1537
+ if (playerId) {
1538
+ h.session?.send(playerId, {
1539
+ k: 'hub-go',
1540
+ door,
1541
+ pad: pad.padId,
1542
+ key: null,
1543
+ place: found?.to ?? null,
1544
+ scene: null,
1545
+ title: found?.title ?? null,
1546
+ party: group.length,
1547
+ });
1548
+ }
1549
+ }
1550
+ console.log(`[hub] door ${door}: pad ${pad.padId} fired with ${group.length}`);
1551
+ }
1552
+
1553
+ // Ghost's word on who the players are: the result each brings back from the
1554
+ // game they came from (for the arrival, the innkeeper and the ribbon) and the
1555
+ // platform avatar (§11); and the boards of this place's doors.
1556
+ function readResults(h) {
1557
+ const hub = platformHub(h);
1558
+ if (!hub) {
1559
+ return;
1560
+ }
1561
+ History.refresh(h, hub, membersOf, refused);
1562
+ const users = new Map();
1563
+ for (const [playerId, entry] of h.players) {
1564
+ if (entry.read !== 'want') {
1565
+ continue;
1566
+ }
1567
+ const userId = [...membersOf(h, [playerId]).keys()][0];
1568
+ if (!userId) {
1569
+ entry.read = 'done';
1570
+ continue;
1571
+ }
1572
+ entry.read = 'reading';
1573
+ users.set(userId, { playerId, avatarRev: entry.avatarRev, wearRev: h.wearRev.get(playerId) ?? 0, startedAt: Date.now() });
1574
+ }
1575
+ if (users.size) {
1576
+ hub
1577
+ .readResults({ userIds: [...users.keys()] })
1578
+ .then((read) => {
1579
+ for (const [userId, asked] of users) {
1580
+ applyRead(h, asked, read.players?.[userId]);
1581
+ }
1582
+ })
1583
+ .catch((err) => refused(h, 'results', err))
1584
+ .finally(() => {
1585
+ for (const { playerId } of users.values()) {
1586
+ const entry = h.players.get(playerId);
1587
+ if (entry?.read === 'reading') {
1588
+ entry.read = 'done';
1589
+ }
1590
+ }
1591
+ });
1592
+ }
1593
+ const now = Date.now();
1594
+ if (now - h.boardsAt < BOARD_EVERY_MS) {
1595
+ return;
1596
+ }
1597
+ // A cabinet's board carries its pictures (v1.7), and a read answers in one
1598
+ // frame of the host's channel: cabinets are read apart from the doors, a
1599
+ // few at a time. A place with none makes the one read it always did.
1600
+ const cabinets = Cabinets.cabinetDoorIds(h);
1601
+ const all = doors(h).map((d) => d.id);
1602
+ const doorIds = all.filter((id) => !cabinets.has(id)).slice(0, MAX_BOARD_DOORS);
1603
+ const batches = doorIds.length ? [doorIds] : [];
1604
+ const cabinetIds = all.filter((id) => cabinets.has(id)).slice(0, MAX_BOARD_DOORS);
1605
+ for (let i = 0; i < cabinetIds.length; i += CABINET_BOARDS_PER_READ) {
1606
+ batches.push(cabinetIds.slice(i, i + CABINET_BOARDS_PER_READ));
1607
+ }
1608
+ if (batches.length) {
1609
+ h.boardsAt = now;
1610
+ Promise.all(batches.map((ids) => hub.readResults({ doorIds: ids })))
1611
+ .then((reads) => {
1612
+ h.boards = new Map(reads.flatMap((read) => Object.entries(read.boards ?? {})));
1613
+ // Doors to other decks take their title and group from the boards,
1614
+ // and a cabinet its card.
1615
+ Cabinets.refresh(h, doors(h));
1616
+ })
1617
+ .catch((err) => refused(h, 'boards', err));
1618
+ }
1619
+ }
1620
+
1621
+ function applyRead(h, { playerId, avatarRev, wearRev, startedAt }, read) {
1622
+ const entry = h.players.get(playerId);
1623
+ if (!entry || !read) {
1624
+ return;
1625
+ }
1626
+ // Their results and records, for `hub.results` (v1.5).
1627
+ History.take(h, playerId, read, startedAt);
1628
+ // The wearable likewise, unless the game put one on since (v1.4).
1629
+ Wear.applyRead(h, playerId, wearRev, read);
1630
+ // The platform avatar, unless the client chose another since the read began.
1631
+ if (Number.isInteger(read.avatar) && read.avatar >= 0 && read.avatar < AVATARS && entry.avatarRev === avatarRev) {
1632
+ entry.avatar = read.avatar;
1633
+ }
1634
+ const row = entry.fromDeckId
1635
+ ? (read.recent ?? []).find((r) => r.deckId === entry.fromDeckId && Date.now() - Date.parse(r.at) < RESULT_FRESH_MS)
1636
+ : null;
1637
+ if (!row || !outcomeOrNone(row.outcome)) {
1638
+ return;
1639
+ }
1640
+ const result = {
1641
+ title: String(row.title ?? '').slice(0, 40),
1642
+ outcome: row.outcome ?? null,
1643
+ score: typeof row.score === 'number' && Number.isFinite(row.score) ? row.score : null,
1644
+ unit: ['ms', 's', 'points'].includes(row.unit) ? row.unit : null,
1645
+ better: row.better === 'higher' || row.better === 'lower' ? row.better : null,
1646
+ verified: true,
1647
+ };
1648
+ entry.carry = { result };
1649
+ h.session?.send(playerId, { k: 'hub-result', result });
1650
+ // A read slower than the arrival window: the player arrived without it.
1651
+ if (entry.arrived) {
1652
+ h.hooks.carry?.(h.ctx, playerId, entry.carry);
1653
+ }
1654
+ }
1655
+
1656
+ // A hub op the host or ghost refused, logged once per kind.
1657
+ function refused(h, op, err) {
1658
+ const code = err?.code ?? 'error';
1659
+ if (!h.refusals.has(`${op}:${code}`)) {
1660
+ h.refusals.add(`${op}:${code}`);
1661
+ console.warn(`[hub] ${op} refused (${code}): ${err?.message ?? err}`);
1662
+ }
1663
+ }
1664
+
1665
+ // Per-player HUD overrides go to their player alone, when they change. Where
1666
+ // a block hides players, each player is also sent the shared HUD as they may
1667
+ // read it, when that names someone the shared one leaves out.
1668
+ function sendHudOverrides(h) {
1669
+ const hidden = blockedPairs(h);
1670
+ const all = hidden ? namesOf(h, hidden.keys()) : null;
1671
+ for (const playerId of h.sim.players.keys()) {
1672
+ let spec = h.hudMe.get(playerId) ?? null;
1673
+ if (hidden) {
1674
+ const names = namesOf(h, hidden.get(playerId) ?? []);
1675
+ if (spec) {
1676
+ spec = Blocks.redactHud(spec, names);
1677
+ } else {
1678
+ const mine = Blocks.redactHud(h.hud, names);
1679
+ spec = JSON.stringify(mine) === JSON.stringify(Blocks.redactHud(h.hud, all)) ? null : mine;
1680
+ }
1681
+ }
1682
+ const json = JSON.stringify(spec);
1683
+ if ((h.sentHudMe.get(playerId) ?? 'null') !== json) {
1684
+ h.sentHudMe.set(playerId, json);
1685
+ h.session?.send(playerId, { k: 'hub-hud', hud: spec });
1686
+ }
1687
+ }
1688
+ }
1689
+
1690
+ // Per-player labels go to their player alone, when they change. Where a block
1691
+ // hides players, each player is also sent the shared labels as they may see
1692
+ // them where those differ from what the shared block carries for everyone.
1693
+ function sendLabelOverrides(h) {
1694
+ const now = h.sim.timeMs;
1695
+ const hidden = blockedPairs(h);
1696
+ const shared = hidden ? liveLabels(h) : null;
1697
+ const all = hidden ? labelsForAll(h) : null;
1698
+ for (const playerId of h.sim.players.keys()) {
1699
+ const mine = h.labelsMe.get(playerId);
1700
+ const hiddenIds = hidden?.get(playerId) ?? null;
1701
+ const names = hidden ? namesOf(h, hiddenIds ?? []) : null;
1702
+ const out = {};
1703
+ for (const [id, label] of shared ?? []) {
1704
+ const view = Blocks.labelFor(label, wireLabel(label), hiddenIds, names);
1705
+ if (view && JSON.stringify(view) !== JSON.stringify(all[id] ?? null)) {
1706
+ out[id] = view;
1707
+ }
1708
+ }
1709
+ for (const [id, label] of mine ?? []) {
1710
+ if (label.until !== null && now >= label.until) {
1711
+ mine.delete(id);
1712
+ continue;
1713
+ }
1714
+ const view = hidden ? Blocks.labelFor(label, wireLabel(label), hiddenIds, names) : wireLabel(label);
1715
+ if (view) {
1716
+ out[id] = view;
1717
+ } else {
1718
+ delete out[id];
1719
+ }
1720
+ }
1721
+ const json = JSON.stringify(out);
1722
+ if ((h.sentLabelsMe.get(playerId) ?? '{}') !== json) {
1723
+ h.sentLabelsMe.set(playerId, json);
1724
+ h.session?.send(playerId, { k: 'hub-labels', labels: out });
1725
+ }
1726
+ }
1727
+ }
1728
+
1729
+ // The HUD as every player may read it: without the name of anyone a block
1730
+ // hides from someone here. The HUD itself where nobody is hidden.
1731
+ function hudForAll(h) {
1732
+ const hidden = blockedPairs(h);
1733
+ return hidden ? Blocks.redactHud(h.hud, namesOf(h, hidden.keys())) : h.hud;
1734
+ }
1735
+
1736
+ // The shared labels as every player may see them: none about a player a block
1737
+ // hides from someone here, and no such player's name in any.
1738
+ function labelsForAll(h) {
1739
+ const hidden = blockedPairs(h);
1740
+ if (!hidden) {
1741
+ return labelsOf(h);
1742
+ }
1743
+ const names = namesOf(h, hidden.keys());
1744
+ const ids = new Set(hidden.keys());
1745
+ const out = {};
1746
+ for (const [id, label] of liveLabels(h)) {
1747
+ const view = Blocks.labelFor(label, wireLabel(label), ids, names);
1748
+ if (view) {
1749
+ out[id] = view;
1750
+ }
1751
+ }
1752
+ return out;
1753
+ }
1754
+
1755
+ function liveLabels(h) {
1756
+ labelsOf(h);
1757
+ return h.labels;
1758
+ }
1759
+
1760
+ // The usernames of these players, for taking out of free text.
1761
+ function namesOf(h, playerIds) {
1762
+ const out = [];
1763
+ for (const playerId of playerIds) {
1764
+ const name = h.session?.players.find((p) => p.playerId === playerId)?.username;
1765
+ if (name) {
1766
+ out.push(name);
1767
+ }
1768
+ }
1769
+ return out;
1770
+ }
1771
+
1772
+ function cleanHud(spec) {
1773
+ if (!spec || typeof spec !== 'object') {
1774
+ return null;
1775
+ }
1776
+ const out = {};
1777
+ for (const [key, max] of Object.entries(HUD_LIMITS)) {
1778
+ if (spec[key] !== undefined && spec[key] !== null) {
1779
+ out[key] = String(spec[key]).slice(0, max);
1780
+ }
1781
+ }
1782
+ const timer = spec.timer;
1783
+ if (timer && Number.isFinite(timer.since)) {
1784
+ out.timer = { since: timer.since };
1785
+ } else if (timer && Number.isFinite(timer.until)) {
1786
+ out.timer = { until: timer.until };
1787
+ }
1788
+ return Object.keys(out).length ? out : null;
1789
+ }
1790
+
1791
+ function labelsOf(h) {
1792
+ const out = {};
1793
+ const now = h.sim?.timeMs ?? 0;
1794
+ for (const [id, label] of h.labels) {
1795
+ if (label.until !== null && now >= label.until) {
1796
+ h.labels.delete(id);
1797
+ continue;
1798
+ }
1799
+ out[id] = wireLabel(label);
1800
+ }
1801
+ return out;
1802
+ }
1803
+
1804
+ // Every helloed player's avatar, for everyone: all but the players a block
1805
+ // hides from someone here, whose avatars go to each player who may see them
1806
+ // alone (`sendAvatarOverrides`).
1807
+ function avatars(h, hidden) {
1808
+ const out = {};
1809
+ for (const [playerId, entry] of h.players) {
1810
+ if (entry.hello && !hidden?.has(playerId)) {
1811
+ out[playerId] = entry.avatar;
1812
+ }
1813
+ }
1814
+ return out;
1815
+ }
1816
+
1817
+ // Who a block hides from whom (`blocks.js`), asked of the host once a tick
1818
+ // and again when the roster changes.
1819
+ function blockedPairs(h) {
1820
+ const players = h.session?.players ?? [];
1821
+ const key = `${h.sim?.timeMs ?? ''}:${players.map((p) => p.playerId).join(',')}`;
1822
+ if (h.blocked.key !== key) {
1823
+ h.blocked = { key, pairs: Blocks.hiddenPairs(h.session, players.map((p) => p.playerId)) };
1824
+ }
1825
+ return h.blocked.pairs;
1826
+ }
1827
+
1828
+ // The avatars of players in a hidden pair, each to the players who may see
1829
+ // them, when they change. A session with no blocks sends nothing here.
1830
+ function sendAvatarOverrides(h) {
1831
+ const hidden = blockedPairs(h);
1832
+ for (const playerId of h.sim.players.keys()) {
1833
+ const out = {};
1834
+ for (const shrouded of hidden?.keys() ?? []) {
1835
+ const entry = h.players.get(shrouded);
1836
+ if (entry?.hello && !hidden.get(playerId)?.has(shrouded)) {
1837
+ out[shrouded] = entry.avatar;
1838
+ }
1839
+ }
1840
+ const json = JSON.stringify(out);
1841
+ if ((h.sentAvMe.get(playerId) ?? '{}') !== json) {
1842
+ h.sentAvMe.set(playerId, json);
1843
+ h.session?.send(playerId, { k: 'hub-av', hubAv: out });
1844
+ }
1845
+ }
1846
+ }
1847
+
1848
+ // `hub.wear` (v1.4): kept here and, where the host has hub ops, sent to ghost
1849
+ // for a signed-in player.
1850
+ function wear(h, playerId, spec) {
1851
+ return Wear.wear(h, playerId, spec, {
1852
+ platform: platformHub(h),
1853
+ userId: userIdOf(h, playerId),
1854
+ refused: (err) => refused(h, 'wear', err),
1855
+ });
1856
+ }
1857
+
1858
+ // `hubWear` rides the snapshot only once someone has worn something, so a
1859
+ // place nobody wears anything in sends what it always did.
1860
+ function wearingForJoin(h) {
1861
+ const wearing = Wear.wearingOf(h, blockedPairs(h));
1862
+ return Object.keys(wearing).length ? { hubWear: wearing } : {};
1863
+ }
1864
+
1865
+ function latchWearing(h, out) {
1866
+ const wearing = Wear.wearingOf(h, blockedPairs(h));
1867
+ if (Object.keys(wearing).length || h.sent.has('hubWear')) {
1868
+ latch(h, 'hubWear', wearing, out);
1869
+ }
1870
+ }
1871
+
1872
+ function latch(h, field, value, out) {
1873
+ const json = JSON.stringify(value);
1874
+ if (h.sent.get(field) !== json) {
1875
+ h.sent.set(field, json);
1876
+ out[field] = value;
1877
+ }
1878
+ }
1879
+
1880
+ // A scene actor of the place, or a copy the game spawned.
1881
+ function isSceneActor(h, id) {
1882
+ return Actors.isActor(h, id);
1883
+ }
1884
+
1885
+ // A signed-in player's user id (what `session.storage.user` and ghost key a
1886
+ // player by), or null for an anonymous one. On the dev serve its guests'
1887
+ // subjects (`dev-guest-<n>`) count, since their storage works there.
1888
+ const DEV_GUEST = /^dev-guest-\d{1,6}$/;
1889
+
1890
+ function userIdOf(h, playerId) {
1891
+ const p = h.session?.players.find((q) => q.playerId === playerId);
1892
+ if (!p) {
1893
+ return null;
1894
+ }
1895
+ if (!p.isAnonymous && USER_ID.test(String(p.userId))) {
1896
+ return String(p.userId);
1897
+ }
1898
+ const dev = String(h.session?.sessionId ?? '').startsWith('dev');
1899
+ return dev && DEV_GUEST.test(String(p.userId)) ? String(p.userId) : null;
1900
+ }
1901
+
1902
+ function usernameOf(h, playerId) {
1903
+ return h.session?.players.find((p) => p.playerId === playerId)?.username ?? 'player';
1904
+ }