castle-web-cli 0.4.157 → 0.4.158

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 (243) hide show
  1. package/dist/agent-failures.d.ts +1 -0
  2. package/dist/agent-failures.js +6 -4
  3. package/dist/agent-prompts.js +4 -0
  4. package/dist/agent.d.ts +11 -0
  5. package/dist/agent.js +175 -15
  6. package/dist/bundle.js +8 -2
  7. package/dist/castle-host/host.js +4 -2
  8. package/dist/castleJson.js +6 -1
  9. package/dist/check.d.ts +1 -0
  10. package/dist/check.js +25 -0
  11. package/dist/devSessionServer.js +31 -7
  12. package/dist/imports.js +1 -19
  13. package/dist/index.js +15 -1
  14. package/dist/init.d.ts +2 -2
  15. package/dist/init.js +78 -42
  16. package/dist/mcpPlaytest.d.ts +1 -0
  17. package/dist/mcpPlaytest.js +182 -0
  18. package/dist/metering.d.ts +24 -0
  19. package/dist/metering.js +87 -0
  20. package/dist/sdkResolve.d.ts +3 -0
  21. package/dist/sdkResolve.js +55 -0
  22. package/dist/serve.js +50 -4
  23. package/dist/serverBundle.js +8 -3
  24. package/dist/shell/assets/{index-DsDkYFvP.js → index-BuSYLy-C.js} +64 -64
  25. package/dist/shell/assets/{index-DwezawBs.css → index-DfZmu3XC.css} +1 -1
  26. package/dist/shell/index.html +2 -2
  27. package/dist/vitePlugins.d.ts +1 -0
  28. package/dist/vitePlugins.js +20 -0
  29. package/kits/base/CLAUDE.md +196 -0
  30. package/kits/{blank → base}/castle.json +5 -2
  31. package/kits/base/editorHost.js +172 -0
  32. package/kits/{blank → base}/node_modules/.package-lock.json +3 -2
  33. package/kits/{blank → base}/package-lock.json +7 -4
  34. package/kits/{blank → base}/package.json +4 -2
  35. package/kits/base/sdk/README.md +569 -0
  36. package/kits/base/sdk/castle.d.ts +27 -0
  37. package/kits/base/sdk/castle.js +16 -0
  38. package/kits/base/sdk/commands.d.ts +181 -0
  39. package/kits/base/sdk/commands.js +16 -0
  40. package/kits/base/sdk/context.d.ts +17 -0
  41. package/kits/base/sdk/context.js +15 -0
  42. package/kits/base/sdk/errors.d.ts +22 -0
  43. package/kits/base/sdk/errors.js +16 -0
  44. package/kits/base/sdk/files.d.ts +15 -0
  45. package/kits/base/sdk/files.js +52 -0
  46. package/kits/base/sdk/haptics.d.ts +6 -0
  47. package/kits/base/sdk/haptics.js +36 -0
  48. package/kits/base/sdk/leaderboard.d.ts +26 -0
  49. package/kits/base/sdk/leaderboard.js +296 -0
  50. package/kits/base/sdk/lifecycle.d.ts +4 -0
  51. package/kits/base/sdk/lifecycle.js +13 -0
  52. package/kits/base/sdk/multiplayer.d.ts +43 -0
  53. package/kits/base/sdk/multiplayer.js +464 -0
  54. package/kits/base/sdk/multiplayerProtocol.d.ts +51 -0
  55. package/kits/base/sdk/multiplayerProtocol.js +5 -0
  56. package/kits/base/sdk/passes.d.ts +7 -0
  57. package/kits/base/sdk/passes.js +84 -0
  58. package/kits/base/sdk/portal.d.ts +7 -0
  59. package/kits/base/sdk/portal.js +35 -0
  60. package/kits/base/sdk/runtime.d.ts +62 -0
  61. package/kits/base/sdk/runtime.js +970 -0
  62. package/kits/base/sdk/saveQueue.d.ts +27 -0
  63. package/kits/base/sdk/saveQueue.js +205 -0
  64. package/kits/base/sdk/server/platformHandle.d.ts +25 -0
  65. package/kits/base/sdk/server/platformHandle.js +1 -0
  66. package/kits/base/sdk/server/wrapper.d.ts +28 -0
  67. package/kits/base/sdk/server/wrapper.js +109 -0
  68. package/kits/base/sdk/storage.d.ts +16 -0
  69. package/kits/base/sdk/storage.js +323 -0
  70. package/kits/base/sdk/time.d.ts +17 -0
  71. package/kits/base/sdk/time.js +120 -0
  72. package/kits/base/sdk/transport.d.ts +17 -0
  73. package/kits/base/sdk/transport.js +141 -0
  74. package/kits/base/sdk/types.d.ts +3 -0
  75. package/kits/base/sdk/types.js +1 -0
  76. package/kits/base/sdk/user.d.ts +10 -0
  77. package/kits/base/sdk/user.js +45 -0
  78. package/kits/multiplayer-2d/.prettierrc +5 -0
  79. package/kits/multiplayer-2d/CLAUDE.md +129 -0
  80. package/kits/multiplayer-2d/behaviors/Box.jsx +92 -0
  81. package/kits/multiplayer-2d/behaviors/Player.jsx +86 -0
  82. package/kits/multiplayer-2d/blueprints/crate.scene +13 -0
  83. package/kits/multiplayer-2d/blueprints/other-player.scene +13 -0
  84. package/kits/multiplayer-2d/blueprints/player.scene +15 -0
  85. package/kits/multiplayer-2d/blueprints/wall.scene +12 -0
  86. package/kits/multiplayer-2d/castle.json +39 -0
  87. package/kits/multiplayer-2d/code/client/avatars.js +79 -0
  88. package/kits/multiplayer-2d/code/client/poses.js +168 -0
  89. package/kits/multiplayer-2d/code/server/index.js +26 -0
  90. package/kits/multiplayer-2d/code/server/limits.js +99 -0
  91. package/kits/multiplayer-2d/code/server/ownership.js +177 -0
  92. package/kits/multiplayer-2d/code/server/players.js +127 -0
  93. package/kits/multiplayer-2d/code/server/sceneBodies.js +98 -0
  94. package/kits/multiplayer-2d/code/server/world.js +337 -0
  95. package/kits/multiplayer-2d/code/systems/multiplayer.js +424 -0
  96. package/kits/multiplayer-2d/eslint.config.js +21 -0
  97. package/kits/multiplayer-2d/fonts.generated.js +9 -0
  98. package/kits/multiplayer-2d/index.html +25 -0
  99. package/kits/multiplayer-2d/main.jsx +10 -0
  100. package/kits/multiplayer-2d/package-lock.json +351 -0
  101. package/kits/multiplayer-2d/package.json +30 -0
  102. package/kits/multiplayer-2d/scenes/main.scene +20 -0
  103. package/kits/multiplayer-2d/test/two-client-test.mjs +341 -0
  104. package/kits/multiplayer-2d/theme.style +4 -0
  105. package/kits/multiplayer-3d/.prettierrc +5 -0
  106. package/kits/multiplayer-3d/CLAUDE.md +215 -0
  107. package/kits/multiplayer-3d/blueprints/ball.scene +21 -0
  108. package/kits/multiplayer-3d/blueprints/other-player.scene +21 -0
  109. package/kits/multiplayer-3d/castle.json +43 -0
  110. package/kits/multiplayer-3d/code/client/avatars.js +136 -0
  111. package/kits/multiplayer-3d/code/client/nameTags.js +101 -0
  112. package/kits/multiplayer-3d/code/client/poses.js +220 -0
  113. package/kits/multiplayer-3d/code/server/index.js +23 -0
  114. package/kits/multiplayer-3d/code/server/limits.js +107 -0
  115. package/kits/multiplayer-3d/code/server/ownership.js +157 -0
  116. package/kits/multiplayer-3d/code/server/players.js +114 -0
  117. package/kits/multiplayer-3d/code/server/sceneBodies.js +88 -0
  118. package/kits/multiplayer-3d/code/server/world.js +306 -0
  119. package/kits/multiplayer-3d/code/systems/multiplayer.js +427 -0
  120. package/kits/multiplayer-3d/eslint.config.js +20 -0
  121. package/kits/multiplayer-3d/fonts.generated.js +9 -0
  122. package/kits/multiplayer-3d/index.html +22 -0
  123. package/kits/multiplayer-3d/main.jsx +9 -0
  124. package/kits/multiplayer-3d/package-lock.json +368 -0
  125. package/kits/multiplayer-3d/package.json +32 -0
  126. package/kits/multiplayer-3d/scenes/main.scene +409 -0
  127. package/kits/multiplayer-3d/theme.style +3 -0
  128. package/kits/physics-2d/CLAUDE.md +6 -0
  129. package/kits/physics-2d/castle.json +7 -1
  130. package/kits/physics-2d/editors/behaviorRegistry.js +5 -0
  131. package/kits/physics-2d/editors/editorRegistry.jsx +3 -1
  132. package/kits/physics-2d/engine/files.js +9 -5
  133. package/kits/physics-2d/engine/systemRegistry.js +2 -0
  134. package/kits/physics-2d/engine/ui.module.css +11 -0
  135. package/kits/physics-2d/package-lock.json +8 -2
  136. package/kits/physics-2d/package.json +2 -2
  137. package/kits/physics-3d/CLAUDE.md +4 -4
  138. package/kits/physics-3d/behaviors/Shape.jsx +1 -1
  139. package/kits/physics-3d/blueprints/crate.scene +1 -1
  140. package/kits/physics-3d/blueprints/door.scene +4 -4
  141. package/kits/physics-3d/blueprints/pillar.scene +1 -1
  142. package/kits/physics-3d/blueprints/platform.scene +1 -1
  143. package/kits/physics-3d/blueprints/statue.scene +1 -1
  144. package/kits/physics-3d/blueprints/wall.scene +1 -1
  145. package/kits/physics-3d/castle.json +8 -11
  146. package/kits/physics-3d/docs/pxmodel-format.md +1 -1
  147. package/kits/physics-3d/engine3d/materials.js +3 -3
  148. package/kits/physics-3d/engine3d/modelFiles.js +4 -2
  149. package/kits/physics-3d/engine3d/world3d.js +1 -1
  150. package/kits/physics-3d/fonts.generated.js +9 -0
  151. package/kits/physics-3d/main.jsx +1 -1
  152. package/kits/physics-3d/package-lock.json +85 -2
  153. package/kits/physics-3d/package.json +6 -2
  154. package/kits/physics-3d/scenes/main.scene +1 -1
  155. package/kits/physics-3d/scenes/model-lab.scene +1 -1
  156. package/kits/real-time/.prettierrc +5 -0
  157. package/kits/real-time/CLAUDE.md +60 -0
  158. package/kits/real-time/castle.json +19 -0
  159. package/kits/real-time/code/client/clock.js +68 -0
  160. package/kits/real-time/code/client/connection.js +134 -0
  161. package/kits/real-time/code/client/gameHooks.js +50 -0
  162. package/kits/real-time/code/client/interpolate.js +82 -0
  163. package/kits/real-time/code/client/messages.js +55 -0
  164. package/kits/real-time/code/client/ownership.js +94 -0
  165. package/kits/real-time/code/client/smooth.js +54 -0
  166. package/kits/real-time/code/server/blockDelta.js +48 -0
  167. package/kits/real-time/code/server/gameHooks.js +47 -0
  168. package/kits/real-time/code/server/limits.js +35 -0
  169. package/kits/real-time/code/server/session.js +251 -0
  170. package/kits/real-time/eslint.config.js +22 -0
  171. package/kits/real-time/index.html +45 -0
  172. package/kits/real-time/package.json +14 -0
  173. package/kits/{tabletop → turn-based}/CLAUDE.md +42 -49
  174. package/kits/turn-based/blueprints/board.scene +15 -0
  175. package/kits/turn-based/blueprints/square.scene +25 -0
  176. package/kits/turn-based/castle.json +37 -0
  177. package/kits/turn-based/code/behaviors/Board.jsx +169 -0
  178. package/kits/turn-based/code/behaviors/Square.jsx +26 -0
  179. package/kits/turn-based/code/server/index.js +152 -0
  180. package/kits/turn-based/drawings/square.sprite +25 -0
  181. package/kits/turn-based/eslint.config.js +12 -0
  182. package/kits/turn-based/fonts.generated.js +9 -0
  183. package/kits/{tabletop → turn-based}/index.html +5 -3
  184. package/kits/{tabletop → turn-based}/main.jsx +2 -2
  185. package/kits/{tabletop → turn-based}/package-lock.json +17 -4
  186. package/kits/{tabletop → turn-based}/package.json +5 -2
  187. package/kits/turn-based/room.js +289 -0
  188. package/kits/turn-based/scenes/main.scene +227 -0
  189. package/kits/{tabletop → turn-based}/testing.js +131 -99
  190. package/kits/turn-based/theme.style +3 -0
  191. package/package.json +1 -1
  192. package/kits/blank/CLAUDE.md +0 -198
  193. package/kits/tabletop/castle.json +0 -34
  194. package/kits/tabletop/room.js +0 -269
  195. /package/kits/{blank → base}/index.html +0 -0
  196. /package/kits/{blank → base}/node_modules/castle-web-fonts/README.md +0 -0
  197. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.d.ts +0 -0
  198. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/catalog.js +0 -0
  199. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.d.ts +0 -0
  200. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/face.js +0 -0
  201. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.d.ts +0 -0
  202. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Bore.js +0 -0
  203. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.d.ts +0 -0
  204. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/CourierPrime.js +0 -0
  205. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.d.ts +0 -0
  206. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/DMSans.js +0 -0
  207. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.d.ts +0 -0
  208. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Glacier.js +0 -0
  209. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.d.ts +0 -0
  210. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/HelicoCentrica.js +0 -0
  211. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.d.ts +0 -0
  212. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Piazzolla.js +0 -0
  213. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.d.ts +0 -0
  214. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Synco.js +0 -0
  215. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.d.ts +0 -0
  216. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/Tektur.js +0 -0
  217. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.d.ts +0 -0
  218. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/faces/YatraOne.js +0 -0
  219. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.d.ts +0 -0
  220. /package/kits/{blank → base}/node_modules/castle-web-fonts/dist/index.js +0 -0
  221. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/CC-BY-ND-4.0.txt +0 -0
  222. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/FONTS.md +0 -0
  223. /package/kits/{blank → base}/node_modules/castle-web-fonts/licenses/OFL-1.1.txt +0 -0
  224. /package/kits/{blank → base}/node_modules/castle-web-fonts/package.json +0 -0
  225. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Bore.woff2 +0 -0
  226. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/CourierPrime.woff2 +0 -0
  227. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/DMSans.woff2 +0 -0
  228. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Glacier.woff2 +0 -0
  229. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/HelicoCentrica.woff2 +0 -0
  230. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Piazzolla.woff2 +0 -0
  231. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/SOURCE.txt +0 -0
  232. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Synco.woff2 +0 -0
  233. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/Tektur.woff2 +0 -0
  234. /package/kits/{blank → base}/node_modules/castle-web-fonts/woff2/YatraOne.woff2 +0 -0
  235. /package/kits/physics-3d/drawings/{crate.pxart → crate.sprite} +0 -0
  236. /package/kits/physics-3d/drawings/{door-edge.pxart → door-edge.sprite} +0 -0
  237. /package/kits/physics-3d/drawings/{door.pxart → door.sprite} +0 -0
  238. /package/kits/physics-3d/drawings/{face.pxart → face.sprite} +0 -0
  239. /package/kits/physics-3d/drawings/{floor.pxart → floor.sprite} +0 -0
  240. /package/kits/physics-3d/drawings/{platform.pxart → platform.sprite} +0 -0
  241. /package/kits/physics-3d/drawings/{statue.pxart → statue.sprite} +0 -0
  242. /package/kits/physics-3d/drawings/{wall.pxart → wall.sprite} +0 -0
  243. /package/kits/{tabletop → turn-based}/.prettierrc +0 -0
