castle-web-cli 0.4.237 → 0.4.238

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 (216) hide show
  1. package/dist/bundle.d.ts +24 -0
  2. package/dist/bundle.js +447 -4
  3. package/dist/bundleLatin1.d.ts +6 -0
  4. package/dist/bundleLatin1.js +333 -0
  5. package/dist/castle-host/host.d.ts +10 -1
  6. package/dist/castle-host/host.js +78 -9
  7. package/dist/castleJson.d.ts +2 -0
  8. package/dist/castleJson.js +1 -0
  9. package/dist/deckExports.d.ts +35 -0
  10. package/dist/deckExports.js +365 -0
  11. package/dist/importCheckHook.d.ts +1 -0
  12. package/dist/importCheckHook.js +1 -1
  13. package/dist/index.js +5 -0
  14. package/dist/init.js +2 -1
  15. package/dist/save-deck.js +4 -0
  16. package/kits/base/castle.json +1 -1
  17. package/kits/base/sdk/README.md +47 -0
  18. package/kits/base/sdk/castle.d.ts +3 -1
  19. package/kits/base/sdk/castle.js +1 -0
  20. package/kits/base/sdk/commands.d.ts +25 -1
  21. package/kits/base/sdk/commands.js +29 -1
  22. package/kits/base/sdk/hub.d.ts +17 -0
  23. package/kits/base/sdk/hub.js +33 -9
  24. package/kits/base/sdk/localCache.d.ts +27 -0
  25. package/kits/base/sdk/localCache.js +115 -0
  26. package/kits/base/sdk/localCacheStore.d.ts +15 -0
  27. package/kits/base/sdk/localCacheStore.js +358 -0
  28. package/kits/base/sdk/transport.d.ts +1 -0
  29. package/kits/base/sdk/transport.js +4 -5
  30. package/kits/hub-game/CLAUDE.md +22 -2
  31. package/kits/hub-game/castle.json +4 -1
  32. package/kits/hub-game/code/client/act.js +66 -91
  33. package/kits/hub-game/code/client/actCore.js +134 -0
  34. package/kits/hub-game/code/client/car.js +35 -0
  35. package/kits/hub-game/code/client/chrome.js +207 -381
  36. package/kits/hub-game/code/client/crowdNames.js +2 -2
  37. package/kits/hub-game/code/client/emoteWheel.js +109 -0
  38. package/kits/hub-game/code/client/hats.js +2 -0
  39. package/kits/hub-game/code/client/hookLayer.js +99 -48
  40. package/kits/hub-game/code/client/hostGo.js +77 -0
  41. package/kits/hub-game/code/client/hubControls.js +125 -0
  42. package/kits/hub-game/code/client/hubEntry.js +187 -0
  43. package/kits/hub-game/code/client/hudSurface.js +148 -0
  44. package/kits/hub-game/code/client/hudTree.js +96 -0
  45. package/kits/hub-game/code/client/idle.js +59 -13
  46. package/kits/hub-game/code/client/invites.js +13 -4
  47. package/kits/hub-game/code/client/menuIcons.js +8 -0
  48. package/kits/hub-game/code/client/noTrips.js +38 -0
  49. package/kits/hub-game/code/client/qualityEntry.js +6 -1
  50. package/kits/hub-game/code/client/rehello.js +3 -1
  51. package/kits/hub-game/code/client/riders.js +26 -0
  52. package/kits/hub-game/code/client/role.js +79 -0
  53. package/kits/hub-game/code/client/safeLayout.js +32 -3
  54. package/kits/hub-game/code/client/sound.js +10 -3
  55. package/kits/hub-game/code/client/soundscape.js +2 -2
  56. package/kits/hub-game/code/client/soundscapeAmbience.js +38 -8
  57. package/kits/hub-game/code/client/soundscapeBaked.js +24 -5
  58. package/kits/hub-game/code/client/soundscapeCues.js +2 -1
  59. package/kits/hub-game/code/client/state.js +19 -0
  60. package/kits/hub-game/code/client/stuck.js +2 -1
  61. package/kits/hub-game/code/client/talkSurface.js +178 -0
  62. package/kits/hub-game/code/client/talkTree.js +238 -0
  63. package/kits/hub-game/code/client/tiers.js +8 -5
  64. package/kits/hub-game/code/client/uiDom.js +600 -0
  65. package/kits/hub-game/code/client/uiTree.js +359 -0
  66. package/kits/hub-game/code/client/vehicle.js +154 -0
  67. package/kits/hub-game/code/client/wear.js +27 -5
  68. package/kits/hub-game/code/client/worldLabels.js +3 -2
  69. package/kits/hub-game/code/client/yours.js +10 -3
  70. package/kits/hub-game/code/server/actors.js +4 -3
  71. package/kits/hub-game/code/server/analytics.js +56 -6
  72. package/kits/hub-game/code/server/decor.js +56 -16
  73. package/kits/hub-game/code/server/hub.js +258 -46
  74. package/kits/hub-game/code/server/idle.js +118 -5
  75. package/kits/hub-game/code/server/manifest.js +46 -4
  76. package/kits/hub-game/code/server/npcs.js +4 -2
  77. package/kits/hub-game/code/server/players.js +3 -0
  78. package/kits/hub-game/code/server/role.js +142 -0
  79. package/kits/hub-game/code/server/standing.js +6 -4
  80. package/kits/hub-game/code/server/vehicle.js +126 -0
  81. package/kits/hub-game/code/shared/car.js +52 -0
  82. package/kits/hub-game/code/shared/deckFlags.js +34 -0
  83. package/kits/hub-game/code/shared/deviceClass.js +39 -0
  84. package/kits/hub-game/code/shared/expression.js +9 -0
  85. package/kits/hub-game/code/systems/hub.js +272 -84
  86. package/kits/hub-game/docs/analytics.md +11 -2
  87. package/kits/hub-game/docs/contract.md +352 -14
  88. package/kits/hub-game/docs/vehicle-preset.md +132 -0
  89. package/kits/hub-game/models/hats/baker-cap.pxmodel +89 -0
  90. package/kits/hub-game/models/hats/chef-toque.pxmodel +60 -0
  91. package/kits/hub-game/models/hats/delivery-cap.pxmodel +105 -0
  92. package/kits/hub-game/models/hats/fire-helmet.pxmodel +87 -0
  93. package/kits/hub-game/models/hats/hard-hat.pxmodel +71 -0
  94. package/kits/hub-game/models/hats/nurse-cap.pxmodel +61 -0
  95. package/kits/hub-game/models/hats/police-cap.pxmodel +105 -0
  96. package/kits/hub-game/models/hats/teacher-beret.pxmodel +52 -0
  97. package/kits/hub-game/models/role/square/top-apron.pxmodel +109 -0
  98. package/kits/hub-game/models/role/square/top-cardigan.pxmodel +141 -0
  99. package/kits/hub-game/models/role/square/top-coat.pxmodel +157 -0
  100. package/kits/hub-game/models/role/square/top-scrubs.pxmodel +93 -0
  101. package/kits/hub-game/models/role/square/top-tabard.pxmodel +109 -0
  102. package/kits/hub-game/models/role/square/top-vest.pxmodel +109 -0
  103. package/kits/hub-game/models/role/tool-bag.pxmodel +75 -0
  104. package/kits/hub-game/models/role/tool-bell.pxmodel +71 -0
  105. package/kits/hub-game/models/role/tool-hose.pxmodel +60 -0
  106. package/kits/hub-game/models/role/tool-parcel.pxmodel +61 -0
  107. package/kits/hub-game/models/role/tool-torch.pxmodel +55 -0
  108. package/kits/hub-game/models/role/tool-tray.pxmodel +75 -0
  109. package/kits/hub-game/models/role/top-apron.pxmodel +70 -0
  110. package/kits/hub-game/models/role/top-cardigan.pxmodel +102 -0
  111. package/kits/hub-game/models/role/top-coat.pxmodel +79 -0
  112. package/kits/hub-game/models/role/top-scrubs.pxmodel +54 -0
  113. package/kits/hub-game/models/role/top-tabard.pxmodel +70 -0
  114. package/kits/hub-game/models/role/top-vest.pxmodel +70 -0
  115. package/kits/hub-game/package-lock.json +1 -1
  116. package/kits/hub-game/package.json +1 -1
  117. package/kits/hub-game/scripts/check.mjs +7 -4
  118. package/kits/hub-game/scripts/fixtures/car-vectors.json +279 -0
  119. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +2 -1
  120. package/kits/hub-game/scripts/fixtures/hud-surface.json +670 -0
  121. package/kits/hub-game/scripts/fixtures/talk-surface.json +3930 -0
  122. package/kits/hub-game/scripts/gen-hats.mjs +46 -2
  123. package/kits/hub-game/scripts/gen-role.mjs +80 -0
  124. package/kits/hub-game/scripts/test-act-core.mjs +167 -0
  125. package/kits/hub-game/scripts/test-actions-client.mjs +34 -0
  126. package/kits/hub-game/scripts/test-actors.mjs +48 -0
  127. package/kits/hub-game/scripts/test-analytics.mjs +99 -5
  128. package/kits/hub-game/scripts/test-apply-deck.mjs +122 -0
  129. package/kits/hub-game/scripts/test-back-visibility.mjs +3 -1
  130. package/kits/hub-game/scripts/test-ballot.mjs +2 -0
  131. package/kits/hub-game/scripts/test-car.mjs +43 -0
  132. package/kits/hub-game/scripts/test-decor-client.mjs +2 -1
  133. package/kits/hub-game/scripts/test-decor.mjs +77 -0
  134. package/kits/hub-game/scripts/test-device-class.mjs +83 -0
  135. package/kits/hub-game/scripts/test-emote-wheel.mjs +374 -0
  136. package/kits/hub-game/scripts/test-hats.mjs +5 -4
  137. package/kits/hub-game/scripts/test-host-go.mjs +265 -0
  138. package/kits/hub-game/scripts/test-hub-controls.mjs +108 -0
  139. package/kits/hub-game/scripts/test-hub-entry.mjs +531 -0
  140. package/kits/hub-game/scripts/test-hub-ops.mjs +75 -0
  141. package/kits/hub-game/scripts/test-hud-clear.mjs +12 -2
  142. package/kits/hub-game/scripts/test-hud-rate.mjs +6 -2
  143. package/kits/hub-game/scripts/test-hud-surface.mjs +272 -0
  144. package/kits/hub-game/scripts/test-idle.mjs +347 -1
  145. package/kits/hub-game/scripts/test-interest-cells.mjs +8 -1
  146. package/kits/hub-game/scripts/test-invites-client.mjs +42 -1
  147. package/kits/hub-game/scripts/test-manifest.mjs +30 -0
  148. package/kits/hub-game/scripts/test-no-trips.mjs +42 -0
  149. package/kits/hub-game/scripts/test-placement-cache.mjs +1 -1
  150. package/kits/hub-game/scripts/test-quality.mjs +13 -0
  151. package/kits/hub-game/scripts/test-rehello.mjs +258 -3
  152. package/kits/hub-game/scripts/test-resume-pose-server.mjs +203 -0
  153. package/kits/hub-game/scripts/test-resync.mjs +183 -0
  154. package/kits/hub-game/scripts/test-role-client.mjs +421 -0
  155. package/kits/hub-game/scripts/test-role.mjs +350 -0
  156. package/kits/hub-game/scripts/test-safe-layout.mjs +50 -1
  157. package/kits/hub-game/scripts/test-soundscape.mjs +124 -7
  158. package/kits/hub-game/scripts/test-standing.mjs +15 -1
  159. package/kits/hub-game/scripts/test-talk-surface.mjs +296 -0
  160. package/kits/hub-game/scripts/test-tiers.mjs +13 -0
  161. package/kits/hub-game/scripts/test-ui-dom-dom.mjs +96 -0
  162. package/kits/hub-game/scripts/test-ui-tree.mjs +711 -0
  163. package/kits/hub-game/scripts/test-vehicle-client.mjs +159 -0
  164. package/kits/hub-game/scripts/test-vehicle.mjs +135 -0
  165. package/kits/hub-game/scripts/test-yours.mjs +33 -0
  166. package/kits/hub-game/tools/hubScene/export.mjs +613 -0
  167. package/kits/hub-game/tools/hubScene/hubdata.mjs +921 -0
  168. package/kits/hub-game/tools/hubScene/merge-root.mjs +39 -0
  169. package/kits/hub-game/tools/hubScene/nodeworld.mjs +227 -0
  170. package/kits/hub-game/tools/hubScene/test/export-fixture.mjs +798 -0
  171. package/kits/hub-game/tools/hubScene/test/fixture.json +637 -0
  172. package/kits/hub-game/tools/hubScene/test/paint-export.mjs +40 -0
  173. package/kits/hub-game/tools/hubScene/test/upload.test.mjs +655 -0
  174. package/kits/hub-game/tools/hubScene/upload.mjs +636 -0
  175. package/kits/hub-game/tools/hubScene/validate-manifest.mjs +291 -0
  176. package/kits/multiplayer-3d/castle.json +4 -4
  177. package/kits/multiplayer-3d/code/client/resumeGate.js +30 -2
  178. package/kits/multiplayer-3d/code/client/steer.js +3 -1
  179. package/kits/multiplayer-3d/code/systems/multiplayer.js +30 -2
  180. package/kits/multiplayer-3d/package-lock.json +1 -1
  181. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +74 -2
  182. package/kits/physics-3d/CLAUDE.md +1 -1
  183. package/kits/physics-3d/behaviors/Player.jsx +37 -27
  184. package/kits/physics-3d/castle.json +2 -2
  185. package/kits/physics-3d/docs/engine-geometry-memory.md +23 -0
  186. package/kits/physics-3d/engine3d/memoryprofile.js +17 -0
  187. package/kits/physics-3d/engine3d/playerRun.js +6 -1
  188. package/kits/physics-3d/engine3d/pxmodel.js +6 -1
  189. package/kits/physics-3d/engine3d/world3d.js +6 -3
  190. package/kits/physics-3d/package.json +1 -1
  191. package/kits/physics-3d/play/behaviors/Player.js +40 -28
  192. package/kits/physics-3d/scripts/test-memory-profile.mjs +237 -0
  193. package/kits/physics-3d/systems/physics3d.js +5 -2
  194. package/kits/real-time/castle.json +2 -2
  195. package/kits/real-time/code/client/messages.js +5 -0
  196. package/kits/real-time/code/server/session.js +28 -1
  197. package/kits/real-time/package-lock.json +1 -1
  198. package/package.json +5 -4
  199. package/vendor/three/LICENSE +21 -0
  200. package/vendor/three/build/three.core.js +58773 -0
  201. package/vendor/three/build/three.module.js +18251 -0
  202. package/vendor/three/examples/jsm/controls/OrbitControls.js +1860 -0
  203. package/vendor/three/examples/jsm/controls/TransformControls.js +1918 -0
  204. package/vendor/three/examples/jsm/exporters/GLTFExporter.js +3595 -0
  205. package/vendor/three/examples/jsm/geometries/RoundedBoxGeometry.js +216 -0
  206. package/vendor/three/examples/jsm/math/MeshSurfaceSampler.js +315 -0
  207. package/vendor/three/examples/jsm/postprocessing/EffectComposer.js +363 -0
  208. package/vendor/three/examples/jsm/postprocessing/MaskPass.js +195 -0
  209. package/vendor/three/examples/jsm/postprocessing/OutputPass.js +139 -0
  210. package/vendor/three/examples/jsm/postprocessing/Pass.js +191 -0
  211. package/vendor/three/examples/jsm/postprocessing/RenderPass.js +183 -0
  212. package/vendor/three/examples/jsm/postprocessing/ShaderPass.js +135 -0
  213. package/vendor/three/examples/jsm/shaders/CopyShader.js +52 -0
  214. package/vendor/three/examples/jsm/shaders/OutputShader.js +103 -0
  215. package/vendor/three/examples/jsm/utils/BufferGeometryUtils.js +1435 -0
  216. package/vendor/three/package.json +134 -0
