castle-web-cli 0.4.239 → 0.4.240

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 (386) hide show
  1. package/dist/agent.js +5 -1
  2. package/dist/api.d.ts +20 -0
  3. package/dist/api.js +57 -0
  4. package/dist/bundle.d.ts +38 -1
  5. package/dist/bundle.js +309 -13
  6. package/dist/castle-host/host.js +163 -11
  7. package/dist/castleJson.d.ts +10 -0
  8. package/dist/castleJson.js +46 -2
  9. package/dist/check.js +5 -2
  10. package/dist/devSessionServer.js +4 -1
  11. package/dist/devSessionStorage.d.ts +1 -0
  12. package/dist/devSessionStorage.js +32 -7
  13. package/dist/importOrder.d.ts +2 -0
  14. package/dist/importOrder.js +29 -0
  15. package/dist/index.js +6 -3
  16. package/dist/init.js +24 -2
  17. package/dist/platformDoc.js +2 -1
  18. package/dist/playPagePolicy.js +5 -1
  19. package/dist/resetLeaderboards.d.ts +8 -1
  20. package/dist/resetLeaderboards.js +43 -8
  21. package/dist/save-deck.d.ts +32 -2
  22. package/dist/save-deck.js +240 -39
  23. package/kits/base/CLAUDE.md +1 -1
  24. package/kits/base/castle.json +1 -1
  25. package/kits/base/sdk/README.md +174 -6
  26. package/kits/base/sdk/analytics.d.ts +8 -0
  27. package/kits/base/sdk/analytics.js +92 -0
  28. package/kits/base/sdk/castle.d.ts +5 -1
  29. package/kits/base/sdk/castle.js +2 -0
  30. package/kits/base/sdk/commands.d.ts +48 -0
  31. package/kits/base/sdk/commands.js +1 -0
  32. package/kits/base/sdk/debugConsole.d.ts +17 -0
  33. package/kits/base/sdk/debugConsole.js +154 -0
  34. package/kits/base/sdk/experiments.js +24 -1
  35. package/kits/base/sdk/hostRetry.d.ts +7 -0
  36. package/kits/base/sdk/hostRetry.js +57 -0
  37. package/kits/base/sdk/hub.d.ts +20 -2
  38. package/kits/base/sdk/hub.js +99 -13
  39. package/kits/base/sdk/multiplayer.d.ts +2 -0
  40. package/kits/base/sdk/multiplayer.js +168 -26
  41. package/kits/base/sdk/reconnectBudget.d.ts +6 -0
  42. package/kits/base/sdk/reconnectBudget.js +41 -1
  43. package/kits/base/sdk/runtime.js +36 -19
  44. package/kits/base/sdk/server/hub.d.ts +19 -0
  45. package/kits/base/sdk/server/hub.js +12 -0
  46. package/kits/base/sdk/server/platformHandle.d.ts +1 -0
  47. package/kits/base/sdk/server/wrapper.d.ts +1 -1
  48. package/kits/base/sdk/server/wrapper.js +26 -1
  49. package/kits/base/sdk/transport.d.ts +2 -1
  50. package/kits/base/sdk/transport.js +35 -0
  51. package/kits/hub-game/CLAUDE.md +66 -19
  52. package/kits/hub-game/code/client/act.js +9 -6
  53. package/kits/hub-game/code/client/actCore.js +26 -6
  54. package/kits/hub-game/code/client/actGateLog.js +36 -0
  55. package/kits/hub-game/code/client/actionOverflow.js +29 -8
  56. package/kits/hub-game/code/client/actionRailSurface.js +186 -0
  57. package/kits/hub-game/code/client/actionRailTree.js +173 -0
  58. package/kits/hub-game/code/client/askSurface.js +85 -0
  59. package/kits/hub-game/code/client/askTree.js +51 -0
  60. package/kits/hub-game/code/client/attention.js +31 -6
  61. package/kits/hub-game/code/client/ballot.js +42 -5
  62. package/kits/hub-game/code/client/ballotSurface.js +115 -0
  63. package/kits/hub-game/code/client/ballotTree.js +180 -0
  64. package/kits/hub-game/code/client/catchingUp.js +19 -0
  65. package/kits/hub-game/code/client/celebrate.js +66 -0
  66. package/kits/hub-game/code/client/chrome.js +473 -53
  67. package/kits/hub-game/code/client/companion.js +93 -23
  68. package/kits/hub-game/code/client/companionDress.js +1 -1
  69. package/kits/hub-game/code/client/cornerSurface.js +106 -0
  70. package/kits/hub-game/code/client/cornerTree.js +83 -0
  71. package/kits/hub-game/code/client/decor.js +20 -11
  72. package/kits/hub-game/code/client/deviceStorage.js +121 -0
  73. package/kits/hub-game/code/client/disguise.js +23 -0
  74. package/kits/hub-game/code/client/disguiseDraw.js +87 -0
  75. package/kits/hub-game/code/client/dockSurface.js +206 -0
  76. package/kits/hub-game/code/client/dockTree.js +232 -0
  77. package/kits/hub-game/code/client/earned.js +29 -0
  78. package/kits/hub-game/code/client/emoteSurface.js +188 -0
  79. package/kits/hub-game/code/client/emoteTree.js +264 -0
  80. package/kits/hub-game/code/client/farAvatars.js +4 -3
  81. package/kits/hub-game/code/client/fpsTelemetry.js +3 -1
  82. package/kits/hub-game/code/client/grab.js +121 -50
  83. package/kits/hub-game/code/client/holdShow.js +19 -0
  84. package/kits/hub-game/code/client/hookLayer.js +96 -12
  85. package/kits/hub-game/code/client/hubControls.js +7 -1
  86. package/kits/hub-game/code/client/hudSurface.js +11 -3
  87. package/kits/hub-game/code/client/hudTree.js +7 -4
  88. package/kits/hub-game/code/client/idle.js +21 -3
  89. package/kits/hub-game/code/client/invites.js +24 -3
  90. package/kits/hub-game/code/client/keys.js +15 -0
  91. package/kits/hub-game/code/client/labelsNear.js +8 -1
  92. package/kits/hub-game/code/client/layoutCache.js +57 -8
  93. package/kits/hub-game/code/client/loadingCover.js +53 -4
  94. package/kits/hub-game/code/client/menuIcons.js +15 -0
  95. package/kits/hub-game/code/client/menuSurface.js +102 -0
  96. package/kits/hub-game/code/client/menuTree.js +135 -0
  97. package/kits/hub-game/code/client/modelLook.js +41 -0
  98. package/kits/hub-game/code/client/pickerSurface.js +152 -0
  99. package/kits/hub-game/code/client/pickerTree.js +163 -0
  100. package/kits/hub-game/code/client/pushVisit.js +4 -2
  101. package/kits/hub-game/code/client/quality.js +188 -29
  102. package/kits/hub-game/code/client/qualityEntry.js +10 -1
  103. package/kits/hub-game/code/client/quickChatSurface.js +222 -0
  104. package/kits/hub-game/code/client/quickChatTree.js +201 -0
  105. package/kits/hub-game/code/client/rehello.js +75 -0
  106. package/kits/hub-game/code/client/renderVisibility.js +17 -0
  107. package/kits/hub-game/code/client/replay.js +118 -0
  108. package/kits/hub-game/code/client/role.js +3 -0
  109. package/kits/hub-game/code/client/safeLayout.js +441 -56
  110. package/kits/hub-game/code/client/safeStyle.js +13 -10
  111. package/kits/hub-game/code/client/say.js +2 -0
  112. package/kits/hub-game/code/client/soundSurface.js +77 -0
  113. package/kits/hub-game/code/client/soundTree.js +74 -0
  114. package/kits/hub-game/code/client/soundscape.js +12 -9
  115. package/kits/hub-game/code/client/soundscapeCues.js +1 -1
  116. package/kits/hub-game/code/client/state.js +67 -1
  117. package/kits/hub-game/code/client/stuckSurface.js +76 -0
  118. package/kits/hub-game/code/client/stuckTree.js +67 -0
  119. package/kits/hub-game/code/client/talk.js +42 -12
  120. package/kits/hub-game/code/client/talkTree.js +4 -2
  121. package/kits/hub-game/code/client/textAskSurface.js +147 -0
  122. package/kits/hub-game/code/client/textAskTree.js +67 -0
  123. package/kits/hub-game/code/client/tiers.js +252 -27
  124. package/kits/hub-game/code/client/together.js +4 -1
  125. package/kits/hub-game/code/client/uiDom.js +86 -8
  126. package/kits/hub-game/code/client/uiTree.js +33 -4
  127. package/kits/hub-game/code/client/vehicle.js +72 -51
  128. package/kits/hub-game/code/client/weakestTier.js +75 -31
  129. package/kits/hub-game/code/client/wear.js +159 -5
  130. package/kits/hub-game/code/client/worldLabels.js +205 -25
  131. package/kits/hub-game/code/companionSpec.js +4 -2
  132. package/kits/hub-game/code/server/act.js +3 -0
  133. package/kits/hub-game/code/server/actGate.js +83 -0
  134. package/kits/hub-game/code/server/actions.js +71 -15
  135. package/kits/hub-game/code/server/actors.js +20 -5
  136. package/kits/hub-game/code/server/analytics.js +35 -3
  137. package/kits/hub-game/code/server/ask.js +39 -3
  138. package/kits/hub-game/code/server/ballot.js +167 -4
  139. package/kits/hub-game/code/server/celebrate.js +64 -0
  140. package/kits/hub-game/code/server/companion.js +17 -2
  141. package/kits/hub-game/code/server/decor.js +11 -2
  142. package/kits/hub-game/code/server/disguise.js +63 -0
  143. package/kits/hub-game/code/server/earned.js +6 -2
  144. package/kits/hub-game/code/server/friendBests.js +13 -4
  145. package/kits/hub-game/code/server/friendsAmong.js +67 -8
  146. package/kits/hub-game/code/server/grab.js +12 -2
  147. package/kits/hub-game/code/server/heldOffers.js +142 -0
  148. package/kits/hub-game/code/server/holdShow.js +98 -0
  149. package/kits/hub-game/code/server/hub.js +851 -45
  150. package/kits/hub-game/code/server/idle.js +110 -9
  151. package/kits/hub-game/code/server/index.js +9 -0
  152. package/kits/hub-game/code/server/labels.js +13 -3
  153. package/kits/hub-game/code/server/manifest.js +94 -6
  154. package/kits/hub-game/code/server/menu.js +26 -3
  155. package/kits/hub-game/code/server/npcs.js +55 -9
  156. package/kits/hub-game/code/server/observe.js +67 -6
  157. package/kits/hub-game/code/server/players.js +8 -1
  158. package/kits/hub-game/code/server/replay.js +135 -0
  159. package/kits/hub-game/code/server/storageLimit.js +4 -1
  160. package/kits/hub-game/code/server/townDay.js +74 -0
  161. package/kits/hub-game/code/server/vehicle.js +3 -0
  162. package/kits/hub-game/code/server/vis.js +26 -4
  163. package/kits/hub-game/code/server/wallet.js +677 -0
  164. package/kits/hub-game/code/server/wear.js +13 -3
  165. package/kits/hub-game/code/server/writerLease.js +191 -0
  166. package/kits/hub-game/code/shared/act.js +1 -1
  167. package/kits/hub-game/code/shared/expression.js +6 -0
  168. package/kits/hub-game/code/shared/replay.js +37 -0
  169. package/kits/hub-game/code/systems/hub.js +427 -54
  170. package/kits/hub-game/docs/analytics.md +16 -2
  171. package/kits/hub-game/docs/contract.md +942 -99
  172. package/kits/hub-game/docs/home-pieces.md +5 -6
  173. package/kits/hub-game/docs/observed-progress.md +49 -1
  174. package/kits/hub-game/docs/vehicle-preset.md +23 -0
  175. package/kits/hub-game/index.html +1 -0
  176. package/kits/hub-game/models/hats/baker-cap.pxmodel +3 -3
  177. package/kits/hub-game/models/hats/bat-clip.pxmodel +3 -3
  178. package/kits/hub-game/models/hats/beekeeper.pxmodel +3 -3
  179. package/kits/hub-game/models/hats/cap.pxmodel +3 -3
  180. package/kits/hub-game/models/hats/captain.pxmodel +3 -3
  181. package/kits/hub-game/models/hats/chef-toque.pxmodel +3 -3
  182. package/kits/hub-game/models/hats/crooked-top.pxmodel +3 -3
  183. package/kits/hub-game/models/hats/delivery-cap.pxmodel +3 -3
  184. package/kits/hub-game/models/hats/fire-helmet.pxmodel +3 -3
  185. package/kits/hub-game/models/hats/flower-crown.pxmodel +3 -3
  186. package/kits/hub-game/models/hats/foam-crown.pxmodel +3 -3
  187. package/kits/hub-game/models/hats/hard-hat.pxmodel +3 -3
  188. package/kits/hub-game/models/hats/lantern.pxmodel +3 -3
  189. package/kits/hub-game/models/hats/laurel.pxmodel +3 -3
  190. package/kits/hub-game/models/hats/lighthouse.pxmodel +3 -3
  191. package/kits/hub-game/models/hats/nurse-cap.pxmodel +3 -3
  192. package/kits/hub-game/models/hats/police-cap.pxmodel +3 -3
  193. package/kits/hub-game/models/hats/sailor.pxmodel +3 -3
  194. package/kits/hub-game/models/hats/souwester.pxmodel +3 -3
  195. package/kits/hub-game/models/hats/straw.pxmodel +3 -3
  196. package/kits/hub-game/models/hats/sunflower.pxmodel +3 -3
  197. package/kits/hub-game/models/hats/sweatband.pxmodel +3 -3
  198. package/kits/hub-game/models/hats/teacher-beret.pxmodel +3 -3
  199. package/kits/hub-game/models/hats/witch.pxmodel +3 -3
  200. package/kits/hub-game/models/hold-show/daisy.pxmodel +231 -0
  201. package/kits/hub-game/models/hold-show/moonflower.pxmodel +171 -0
  202. package/kits/hub-game/models/hold-show/rose.pxmodel +191 -0
  203. package/kits/hub-game/models/hold-show/square/daisy.pxmodel +233 -0
  204. package/kits/hub-game/models/hold-show/square/moonflower.pxmodel +173 -0
  205. package/kits/hub-game/models/hold-show/square/rose.pxmodel +193 -0
  206. package/kits/hub-game/models/hold-show/square/sunflower.pxmodel +313 -0
  207. package/kits/hub-game/models/hold-show/square/tulip.pxmodel +133 -0
  208. package/kits/hub-game/models/hold-show/sunflower.pxmodel +311 -0
  209. package/kits/hub-game/models/hold-show/tulip.pxmodel +131 -0
  210. package/kits/hub-game/package-lock.json +3 -3
  211. package/kits/hub-game/package.json +4 -3
  212. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +1 -0
  213. package/kits/hub-game/scripts/fixtures/hud-surface.json +12 -12
  214. package/kits/hub-game/scripts/fixtures/talk-surface.json +8 -8
  215. package/kits/hub-game/scripts/gen-hats.mjs +1 -1
  216. package/kits/hub-game/scripts/gen-hold-show.mjs +27 -0
  217. package/kits/hub-game/scripts/pack.mjs +89 -23
  218. package/kits/hub-game/scripts/test-act-client.mjs +5 -0
  219. package/kits/hub-game/scripts/test-act-core.mjs +32 -0
  220. package/kits/hub-game/scripts/test-act-gate.mjs +186 -0
  221. package/kits/hub-game/scripts/test-action-rail-crowded-dom.mjs +7 -1
  222. package/kits/hub-game/scripts/test-action-rail-default-dom.mjs +102 -0
  223. package/kits/hub-game/scripts/test-action-rail-never-silent-dom.mjs +50 -0
  224. package/kits/hub-game/scripts/test-action-rail-surface.mjs +368 -0
  225. package/kits/hub-game/scripts/test-action-rail-town-jobs-dom.mjs +118 -0
  226. package/kits/hub-game/scripts/test-actions-client.mjs +5 -3
  227. package/kits/hub-game/scripts/test-actions.mjs +24 -0
  228. package/kits/hub-game/scripts/test-actors.mjs +19 -0
  229. package/kits/hub-game/scripts/test-again-corner-dom.mjs +59 -0
  230. package/kits/hub-game/scripts/test-analytics.mjs +79 -0
  231. package/kits/hub-game/scripts/test-arrival-pose-server.mjs +25 -8
  232. package/kits/hub-game/scripts/test-ask-client.mjs +9 -0
  233. package/kits/hub-game/scripts/test-ask-surface.mjs +188 -0
  234. package/kits/hub-game/scripts/test-attention.mjs +43 -1
  235. package/kits/hub-game/scripts/test-ballot-sheet-dom.mjs +71 -0
  236. package/kits/hub-game/scripts/test-ballot-surface.mjs +276 -0
  237. package/kits/hub-game/scripts/test-ballot.mjs +420 -3
  238. package/kits/hub-game/scripts/test-ban-join.mjs +1 -1
  239. package/kits/hub-game/scripts/test-celebrate-client.mjs +62 -0
  240. package/kits/hub-game/scripts/test-celebrate.mjs +116 -0
  241. package/kits/hub-game/scripts/test-chat.mjs +73 -0
  242. package/kits/hub-game/scripts/test-companion-client.mjs +203 -21
  243. package/kits/hub-game/scripts/test-companion.mjs +110 -3
  244. package/kits/hub-game/scripts/test-control-layout-dom.mjs +57 -10
  245. package/kits/hub-game/scripts/test-corner-surface.mjs +268 -0
  246. package/kits/hub-game/scripts/test-decor-client.mjs +59 -3
  247. package/kits/hub-game/scripts/test-decor.mjs +27 -0
  248. package/kits/hub-game/scripts/test-device-class.mjs +4 -1
  249. package/kits/hub-game/scripts/test-disguise-client.mjs +281 -0
  250. package/kits/hub-game/scripts/test-disguise.mjs +176 -0
  251. package/kits/hub-game/scripts/test-dock-surface.mjs +404 -0
  252. package/kits/hub-game/scripts/test-door-stay-client.mjs +602 -0
  253. package/kits/hub-game/scripts/test-door-stay.mjs +613 -0
  254. package/kits/hub-game/scripts/test-earned-client.mjs +119 -0
  255. package/kits/hub-game/scripts/test-emote-surface.mjs +616 -0
  256. package/kits/hub-game/scripts/test-fps-telemetry.mjs +39 -4
  257. package/kits/hub-game/scripts/test-friend-bests.mjs +38 -12
  258. package/kits/hub-game/scripts/test-ghost-click-dom.mjs +75 -0
  259. package/kits/hub-game/scripts/test-grab-client.mjs +29 -2
  260. package/kits/hub-game/scripts/test-grab-orbit.mjs +260 -11
  261. package/kits/hub-game/scripts/test-grab.mjs +10 -1
  262. package/kits/hub-game/scripts/test-hats.mjs +28 -0
  263. package/kits/hub-game/scripts/test-held-offers.mjs +394 -0
  264. package/kits/hub-game/scripts/test-high-only.mjs +3 -3
  265. package/kits/hub-game/scripts/test-hold-show-client.mjs +175 -0
  266. package/kits/hub-game/scripts/test-hold-show.mjs +355 -0
  267. package/kits/hub-game/scripts/test-hub-controls.mjs +3 -1
  268. package/kits/hub-game/scripts/test-hub-idle.mjs +348 -0
  269. package/kits/hub-game/scripts/test-hub-leaving.mjs +21 -0
  270. package/kits/hub-game/scripts/test-hub-ops.mjs +119 -0
  271. package/kits/hub-game/scripts/test-hub-trip.mjs +240 -4
  272. package/kits/hub-game/scripts/test-hud-clear.mjs +83 -0
  273. package/kits/hub-game/scripts/test-hud-rate.mjs +2 -1
  274. package/kits/hub-game/scripts/test-idle.mjs +160 -0
  275. package/kits/hub-game/scripts/test-invites-client.mjs +53 -0
  276. package/kits/hub-game/scripts/test-labels.mjs +11 -0
  277. package/kits/hub-game/scripts/test-landscape-layout.mjs +20 -0
  278. package/kits/hub-game/scripts/test-loading-cover.mjs +67 -1
  279. package/kits/hub-game/scripts/test-manifest.mjs +27 -0
  280. package/kits/hub-game/scripts/test-menu-client.mjs +54 -5
  281. package/kits/hub-game/scripts/test-menu-surface.mjs +236 -0
  282. package/kits/hub-game/scripts/test-npcs.mjs +128 -0
  283. package/kits/hub-game/scripts/test-observed.mjs +171 -3
  284. package/kits/hub-game/scripts/test-pack.mjs +166 -0
  285. package/kits/hub-game/scripts/test-picker-surface.mjs +321 -0
  286. package/kits/hub-game/scripts/test-placeat-server.mjs +395 -0
  287. package/kits/hub-game/scripts/test-placement-cache.mjs +1 -1
  288. package/kits/hub-game/scripts/test-pointer-clear-dom.mjs +82 -0
  289. package/kits/hub-game/scripts/test-progress-reset.mjs +184 -6
  290. package/kits/hub-game/scripts/test-push-visit.mjs +9 -0
  291. package/kits/hub-game/scripts/test-quality.mjs +312 -9
  292. package/kits/hub-game/scripts/test-quick-chat-surface.mjs +511 -0
  293. package/kits/hub-game/scripts/test-rehello.mjs +237 -0
  294. package/kits/hub-game/scripts/test-rejoin-yaw.mjs +138 -0
  295. package/kits/hub-game/scripts/test-relations-among.mjs +13 -7
  296. package/kits/hub-game/scripts/test-relations-refresh.mjs +90 -2
  297. package/kits/hub-game/scripts/test-replay-client.mjs +110 -0
  298. package/kits/hub-game/scripts/test-replay.mjs +178 -0
  299. package/kits/hub-game/scripts/test-resume-held.mjs +13 -0
  300. package/kits/hub-game/scripts/test-resume-pose-server.mjs +43 -5
  301. package/kits/hub-game/scripts/test-role-client.mjs +2 -1
  302. package/kits/hub-game/scripts/test-safe-act.mjs +233 -0
  303. package/kits/hub-game/scripts/test-safe-caption.mjs +364 -0
  304. package/kits/hub-game/scripts/test-safe-layout.mjs +79 -0
  305. package/kits/hub-game/scripts/test-safe-prompt.mjs +163 -0
  306. package/kits/hub-game/scripts/test-sound-surface.mjs +256 -0
  307. package/kits/hub-game/scripts/test-soundscape.mjs +85 -2
  308. package/kits/hub-game/scripts/test-stuck-surface.mjs +174 -0
  309. package/kits/hub-game/scripts/test-stuck.mjs +31 -0
  310. package/kits/hub-game/scripts/test-talk-surface.mjs +23 -6
  311. package/kits/hub-game/scripts/test-talk-walk-dom.mjs +123 -0
  312. package/kits/hub-game/scripts/test-text-ask-surface.mjs +273 -0
  313. package/kits/hub-game/scripts/test-tiers.mjs +453 -3
  314. package/kits/hub-game/scripts/test-toast-no-row-dom.mjs +71 -0
  315. package/kits/hub-game/scripts/test-together.mjs +11 -0
  316. package/kits/hub-game/scripts/test-town-day.mjs +90 -0
  317. package/kits/hub-game/scripts/test-try-on.mjs +39 -0
  318. package/kits/hub-game/scripts/test-ui-dom-dom.mjs +49 -2
  319. package/kits/hub-game/scripts/test-ui-tree.mjs +28 -0
  320. package/kits/hub-game/scripts/test-vehicle-client.mjs +68 -1
  321. package/kits/hub-game/scripts/test-vis.mjs +145 -0
  322. package/kits/hub-game/scripts/test-wallet.mjs +650 -0
  323. package/kits/hub-game/scripts/test-weakest-tier.mjs +135 -1
  324. package/kits/hub-game/scripts/test-world-labels.mjs +340 -0
  325. package/kits/hub-game/scripts/test-writer-lease-server.mjs +234 -0
  326. package/kits/hub-game/scripts/test-writer-lease.mjs +281 -0
  327. package/kits/hub-game/scripts/writer-storage-fixture.mjs +37 -0
  328. package/kits/hub-game/tools/hubScene/export.mjs +6 -5
  329. package/kits/hub-game/tools/hubScene/hubdata.mjs +10 -0
  330. package/kits/hub-game/tools/hubScene/test/export-fixture.mjs +36 -2
  331. package/kits/hub-game/tools/hubScene/validate-manifest.mjs +10 -2
  332. package/kits/multiplayer-3d/castle.json +5 -5
  333. package/kits/multiplayer-3d/code/client/resumeGate.js +49 -2
  334. package/kits/multiplayer-3d/code/server/ownership.js +25 -6
  335. package/kits/multiplayer-3d/code/server/world.js +19 -4
  336. package/kits/multiplayer-3d/code/systems/multiplayer.js +67 -11
  337. package/kits/multiplayer-3d/package-lock.json +1 -1
  338. package/kits/multiplayer-3d/package.json +2 -1
  339. package/kits/multiplayer-3d/scripts/test-ground-half.mjs +56 -0
  340. package/kits/multiplayer-3d/scripts/test-join-watchdog.mjs +54 -3
  341. package/kits/multiplayer-3d/scripts/test-owned-moves.mjs +190 -0
  342. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +191 -5
  343. package/kits/multiplayer-3d/scripts/test-resync-reconnect.mjs +68 -0
  344. package/kits/physics-2d/castle.json +2 -2
  345. package/kits/physics-2d/engine/scene.js +10 -2
  346. package/kits/physics-3d/CLAUDE.md +14 -0
  347. package/kits/physics-3d/behaviors/Player.jsx +39 -3
  348. package/kits/physics-3d/castle.json +3 -3
  349. package/kits/physics-3d/docs/engine-model-cache.md +109 -0
  350. package/kits/physics-3d/docs/engine-player.md +76 -0
  351. package/kits/physics-3d/docs/engine-skip-work.md +16 -0
  352. package/kits/physics-3d/docs/pxmodel-format.md +5 -1
  353. package/kits/physics-3d/engine3d/gait.js +16 -8
  354. package/kits/physics-3d/engine3d/groundsize.js +23 -0
  355. package/kits/physics-3d/engine3d/kithooks.js +50 -0
  356. package/kits/physics-3d/engine3d/look.js +110 -17
  357. package/kits/physics-3d/engine3d/lookbake.js +19 -1
  358. package/kits/physics-3d/engine3d/materialpresets.js +3 -2
  359. package/kits/physics-3d/engine3d/modelcache.js +280 -0
  360. package/kits/physics-3d/engine3d/modelcachedigest.js +37 -0
  361. package/kits/physics-3d/engine3d/modelcachegate.js +69 -0
  362. package/kits/physics-3d/engine3d/modelrefs.js +13 -0
  363. package/kits/physics-3d/engine3d/optimize.js +20 -9
  364. package/kits/physics-3d/engine3d/playerRun.js +26 -1
  365. package/kits/physics-3d/engine3d/pxmodel.js +7 -3
  366. package/kits/physics-3d/engine3d/templatecache.js +722 -0
  367. package/kits/physics-3d/engine3d/world3d.js +211 -17
  368. package/kits/physics-3d/package-lock.json +1 -1
  369. package/kits/physics-3d/package.json +2 -1
  370. package/kits/physics-3d/play/behaviors/Player.js +43 -3
  371. package/kits/physics-3d/scripts/render.mjs +56 -8
  372. package/kits/physics-3d/scripts/template-cache-fixtures.mjs +37 -0
  373. package/kits/physics-3d/scripts/template-cache-v1-bytes.json +49 -0
  374. package/kits/physics-3d/scripts/test-gait.mjs +53 -9
  375. package/kits/physics-3d/scripts/test-ground-half.mjs +120 -0
  376. package/kits/physics-3d/scripts/test-model-cache.mjs +600 -0
  377. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +1 -0
  378. package/kits/physics-3d/scripts/test-sleeping-models.mjs +384 -0
  379. package/kits/physics-3d/scripts/test-template-cache-minified.mjs +106 -0
  380. package/kits/physics-3d/scripts/test-template-cache.mjs +519 -0
  381. package/kits/physics-3d/scripts/test-wall-slide.mjs +272 -0
  382. package/kits/physics-3d/systems/physics3d.js +51 -2
  383. package/kits/real-time/castle.json +2 -2
  384. package/kits/real-time/code/client/connection.js +3 -0
  385. package/package.json +2 -2
  386. package/vendor/three/examples/jsm/libs/fflate.module.js +2672 -0