@@ -0,0 +1,27 @@
1
+ /** What is waiting to reach disk, and why it hasn't -- for a save indicator. */
2
+ export interface SaveState {
3
+ /** Paths whose newest text the serve has not acknowledged. */
4
+ pending: string[];
5
+ /** The last failure's message, while saves are still failing. */
6
+ error: string | null;
7
+ }
8
+ /**
9
+ * Write `text` to `path`, durably: the newest text per path is held until the
10
+ * serve acknowledges it, retried when it doesn't, and kept across a reload.
11
+ *
12
+ * The returned promise settles with the FIRST attempt -- it rejecting means "not
13
+ * yet", not "lost", and callers that want to say something about that should use
14
+ * `onSaveState` rather than this promise. Anything that truly needs one attempt
15
+ * and a hard failure wants `writeFileOnce`.
16
+ */
17
+ export declare function writeFile(path: string, text: string): Promise<void>;
18
+ /**
19
+ * Attempt every queued save once, resolving when they have all settled
20
+ * (whatever the outcome). What a reload hook wants: give the writes their best
21
+ * shot, then get on with it -- never block on a serve that isn't answering.
22
+ */
23
+ export declare function flushSaves(): Promise<void>;
24
+ /** True while `path` holds text the serve hasn't acknowledged. */
25
+ export declare function hasPendingSave(path: string): boolean;
26
+ /** Subscribe to the queue's state; fires on every change, and once immediately. */
27
+ export declare function onSaveState(listener: (state: SaveState) => void): () => void;
@@ -0,0 +1,205 @@
1
+ // Deck-file writes. `writeFile` lives here rather than beside the socket in
2
+ // runtime.ts because writing a file is not the same thing as getting a request
3
+ // through: the request is `writeFileOnce`, and this is the part that sees it
4
+ // done.
5
+ //
6
+ // It used to be the other way around -- the plain write WAS the one-shot request
7
+ // -- which meant every editor got fire-and-forget semantics by default and a
8
+ // failure left the edit gone while the canvas showed it as saved. Durability is
9
+ // the default now, and the one-shot is the thing you have to ask for.
10
+ //
11
+ // The socket is down more often than it looks from a desktop. A cloud sandbox
12
+ // sits behind a load balancer that closes idle connections after 60s, a phone
13
+ // that sleeps drops every connection it had, and reconnecting takes a couple of
14
+ // seconds after the tab wakes -- none of which is visible to someone dragging an
15
+ // actor around.
16
+ //
17
+ // So a save here is a QUEUE ENTRY rather than a request: the newest text per
18
+ // path is held until the serve acknowledges it, retried with backoff, and
19
+ // flushed the moment the socket comes back. Callers still see the outcome of
20
+ // the FIRST attempt (an editor may want to say something), but they no longer
21
+ // own it -- a rejected promise means "not yet", not "lost".
22
+ import { onLocalConnection, reconnectIfSocketIsDead, writeFileOnce } from "./runtime";
23
+ // Queued text outlives the page, because the page does not reliably outlive the
24
+ // outage: when a dev serve restarts, its client reloads every page it is
25
+ // serving, and an in-memory queue would go with them -- losing exactly the
26
+ // edits it exists to protect. Scoped by origin (localStorage already is, and a
27
+ // deck is served on its own origin), and given a life short enough that
28
+ // restoring can't resurrect yesterday's work over something newer on disk.
29
+ const STORAGE_KEY = "castle-save-queue-v1";
30
+ const RESTORE_WINDOW_MS = 30 * 60 * 1000;
31
+ // Flat tail rather than terminal.ts's give-up: nothing else would ever restart
32
+ // a save. A serve that comes back after ten minutes is still worth writing to,
33
+ // and one attempt every 15s costs nothing while it doesn't.
34
+ const RETRY_DELAYS_MS = [500, 1000, 2000, 4000, 8000, 15000];
35
+ const queue = new Map();
36
+ // One promise chain per path, so two saves of the same file can't be in flight
37
+ // at once (the loser would win on the serve half the time).
38
+ const chains = new Map();
39
+ const listeners = new Set();
40
+ let nextVersion = 1;
41
+ let retryTimer = null;
42
+ let retryAttempt = 0;
43
+ let lastError = null;
44
+ function messageOf(error) {
45
+ return error instanceof Error ? error.message : String(error);
46
+ }
47
+ function state() {
48
+ return { pending: [...queue.keys()], error: queue.size > 0 ? lastError : null };
49
+ }
50
+ function persist() {
51
+ try {
52
+ if (queue.size === 0) {
53
+ localStorage.removeItem(STORAGE_KEY);
54
+ return;
55
+ }
56
+ const entries = {};
57
+ for (const [path, entry] of queue)
58
+ entries[path] = entry.text;
59
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ savedAt: Date.now(), entries }));
60
+ }
61
+ catch {
62
+ // No storage, or full. The in-memory queue still works; only surviving a
63
+ // reload is lost, and there is nothing useful to say about it here.
64
+ }
65
+ }
66
+ // Text queued by a previous page, re-queued so it lands as soon as there is a
67
+ // socket. Refusals (a protected path, a size cap) resolve rather than reject,
68
+ // so nothing that the serve actively said no to can come back this way.
69
+ function restore() {
70
+ let raw = null;
71
+ try {
72
+ raw = localStorage.getItem(STORAGE_KEY);
73
+ }
74
+ catch {
75
+ return;
76
+ }
77
+ if (!raw)
78
+ return;
79
+ try {
80
+ const saved = JSON.parse(raw);
81
+ const savedAt = typeof saved.savedAt === "number" ? saved.savedAt : 0;
82
+ if (Date.now() - savedAt > RESTORE_WINDOW_MS) {
83
+ localStorage.removeItem(STORAGE_KEY);
84
+ return;
85
+ }
86
+ for (const [path, text] of Object.entries(saved.entries ?? {})) {
87
+ if (typeof text === "string")
88
+ queue.set(path, { text, version: nextVersion++ });
89
+ }
90
+ }
91
+ catch {
92
+ localStorage.removeItem(STORAGE_KEY);
93
+ }
94
+ }
95
+ function notify() {
96
+ persist();
97
+ const snapshot = state();
98
+ for (const listener of listeners) {
99
+ try {
100
+ listener(snapshot);
101
+ }
102
+ catch {
103
+ /* one indicator's failure shouldn't stop the next */
104
+ }
105
+ }
106
+ }
107
+ function clearRetry() {
108
+ if (retryTimer === null)
109
+ return;
110
+ clearTimeout(retryTimer);
111
+ retryTimer = null;
112
+ }
113
+ function scheduleRetry() {
114
+ if (retryTimer !== null || queue.size === 0)
115
+ return;
116
+ const delay = RETRY_DELAYS_MS[Math.min(retryAttempt, RETRY_DELAYS_MS.length - 1)];
117
+ retryAttempt += 1;
118
+ retryTimer = setTimeout(() => {
119
+ retryTimer = null;
120
+ void flushSaves();
121
+ }, delay);
122
+ }
123
+ // One attempt at whatever `path` currently holds. Anything queued while this is
124
+ // in flight is picked up by the next link in the chain, so the newest text
125
+ // always gets its own attempt.
126
+ async function sendOnce(path) {
127
+ const entry = queue.get(path);
128
+ if (!entry)
129
+ return; // already acknowledged, by this chain or a newer save
130
+ try {
131
+ await writeFileOnce(path, entry.text);
132
+ }
133
+ catch (error) {
134
+ lastError = messageOf(error);
135
+ // A write that failed over a socket still reporting OPEN means the socket
136
+ // is lying: replace it now rather than spending the whole backoff posting
137
+ // into it. Retrying is still scheduled -- the fresh socket is what the
138
+ // retry will find, and `onLocalConnection` pulls the flush forward anyway.
139
+ reconnectIfSocketIsDead();
140
+ scheduleRetry();
141
+ notify();
142
+ throw error;
143
+ }
144
+ const current = queue.get(path);
145
+ if (current && current.version === entry.version)
146
+ queue.delete(path);
147
+ if (queue.size === 0) {
148
+ lastError = null;
149
+ retryAttempt = 0;
150
+ clearRetry();
151
+ }
152
+ notify();
153
+ }
154
+ function attempt(path) {
155
+ const previous = chains.get(path) ?? Promise.resolve();
156
+ const next = previous.then(() => sendOnce(path));
157
+ // The stored link swallows failures so the chain survives one: the retry is
158
+ // the queue's job, and an unhandled rejection here would be noise.
159
+ chains.set(path, next.catch(() => undefined));
160
+ return next;
161
+ }
162
+ /**
163
+ * Write `text` to `path`, durably: the newest text per path is held until the
164
+ * serve acknowledges it, retried when it doesn't, and kept across a reload.
165
+ *
166
+ * The returned promise settles with the FIRST attempt -- it rejecting means "not
167
+ * yet", not "lost", and callers that want to say something about that should use
168
+ * `onSaveState` rather than this promise. Anything that truly needs one attempt
169
+ * and a hard failure wants `writeFileOnce`.
170
+ */
171
+ export function writeFile(path, text) {
172
+ queue.set(path, { text, version: nextVersion++ });
173
+ notify();
174
+ return attempt(path);
175
+ }
176
+ /**
177
+ * Attempt every queued save once, resolving when they have all settled
178
+ * (whatever the outcome). What a reload hook wants: give the writes their best
179
+ * shot, then get on with it -- never block on a serve that isn't answering.
180
+ */
181
+ export function flushSaves() {
182
+ const paths = [...queue.keys()];
183
+ return Promise.all(paths.map((path) => attempt(path).catch(() => undefined))).then(() => undefined);
184
+ }
185
+ /** True while `path` holds text the serve hasn't acknowledged. */
186
+ export function hasPendingSave(path) {
187
+ return queue.has(path);
188
+ }
189
+ /** Subscribe to the queue's state; fires on every change, and once immediately. */
190
+ export function onSaveState(listener) {
191
+ listeners.add(listener);
192
+ listener(state());
193
+ return () => listeners.delete(listener);
194
+ }
195
+ // A fresh socket is the one moment a retry is known to be worth taking, so the
196
+ // backoff resets and the queue drains immediately instead of waiting out a
197
+ // delay that was scheduled against a connection that no longer exists.
198
+ onLocalConnection((connected) => {
199
+ if (!connected || queue.size === 0)
200
+ return;
201
+ retryAttempt = 0;
202
+ clearRetry();
203
+ void flushSaves();
204
+ });
205
+ restore();
@@ -0,0 +1,25 @@
1
+ export type MultiplayerSessionMode = "named" | "party" | "public";
2
+ export interface PlayerIdentity {
3
+ userId: string;
4
+ username: string;
5
+ isAnonymous: boolean;
6
+ scopedUserId?: string;
7
+ }
8
+ export interface PlatformSessionConfig {
9
+ readonly sessionId: string;
10
+ readonly deckId: string;
11
+ readonly mode: MultiplayerSessionMode;
12
+ readonly tickRate: number;
13
+ readonly maxPlayers: number;
14
+ }
15
+ export interface PlatformHandle {
16
+ send(connId: string, text: string): void;
17
+ broadcast(text: string): void;
18
+ disconnect(connId: string, code: string | number): void;
19
+ on(event: "join", callback: (connId: string, player: PlayerIdentity) => unknown): void;
20
+ on(event: "leave", callback: (connId: string) => unknown): void;
21
+ on(event: "message", callback: (connId: string, text: string) => unknown): void;
22
+ on(event: "replaced", callback: () => unknown): void;
23
+ on(event: "shutdown", callback: (reason?: string) => unknown): void;
24
+ readonly config: PlatformSessionConfig;
25
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,28 @@
1
+ import type { MultiplayerSessionMode, PlatformHandle, PlayerIdentity } from "./platformHandle";
2
+ export type { MultiplayerSessionMode, PlatformHandle, PlatformSessionConfig, PlayerIdentity, } from "./platformHandle";
3
+ export interface MultiplayerServerPlayer extends PlayerIdentity {
4
+ playerId: string;
5
+ }
6
+ export interface MultiplayerBroadcastOptions {
7
+ except?: string;
8
+ }
9
+ export interface MultiplayerServerSession {
10
+ readonly players: MultiplayerServerPlayer[];
11
+ readonly sessionId: string;
12
+ readonly deckId: string;
13
+ readonly mode: MultiplayerSessionMode;
14
+ send(playerId: string, data: unknown): void;
15
+ broadcast(data: unknown, options?: MultiplayerBroadcastOptions): void;
16
+ disconnect(playerId: string, reason?: string): void;
17
+ }
18
+ type CallbackResult = unknown | Promise<unknown>;
19
+ export interface MultiplayerServerCallbacks {
20
+ onStart?: (session: MultiplayerServerSession) => CallbackResult;
21
+ onPlayerJoin?: (session: MultiplayerServerSession, player: MultiplayerServerPlayer) => CallbackResult;
22
+ onPlayerLeave?: (session: MultiplayerServerSession, player: MultiplayerServerPlayer) => CallbackResult;
23
+ onMessage?: (session: MultiplayerServerSession, player: MultiplayerServerPlayer, data: unknown) => CallbackResult;
24
+ onTick?: (session: MultiplayerServerSession) => CallbackResult;
25
+ onReplaced?: (session: MultiplayerServerSession) => CallbackResult;
26
+ }
27
+ export type CastleSessionBoot = (platformHandle: PlatformHandle) => Promise<void>;
28
+ export declare function createCastleSessionBoot(callbacks: MultiplayerServerCallbacks): CastleSessionBoot;
@@ -0,0 +1,109 @@
1
+ // The publish bundler binds the author's default callbacks export once and
2
+ // exports the returned one-argument function as `__castleBootSession`.
3
+ export function createCastleSessionBoot(callbacks) {
4
+ return async function __castleBootSession(platformHandle) {
5
+ await bootSession(platformHandle, callbacks);
6
+ };
7
+ }
8
+ async function bootSession(platformHandle, callbacks) {
9
+ const players = new Map();
10
+ const session = createAuthorSession(platformHandle, players);
11
+ let tickTimer = null;
12
+ platformHandle.on("join", async (connId, identity) => {
13
+ // The compatibility branch accepts the current Node shim's legacy
14
+ // single-argument SessionPlayer event while the public handle contract uses
15
+ // the runtime-agnostic (connId, trusted identity) pair.
16
+ const player = joinedPlayer(connId, identity);
17
+ players.set(player.playerId, player);
18
+ await callbacks.onPlayerJoin?.(session, player);
19
+ });
20
+ platformHandle.on("leave", async (connId) => {
21
+ const player = players.get(connId);
22
+ players.delete(connId);
23
+ if (player)
24
+ await callbacks.onPlayerLeave?.(session, player);
25
+ });
26
+ platformHandle.on("message", async (connId, text) => {
27
+ const player = players.get(connId);
28
+ if (!player)
29
+ return;
30
+ await callbacks.onMessage?.(session, player, parseHandleMessage(text));
31
+ });
32
+ platformHandle.on("replaced", async () => {
33
+ await callbacks.onReplaced?.(session);
34
+ });
35
+ platformHandle.on("shutdown", () => {
36
+ if (tickTimer !== null)
37
+ clearInterval(tickTimer);
38
+ tickTimer = null;
39
+ });
40
+ await callbacks.onStart?.(session);
41
+ const onTick = callbacks.onTick;
42
+ if (onTick && platformHandle.config.tickRate > 0) {
43
+ tickTimer = setInterval(() => {
44
+ invokeTick(onTick, session);
45
+ }, 1_000 / platformHandle.config.tickRate);
46
+ }
47
+ }
48
+ function createAuthorSession(platformHandle, players) {
49
+ return {
50
+ get players() {
51
+ return Array.from(players.values());
52
+ },
53
+ sessionId: platformHandle.config.sessionId,
54
+ deckId: platformHandle.config.deckId,
55
+ mode: platformHandle.config.mode,
56
+ send(playerId, data) {
57
+ platformHandle.send(playerId, stringifyHandleMessage(data));
58
+ },
59
+ broadcast(data, options) {
60
+ const text = stringifyHandleMessage(data);
61
+ if (!options?.except) {
62
+ platformHandle.broadcast(text);
63
+ return;
64
+ }
65
+ for (const playerId of players.keys()) {
66
+ if (playerId !== options.except)
67
+ platformHandle.send(playerId, text);
68
+ }
69
+ },
70
+ disconnect(playerId, reason) {
71
+ platformHandle.disconnect(playerId, reason ?? 1000);
72
+ },
73
+ };
74
+ }
75
+ function joinedPlayer(connId, identity) {
76
+ if (typeof connId === "string")
77
+ return { ...identity, playerId: connId };
78
+ const legacy = connId;
79
+ return {
80
+ playerId: legacy.playerId,
81
+ userId: legacy.userId,
82
+ username: legacy.username,
83
+ isAnonymous: legacy.isAnonymous,
84
+ ...(legacy.scopedUserId ? { scopedUserId: legacy.scopedUserId } : {}),
85
+ };
86
+ }
87
+ function parseHandleMessage(text) {
88
+ if (typeof text !== "string")
89
+ return text;
90
+ return JSON.parse(text);
91
+ }
92
+ function stringifyHandleMessage(data) {
93
+ const text = JSON.stringify(data);
94
+ if (text === undefined) {
95
+ throw new TypeError("Multiplayer server messages must be JSON-serializable.");
96
+ }
97
+ return text;
98
+ }
99
+ function invokeTick(callback, session) {
100
+ try {
101
+ void Promise.resolve(callback(session)).catch(reportTickError);
102
+ }
103
+ catch (error) {
104
+ reportTickError(error);
105
+ }
106
+ }
107
+ function reportTickError(error) {
108
+ console.error(`onTick failed: ${error instanceof Error ? error.message : String(error)}`);
109
+ }
@@ -0,0 +1,16 @@
1
+ import { type SharedScope } from "./commands";
2
+ import type { Json } from "./types";
3
+ export interface StorageApi {
4
+ get<T extends Json = Json>(key: string): Promise<T | null>;
5
+ set(key: string, value: Json): void;
6
+ remove(key: string): void;
7
+ }
8
+ export interface SharedStorageApi {
9
+ get<T extends Json = Json>(scope: "deck", key: string): Promise<T | null>;
10
+ get<T extends Json = Json>(scope: "user", key: string): Promise<T | null>;
11
+ get<T extends Json = Json>(scope: "user", userId: string, key: string): Promise<T | null>;
12
+ set(scope: SharedScope, key: string, value: Json): void;
13
+ remove(scope: SharedScope, key: string): void;
14
+ }
15
+ export declare const Storage: StorageApi;
16
+ export declare const SharedStorage: SharedStorageApi;