@@ -20,6 +20,7 @@ export const Hub = {
20
20
  reportChat,
21
21
  cancel,
22
22
  onBack,
23
+ onGo,
23
24
  };
24
25
  async function go(doorId, options = {}) {
25
26
  if (typeof doorId !== "string" || doorId.length === 0) {
@@ -155,29 +156,52 @@ async function cancel() {
155
156
  return hostRequest("hub.cancel", {});
156
157
  }
157
158
  const backListeners = new Set();
159
+ const goListeners = new Set();
158
160
  function onBack(listener) {
161
+ return subscribe(backListeners, listener, "Hub.onBack");
162
+ }
163
+ function onGo(listener) {
164
+ return subscribe(goListeners, listener, "Hub.onGo");
165
+ }
166
+ // The host's hub event handler stays installed while any listener of any kind
167
+ // is left, so dropping the last Back listener never silences Go, or vice versa.
168
+ function subscribe(listeners, listener, operation) {
159
169
  if (typeof listener !== "function") {
160
170
  throw new CastleError({
161
171
  code: "INVALID_ARGUMENT",
162
- message: "Hub.onBack requires a function.",
163
- operation: "Hub.onBack",
172
+ message: `${operation} requires a function.`,
173
+ operation,
164
174
  });
165
175
  }
166
- backListeners.add(listener);
176
+ listeners.add(listener);
167
177
  setHubEventHandler(dispatchHubEvent);
168
178
  return () => {
169
- backListeners.delete(listener);
170
- if (backListeners.size === 0)
179
+ listeners.delete(listener);
180
+ if (backListeners.size === 0 && goListeners.size === 0)
171
181
  setHubEventHandler(null);
172
182
  };
173
183
  }
174
- function dispatchHubEvent() {
175
- for (const listener of [...backListeners]) {
184
+ function dispatchHubEvent(event) {
185
+ if (event.type === "back") {
186
+ notify(backListeners, (listener) => listener(), "Hub.onBack");
187
+ }
188
+ else if (event.type === "go") {
189
+ const go = {
190
+ doorId: event.doorId,
191
+ owner: event.owner ?? null,
192
+ title: event.title ?? null,
193
+ party: event.party ?? 1,
194
+ };
195
+ notify(goListeners, (listener) => listener({ ...go }), "Hub.onGo");
196
+ }
197
+ }
198
+ function notify(listeners, call, operation) {
199
+ for (const listener of [...listeners]) {
176
200
  try {
177
- listener();
201
+ call(listener);
178
202
  }
179
203
  catch (error) {
180
- console.error("Castle Hub.onBack listener threw:", error);
204
+ console.error(`Castle ${operation} listener threw:`, error);
181
205
  }
182
206
  }
183
207
  }
@@ -0,0 +1,27 @@
1
+ export interface LocalCacheApi {
2
+ getBinary(key: string): Promise<ArrayBuffer | null>;
3
+ getText(key: string): Promise<string | null>;
4
+ set(key: string, value: ArrayBuffer | Uint8Array | string): Promise<void>;
5
+ remove(key: string): Promise<void>;
6
+ }
7
+ /**
8
+ * A cache on the player's device, for bytes and text the deck can rebuild:
9
+ * downloaded or unpacked assets, compiled data. Entries belong to the deck
10
+ * whose code is running. A hub town's doors change the place but not the
11
+ * code, so the games played through them use the town's entries. In the app,
12
+ * decks loaded from the same web address share entries.
13
+ *
14
+ * Any entry can be gone at any time. Each deck has 20 MB; past that its own
15
+ * least recently used entries are evicted. On the web all decks together
16
+ * have 300 MB; past that the least recently used entries of any deck are
17
+ * evicted. Both are less when the device is short of space. The browser or
18
+ * app may also clear the whole cache.
19
+ *
20
+ * `getBinary` returns bytes (text entries as UTF-8), `getText` returns text
21
+ * (byte entries decoded as UTF-8). `set` takes an ArrayBuffer, a Uint8Array or
22
+ * a string. An ArrayBuffer is moved into the cache and is empty (detached)
23
+ * afterwards, so pass `buffer.slice(0)` to keep a copy; so is the buffer of a
24
+ * Uint8Array that covers all of it. A Uint8Array over part of a buffer is
25
+ * copied.
26
+ */
27
+ export declare const LocalCache: LocalCacheApi;
@@ -0,0 +1,115 @@
1
+ import { openLocalCacheStore } from "./localCacheStore";
2
+ import { getCommandChannel, hostRequest } from "./transport";
3
+ // The deck's own origin is its namespace, so every entry there uses this one.
4
+ const OWN_ORIGIN_NAMESPACE = "deck";
5
+ let ownStore = null;
6
+ function usesOwnOrigin() {
7
+ return getCommandChannel() !== "web";
8
+ }
9
+ function store() {
10
+ ownStore ??= openLocalCacheStore();
11
+ return ownStore;
12
+ }
13
+ async function read(key, operation) {
14
+ assertKey(key, operation);
15
+ try {
16
+ if (usesOwnOrigin()) {
17
+ return await store().get(OWN_ORIGIN_NAMESPACE, key);
18
+ }
19
+ const { value } = await hostRequest("localCache.get", { key });
20
+ return value;
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
26
+ async function write(key, value) {
27
+ assertKey(key, "LocalCache.set");
28
+ const moved = moveIn(value);
29
+ try {
30
+ if (usesOwnOrigin()) {
31
+ await store().set(OWN_ORIGIN_NAMESPACE, key, moved);
32
+ return;
33
+ }
34
+ const transfer = typeof moved === "string" ? [] : [moved];
35
+ await hostRequest("localCache.set", { key, value: moved }, { transfer });
36
+ }
37
+ catch {
38
+ // A write that fails stores nothing.
39
+ }
40
+ }
41
+ async function remove(key) {
42
+ assertKey(key, "LocalCache.remove");
43
+ try {
44
+ if (usesOwnOrigin()) {
45
+ await store().remove(OWN_ORIGIN_NAMESPACE, key);
46
+ return;
47
+ }
48
+ await hostRequest("localCache.remove", { key });
49
+ }
50
+ catch {
51
+ // A host without LocalCache never stored the entry.
52
+ }
53
+ }
54
+ // An ArrayBuffer is moved, not copied, in every host, so a deck sees the same
55
+ // detached buffer after the call wherever it runs. A Uint8Array that covers
56
+ // its whole buffer moves that buffer the same way; one that covers part of it
57
+ // has its bytes copied, and its buffer is left as it was.
58
+ function moveIn(value) {
59
+ if (typeof value === "string") {
60
+ return value;
61
+ }
62
+ if (value instanceof ArrayBuffer) {
63
+ return structuredClone(value, { transfer: [value] });
64
+ }
65
+ if (value instanceof Uint8Array) {
66
+ const buffer = value.buffer;
67
+ const whole = buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength;
68
+ return whole ? structuredClone(buffer, { transfer: [buffer] }) : value.slice().buffer;
69
+ }
70
+ throw new TypeError("LocalCache.set takes an ArrayBuffer, a Uint8Array or a string.");
71
+ }
72
+ // The host refuses a key with NUL in it, so the SDK does too, in every host.
73
+ function assertKey(key, operation) {
74
+ if (typeof key !== "string" || key.length === 0 || key.length > 1024 || key.includes("\0")) {
75
+ throw new TypeError(`${operation} takes a key of 1 to 1024 characters, without NUL.`);
76
+ }
77
+ }
78
+ /**
79
+ * A cache on the player's device, for bytes and text the deck can rebuild:
80
+ * downloaded or unpacked assets, compiled data. Entries belong to the deck
81
+ * whose code is running. A hub town's doors change the place but not the
82
+ * code, so the games played through them use the town's entries. In the app,
83
+ * decks loaded from the same web address share entries.
84
+ *
85
+ * Any entry can be gone at any time. Each deck has 20 MB; past that its own
86
+ * least recently used entries are evicted. On the web all decks together
87
+ * have 300 MB; past that the least recently used entries of any deck are
88
+ * evicted. Both are less when the device is short of space. The browser or
89
+ * app may also clear the whole cache.
90
+ *
91
+ * `getBinary` returns bytes (text entries as UTF-8), `getText` returns text
92
+ * (byte entries decoded as UTF-8). `set` takes an ArrayBuffer, a Uint8Array or
93
+ * a string. An ArrayBuffer is moved into the cache and is empty (detached)
94
+ * afterwards, so pass `buffer.slice(0)` to keep a copy; so is the buffer of a
95
+ * Uint8Array that covers all of it. A Uint8Array over part of a buffer is
96
+ * copied.
97
+ */
98
+ export const LocalCache = {
99
+ async getBinary(key) {
100
+ const value = await read(key, "LocalCache.getBinary");
101
+ if (typeof value === "string") {
102
+ return new TextEncoder().encode(value).buffer;
103
+ }
104
+ return value;
105
+ },
106
+ async getText(key) {
107
+ const value = await read(key, "LocalCache.getText");
108
+ if (value instanceof ArrayBuffer) {
109
+ return new TextDecoder().decode(value);
110
+ }
111
+ return value;
112
+ },
113
+ set: write,
114
+ remove,
115
+ };
@@ -0,0 +1,15 @@
1
+ export type LocalCacheValue = ArrayBuffer | string;
2
+ export interface LocalCacheStore {
3
+ get(namespace: string, key: string): Promise<LocalCacheValue | null>;
4
+ set(namespace: string, key: string, value: LocalCacheValue): Promise<void>;
5
+ remove(namespace: string, key: string): Promise<void>;
6
+ }
7
+ export interface LocalCacheStoreOptions {
8
+ databaseName?: string;
9
+ deckBudgetBytes?: number;
10
+ totalBudgetBytes?: number;
11
+ }
12
+ export declare const LOCAL_CACHE_DATABASE_NAME = "castle-local-cache";
13
+ export declare const LOCAL_CACHE_DECK_BUDGET_BYTES: number;
14
+ export declare const LOCAL_CACHE_TOTAL_BUDGET_BYTES: number;
15
+ export declare function openLocalCacheStore(options?: LocalCacheStoreOptions): LocalCacheStore;
@@ -0,0 +1,358 @@
1
+ // An IndexedDB store for LocalCache entries, with least-recently-used eviction
2
+ // over a budget for each namespace and one for the whole store. The SDK opens
3
+ // it in a deck's own origin (mobile, the dev serve), where there is one
4
+ // namespace; castle-www opens it in castle.xyz's origin for every deck it
5
+ // hosts, so there the namespace is the deck id.
6
+ //
7
+ // No imports: host repos vendor the built file as it is
8
+ // (scripts/copy-host-module.mjs).
9
+ export const LOCAL_CACHE_DATABASE_NAME = "castle-local-cache";
10
+ export const LOCAL_CACHE_DECK_BUDGET_BYTES = 20 * 1024 * 1024;
11
+ export const LOCAL_CACHE_TOTAL_BUDGET_BYTES = 300 * 1024 * 1024;
12
+ const DATABASE_VERSION = 3;
13
+ const VALUES = "values";
14
+ const ENTRIES = "entries";
15
+ const META = "meta";
16
+ const ACCESSED = "accessed";
17
+ const NAMESPACE_ACCESSED = "namespaceAccessed";
18
+ // The `meta` record holding the charged total of every entry, so a write
19
+ // changes the total without reading the other records. Each namespace's total
20
+ // is kept the same way, under namespaceTotalKey.
21
+ const TOTAL = "total";
22
+ // The fixed part of an entry's charge, for its two records. The namespace and
23
+ // key are charged too, at two bytes a character for each of the two places
24
+ // they are stored.
25
+ const RECORD_BYTES = 256;
26
+ // Access times from reads are written in one batch shortly after, so reads run
27
+ // in read-only transactions and do not queue behind each other. Each keeps the
28
+ // time of its read.
29
+ const TOUCH_DELAY_MS = 50;
30
+ export function openLocalCacheStore(options = {}) {
31
+ const databaseName = options.databaseName ?? LOCAL_CACHE_DATABASE_NAME;
32
+ const budgets = {
33
+ deck: options.deckBudgetBytes ?? LOCAL_CACHE_DECK_BUDGET_BYTES,
34
+ total: options.totalBudgetBytes ?? LOCAL_CACHE_TOTAL_BUDGET_BYTES,
35
+ };
36
+ let database = null;
37
+ const touched = new Map();
38
+ let touchTimer = null;
39
+ // A connection that closes or fails to open is dropped, and the next call
40
+ // opens a new one.
41
+ const open = () => {
42
+ if (database) {
43
+ return database;
44
+ }
45
+ const opening = openDatabase(databaseName, () => {
46
+ if (database === opening) {
47
+ database = null;
48
+ }
49
+ }).catch((error) => {
50
+ if (database === opening) {
51
+ database = null;
52
+ }
53
+ throw error;
54
+ });
55
+ database = opening;
56
+ return opening;
57
+ };
58
+ const flushTouches = async () => {
59
+ touchTimer = null;
60
+ const touches = Array.from(touched.values());
61
+ touched.clear();
62
+ await touchEntries(await open(), touches);
63
+ };
64
+ const touch = (id) => {
65
+ touched.set(JSON.stringify(id), { id, accessed: Date.now() });
66
+ touchTimer ??= setTimeout(() => {
67
+ flushTouches().catch(() => undefined);
68
+ }, TOUCH_DELAY_MS);
69
+ };
70
+ return {
71
+ async get(namespace, key) {
72
+ const id = [namespace, key];
73
+ const value = await readValue(await open(), id);
74
+ if (value !== null) {
75
+ touch(id);
76
+ }
77
+ return value;
78
+ },
79
+ async set(namespace, key, value) {
80
+ const id = [namespace, key];
81
+ touched.delete(JSON.stringify(id));
82
+ const write = { id, value, charge: chargeOf(id, value) };
83
+ const freeBytes = await originFreeBytes();
84
+ await writeValue(await open(), write, budgets, freeBytes);
85
+ },
86
+ async remove(namespace, key) {
87
+ const id = [namespace, key];
88
+ touched.delete(JSON.stringify(id));
89
+ await removeValue(await open(), id);
90
+ },
91
+ };
92
+ }
93
+ function openDatabase(name, onClosed) {
94
+ return new Promise((resolve, reject) => {
95
+ if (typeof indexedDB === "undefined") {
96
+ reject(new Error("IndexedDB is unavailable."));
97
+ return;
98
+ }
99
+ let blocked = false;
100
+ const request = indexedDB.open(name, DATABASE_VERSION);
101
+ request.onupgradeneeded = () => createStores(request.result);
102
+ request.onsuccess = () => {
103
+ const database = request.result;
104
+ // A blocked open has already failed its callers. The connection it gets
105
+ // once the other tab lets go is closed, and the next call opens again.
106
+ if (blocked) {
107
+ database.close();
108
+ return;
109
+ }
110
+ // Another tab opening a later version, or deleting the database, waits
111
+ // until this connection closes.
112
+ database.onversionchange = () => {
113
+ database.close();
114
+ onClosed();
115
+ };
116
+ // The browser closes a connection itself when it clears site data.
117
+ database.onclose = onClosed;
118
+ resolve(database);
119
+ };
120
+ request.onerror = () => reject(request.error ?? new Error("IndexedDB open failed."));
121
+ request.onblocked = () => {
122
+ blocked = true;
123
+ reject(new Error("IndexedDB open was blocked."));
124
+ };
125
+ });
126
+ }
127
+ // Older versions kept no totals for each namespace, so an older database
128
+ // starts empty, which a cache allows.
129
+ function createStores(database) {
130
+ for (const name of Array.from(database.objectStoreNames)) {
131
+ database.deleteObjectStore(name);
132
+ }
133
+ database.createObjectStore(VALUES);
134
+ const entries = database.createObjectStore(ENTRIES, { keyPath: ["namespace", "key"] });
135
+ entries.createIndex(ACCESSED, "accessed");
136
+ entries.createIndex(NAMESPACE_ACCESSED, ["namespace", "accessed"]);
137
+ database.createObjectStore(META);
138
+ }
139
+ function readValue(database, id) {
140
+ const transaction = database.transaction(VALUES, "readonly");
141
+ const request = transaction.objectStore(VALUES).get(id);
142
+ return finished(transaction).then(() => asValue(request.result));
143
+ }
144
+ function touchEntries(database, touches) {
145
+ if (touches.length === 0) {
146
+ return Promise.resolve();
147
+ }
148
+ const transaction = database.transaction(ENTRIES, "readwrite");
149
+ const entries = transaction.objectStore(ENTRIES);
150
+ for (const { id, accessed } of touches) {
151
+ const request = entries.get(id);
152
+ request.onsuccess = () => {
153
+ const entry = request.result;
154
+ // An entry removed since the read stays removed, and one written since
155
+ // keeps its newer time.
156
+ if (entry && entry.accessed < accessed) {
157
+ entries.put({ ...entry, accessed });
158
+ }
159
+ };
160
+ }
161
+ return finished(transaction);
162
+ }
163
+ // What the browser says this origin can still store. Neither budget is ever
164
+ // more than the store's own total plus this.
165
+ async function originFreeBytes() {
166
+ try {
167
+ const { quota, usage } = await navigator.storage.estimate();
168
+ if (typeof quota === "number" && typeof usage === "number") {
169
+ return Math.max(0, quota - usage);
170
+ }
171
+ }
172
+ catch {
173
+ // No estimate in this context, or no navigator at all.
174
+ }
175
+ return Infinity;
176
+ }
177
+ // A write the browser refuses for want of space evicts the least recently used
178
+ // entries and is tried once more.
179
+ async function writeValue(database, write, budgets, freeBytes) {
180
+ try {
181
+ await putValue(database, write, budgets, freeBytes);
182
+ }
183
+ catch (error) {
184
+ if (!isQuotaError(error)) {
185
+ throw error;
186
+ }
187
+ await makeRoom(database, write);
188
+ await putValue(database, write, budgets, freeBytes);
189
+ }
190
+ }
191
+ // The write, the totals and the eviction happen in one transaction, so two
192
+ // tabs writing at once still leave the store within its budgets. The writing
193
+ // namespace's own entries are evicted first, until it is within the budget for
194
+ // a namespace; then the entries of every namespace, until the store is within
195
+ // its total budget.
196
+ function putValue(database, write, budgets, freeBytes) {
197
+ const transaction = database.transaction([VALUES, ENTRIES, META], "readwrite");
198
+ const stores = storesOf(transaction);
199
+ const [namespace, key] = write.id;
200
+ readTotals(stores, write.id, (total, namespaceTotal, old) => {
201
+ const totalBudget = Math.min(budgets.total, total + freeBytes);
202
+ const namespaceBudget = Math.min(budgets.deck, totalBudget);
203
+ // An entry over the budget for a namespace is not kept, and the old value
204
+ // under its key goes too, so a later get does not return it.
205
+ if (write.charge > namespaceBudget) {
206
+ deleteEntry(stores, write.id);
207
+ saveTotals(stores, total, new Map(old ? [[namespace, old.size]] : []));
208
+ return;
209
+ }
210
+ stores.values.put(write.value, write.id);
211
+ const entry = { namespace, key, size: write.charge, accessed: Date.now() };
212
+ stores.entries.put(entry);
213
+ const written = write.charge - (old?.size ?? 0);
214
+ stores.meta.put(namespaceTotal + written, namespaceTotalKey(namespace));
215
+ const freed = new Map();
216
+ const namespaceExcess = namespaceTotal + written - namespaceBudget;
217
+ evictOldest(stores, namespace, namespaceExcess, write.id, freed, () => {
218
+ const totalExcess = total + written - sumOf(freed) - totalBudget;
219
+ evictOldest(stores, null, totalExcess, write.id, freed, () => {
220
+ saveTotals(stores, total + written, freed);
221
+ });
222
+ });
223
+ });
224
+ return finished(transaction);
225
+ }
226
+ // After a write is refused for want of space, the old value under its key is
227
+ // removed, and the least recently used entries are evicted until the entries
228
+ // and the new value together take at most half of what the entries took.
229
+ function makeRoom(database, write) {
230
+ const transaction = database.transaction([VALUES, ENTRIES, META], "readwrite");
231
+ const stores = storesOf(transaction);
232
+ readTotals(stores, write.id, (total, _namespaceTotal, old) => {
233
+ deleteEntry(stores, write.id);
234
+ const freed = new Map();
235
+ if (old) {
236
+ freed.set(old.namespace, old.size);
237
+ }
238
+ const target = Math.max(0, total / 2 - write.charge);
239
+ evictOldest(stores, null, total - sumOf(freed) - target, null, freed, () => {
240
+ saveTotals(stores, total, freed);
241
+ });
242
+ });
243
+ return finished(transaction);
244
+ }
245
+ // Walks the entries from least recently accessed, those of one namespace or of
246
+ // all, deleting until `excess` bytes are freed, then calls `then`. The entry
247
+ // just written is skipped. Each deletion is added to `freed` under its
248
+ // namespace.
249
+ function evictOldest(stores, namespace, excess, kept, freed, then) {
250
+ if (excess <= 0) {
251
+ then();
252
+ return;
253
+ }
254
+ const request = namespace === null
255
+ ? stores.entries.index(ACCESSED).openCursor()
256
+ : stores.entries
257
+ .index(NAMESPACE_ACCESSED)
258
+ .openCursor(IDBKeyRange.bound([namespace, -Infinity], [namespace, Infinity]));
259
+ request.onsuccess = () => {
260
+ const cursor = request.result;
261
+ if (!cursor || excess <= 0) {
262
+ then();
263
+ return;
264
+ }
265
+ const entry = cursor.value;
266
+ if (!kept || entry.namespace !== kept[0] || entry.key !== kept[1]) {
267
+ stores.values.delete(cursor.primaryKey);
268
+ cursor.delete();
269
+ excess -= entry.size;
270
+ freed.set(entry.namespace, (freed.get(entry.namespace) ?? 0) + entry.size);
271
+ }
272
+ cursor.continue();
273
+ };
274
+ }
275
+ function removeValue(database, id) {
276
+ const transaction = database.transaction([VALUES, ENTRIES, META], "readwrite");
277
+ const stores = storesOf(transaction);
278
+ readTotals(stores, id, (total, _namespaceTotal, entry) => {
279
+ deleteEntry(stores, id);
280
+ if (entry) {
281
+ saveTotals(stores, total, new Map([[entry.namespace, entry.size]]));
282
+ }
283
+ });
284
+ return finished(transaction);
285
+ }
286
+ function storesOf(transaction) {
287
+ return {
288
+ values: transaction.objectStore(VALUES),
289
+ entries: transaction.objectStore(ENTRIES),
290
+ meta: transaction.objectStore(META),
291
+ };
292
+ }
293
+ // Requests in a transaction complete in the order they were made, so both
294
+ // totals have been read when the entry's request succeeds.
295
+ function readTotals(stores, id, then) {
296
+ const total = stores.meta.get(TOTAL);
297
+ const namespaceTotal = stores.meta.get(namespaceTotalKey(id[0]));
298
+ const entry = stores.entries.get(id);
299
+ entry.onsuccess = () => {
300
+ then(total.result ?? 0, namespaceTotal.result ?? 0, entry.result);
301
+ };
302
+ }
303
+ // Stores the total less what was freed, and takes what was freed off each
304
+ // namespace's total. A namespace left with nothing loses its record.
305
+ function saveTotals(stores, total, freed) {
306
+ stores.meta.put(total - sumOf(freed), TOTAL);
307
+ for (const [namespace, bytes] of freed) {
308
+ const request = stores.meta.get(namespaceTotalKey(namespace));
309
+ request.onsuccess = () => {
310
+ const left = (request.result ?? 0) - bytes;
311
+ if (left > 0) {
312
+ stores.meta.put(left, namespaceTotalKey(namespace));
313
+ }
314
+ else {
315
+ stores.meta.delete(namespaceTotalKey(namespace));
316
+ }
317
+ };
318
+ }
319
+ }
320
+ function namespaceTotalKey(namespace) {
321
+ return ["namespace", namespace];
322
+ }
323
+ function sumOf(freed) {
324
+ let sum = 0;
325
+ for (const bytes of freed.values()) {
326
+ sum += bytes;
327
+ }
328
+ return sum;
329
+ }
330
+ function deleteEntry(stores, id) {
331
+ stores.values.delete(id);
332
+ stores.entries.delete(id);
333
+ }
334
+ // Text is counted at two bytes a character, the size of a JavaScript string,
335
+ // so measuring it costs no encoding.
336
+ function chargeOf(id, value) {
337
+ const valueBytes = typeof value === "string" ? value.length * 2 : value.byteLength;
338
+ return valueBytes + (id[0].length + id[1].length) * 4 + RECORD_BYTES;
339
+ }
340
+ function asValue(stored) {
341
+ if (typeof stored === "string" || stored instanceof ArrayBuffer) {
342
+ return stored;
343
+ }
344
+ return null;
345
+ }
346
+ function isQuotaError(error) {
347
+ return error instanceof DOMException && error.name === "QuotaExceededError";
348
+ }
349
+ // A failed request aborts its transaction with that request's error, so a write
350
+ // the browser refuses for space rejects with QuotaExceededError.
351
+ function finished(transaction) {
352
+ return new Promise((resolve, reject) => {
353
+ transaction.oncomplete = () => resolve();
354
+ transaction.onabort = () => {
355
+ reject(transaction.error ?? new Error("IndexedDB transaction aborted."));
356
+ };
357
+ });
358
+ }
@@ -3,6 +3,7 @@ type PostChannel = "mobile" | "web";
3
3
  export interface HostStreamOptions {
4
4
  onStream?: (event: unknown) => void;
5
5
  signal?: AbortSignal;
6
+ transfer?: Transferable[];
6
7
  }
7
8
  interface ReactNativeWebViewBridge {
8
9
  postMessage: (message: string) => void;
@@ -143,7 +143,7 @@ function sendCommand(channel, command, params, stream) {
143
143
  return;
144
144
  }
145
145
  installHostListener();
146
- sendEnvelope(channel, { castleSdk: CASTLE_SDK_PROTOCOL, requestId, command, params });
146
+ sendEnvelope(channel, { castleSdk: CASTLE_SDK_PROTOCOL, requestId, command, params }, stream.transfer);
147
147
  });
148
148
  }
149
149
  // Interactive commands have no timeout; they resolve only when the host replies.
@@ -202,13 +202,12 @@ function cancelledError(command) {
202
202
  operation: command,
203
203
  });
204
204
  }
205
- function sendEnvelope(channel, envelope) {
206
- const json = JSON.stringify(envelope);
205
+ function sendEnvelope(channel, envelope, transfer = []) {
207
206
  if (channel === "mobile") {
208
- window.ReactNativeWebView?.postMessage(json);
207
+ window.ReactNativeWebView?.postMessage(JSON.stringify(envelope));
209
208
  }
210
209
  else {
211
- window.parent.postMessage(envelope, "*");
210
+ window.parent.postMessage(envelope, "*", transfer);
212
211
  }
213
212
  }
214
213
  // The mobile host can't dispatch a DOM 'message' event, so it calls this global