@@ -0,0 +1,677 @@
1
+ // v1.185 `hub.wallet`: one coin wallet per account on the SDK's gated
2
+ // conditional storage (sdk/README.md "Conditional writes and recovery"),
3
+ // declared by the deck as `hub.wallet: { name, start? }`.
4
+ //
5
+ // A DECK target `wallet:<name>:<userId>:` holds one key, `...:state`, whose
6
+ // value is `{ v: 1, gen, coins, owned: [id], data: {} }`, `gen` the reset
7
+ // generation it was written under. A progress reset does not delete deck rows
8
+ // (ghost-server cauldronDeckProgressReset.ts clears deck scope only on a town
9
+ // or the house deck, by their own key lists), so a row from an older
10
+ // generation reads as a fresh wallet at `start`. Each spend or earn is an
11
+ // operation against the stored wallet, never a whole-save SET: a
12
+ // `conditionalWrite` naming the snapshot's access, the target's revision and a
13
+ // reset fence carrying the generation read BEFORE that snapshot, under a fresh
14
+ // operation id. So a server holding an older read cannot overwrite a newer
15
+ // wallet (its write is refused; the stored wallet is adopted and the operation
16
+ // applied once more against it), and a write still in flight across a progress
17
+ // reset cannot bring the old wallet back.
18
+ //
19
+ // One writer per account: an account's operations run one after another.
20
+ // A lost reply is retried with the identical request (same id and bytes), which
21
+ // returns the original receipt if it committed; `operation(id)` is asked first.
22
+ // A failed read, an unreadable row, or storage without the API or with the
23
+ // deck's flag off locks a signed-in wallet for the visit (`read` null, every
24
+ // change 'locked'); nothing is ever written then, and there is no fallback to
25
+ // ordinary writes. Anonymous players and dev guests get a session-only wallet.
26
+
27
+ const CONFLICT = 'CAULDRON_STORAGE_REVISION_CONFLICT';
28
+ const STALE_RESET = 'CAULDRON_STORAGE_STALE_RESET_GENERATION';
29
+ const STALE_ACCESS = 'CAULDRON_STORAGE_STALE_ACCESS';
30
+ const UNAVAILABLE = 'CAULDRON_STORAGE_UNAVAILABLE';
31
+ const MAX_GENERATION = 2147483647;
32
+
33
+ // Item ids are the deck's own; a wallet keeps at most MAX_OWNED of them and a
34
+ // `data` object of at most MAX_DATA_BYTES as JSON, so a row stays small.
35
+ export const ITEM_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
36
+ export const MAX_OWNED = 256;
37
+ export const MAX_DATA_BYTES = 4096;
38
+ // Operations an account may have waiting behind the one running; past it a
39
+ // change answers 'busy' at once (a read, null) rather than queueing unbounded.
40
+ export const MAX_WAITING = 16;
41
+ // Waits before each identical resend of a write whose outcome is unknown. Tests
42
+ // shorten them.
43
+ export const tuning = { retryMs: [250, 1000, 3000], gateOffMs: 5 * 60000 };
44
+
45
+ const LOCKED = Object.freeze({ ok: false, why: 'locked' });
46
+ const BUSY = Object.freeze({ ok: false, why: 'busy' });
47
+ const copy = (value) => JSON.parse(JSON.stringify(value));
48
+ const wait = (ms) => (ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve());
49
+ const operationId = () => `wallet-${globalThis.crypto.randomUUID().replaceAll('-', '')}`;
50
+ const isPlain = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
51
+ // A caller's bad argument found only against the wallet (a `data` patch too big
52
+ // once merged): the call rejects with it rather than answering a result.
53
+ const argument = (message) => Object.assign(new TypeError(`hub.wallet: ${message}`), { walletArgument: true });
54
+ const fail = (message, code) => Object.assign(Error(message), code ? { code } : {});
55
+ const capable = (api) =>
56
+ ['snapshot', 'conditionalWrite', 'resetGeneration', 'operation', 'recentOperations'].every((m) => typeof api?.[m] === 'function');
57
+ const sameTarget = (a, b) => a?.scope?.toLowerCase() === b.scope && a?.prefix === b.prefix;
58
+
59
+ // What storage holds, `{ gen, state }`, or null when it is not a wallet this
60
+ // kit can read. `gen` is the account's reset generation the row was written
61
+ // under: a progress reset does not delete a deck row, so a row from an older
62
+ // generation is the wallet of a playthrough that was reset.
63
+ export function parseWallet(raw) {
64
+ let value = raw;
65
+ if (typeof raw === 'string') {
66
+ try {
67
+ value = JSON.parse(raw);
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+ if (!isPlain(value) || value.v !== 1 || !Number.isSafeInteger(value.coins) || value.coins < 0 ||
73
+ !Number.isInteger(value.gen) || value.gen < 0 || value.gen > MAX_GENERATION) {
74
+ return null;
75
+ }
76
+ const owned = value.owned ?? [];
77
+ if (!Array.isArray(owned) || owned.length > MAX_OWNED || owned.some((id) => typeof id !== 'string' || !ITEM_ID.test(id)) ||
78
+ new Set(owned).size !== owned.length) {
79
+ return null;
80
+ }
81
+ const data = value.data ?? {};
82
+ if (!isPlain(data)) {
83
+ return null;
84
+ }
85
+ return { gen: value.gen, state: { coins: value.coins, owned: [...owned], data: copy(data) } };
86
+ }
87
+
88
+ const row = (state, gen) => ({ v: 1, gen, coins: state.coins, owned: [...state.owned], data: copy(state.data) });
89
+ const view = (state) => ({ coins: state.coins, owned: [...state.owned], data: copy(state.data) });
90
+
91
+ // A `data` patch: a plain object of JSON values merged key by key.
92
+ function patched(data, patch) {
93
+ if (patch === undefined) {
94
+ return data;
95
+ }
96
+ if (!isPlain(patch)) {
97
+ throw argument('data must be a plain object.');
98
+ }
99
+ const out = { ...data };
100
+ for (const [key, value] of Object.entries(patch)) {
101
+ if (value !== undefined) {
102
+ out[key] = value;
103
+ }
104
+ }
105
+ let text;
106
+ try {
107
+ text = JSON.stringify(out);
108
+ } catch {
109
+ throw argument('data must be JSON.');
110
+ }
111
+ if (new TextEncoder().encode(text).length > MAX_DATA_BYTES) {
112
+ throw argument(`data is over ${MAX_DATA_BYTES} bytes.`);
113
+ }
114
+ return JSON.parse(text);
115
+ }
116
+
117
+ const amountOk = (n) => Number.isSafeInteger(n) && n >= 0;
118
+
119
+ // The change each verb makes to a wallet: `{ next }`, or `{ why }` when refused.
120
+ // They run again, unchanged, against a wallet adopted after a conflict.
121
+ function spendOp(cost, add, data) {
122
+ return (state) => {
123
+ if (add !== undefined && state.owned.includes(add)) {
124
+ return { why: 'owned' };
125
+ }
126
+ if (state.coins < cost) {
127
+ return { why: 'short' };
128
+ }
129
+ if (add !== undefined && state.owned.length >= MAX_OWNED) {
130
+ return { why: 'full' };
131
+ }
132
+ return { next: { coins: state.coins - cost, owned: add === undefined ? [...state.owned] : [...state.owned, add], data: patched(state.data, data) } };
133
+ };
134
+ }
135
+ function earnOp(amount, data) {
136
+ return (state) => {
137
+ const coins = state.coins + amount;
138
+ if (!Number.isSafeInteger(coins)) {
139
+ return { why: 'full' };
140
+ }
141
+ return { next: { coins, owned: [...state.owned], data: patched(state.data, data) } };
142
+ };
143
+ }
144
+ function seedOp(coins, owned) {
145
+ return (state, exists) => (exists ? { why: 'seeded' } : { next: { coins, owned: [...owned], data: copy(state.data) } });
146
+ }
147
+
148
+ // `storage()` the session's storage now; `identify(playerId)` is
149
+ // `{ stored: true, userId }` for a signed-in account (numeric id),
150
+ // `{ stored: false, key }` for a session-only wallet, or null for nobody here.
151
+ // `fence(userId)`, when given, settles before every write of that account and
152
+ // rejects once this instance may no longer save it (the writer lease).
153
+ export function createWallet({ name, start = 0, storage, identify, fence = null }) {
154
+ const prefix = (userId) => `wallet:${name}:${userId}:`;
155
+ const target = (userId) => ({ scope: 'deck', prefix: prefix(userId) });
156
+ const key = (userId) => `${prefix(userId)}state`;
157
+ const accounts = new Map();
158
+ const guests = new Map();
159
+ // The deck's conditional-storage flag, as `recentOperations` answers it:
160
+ // 'on' for the layer's life; 'off' rechecked after a while.
161
+ let gate = { state: 'unknown', at: 0 };
162
+ const fresh = () => ({ coins: start, owned: [], data: {} });
163
+
164
+ function account(userId) {
165
+ let a = accounts.get(userId);
166
+ if (!a) {
167
+ a = { userId, state: null, exists: false, base: null, locked: null, pending: null, epoch: 0, observed: null, unbound: new Set(), tail: Promise.resolve(), waiting: 0 };
168
+ accounts.set(userId, a);
169
+ }
170
+ return a;
171
+ }
172
+ // Runs `fn` after the account's earlier operations; `busy` when too many wait.
173
+ function enqueue(a, fn, busy) {
174
+ if (a.waiting >= MAX_WAITING) {
175
+ return Promise.resolve(busy);
176
+ }
177
+ a.waiting += 1;
178
+ const run = a.tail.then(fn).catch((error) => {
179
+ if (error?.walletArgument) {
180
+ throw error;
181
+ }
182
+ console.warn(`[hub] wallet failed: ${error?.code ?? error?.message ?? error}`);
183
+ return busy;
184
+ }).finally(() => {
185
+ a.waiting -= 1;
186
+ });
187
+ a.tail = run.then(() => {}, () => {});
188
+ return run;
189
+ }
190
+
191
+ async function gateOpen(api) {
192
+ if (gate.state === 'on') {
193
+ return true;
194
+ }
195
+ if (gate.state === 'off' && Date.now() - gate.at < tuning.gateOffMs) {
196
+ return false;
197
+ }
198
+ try {
199
+ await api.recentOperations({ limit: 1 });
200
+ gate = { state: 'on', at: Date.now() };
201
+ return true;
202
+ } catch (error) {
203
+ if (error?.code === UNAVAILABLE && error.retryable !== true) {
204
+ gate = { state: 'off', at: Date.now() };
205
+ return false;
206
+ }
207
+ throw error;
208
+ }
209
+ }
210
+
211
+ // Reset generation, snapshot, generation again (a reset between the two
212
+ // reads would stamp an old snapshot with a new generation). A present row
213
+ // this kit cannot parse is never read as empty.
214
+ async function readStored(api, userId, observe) {
215
+ const t = target(userId);
216
+ for (let attempt = 0; attempt < 3; attempt++) {
217
+ const generation = await api.resetGeneration(userId);
218
+ observe(generation);
219
+ if (!Number.isInteger(generation) || generation < 0 || generation > MAX_GENERATION) {
220
+ throw fail('Invalid reset generation');
221
+ }
222
+ const snap = await api.snapshot({ targets: [{ target: t }] });
223
+ const entry = adoptable(snap, userId, generation);
224
+ if (!entry) {
225
+ throw fail('Invalid snapshot');
226
+ }
227
+ if (entry.newer) {
228
+ throw fail('Unreadable wallet');
229
+ }
230
+ const again = await api.resetGeneration(userId);
231
+ observe(again);
232
+ if (again !== generation) {
233
+ continue;
234
+ }
235
+ return { ...entry, base: { ...entry.base, generation } };
236
+ }
237
+ throw fail('Progress reset kept moving', STALE_RESET);
238
+ }
239
+ // A snapshot of this account's target as a wallet under reset generation
240
+ // `generation`, or null when it is not one (wrong shape, foreign keys) --
241
+ // and throws when the row is unreadable. A row from an older generation
242
+ // reads as no wallet (`start`); one from a newer generation is `{ newer }`:
243
+ // the account was reset after `generation` was read.
244
+ function adoptable(snap, userId, generation) {
245
+ const t = target(userId);
246
+ const entry = snap?.targets?.find?.((e) => sameTarget(e?.target, t));
247
+ if (typeof snap?.access !== 'string' || !snap.access || !entry || entry.complete !== true) {
248
+ return null;
249
+ }
250
+ if (!(entry.revision === null || (typeof entry.revision === 'string' && entry.revision))) {
251
+ return null;
252
+ }
253
+ const keys = Object.keys(entry.rows ?? {});
254
+ if (!keys.every((k) => k === key(userId)) || (entry.revision === null && keys.length)) {
255
+ return null;
256
+ }
257
+ const raw = entry.rows?.[key(userId)];
258
+ let state = fresh();
259
+ let exists = false;
260
+ if (raw !== undefined) {
261
+ const parsed = parseWallet(raw);
262
+ if (!parsed) {
263
+ throw fail('Unreadable wallet');
264
+ }
265
+ if (parsed.gen > generation) {
266
+ return { newer: true };
267
+ }
268
+ if (parsed.gen === generation) {
269
+ state = parsed.state;
270
+ exists = true;
271
+ }
272
+ }
273
+ return { state, exists, base: { access: snap.access, revision: entry.revision } };
274
+ }
275
+
276
+ // Locks the account for the visit: nothing is written until a progress
277
+ // reset or the account leaves and comes back.
278
+ function lock(a, why) {
279
+ a.locked = why;
280
+ a.state = null;
281
+ a.base = null;
282
+ a.pending = null;
283
+ return LOCKED;
284
+ }
285
+ // Every reset generation a read of this account sees, in order: calls
286
+ // admitted before any was seen are bound to the first one seen after them.
287
+ function observe(a, generation) {
288
+ if (!Number.isInteger(generation)) {
289
+ return;
290
+ }
291
+ a.observed = generation;
292
+ for (const admitted of a.unbound) {
293
+ admitted.generation = generation;
294
+ }
295
+ a.unbound.clear();
296
+ }
297
+ async function load(a, api) {
298
+ if (!capable(api) || !/^\d{1,20}$/.test(a.userId)) {
299
+ lock(a, 'unavailable');
300
+ return false;
301
+ }
302
+ const epoch = a.epoch;
303
+ try {
304
+ if (!(await gateOpen(api))) {
305
+ if (a.epoch === epoch) {lock(a, 'unavailable');}
306
+ return false;
307
+ }
308
+ const read = await readStored(api, a.userId, (generation) => observe(a, generation));
309
+ if (a.epoch !== epoch) {
310
+ return false;
311
+ }
312
+ a.state = read.state;
313
+ a.exists = read.exists;
314
+ a.base = read.base;
315
+ return true;
316
+ } catch (error) {
317
+ if (a.epoch === epoch) {
318
+ lock(a, error?.code === UNAVAILABLE && error.retryable !== true ? 'unavailable' : 'failed');
319
+ }
320
+ return false;
321
+ }
322
+ }
323
+
324
+ // The request for one change, serialized once: a lost reply is retried
325
+ // with exactly these bytes.
326
+ function intend(a, next) {
327
+ const id = operationId();
328
+ return {
329
+ id,
330
+ next,
331
+ epoch: a.epoch,
332
+ generation: a.base.generation,
333
+ bytes: JSON.stringify({
334
+ operationId: id,
335
+ expectedAccess: a.base.access,
336
+ resetFences: [{ playerId: a.userId, resetGeneration: a.base.generation }],
337
+ changes: [{ target: target(a.userId), expectedRevision: a.base.revision, put: { [key(a.userId)]: row(next, a.base.generation) } }],
338
+ }),
339
+ };
340
+ }
341
+ function revisionFrom(a, intent, receipt) {
342
+ const entry =
343
+ receipt?.operationId === intent.id && Array.isArray(receipt.revisions)
344
+ ? receipt.revisions.find((r) => sameTarget(r?.target, target(a.userId)))
345
+ : null;
346
+ return typeof entry?.revision === 'string' && entry.revision ? entry.revision : null;
347
+ }
348
+ // Sends one intent until it settles: { kind: 'ok', revision, access } |
349
+ // 'conflict' (with the error) | 'reset' | 'locked' | 'unknown' (still not
350
+ // known after the resends; the intent is kept to settle first next time).
351
+ async function send(a, api, intent, resend) {
352
+ let recovered = resend;
353
+ for (let attempt = 0; ; attempt++) {
354
+ let receipt = null;
355
+ // Every attempt, a retry included, waits on the writer lease first.
356
+ if (fence) {
357
+ try {
358
+ await fence(a.userId);
359
+ } catch (error) {
360
+ // Lost for good locks the account; anything else sent nothing more,
361
+ // so the intent waits to be sent again.
362
+ if (error?.code === 'CAULDRON_STORAGE_WRITER_LOST') {
363
+ lock(a, 'failed');
364
+ return { kind: 'locked' };
365
+ }
366
+ return { kind: 'unknown' };
367
+ }
368
+ }
369
+ try {
370
+ try {
371
+ receipt = await api.conditionalWrite(JSON.parse(intent.bytes));
372
+ } catch (error) {
373
+ if (error?.committed === true && error.receipt) {
374
+ receipt = error.receipt;
375
+ recovered = true;
376
+ } else {
377
+ throw error;
378
+ }
379
+ }
380
+ } catch (error) {
381
+ const code = error?.code;
382
+ if (error?.committed === false && code === CONFLICT) {
383
+ return { kind: 'conflict', error };
384
+ }
385
+ if (error?.committed === false && (code === STALE_RESET || code === STALE_ACCESS)) {
386
+ return { kind: 'reset' };
387
+ }
388
+ if (error?.committed === false && error.retryable !== true) {
389
+ lock(a, code === UNAVAILABLE ? 'unavailable' : 'failed');
390
+ return { kind: 'locked' };
391
+ }
392
+ // Unknown outcome, or refused before it ran: the identical request
393
+ // returns the original receipt if it did commit.
394
+ if (attempt >= tuning.retryMs.length) {
395
+ return { kind: 'unknown' };
396
+ }
397
+ await wait(tuning.retryMs[attempt]);
398
+ recovered = true;
399
+ try {
400
+ const known = await api.operation(intent.id);
401
+ if (known?.state === 'committed' && known.receipt) {
402
+ receipt = known.receipt;
403
+ }
404
+ } catch {
405
+ // The resend settles it.
406
+ }
407
+ if (!receipt) {
408
+ continue;
409
+ }
410
+ }
411
+ // A recovered receipt proves the write once committed, not that it
412
+ // survived a reset since: check the generation before trusting it.
413
+ if (recovered) {
414
+ let generation;
415
+ try {
416
+ generation = await api.resetGeneration(a.userId);
417
+ } catch {
418
+ return { kind: 'unknown' };
419
+ }
420
+ if (generation !== intent.generation) {
421
+ return { kind: 'reset' };
422
+ }
423
+ }
424
+ const revision = revisionFrom(a, intent, receipt);
425
+ if (!revision) {
426
+ // A receipt that does not name this target: trust storage, not it.
427
+ return { kind: 'reset' };
428
+ }
429
+ return { kind: 'ok', revision, access: typeof receipt.access === 'string' && receipt.access ? receipt.access : a.base.access };
430
+ }
431
+ }
432
+ function settled(a, intent, out) {
433
+ if (a.epoch !== intent.epoch) {
434
+ // A progress reset came while it was on the wire: read again next time.
435
+ a.state = null;
436
+ a.base = null;
437
+ return;
438
+ }
439
+ a.state = intent.next;
440
+ a.exists = true;
441
+ a.base = { ...a.base, revision: out.revision, access: out.access };
442
+ }
443
+ // The stored wallet a conflict carries, else a fresh read.
444
+ async function adopt(a, api, error, epoch) {
445
+ if (a.epoch !== epoch || !a.base) {
446
+ return load(a, api);
447
+ }
448
+ try {
449
+ const entry = adoptable(error?.current, a.userId, a.base.generation);
450
+ if (entry?.newer) {
451
+ // Written after a reset this server has not read yet.
452
+ a.state = null;
453
+ a.base = null;
454
+ return load(a, api);
455
+ }
456
+ if (entry) {
457
+ a.state = entry.state;
458
+ a.exists = entry.exists;
459
+ a.base = { ...entry.base, generation: a.base.generation };
460
+ return true;
461
+ }
462
+ } catch {
463
+ lock(a, 'failed');
464
+ return false;
465
+ }
466
+ return load(a, api);
467
+ }
468
+ // A write left unknown last time goes first, with its own bytes.
469
+ async function settlePending(a, api) {
470
+ const intent = a.pending;
471
+ if (!intent) {
472
+ return true;
473
+ }
474
+ const out = await send(a, api, intent, true);
475
+ if (out.kind === 'unknown') {
476
+ return false;
477
+ }
478
+ a.pending = null;
479
+ if (out.kind === 'ok') {
480
+ settled(a, intent, out);
481
+ } else if (out.kind !== 'locked') {
482
+ // It did not commit (or a reset came): read what storage holds.
483
+ a.state = null;
484
+ a.base = null;
485
+ }
486
+ return !a.locked;
487
+ }
488
+
489
+ // `admitted` is the account's reset epoch and generation when the call was
490
+ // made: a call made before a progress reset never runs after it, not even as
491
+ // a conflict's re-apply, since what it was spending belongs to the old
492
+ // playthrough. It answers 'busy'.
493
+ async function change(a, op, admitted) {
494
+ const api = storage();
495
+ const stale = () => a.epoch !== admitted.epoch ||
496
+ (admitted.generation !== null && a.base !== null && a.base.generation !== admitted.generation);
497
+ // The invariant's last word: nothing is sent under any other generation.
498
+ const unbound = () => admitted.generation === null || a.base === null || a.base.generation !== admitted.generation;
499
+ if (a.locked) {
500
+ return LOCKED;
501
+ }
502
+ if (stale()) {
503
+ return BUSY;
504
+ }
505
+ if (!(await settlePending(a, api))) {
506
+ return a.locked ? LOCKED : BUSY;
507
+ }
508
+ if (!a.state && !(await load(a, api))) {
509
+ return a.locked ? LOCKED : BUSY;
510
+ }
511
+ if (stale()) {
512
+ return BUSY;
513
+ }
514
+ for (let conflicts = 0; ;) {
515
+ const out = op(a.state, a.exists);
516
+ if (!out.next) {
517
+ return { ok: false, why: out.why };
518
+ }
519
+ if (stale() || unbound()) {
520
+ return BUSY;
521
+ }
522
+ const intent = intend(a, out.next);
523
+ const sent = await send(a, api, intent, false);
524
+ if (sent.kind === 'ok') {
525
+ settled(a, intent, sent);
526
+ return { ok: true, coins: intent.next.coins };
527
+ }
528
+ if (sent.kind === 'locked') {
529
+ return LOCKED;
530
+ }
531
+ if (sent.kind === 'unknown') {
532
+ a.pending = intent;
533
+ return BUSY;
534
+ }
535
+ if (sent.kind === 'reset') {
536
+ // The account was reset under it: what it was spending is gone. Read
537
+ // the reset wallet; the caller offers again from that.
538
+ a.state = null;
539
+ a.base = null;
540
+ await load(a, api);
541
+ return a.locked ? LOCKED : BUSY;
542
+ }
543
+ // Another server wrote first: adopt the stored wallet and apply the
544
+ // same operation once more against it.
545
+ conflicts += 1;
546
+ if (!(await adopt(a, api, sent.error, intent.epoch))) {
547
+ return a.locked ? LOCKED : BUSY;
548
+ }
549
+ if (conflicts >= 2 || stale()) {
550
+ return BUSY;
551
+ }
552
+ }
553
+ }
554
+
555
+ function guest(k) {
556
+ let g = guests.get(k);
557
+ if (!g) {
558
+ g = { state: fresh(), exists: false };
559
+ guests.set(k, g);
560
+ }
561
+ return g;
562
+ }
563
+ function guestChange(k, op) {
564
+ const g = guest(k);
565
+ const out = op(g.state, g.exists);
566
+ if (!out.next) {
567
+ return { ok: false, why: out.why };
568
+ }
569
+ g.state = out.next;
570
+ g.exists = true;
571
+ return { ok: true, coins: g.state.coins };
572
+ }
573
+ function run(playerId, op) {
574
+ const who = identify(playerId);
575
+ if (!who) {
576
+ return Promise.resolve(LOCKED);
577
+ }
578
+ if (!who.stored) {
579
+ return Promise.resolve().then(() => guestChange(who.key, op));
580
+ }
581
+ const a = account(who.userId);
582
+ // INVARIANT: every admitted call is bound to one concrete reset generation
583
+ // -- the newest one any read of this account had seen when it was
584
+ // admitted, or, if none had, the first one a read sees after it (its own
585
+ // load's first `resetGeneration`, or one already in flight). A call that
586
+ // would write under any other generation answers 'busy' without writing:
587
+ // a reset between admission and write (seen by the kit's hook, a write's
588
+ // fence, or any later read, including the retry inside a first load)
589
+ // never lets an older call land in the new playthrough.
590
+ const admitted = { epoch: a.epoch, generation: a.observed ?? a.base?.generation ?? null };
591
+ if (admitted.generation === null) {
592
+ a.unbound.add(admitted);
593
+ }
594
+ return enqueue(a, () => change(a, op, admitted), BUSY).finally(() => a.unbound.delete(admitted));
595
+ }
596
+ const argError = (message) => Promise.reject(new TypeError(`hub.wallet: ${message}`));
597
+
598
+ const api = Object.freeze({
599
+ read(playerId) {
600
+ const who = identify(playerId);
601
+ if (!who) {
602
+ return Promise.resolve(null);
603
+ }
604
+ if (!who.stored) {
605
+ return Promise.resolve(view(guest(who.key).state));
606
+ }
607
+ const a = account(who.userId);
608
+ return enqueue(a, async () => {
609
+ const storageApi = storage();
610
+ if (a.locked) {
611
+ return null;
612
+ }
613
+ if (!(await settlePending(a, storageApi))) {
614
+ // A write whose outcome is still unknown: no balance is true yet.
615
+ return null;
616
+ }
617
+ // A read is always fresh: another room may have written since.
618
+ return (await load(a, storageApi)) ? view(a.state) : null;
619
+ }, null);
620
+ },
621
+ spend(playerId, spec) {
622
+ const { cost, add, data } = spec ?? {};
623
+ if (!amountOk(cost)) {return argError('cost must be a non-negative safe integer.');}
624
+ if (add !== undefined && (typeof add !== 'string' || !ITEM_ID.test(add))) {return argError('add must be an item id.');}
625
+ if (data !== undefined && !isPlain(data)) {return argError('data must be a plain object.');}
626
+ return run(playerId, spendOp(cost, add, data));
627
+ },
628
+ earn(playerId, amount, options) {
629
+ const data = options?.data;
630
+ if (!amountOk(amount)) {return argError('amount must be a non-negative safe integer.');}
631
+ if (data !== undefined && !isPlain(data)) {return argError('data must be a plain object.');}
632
+ return run(playerId, earnOp(amount, data));
633
+ },
634
+ seed(playerId, spec) {
635
+ const { coins, owned = [] } = spec ?? {};
636
+ if (!amountOk(coins)) {return argError('coins must be a non-negative safe integer.');}
637
+ if (!Array.isArray(owned) || owned.length > MAX_OWNED || owned.some((id) => typeof id !== 'string' || !ITEM_ID.test(id))) {
638
+ return argError(`owned must be at most ${MAX_OWNED} item ids.`);
639
+ }
640
+ return run(playerId, seedOp(coins, [...new Set(owned)]));
641
+ },
642
+ });
643
+
644
+ return {
645
+ api,
646
+ // A progress reset of this account: forget the cache, any lock and any
647
+ // unknown write (its fence refuses it now); the next call reads again.
648
+ reset(userId) {
649
+ const a = accounts.get(String(userId));
650
+ if (!a) {
651
+ return;
652
+ }
653
+ a.epoch += 1;
654
+ a.observed = null;
655
+ a.state = null;
656
+ a.base = null;
657
+ a.locked = null;
658
+ a.pending = null;
659
+ },
660
+ // The account left: drop it once idle, unless one of its players is here.
661
+ forget(userId, present) {
662
+ const a = accounts.get(String(userId));
663
+ if (!a) {
664
+ return;
665
+ }
666
+ void a.tail.then(() => {
667
+ if (accounts.get(a.userId) === a && a.waiting === 0 && !a.pending && !present(a.userId)) {
668
+ accounts.delete(a.userId);
669
+ }
670
+ });
671
+ },
672
+ // Settles once every account's queued work has (shutdown).
673
+ settled: () => Promise.all([...accounts.values()].map((a) => a.tail)),
674
+ // Test seam.
675
+ accounts,
676
+ };
677
+ }