castle-web-cli 0.4.157 → 0.4.159

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-DMSoTyXh.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 +93 -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,323 @@
1
+ import { CastleError } from "./errors";
2
+ import { hostRequest } from "./transport";
3
+ // Writes coalesce by key as they are made, so setting the same key repeatedly
4
+ // costs one entry; this is how often the result is handed to the host. The host, not the deck, talks to the
5
+ // server and owns retry: it lives in the page, so it is still alive to finish a
6
+ // write while the deck's frame is being torn down.
7
+ const FLUSH_INTERVAL_MS = 200;
8
+ // Per-player private storage. The host stamps deckId/sessionId, so one deck
9
+ // session = one stable blob: load once, then serve reads from cache and batch
10
+ // writes on a 2s flush. Dirty writes overlay the server blob so an in-flight
11
+ // write isn't clobbered by the flush response.
12
+ class PrivateStorageImpl {
13
+ cache = new Map();
14
+ dirty = new Map();
15
+ loadPromise = null;
16
+ flushTimer = null;
17
+ async get(key) {
18
+ await this.ensureLoaded();
19
+ return (this.cache.get(key) ?? null);
20
+ }
21
+ set(key, value) {
22
+ this.cache.set(key, value);
23
+ this.dirty.set(key, encodeStorageValue(value, "Storage.set"));
24
+ this.scheduleFlush();
25
+ }
26
+ remove(key) {
27
+ this.cache.delete(key);
28
+ this.dirty.set(key, null);
29
+ this.scheduleFlush();
30
+ }
31
+ ensureLoaded() {
32
+ if (!this.loadPromise) {
33
+ this.loadPromise = this.load().catch((error) => {
34
+ this.loadPromise = null;
35
+ throw error;
36
+ });
37
+ }
38
+ return this.loadPromise;
39
+ }
40
+ async load() {
41
+ const { blob } = await hostRequest("deckStorage.load", {});
42
+ this.cache = decodeStorageBlob(blob, "Storage.get");
43
+ this.overlayDirty();
44
+ }
45
+ async flush(unload = false) {
46
+ if (this.dirty.size === 0)
47
+ return;
48
+ const snapshot = new Map(this.dirty);
49
+ await hostRequest("deckStorage.update", {
50
+ updates: updatesFromDirty(snapshot),
51
+ unload,
52
+ });
53
+ // Staged, not stored: the host has taken ownership, so these stop being the
54
+ // deck's problem. `cache` already carries them from the write.
55
+ clearAcknowledgedDirty(this.dirty, snapshot);
56
+ }
57
+ overlayDirty() {
58
+ for (const [key, encoded] of this.dirty) {
59
+ if (encoded === null)
60
+ this.cache.delete(key);
61
+ else
62
+ this.cache.set(key, decodeStorageValue(encoded, "Storage.dirty"));
63
+ }
64
+ }
65
+ scheduleFlush() {
66
+ hookUnloadFlush();
67
+ if (this.flushTimer)
68
+ return;
69
+ this.flushTimer = setTimeout(() => {
70
+ this.flushTimer = null;
71
+ void this.flush();
72
+ }, FLUSH_INTERVAL_MS);
73
+ }
74
+ flushNow() {
75
+ void this.flush(true);
76
+ }
77
+ }
78
+ // Cross-player storage. Writes always target the current player (the host
79
+ // forces 'user'-scope writes to whoever is signed in), so dirty writes bucket
80
+ // under a fixed key; reads of another player's 'user' bucket take an explicit
81
+ // userId and never have pending writes. Reads coalesce per microtask into one
82
+ // command with a keys[] array.
83
+ class SharedStorageImpl {
84
+ dirtyBuckets = new Map();
85
+ readBatches = new Map();
86
+ flushTimer = null;
87
+ async get(scope, userOrKey, maybeKey) {
88
+ assertScope(scope, "SharedStorage.get");
89
+ const userId = scope === "user" && maybeKey ? userOrKey : undefined;
90
+ const key = maybeKey ?? userOrKey;
91
+ const dirty = this.peekDirty(scope, userId, key);
92
+ if (dirty !== undefined) {
93
+ return (dirty === null ? null : decodeStorageValue(dirty, "SharedStorage.get"));
94
+ }
95
+ return this.queueRead(scope, userId, key);
96
+ }
97
+ set(scope, key, value) {
98
+ assertScope(scope, "SharedStorage.set");
99
+ this.write(scope, key, encodeStorageValue(value, "SharedStorage.set"));
100
+ }
101
+ remove(scope, key) {
102
+ assertScope(scope, "SharedStorage.remove");
103
+ this.write(scope, key, null);
104
+ }
105
+ write(scope, key, encoded) {
106
+ const bucketKey = writeBucketKey(scope);
107
+ const dirty = this.dirtyBuckets.get(bucketKey) ?? new Map();
108
+ dirty.set(key, encoded);
109
+ this.dirtyBuckets.set(bucketKey, dirty);
110
+ this.scheduleFlush();
111
+ }
112
+ peekDirty(scope, userId, key) {
113
+ if (scope === "user" && userId)
114
+ return undefined;
115
+ return this.dirtyBuckets.get(writeBucketKey(scope))?.get(key);
116
+ }
117
+ queueRead(scope, userId, key) {
118
+ const bucketKey = readBucketKey(scope, userId);
119
+ let batch = this.readBatches.get(bucketKey);
120
+ if (!batch) {
121
+ batch = { bucketKey, scope, userId, reads: new Map(), scheduled: false };
122
+ this.readBatches.set(bucketKey, batch);
123
+ }
124
+ const reads = batch.reads.get(key) ?? [];
125
+ batch.reads.set(key, reads);
126
+ const promise = new Promise((resolve, reject) => {
127
+ reads.push({ resolve, reject });
128
+ });
129
+ if (!batch.scheduled) {
130
+ batch.scheduled = true;
131
+ queueMicrotask(() => void this.flushReadBatch(bucketKey));
132
+ }
133
+ return promise;
134
+ }
135
+ async flushReadBatch(bucketKey) {
136
+ const batch = this.readBatches.get(bucketKey);
137
+ if (!batch)
138
+ return;
139
+ this.readBatches.delete(bucketKey);
140
+ const keys = Array.from(batch.reads.keys());
141
+ try {
142
+ const { blob } = await hostRequest("sharedDeckStorage.load", {
143
+ scope: batch.scope,
144
+ userId: batch.userId ?? null,
145
+ keys,
146
+ });
147
+ this.resolveReadBatch(batch, blob);
148
+ }
149
+ catch (error) {
150
+ rejectReadBatch(batch, error);
151
+ }
152
+ }
153
+ resolveReadBatch(batch, blob) {
154
+ for (const [key, reads] of batch.reads) {
155
+ const encoded = this.peekDirty(batch.scope, batch.userId, key) ?? blob[key] ?? null;
156
+ const value = encoded === null
157
+ ? null
158
+ : decodeStorageValue(encoded, "SharedStorage.get");
159
+ for (const read of reads)
160
+ read.resolve(value);
161
+ }
162
+ }
163
+ async flush(unload = false) {
164
+ if (this.dirtyBuckets.size === 0)
165
+ return;
166
+ const tasks = Array.from(this.dirtyBuckets, ([bucketKey, dirty]) => this.flushBucket(bucketKey, new Map(dirty), unload));
167
+ await Promise.all(tasks);
168
+ }
169
+ async flushBucket(bucketKey, snapshot, unload = false) {
170
+ if (snapshot.size === 0)
171
+ return;
172
+ await hostRequest("sharedDeckStorage.update", {
173
+ scope: scopeFromWriteKey(bucketKey),
174
+ updates: updatesFromDirty(snapshot),
175
+ unload,
176
+ });
177
+ const dirty = this.dirtyBuckets.get(bucketKey);
178
+ if (!dirty)
179
+ return;
180
+ clearAcknowledgedDirty(dirty, snapshot);
181
+ if (dirty.size === 0)
182
+ this.dirtyBuckets.delete(bucketKey);
183
+ }
184
+ scheduleFlush() {
185
+ hookUnloadFlush();
186
+ if (this.flushTimer)
187
+ return;
188
+ this.flushTimer = setTimeout(() => {
189
+ this.flushTimer = null;
190
+ void this.flush().catch(reportSharedStorageError);
191
+ }, FLUSH_INTERVAL_MS);
192
+ }
193
+ flushNow() {
194
+ void this.flush(true).catch(reportSharedStorageError);
195
+ }
196
+ }
197
+ // Writes batch on a timer, so leaving the page inside that window would lose
198
+ // them -- a deck saving progress as someone quits is exactly when it matters.
199
+ // `pagehide` is the reliable signal on iOS, where unload often never fires, and
200
+ // visibilitychange covers backgrounding without a navigation. Hooked on the
201
+ // first write so a deck that never stores anything registers nothing.
202
+ let unloadFlushHooked = false;
203
+ function hookUnloadFlush() {
204
+ if (unloadFlushHooked || typeof window === "undefined")
205
+ return;
206
+ unloadFlushHooked = true;
207
+ const flush = () => {
208
+ Storage.flushNow();
209
+ SharedStorage.flushNow();
210
+ };
211
+ window.addEventListener("pagehide", flush);
212
+ document.addEventListener("visibilitychange", () => {
213
+ if (document.visibilityState === "hidden")
214
+ flush();
215
+ });
216
+ }
217
+ export const Storage = new PrivateStorageImpl();
218
+ export const SharedStorage = new SharedStorageImpl();
219
+ // 'user'-scope writes/self-reads share one bucket (the host resolves the
220
+ // current player); a 'user' read of someone else keys by their id.
221
+ function writeBucketKey(scope) {
222
+ return scope === "deck" ? "deck" : "user:self";
223
+ }
224
+ function readBucketKey(scope, userId) {
225
+ if (scope === "deck")
226
+ return "deck";
227
+ return userId ? `user:other:${userId}` : "user:self";
228
+ }
229
+ function scopeFromWriteKey(bucketKey) {
230
+ return bucketKey === "deck" ? "deck" : "user";
231
+ }
232
+ function updatesFromDirty(dirty) {
233
+ return Array.from(dirty, ([key, value]) => ({ key, value }));
234
+ }
235
+ function clearAcknowledgedDirty(dirty, acknowledged) {
236
+ for (const [key, value] of acknowledged) {
237
+ if (dirty.get(key) === value)
238
+ dirty.delete(key);
239
+ }
240
+ }
241
+ function decodeStorageBlob(blob, operation) {
242
+ return new Map(Object.entries(blob).map(([key, value]) => [
243
+ key,
244
+ decodeStorageValue(value, operation),
245
+ ]));
246
+ }
247
+ function decodeStorageValue(encoded, operation) {
248
+ try {
249
+ return JSON.parse(encoded);
250
+ }
251
+ catch {
252
+ throw storageError("CASTLE_STORAGE_PARSE_FAILED", "Stored Castle value is not valid JSON.", operation);
253
+ }
254
+ }
255
+ function encodeStorageValue(value, operation) {
256
+ try {
257
+ assertJsonValue(value, new Set(), operation);
258
+ return JSON.stringify(value);
259
+ }
260
+ catch (error) {
261
+ if (error instanceof CastleError)
262
+ throw error;
263
+ throw storageError("CASTLE_STORAGE_SERIALIZE_FAILED", "Castle storage values must be JSON.", operation);
264
+ }
265
+ }
266
+ function assertJsonValue(value, seen, operation) {
267
+ if (value === null || typeof value === "boolean" || typeof value === "string")
268
+ return;
269
+ if (typeof value === "number") {
270
+ if (Number.isFinite(value))
271
+ return;
272
+ throw storageError("CASTLE_STORAGE_SERIALIZE_FAILED", "Castle storage numbers must be finite.", operation);
273
+ }
274
+ if (Array.isArray(value)) {
275
+ assertJsonArray(value, seen, operation);
276
+ return;
277
+ }
278
+ if (typeof value === "object") {
279
+ assertJsonObject(value, seen, operation);
280
+ return;
281
+ }
282
+ throw storageError("CASTLE_STORAGE_SERIALIZE_FAILED", "Castle storage values must be JSON.", operation);
283
+ }
284
+ function assertJsonArray(values, seen, operation) {
285
+ assertNotCyclic(values, seen, operation);
286
+ seen.add(values);
287
+ for (const value of values)
288
+ assertJsonValue(value, seen, operation);
289
+ seen.delete(values);
290
+ }
291
+ function assertJsonObject(value, seen, operation) {
292
+ assertNotCyclic(value, seen, operation);
293
+ const prototype = Object.getPrototypeOf(value);
294
+ if (prototype !== Object.prototype && prototype !== null) {
295
+ throw storageError("CASTLE_STORAGE_SERIALIZE_FAILED", "Castle storage objects must be plain JSON.", operation);
296
+ }
297
+ seen.add(value);
298
+ for (const child of Object.values(value))
299
+ assertJsonValue(child, seen, operation);
300
+ seen.delete(value);
301
+ }
302
+ function assertNotCyclic(value, seen, operation) {
303
+ if (seen.has(value)) {
304
+ throw storageError("CASTLE_STORAGE_SERIALIZE_FAILED", "Castle storage values cannot be cyclic.", operation);
305
+ }
306
+ }
307
+ function assertScope(scope, operation) {
308
+ if (scope !== "deck" && scope !== "user") {
309
+ throw storageError("CASTLE_STORAGE_INVALID_SCOPE", 'SharedStorage scope must be "deck" or "user".', operation);
310
+ }
311
+ }
312
+ function rejectReadBatch(batch, error) {
313
+ for (const reads of batch.reads.values()) {
314
+ for (const read of reads)
315
+ read.reject(error);
316
+ }
317
+ }
318
+ function reportSharedStorageError(error) {
319
+ console.warn("Castle shared storage write failed", error);
320
+ }
321
+ function storageError(code, message, operation) {
322
+ return new CastleError({ code, message, operation });
323
+ }
@@ -0,0 +1,17 @@
1
+ export type CastleClockZone = "player" | "Castle";
2
+ export interface CastleDateParts {
3
+ sec: number;
4
+ min: number;
5
+ hour: number;
6
+ day: number;
7
+ month: number;
8
+ year: number;
9
+ wday: number;
10
+ yday: number;
11
+ daysSinceCastleEpoch: number;
12
+ }
13
+ export interface CastleTimeApi {
14
+ getServerTime(): Promise<number>;
15
+ getServerDate(timezone?: CastleClockZone): Promise<CastleDateParts>;
16
+ }
17
+ export declare const Time: CastleTimeApi;
@@ -0,0 +1,120 @@
1
+ import { CastleError } from "./errors";
2
+ import { hostRequest } from "./transport";
3
+ let serverTimeSnapshot = null;
4
+ let serverTimePromise = null;
5
+ export const Time = {
6
+ getServerTime,
7
+ getServerDate,
8
+ };
9
+ async function getServerTime() {
10
+ const snapshot = await syncServerTime();
11
+ return clientUnixSeconds() + snapshot.offsetSeconds;
12
+ }
13
+ async function getServerDate(timezone = "Castle") {
14
+ const operation = "Time.getServerDate";
15
+ const zone = clockZone(timezone, operation);
16
+ const snapshot = await syncServerTime();
17
+ return dateParts(clientUnixSeconds() + snapshot.offsetSeconds, zone, snapshot);
18
+ }
19
+ async function syncServerTime() {
20
+ if (serverTimeSnapshot)
21
+ return serverTimeSnapshot;
22
+ if (!serverTimePromise) {
23
+ serverTimePromise = fetchServerTime().then((snapshot) => {
24
+ serverTimeSnapshot = snapshot;
25
+ return snapshot;
26
+ });
27
+ }
28
+ return serverTimePromise;
29
+ }
30
+ async function fetchServerTime() {
31
+ const operation = "Time.getServerTime";
32
+ const data = await hostRequest("time.getServerTime", {});
33
+ const timestamp = numberField(data.timestamp, "serverTime.timestamp", operation);
34
+ const timezoneOffset = numberField(data.timezoneOffset, "serverTime.timezoneOffset", operation);
35
+ const epochData = jsonObject(data.castleEpochData, "serverTime.castleEpochData", operation);
36
+ return {
37
+ offsetSeconds: snappedOffset(timestamp - clientUnixSeconds()),
38
+ castleTimezoneOffsetMinutes: timezoneOffset,
39
+ daysSinceCastleEpoch: {
40
+ Castle: numberField(epochData.daysSinceServerTz, "castleEpochData.daysSinceServerTz", operation),
41
+ player: numberField(epochData.daysSinceUserTz, "castleEpochData.daysSinceUserTz", operation),
42
+ },
43
+ };
44
+ }
45
+ function dateParts(unixSeconds, timezone, snapshot) {
46
+ const shiftedSeconds = timezone === "Castle"
47
+ ? unixSeconds + snapshot.castleTimezoneOffsetMinutes * 60
48
+ : unixSeconds;
49
+ const date = new Date(shiftedSeconds * 1000);
50
+ return timezone === "Castle"
51
+ ? utcDateParts(date, snapshot.daysSinceCastleEpoch.Castle)
52
+ : localDateParts(date, snapshot.daysSinceCastleEpoch.player);
53
+ }
54
+ function utcDateParts(date, daysSinceCastleEpoch) {
55
+ return {
56
+ sec: date.getUTCSeconds(),
57
+ min: date.getUTCMinutes(),
58
+ hour: date.getUTCHours(),
59
+ day: date.getUTCDate(),
60
+ month: date.getUTCMonth() + 1,
61
+ year: date.getUTCFullYear(),
62
+ wday: date.getUTCDay() + 1,
63
+ yday: dayOfYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()),
64
+ daysSinceCastleEpoch,
65
+ };
66
+ }
67
+ function localDateParts(date, daysSinceCastleEpoch) {
68
+ return {
69
+ sec: date.getSeconds(),
70
+ min: date.getMinutes(),
71
+ hour: date.getHours(),
72
+ day: date.getDate(),
73
+ month: date.getMonth() + 1,
74
+ year: date.getFullYear(),
75
+ wday: date.getDay() + 1,
76
+ yday: dayOfYear(date.getFullYear(), date.getMonth(), date.getDate()),
77
+ daysSinceCastleEpoch,
78
+ };
79
+ }
80
+ function dayOfYear(year, monthIndex, day) {
81
+ const start = Date.UTC(year, 0, 1);
82
+ const current = Date.UTC(year, monthIndex, day);
83
+ return Math.floor((current - start) / 86400000) + 1;
84
+ }
85
+ function clockZone(timezone, operation) {
86
+ const normalized = timezone.trim().toLowerCase();
87
+ if (normalized === "castle")
88
+ return "Castle";
89
+ if (normalized === "player")
90
+ return "player";
91
+ throw new CastleError({
92
+ code: "UNSUPPORTED_TIMEZONE",
93
+ message: 'Time.getServerDate timezone must be "Castle" or "player".',
94
+ operation,
95
+ });
96
+ }
97
+ function clientUnixSeconds() {
98
+ return Math.floor(Date.now() / 1000);
99
+ }
100
+ function snappedOffset(offsetSeconds) {
101
+ return Math.abs(offsetSeconds) < 10 ? 0 : offsetSeconds;
102
+ }
103
+ function jsonObject(value, field, operation) {
104
+ if (value !== null && typeof value === "object" && !Array.isArray(value))
105
+ return value;
106
+ throw new CastleError({
107
+ code: "GRAPHQL_BAD_DATA",
108
+ message: `Castle GraphQL field ${field} was not an object.`,
109
+ operation,
110
+ });
111
+ }
112
+ function numberField(value, field, operation) {
113
+ if (typeof value === "number" && Number.isFinite(value))
114
+ return value;
115
+ throw new CastleError({
116
+ code: "GRAPHQL_BAD_DATA",
117
+ message: `Castle GraphQL field ${field} was not a number.`,
118
+ operation,
119
+ });
120
+ }
@@ -0,0 +1,17 @@
1
+ import { type CommandName, type CommandParams, type CommandResult, type LifecycleEvent } from "./commands";
2
+ type PostChannel = "mobile" | "web";
3
+ interface ReactNativeWebViewBridge {
4
+ postMessage: (message: string) => void;
5
+ }
6
+ declare global {
7
+ interface Window {
8
+ ReactNativeWebView?: ReactNativeWebViewBridge;
9
+ __castleSdkHost?: {
10
+ receive: (message: unknown) => void;
11
+ };
12
+ }
13
+ }
14
+ export declare function hostRequest<C extends CommandName>(command: C, params: CommandParams[C]): Promise<CommandResult[C]>;
15
+ export declare function getCommandChannel(): PostChannel | "local";
16
+ export declare function hostNotify(event: LifecycleEvent): void;
17
+ export {};
@@ -0,0 +1,141 @@
1
+ // Deck-side command-poster. The SDK never makes API calls or holds the auth
2
+ // token; every privileged operation becomes a `command` posted to the outer
3
+ // runtime (host), which validates it, stamps trusted context, runs the call
4
+ // with its own auth, and replies. Three host channels:
5
+ // - mobile → window.ReactNativeWebView.postMessage; host pushes responses
6
+ // back by calling window.__castleSdkHost.receive(...)
7
+ // - web → window.parent.postMessage; responses via 'message' events
8
+ // - local → the castle-web serve dev server, over runtime.ts's websocket
9
+ // Error reconstruction is uniform here so callers always get a CastleError.
10
+ import { CASTLE_SDK_PROTOCOL, isResponseEnvelope, } from "./commands";
11
+ import { getCastleEmbed } from "./context";
12
+ import { CastleError } from "./errors";
13
+ import { sendLocalCommand } from "./runtime";
14
+ const REQUEST_TIMEOUT_MS = 15000;
15
+ // Interactive platform commands hold the screen while the player interacts with
16
+ // a host-native sheet (e.g. a pass purchase), so the flat data-command timeout
17
+ // is wrong for them: they get NO timeout and resolve only when the host replies.
18
+ const INTERACTIVE_COMMANDS = new Set([
19
+ "pass.offer",
20
+ "portal.open",
21
+ ]);
22
+ let nextRequestId = 1;
23
+ const pending = new Map();
24
+ let listenersInstalled = false;
25
+ export async function hostRequest(command, params) {
26
+ try {
27
+ const channel = resolveChannel();
28
+ const env = channel === "local"
29
+ ? await sendLocalCommand(command, params)
30
+ : await postCommand(channel, command, params);
31
+ return interpretResponse(command, env);
32
+ }
33
+ catch (error) {
34
+ // Honor the SDK contract that every thrown error is a CastleError. Errors
35
+ // surfaced by the host (interpretResponse) are already CastleErrors; this
36
+ // wraps transport-level failures (host timeout / unreachable / dev server
37
+ // disconnected) that would otherwise be plain Errors.
38
+ if (error instanceof CastleError)
39
+ throw error;
40
+ throw new CastleError({
41
+ code: "CASTLE_HOST_UNAVAILABLE",
42
+ message: error instanceof Error
43
+ ? error.message
44
+ : `Castle host did not handle ${command}.`,
45
+ operation: command,
46
+ });
47
+ }
48
+ }
49
+ // Exposed so capability modules (e.g. passes) can tell whether the current host
50
+ // has its own UI surface over the deck. "mobile"/"web" hosts render their own
51
+ // purchase/upsell UI; the "local" dev server has none, so the SDK itself shows
52
+ // a minimal in-page notice there.
53
+ export function getCommandChannel() {
54
+ return resolveChannel();
55
+ }
56
+ // Fire-and-forget counterpart to hostRequest: no reply, no timeout. The local
57
+ // dev server has no surface to react to lifecycle events, so it's skipped.
58
+ export function hostNotify(event) {
59
+ if (typeof window === "undefined")
60
+ return;
61
+ const channel = resolveChannel();
62
+ if (channel === "local")
63
+ return;
64
+ const envelope = {
65
+ castleSdk: CASTLE_SDK_PROTOCOL,
66
+ lifecycle: event,
67
+ };
68
+ sendEnvelope(channel, envelope);
69
+ }
70
+ function resolveChannel() {
71
+ if (typeof window === "undefined")
72
+ return "local";
73
+ if (window.ReactNativeWebView)
74
+ return "mobile";
75
+ const host = getCastleEmbed()?.host;
76
+ if (host === "web")
77
+ return "web";
78
+ if (host === "dev")
79
+ return "local";
80
+ // Fallback: an iframe with a parent is the web player; otherwise assume the
81
+ // local dev server (top-level page served by `castle-web serve`).
82
+ return window.parent && window.parent !== window ? "web" : "local";
83
+ }
84
+ function postCommand(channel, command, params) {
85
+ installResponseListener();
86
+ const requestId = `csdk_${nextRequestId++}`;
87
+ return new Promise((resolve, reject) => {
88
+ const timeout = INTERACTIVE_COMMANDS.has(command)
89
+ ? undefined
90
+ : setTimeout(() => {
91
+ pending.delete(requestId);
92
+ reject(new Error(`Castle host did not respond to ${command}.`));
93
+ }, REQUEST_TIMEOUT_MS);
94
+ pending.set(requestId, { resolve, reject, timeout });
95
+ sendEnvelope(channel, { castleSdk: CASTLE_SDK_PROTOCOL, requestId, command, params });
96
+ });
97
+ }
98
+ function sendEnvelope(channel, envelope) {
99
+ const json = JSON.stringify(envelope);
100
+ if (channel === "mobile") {
101
+ window.ReactNativeWebView?.postMessage(json);
102
+ }
103
+ else {
104
+ window.parent.postMessage(envelope, "*");
105
+ }
106
+ }
107
+ // The mobile host can't dispatch a DOM 'message' event, so it calls this global
108
+ // directly with the parsed envelope. The web host posts a 'message' event.
109
+ function installResponseListener() {
110
+ if (listenersInstalled || typeof window === "undefined")
111
+ return;
112
+ listenersInstalled = true;
113
+ window.__castleSdkHost = { receive: (message) => settle(message) };
114
+ window.addEventListener("message", (event) => {
115
+ settle(event.data);
116
+ });
117
+ }
118
+ function settle(message) {
119
+ if (!isResponseEnvelope(message))
120
+ return;
121
+ const entry = pending.get(message.requestId);
122
+ if (!entry)
123
+ return;
124
+ if (entry.timeout)
125
+ clearTimeout(entry.timeout);
126
+ pending.delete(message.requestId);
127
+ entry.resolve(message);
128
+ }
129
+ function interpretResponse(command, env) {
130
+ if (env.ok)
131
+ return env.data;
132
+ throw fromSerializedError(env.error, command);
133
+ }
134
+ function fromSerializedError(error, command) {
135
+ return new CastleError({
136
+ code: error?.code ?? "CASTLE_HOST_ERROR",
137
+ message: error?.message ?? `Castle command ${command} failed.`,
138
+ operation: error?.command ?? command,
139
+ extensions: error?.extensions,
140
+ });
141
+ }
@@ -0,0 +1,3 @@
1
+ export type Json = null | boolean | number | string | Json[] | {
2
+ [key: string]: Json;
3
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ export interface CastleUser {
2
+ userId: string;
3
+ username: string;
4
+ isAnonymous: boolean;
5
+ isActive: boolean;
6
+ }
7
+ export interface CastleUserApi {
8
+ getCurrent(): Promise<CastleUser>;
9
+ }
10
+ export declare const User: CastleUserApi;
@@ -0,0 +1,45 @@
1
+ import { CastleError } from "./errors";
2
+ import { hostRequest } from "./transport";
3
+ let currentUser = null;
4
+ let currentUserPromise = null;
5
+ export const User = {
6
+ getCurrent,
7
+ };
8
+ async function getCurrent() {
9
+ if (currentUser)
10
+ return currentUser;
11
+ currentUserPromise ??= fetchCurrentUser().then((user) => {
12
+ currentUser = user;
13
+ return user;
14
+ });
15
+ return currentUserPromise;
16
+ }
17
+ async function fetchCurrentUser() {
18
+ const operation = "User.getCurrent";
19
+ const { user } = await hostRequest("user.getCurrent", {});
20
+ if (!user) {
21
+ throw new CastleError({
22
+ code: "LOGIN_REQUIRED",
23
+ message: "Log in to Castle before using User.getCurrent().",
24
+ operation,
25
+ });
26
+ }
27
+ const username = requiredString(user.username, "user.username", operation);
28
+ return {
29
+ userId: requiredString(user.userId, "user.userId", operation),
30
+ username,
31
+ // A host that predates the flag omits it; anonymous account usernames are
32
+ // always minted as `anonymous-user-<uuid>`, so the prefix is the fallback.
33
+ isAnonymous: user.isAnonymous === true || username.toLowerCase().startsWith("anonymous-user-"),
34
+ isActive: true,
35
+ };
36
+ }
37
+ function requiredString(value, field, operation) {
38
+ if (typeof value === "string" && value.length > 0)
39
+ return value;
40
+ throw new CastleError({
41
+ code: "GRAPHQL_BAD_DATA",
42
+ message: `Castle response did not include ${field}.`,
43
+ operation,
44
+ });
45
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "printWidth": 100,
3
+ "tabWidth": 2,
4
+ "singleQuote": true
5
+ }