castle-web-sdk 0.4.56 → 0.4.58

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.
package/README.md CHANGED
@@ -158,24 +158,46 @@ client.
158
158
  ### `session.storage`
159
159
 
160
160
  A session ends when its last player leaves, and its memory goes with it.
161
- `session.storage` is what outlives one, and it is the same store the deck's
162
- clients see through [`Store`](#store):
161
+ `session.storage` is what outlives one. It is the same store the deck's
162
+ clients see through [`Store`](#store), with the same JSON values and
163
+ the same limits:
163
164
 
164
165
  ```js
165
166
  export default {
166
167
  async onPlayerJoin(session, player) {
167
- const { wins = 0 } = await session.storage.deck.get(["wins"]);
168
- session.send(player.playerId, { wins });
168
+ const key = `wins:${player.userId}`;
169
+ const { [key]: wins = 0 } = await session.storage.deck.get([key]);
170
+ session.send(player.playerId, { type: "wins", wins });
171
+ },
172
+
173
+ async onMessage(session, player, data) {
174
+ if (data.type !== "move") return;
175
+ // Your rules decide the winner from the server's own game state,
176
+ // never from a client saying it won.
177
+ const winner = applyMove(session, player, data);
178
+ if (winner) {
179
+ const wins = await session.storage.deck.increment(`wins:${winner.userId}`);
180
+ session.broadcast({ type: "won", userId: winner.userId, wins });
181
+ }
169
182
  },
170
183
 
171
184
  async onShutdown(session) {
172
- await session.storage.deck.set({ endedAt: Date.now() });
185
+ await session.storage.deck.set({ lastGame: { endedAt: Date.now() } });
173
186
  },
174
187
  };
175
188
  ```
176
189
 
177
- `session.storage.deck` is shared by everyone playing.
178
- `session.storage.user(userId)` is one player's public data.
190
+ - `session.storage.deck` is shared by everyone playing.
191
+ - `session.storage.user(userId)` is one player's public data, the same
192
+ keys that player reads and writes as `Store.me`.
193
+ - `session.storage.board(name)` is a leaderboard.
194
+
195
+ Each scope has `get(keys)`, `set(values)`, `remove(keys)`,
196
+ `increment(key, delta?)` and `list({ prefix, limit, cursor })`, which
197
+ work as they do on `Store`, and the root and its buckets also support
198
+ the [atomic save API](#atomic-saves). A board has
199
+ `submit(userId, score)`, `top(limit?)` and `get(userId)`.
200
+
179
201
  `await session.storage.playthrough(userId)` opens that player's generation-bound
180
202
  game state. Its `resetGeneration` is present only after an administrator has
181
203
  reset that player's progress for this deck. It is a monotonic reset marker,
@@ -183,9 +205,6 @@ separate from the handle's `generation`, which fences playthrough operations.
183
205
  Deck-scope storage writes are not fenced by either generation; a server using
184
206
  `session.storage.deck` must discard its own stale queued writes and cached
185
207
  per-player values when it observes a newer reset marker.
186
- `session.storage.board(name)` is a leaderboard. The root and its buckets also
187
- support the [atomic save API](#atomic-saves). Each scope has the same
188
- `get`, `set`, `remove`, `increment` and `list` as `Store`.
189
208
 
190
209
  `session.storage.town(userId)` lets a door deck's server read and write one
191
210
  signed-in player's rows in its source town's deck scope, for things such as
@@ -204,20 +223,103 @@ During dev serve, keys live under `town/` in the dev deck's own deck scope,
204
223
  so testing a door never changes a real town. An unpublished deck still needs
205
224
  a published deck id for storage.
206
225
 
207
- Two differences follow from a session server not being a player:
226
+ Three differences follow from a session server not being a player:
208
227
 
209
- - **It owns `deck` scope.** Once a deck has a published server, clients read
210
- that data but no longer write it, which is what lets you keep authoritative
211
- state players cannot forge.
228
+ - **It owns `deck` scope.** Once a deck has a published server, clients
229
+ read that data but no longer write it, which is what lets you keep
230
+ authoritative state players cannot forge. Saving the deck again without
231
+ a server entry hands it back, but only when `save-deck` runs from the
232
+ project that published the server (its
233
+ `.castle/published-server-bundle.json` records that publish); otherwise
234
+ the old server stays published.
212
235
  - **It has no self.** There is no `storage.me`, and a user scope or a board
213
236
  submission must name the player: `session.storage.user(player.userId)`,
214
- `session.storage.board("high").submit(player.userId, score)`. A server can
215
- submit anyone's score, which is what makes a server-run leaderboard worth
216
- trusting. It can never read `private` storage, not even for its own players.
237
+ `session.storage.board("high").submit(player.userId, score)`. Castle
238
+ does not check that the id belongs to a real player, so use only the
239
+ `userId` of a `player` Castle gave your callbacks, never one a client
240
+ sends.
241
+ - **It never sees `private`.** `Store.private` is the player's alone, and
242
+ `session.storage` has no way to reach it.
243
+
244
+ A server's writes are not batched the way a client's are: each `set` or
245
+ `remove` is sent at once and resolves when the platform has it. Each
246
+ request commits as a unit, but a `set` with more than 32 keys, or more
247
+ than 316 KB once encoded, goes out as several requests, so it can land
248
+ partly. A value is encoded twice on the way, so one full of quotes or
249
+ backslashes can be refused even under the 256 KB value limit. `remove`
250
+ splits by key count only. A session has its own rate limit, 30 calls and
251
+ 2 MB a second, shared by every player in it.
252
+
253
+ Don't await storage in `onStart`: the session is not ready for it yet, so
254
+ a call there can fail or stall. Read on the first join or message
255
+ instead. `onPlayerJoin` runs again when a player reconnects (with the
256
+ same `playerId`), so a counter bumped on join counts reconnects too.
257
+
258
+ `onShutdown` is awaited, so a write you await there gets its chance to
259
+ land, but it can still be refused (by a rate limit, for one), and
260
+ `onShutdown` runs only on a clean stop. An out-of-memory kill or a host
261
+ failing sends no shutdown at all, so save as things change and treat
262
+ `onShutdown` as the last chance, not the plan.
263
+
264
+ #### A leaderboard players can't fake
265
+
266
+ On a deck with a published server, only the server submits scores; a
267
+ client `submit` is refused with `CAULDRON_STORAGE_FORBIDDEN`. Work the
268
+ score out on the server and submit it for the player. Clients show the
269
+ board with `Store.board("high").top(10)` and `Store.board("high").get()`.
270
+
271
+ ```js
272
+ export default {
273
+ async onMessage(session, player, data) {
274
+ if (data.type !== "finished") return;
275
+ // From what the server saw of the run, not from anything in `data`.
276
+ const score = scoreRun(session, player);
277
+ const board = session.storage.board("high");
278
+ const best = await board.get(player.userId);
279
+ if (!best || score > best.score) await board.submit(player.userId, score);
280
+ },
281
+ };
282
+ ```
283
+
284
+ `submit` replaces the player's score rather than keeping the higher one,
285
+ and this read-then-submit is not atomic: if one player finishes in two
286
+ sessions at the same moment, the lower score can land last. That is rare
287
+ enough to accept for most games.
288
+
289
+ Moving a game that used client submits over to a server keeps the scores
290
+ already on the board, forged ones included. Use a new board name for the
291
+ server's scores.
292
+
293
+ #### Per-player records
294
+
295
+ Anything the server must be able to trust about a player, such as a coin
296
+ balance, a rating or an unlock, goes in deck scope under a key named
297
+ after them. Every player can read deck scope, so nothing secret goes
298
+ there. A player can write their own `user(userId)` keys from a client,
299
+ so those are only for things they are allowed to set, such as a display
300
+ name or an outfit.
217
301
 
218
- `onShutdown` is awaited, so a save made there does land — but only on a clean
219
- stop. An out-of-memory kill or a host failing sends no shutdown at all, so
220
- save as things change and treat `onShutdown` as the last chance, not the plan.
302
+ ```js
303
+ // The coins this server placed, by id.
304
+ const coins = new Map([["c1", { x: 4, y: 2 }], ["c2", { x: 9, y: 7 }]]);
305
+
306
+ export default {
307
+ async onMessage(session, player, data) {
308
+ if (data.type !== "collect") return;
309
+ const coin = coins.get(data.coinId);
310
+ // The server decides: the coin must still be there, and the player
311
+ // must be standing on it by the server's own record of where they are.
312
+ if (!coin || !isTouching(positionOf(player), coin)) return;
313
+ coins.delete(data.coinId);
314
+ const total = await session.storage.deck.increment(`coins:${player.userId}`, 5);
315
+ session.send(player.playerId, { type: "coins", coins: total });
316
+ },
317
+ };
318
+ ```
319
+
320
+ Deck-scope keys count against the deck's shared allowance (500 MB and
321
+ 1,000,000 keys, see the `Store` limits), not the player's, so keep one
322
+ key or a few per player rather than one per event.
221
323
 
222
324
  ### `session.hub`
223
325
 
@@ -233,7 +335,8 @@ dev serve.
233
335
  - `session.hub.place`, `.title` and `.result` are the place and the result shape
234
336
  as published (`result` is `null` for a place that reports none, such as a town).
235
337
  - `session.hub.reconnectWindowMs`, when present, is Castle's pinned hub-place
236
- reconnect grace in milliseconds, inclusive at the deadline. It is absent on
338
+ reconnect grace in milliseconds, inclusive at the deadline (at most 180000, or
339
+ 300000 on an owner house that opted into `houseResume`). It is absent on
237
340
  sessions without a pinned grace and older hosts. Kits use it to match visit retention to the
238
341
  transport window; deck code does not choose it.
239
342
  - `session.hub.arrival(playerId)` is how a player came in when Castle placed them
@@ -449,7 +552,11 @@ overwrite each other, a counter can be added to safely from several
449
552
  places at once, and a deck can hold much more than `Storage` allows and
450
553
  read back a slice of it rather than the whole thing.
451
554
 
452
- Values can be anything that converts to JSON, the same as `Storage`.
555
+ Values are JSON: numbers, strings, booleans, `null`, and arrays and plain
556
+ objects of those. You get back the same value you stored, not a string, so
557
+ there is nothing to parse. `undefined`, `NaN`, `Infinity`, a `Date`, a class
558
+ instance or a cycle is refused with a `CastleError`
559
+ (`CASTLE_STORAGE_SERIALIZE_FAILED`); store a date as `Date.now()`.
453
560
 
454
561
  Scopes decide who owns a key:
455
562
 
@@ -459,7 +566,10 @@ Scopes decide who owns a key:
459
566
  - `Store.user(userId)` — another player's public data. Anyone can read
460
567
  it; only that player, or the deck's session server, can write it.
461
568
  - `Store.private` — the current player's own data. Nobody else can read
462
- it, and a session server never sees it.
569
+ it, and a session server never sees it. Only a client can use it.
570
+
571
+ Each scope has the same five calls: `get`, `set`, `remove`, `increment`
572
+ and `list`.
463
573
 
464
574
  ### `Store.<scope>.get<T>(keys): Promise<Record<string, T>>`
465
575
 
@@ -468,8 +578,11 @@ the result rather than present as `null`.
468
578
 
469
579
  ```js
470
580
  const { level = 1, name } = await Store.deck.get(["level", "name"]);
581
+ const { save } = await Store.private.get(["save"]); // { coins: 12, ... } or undefined
471
582
  ```
472
583
 
584
+ At most 32 keys in one call.
585
+
473
586
  ### `Store.<scope>.set(values): Promise<void>`
474
587
 
475
588
  Writes several keys. Nearby writes are grouped, so saving on every
@@ -477,13 +590,20 @@ change costs one request per burst. The promise resolves once the
477
590
  platform has the write, so a deck can tell whether saving worked.
478
591
 
479
592
  ```js
480
- await Store.deck.set({ level: 7, name: "Ada" });
593
+ await Store.me.set({ name: "Ada", outfit: { hat: "tophat", color: "#f80" } });
481
594
  ```
482
595
 
596
+ Once the deck publishes a session server, `Store.deck.set` is refused:
597
+ the server owns deck scope. See [`session.storage`](#sessionstorage).
598
+
483
599
  ### `Store.<scope>.remove(keys): Promise<void>`
484
600
 
485
601
  Removes keys.
486
602
 
603
+ ```js
604
+ await Store.private.remove(["save"]);
605
+ ```
606
+
487
607
  ### `Store.<scope>.increment(key, delta?): Promise<number>`
488
608
 
489
609
  Adds `delta` (default `1`) to a number and returns the new total,
@@ -498,7 +618,11 @@ const plays = await Store.deck.increment("plays");
498
618
  ### `Store.<scope>.list(options?): Promise<{ entries, cursor }>`
499
619
 
500
620
  Reads a page of keys in order, optionally only those starting with
501
- `prefix`. Pass the `cursor` from one page to get the next.
621
+ `prefix`. Pass the `cursor` from one page to get the next. A page holds
622
+ 100 entries unless you pass a `limit`, and at most 1,000. A page can
623
+ carry up to 1 MB, more than a player's 512 KB a second, so a page of
624
+ large values can be refused even when nothing else is reading; with
625
+ large values, pass a smaller `limit`.
502
626
 
503
627
  ```js
504
628
  let cursor = null;
@@ -529,16 +653,22 @@ const top = await Store.board("highscores").top(10);
529
653
  const mine = await Store.board("highscores").get();
530
654
  ```
531
655
 
532
- - `submit(score)` records the current player's score. A later submission
533
- replaces an earlier one, so compare first if you only want to keep a
534
- personal best.
535
- - `top(limit?)` returns the highest scores, best first.
656
+ - `submit(score)` records the current player's score, on a deck without
657
+ a session server. A later submission replaces an earlier one, so
658
+ compare first if you only want to keep a personal best.
659
+ - `top(limit?)` returns the highest scores, best first: 10 unless you
660
+ pass a `limit`, and at most 100.
536
661
  - `get(userId?)` returns one player's score, defaulting to the current
537
662
  player, or `null` if they have none.
538
663
 
539
- A deck's session server can submit any player's score, which is how a
540
- leaderboard becomes something a player cannot fake. See the multiplayer
541
- guide.
664
+ Each score is `{ subject, score, updatedAt }`, where `subject` is the
665
+ player's user id. A board name is at most 128 bytes.
666
+
667
+ A client can only submit its own score, and only on a deck without a
668
+ session server. Once a deck publishes a server, only the server submits
669
+ scores, for any player, after checking the result; a client `submit`
670
+ rejects with `CAULDRON_STORAGE_FORBIDDEN`, while `top` and `get` keep
671
+ working. See the [leaderboard pattern](#a-leaderboard-players-cant-fake).
542
672
 
543
673
  ### `Store.usage(): Promise<StoreUsage>`
544
674
 
@@ -561,11 +691,11 @@ if (player.byteCount > player.byteLimit * 0.9) {
561
691
  Each has `byteCount`, `byteLimit`, `keyCount` and `keyLimit`. A board
562
692
  score counts as a key. The answer includes the `set` and `remove` calls
563
693
  the page made before calling it, even ones still being batched; await an
564
- `increment` or a board `submit` first if the answer should include it. A player can only ever see their own usage, not
565
- another player's.
694
+ `increment` or a board `submit` first if the answer should include it.
695
+ A player can only ever see their own usage, not another player's.
566
696
 
567
- `rate` says how much of the per-second rate limits (the last two rows of
568
- the table below) is spent right now, so a deck that writes often can back
697
+ `rate` says how much of the per-second rate limits (the last three rows
698
+ of the table below) is spent right now, so a deck that writes often can back
569
699
  off before a call is refused rather than after:
570
700
 
571
701
  ```js
@@ -579,7 +709,7 @@ if (rate && rate.caller.opsUsed > rate.caller.opsLimit * 0.8) {
579
709
  one every player of the deck shares.
580
710
  - Each has `opsUsed`, `opsLimit`, `bytesUsed` and `bytesLimit`, counted
581
711
  over the current one-second window, and the `usage` call itself is
582
- counted in them.
712
+ counted in them. The session server's own limit is not reported here.
583
713
  - `rate.callerClass` names which limit `caller` is: `"client"` for a
584
714
  page.
585
715
 
@@ -595,7 +725,8 @@ The platform caps key length, value size, how many keys one read may
595
725
  name, and how much each player may store, and it limits how fast a
596
726
  player may read and write. Going over one of these rejects with a
597
727
  `CastleError` whose `code` says which, so a deck can tell a player it is
598
- saving too fast apart from a player who is out of space:
728
+ saving too fast apart from a player who is out of space. These are the
729
+ limits for an ordinary deck:
599
730
 
600
731
  | limit | value |
601
732
  |---|---|
@@ -604,18 +735,23 @@ saving too fast apart from a player who is out of space:
604
735
  | keys in one `get` | 32 |
605
736
  | one player's data in a deck | 50 MB, 50,000 keys |
606
737
  | the deck's shared data (`Store.deck`) | 500 MB, 1,000,000 keys |
738
+ | a board name, a `list` prefix | 128 bytes |
607
739
  | one player's calls | 20 a second, 512 KB a second |
740
+ | one session server's calls | 30 a second, 2 MB a second |
608
741
  | every player of a deck together | 500 calls a second, 8 MB a second |
609
742
 
610
743
  These do not reject. `set` and `remove` with more than 32 keys are split
611
744
  into several calls by the SDK (each still counts against the rate above).
612
745
  A `list` page holds at most 1,000 entries (a larger `limit` is lowered to
613
746
  it) and ends early once it reaches 1 MB; take the next page with its
614
- `cursor`.
747
+ `cursor`. A page still counts against a player's 512 KB a second, so
748
+ lower `limit` when values are large. `top` returns at most 100 scores.
615
749
 
616
750
  A player's data is everything stored for them: their `Store.private`
617
751
  keys, their `Store.user(id)` keys, their scores on every board, and
618
- their `Characters` playthrough.
752
+ their `Characters` playthrough, whoever wrote them. Deck-scope keys count
753
+ against the deck's shared allowance, even when they're named after a
754
+ player.
619
755
  Each player has their own allowance, so a deck with more
620
756
  players can hold more, and one player filling theirs does not stop
621
757
  anyone else. A write that shrinks what a player stores always succeeds,
package/dist/runtime.js CHANGED
@@ -504,6 +504,54 @@ function loadHtml2Canvas() {
504
504
  }
505
505
  return html2canvasPromise;
506
506
  }
507
+ // html2canvas crops its output to the target's transformed box and then paints
508
+ // the target with its own transform on top of that, so a translated target comes
509
+ // out shifted by the translation twice over. The play card is one: it centers
510
+ // itself with `translate(-50%, -50%)`, and its capture showed only the stage's
511
+ // lower-right quarter. html2canvas tries to clear the transform itself, but with
512
+ // a plain inline style that loses to the play card's `!important` rule.
513
+ //
514
+ // A pure translation can be traded for an offset that puts the box in the same
515
+ // place with no transform at all, and that is what the clone gets. Scales and
516
+ // rotations have no such equivalent, so those still go to html2canvas as is.
517
+ function untranslateClone(target) {
518
+ if (target === document.body || target === document.documentElement) {
519
+ return undefined;
520
+ }
521
+ const style = getComputedStyle(target);
522
+ const m = /^matrix\(1, 0, 0, 1, (-?[\d.e+-]+), (-?[\d.e+-]+)\)$/.exec(style.transform);
523
+ if (!m)
524
+ return undefined;
525
+ const tx = Number(m[1]);
526
+ const ty = Number(m[2]);
527
+ let position = style.position;
528
+ let left = parseFloat(style.left);
529
+ let top = parseFloat(style.top);
530
+ if (position === "static") {
531
+ // A relative offset moves a static box without moving anything around it,
532
+ // just as the translation did.
533
+ position = "relative";
534
+ left = 0;
535
+ top = 0;
536
+ }
537
+ else if (position === "sticky" || Number.isNaN(left) || Number.isNaN(top)) {
538
+ return undefined;
539
+ }
540
+ // A box held by opposing insets (`inset: 0`) would stretch or shrink when only
541
+ // left/top move, so the clone keeps the size the original was laid out at.
542
+ const width = style.width;
543
+ const height = style.height;
544
+ return (_doc, clone) => {
545
+ clone.style.setProperty("transform", "none", "important");
546
+ clone.style.setProperty("position", position, "important");
547
+ clone.style.setProperty("left", `${left + tx}px`, "important");
548
+ clone.style.setProperty("top", `${top + ty}px`, "important");
549
+ clone.style.setProperty("right", "auto", "important");
550
+ clone.style.setProperty("bottom", "auto", "important");
551
+ clone.style.setProperty("width", width, "important");
552
+ clone.style.setProperty("height", height, "important");
553
+ };
554
+ }
507
555
  async function captureWithHtml2Canvas(target) {
508
556
  try {
509
557
  const mod = await loadHtml2Canvas();
@@ -511,6 +559,7 @@ async function captureWithHtml2Canvas(target) {
511
559
  backgroundColor: null,
512
560
  scale: devicePixelRatio,
513
561
  useCORS: true,
562
+ onclone: untranslateClone(target),
514
563
  });
515
564
  return c.toDataURL("image/png");
516
565
  }
@@ -741,6 +790,10 @@ function connectBridge() {
741
790
  return;
742
791
  }
743
792
  const port = event.ports[0];
793
+ // A shell that answers reload requests: tell it this SDK will ask before
794
+ // reloading, so it lets restarts through to us (we flush saves first).
795
+ const reloadRequests = data.reloadRequests === true;
796
+ bridgeReloadPort = reloadRequests ? port : null;
744
797
  const socket = {
745
798
  readyState: WebSocket.OPEN,
746
799
  send: (value) => {
@@ -756,9 +809,15 @@ function connectBridge() {
756
809
  const value = messageEvent.data;
757
810
  if (!value || typeof value !== "object")
758
811
  return;
812
+ if (value.type === "castle-reload-response") {
813
+ settleReloadRequest(value);
814
+ return;
815
+ }
759
816
  handleLocalMessage(value);
760
817
  };
761
818
  port.start();
819
+ if (reloadRequests)
820
+ port.postMessage({ type: "castle-sdk-hello", reloadRequests: true });
762
821
  localServeSeen = true;
763
822
  ws = socket;
764
823
  for (const msg of logBuffer)
@@ -1108,6 +1167,48 @@ function stashReloadState() {
1108
1167
  export function requestReload() {
1109
1168
  scheduleReload(REQUEST_RELOAD_DEBOUNCE_MS, "requestReload");
1110
1169
  }
1170
+ // Set when the shell's bridge answers reload requests (castle-bridge-init's
1171
+ // `reloadRequests`). Before reloading, this frame asks the shell: a frame whose
1172
+ // content-origin grant has expired would only fail to reload in place, so the
1173
+ // shell moves it to fresh origins instead and this page does nothing more.
1174
+ let bridgeReloadPort = null;
1175
+ const RELOAD_REQUEST_TIMEOUT_MS = 4000;
1176
+ const pendingReloadRequests = new Map();
1177
+ let nextReloadRequest = 1;
1178
+ function settleReloadRequest(value) {
1179
+ if (typeof value.requestId !== "string")
1180
+ return;
1181
+ const settle = pendingReloadRequests.get(value.requestId);
1182
+ if (!settle)
1183
+ return;
1184
+ pendingReloadRequests.delete(value.requestId);
1185
+ settle(value.relocated === true);
1186
+ }
1187
+ /** Whether the shell moved this frame (so it must not reload itself). */
1188
+ function askShellToRelocate() {
1189
+ const port = bridgeReloadPort;
1190
+ if (!port)
1191
+ return Promise.resolve(false);
1192
+ const requestId = `reload-${nextReloadRequest++}`;
1193
+ return new Promise((resolve) => {
1194
+ const timer = setTimeout(() => {
1195
+ pendingReloadRequests.delete(requestId);
1196
+ resolve(false);
1197
+ }, RELOAD_REQUEST_TIMEOUT_MS);
1198
+ pendingReloadRequests.set(requestId, (relocated) => {
1199
+ clearTimeout(timer);
1200
+ resolve(relocated);
1201
+ });
1202
+ try {
1203
+ port.postMessage({ type: "castle-reload-request", requestId, href: location.href });
1204
+ }
1205
+ catch {
1206
+ clearTimeout(timer);
1207
+ pendingReloadRequests.delete(requestId);
1208
+ resolve(false);
1209
+ }
1210
+ });
1211
+ }
1111
1212
  function scheduleReload(delayMs, reason = "unknown") {
1112
1213
  console.log(`[reload] ${panelTag()} scheduling reload (${reason})`);
1113
1214
  if (restartTimer !== null)
@@ -1121,6 +1222,11 @@ function scheduleReload(delayMs, reason = "unknown") {
1121
1222
  // a failed flush shouldn't block the reload
1122
1223
  }
1123
1224
  stashReloadState();
1225
+ // Saves are flushed above either way. A frame the shell moves (its
1226
+ // grant expired) loads afresh elsewhere; otherwise reload in place,
1227
+ // keeping this origin and the save queue stored on it.
1228
+ if (await askShellToRelocate())
1229
+ return;
1124
1230
  location.reload();
1125
1231
  })();
1126
1232
  }, delayMs);
@@ -46,9 +46,13 @@ function unavailable(op, what) {
46
46
  operation: `session.hub.${op}`,
47
47
  });
48
48
  }
49
+ // An opted-in owner house may be pinned up to 300 s (a three-minute app switch keeps
50
+ // it); every other hub place keeps the host's 180 s cap.
49
51
  function reconnectMetadata(pinned) {
50
52
  const value = pinned.reconnectWindowMs;
51
- return pinned.result === null && typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 180_000
53
+ const cap = pinned.houseResume === true && typeof pinned.owner === "string" && pinned.owner.length > 0
54
+ ? 300_000 : 180_000;
55
+ return pinned.result === null && typeof value === "number" && Number.isInteger(value) && value > 0 && value <= cap
52
56
  ? { reconnectWindowMs: value } : {};
53
57
  }
54
58
  export function createServerHub(platformHandle, arrivals, hiddenPair = () => false) {
@@ -126,6 +126,8 @@ export interface PlatformHubPlace {
126
126
  version: 1;
127
127
  };
128
128
  owner?: string;
129
+ /** Ghost's trusted owner-house opt-in; such a house may pin up to 300 s of grace. */
130
+ houseResume?: true;
129
131
  reconnectWindowMs?: number;
130
132
  place?: string;
131
133
  title?: string | null;
@@ -1,7 +1,7 @@
1
1
  import type { Json } from "../types";
2
2
  import type { CharacterHistory, CharacterOperation } from "../commands";
3
3
  import type { PlatformHandle } from "./platformHandle";
4
- import { type SaveApi, type SaveBucketApi } from "../save";
4
+ import { type SaveApi, type SaveBucketApi, type SaveTarget, type SaveWriter } from "../save";
5
5
  export interface ServerStorageListOptions {
6
6
  prefix?: string;
7
7
  limit?: number;
@@ -16,11 +16,24 @@ export interface ServerStorageListPage<T extends Json = Json> {
16
16
  /** Null means there is nothing left. A short page alone does not mean that. */
17
17
  cursor: string | null;
18
18
  }
19
+ /**
20
+ * Optional writer fence on an ordinary write. The platform applies the write only if
21
+ * `writer` (from `claim`) still holds `target` for this session, checked atomically
22
+ * with the write; otherwise it rejects with `CAULDRON_STORAGE_WRITER_LOST`
23
+ * (`committed: false`) and nothing is written. A `set` large enough to need several
24
+ * requests checks each one, so a claim lost partway stops the rest.
25
+ */
26
+ export interface ServerStorageWriteOptions {
27
+ check?: {
28
+ target: SaveTarget;
29
+ writer: SaveWriter;
30
+ };
31
+ }
19
32
  export interface ServerStorageScope extends SaveBucketApi {
20
33
  get<T extends Json = Json>(keys: string[]): Promise<Record<string, T>>;
21
- set(values: Record<string, Json>): Promise<void>;
22
- remove(keys: string[]): Promise<void>;
23
- increment(key: string, delta?: number): Promise<number>;
34
+ set(values: Record<string, Json>, options?: ServerStorageWriteOptions): Promise<void>;
35
+ remove(keys: string[], options?: ServerStorageWriteOptions): Promise<void>;
36
+ increment(key: string, delta?: number, options?: ServerStorageWriteOptions): Promise<number>;
24
37
  list<T extends Json = Json>(options?: ServerStorageListOptions): Promise<ServerStorageListPage<T>>;
25
38
  }
26
39
  export interface ServerTownStorage {
@@ -1,6 +1,6 @@
1
1
  import { chunked } from "../chunk";
2
2
  import { decodeStorageValue, encodeStorageValue, storageError, } from "../storageJson";
3
- import { createSaveApi, createSaveBucket, preflightSaveRequest, SaveError, } from "../save";
3
+ import { createSaveApi, createSaveBucket, preflightSaveRequest, SaveError, validateSaveTarget, } from "../save";
4
4
  // Deck storage for an author's session server.
5
5
  //
6
6
  // The same store the deck's clients use, reached over the platform channel instead of
@@ -311,19 +311,22 @@ function createScope(call, scope, subject, saveApi) {
311
311
  });
312
312
  return decodeEntries(entries, "session.storage.get");
313
313
  },
314
- async set(values) {
314
+ async set(values, options) {
315
+ const fence = writerCheck(options, "session.storage.set");
315
316
  const entries = encodeEntries(values, "session.storage.set");
316
317
  for (const chunk of batched(entries)) {
317
- await call("set", { scope, subject, entries: chunk });
318
+ await call("set", { scope, subject, entries: chunk, ...fence });
318
319
  }
319
320
  },
320
- async remove(keys) {
321
+ async remove(keys, options) {
322
+ const fence = writerCheck(options, "session.storage.remove");
321
323
  for (const chunk of chunked(assertKeys(keys, "session.storage.remove"), MAX_KEYS_PER_CALL)) {
322
- await call("delete", { scope, subject, keys: chunk });
324
+ await call("delete", { scope, subject, keys: chunk, ...fence });
323
325
  }
324
326
  },
325
- async increment(key, delta = 1) {
326
- const value = await call("increment", { scope, subject, key, delta });
327
+ async increment(key, delta = 1, options) {
328
+ const fence = writerCheck(options, "session.storage.increment");
329
+ const value = await call("increment", { scope, subject, key, delta, ...fence });
327
330
  return Number(value);
328
331
  },
329
332
  async list(options = {}) {
@@ -394,6 +397,31 @@ function assertUserId(userId, operation) {
394
397
  }
395
398
  return userId;
396
399
  }
400
+ /**
401
+ * The `writerCheck` request field, or nothing at all when no check was asked for, so
402
+ * an unchecked write sends exactly the request it always has. Bounded (prefix and
403
+ * writer 128 bytes, subject 256) so it fits inside REQUEST_OVERHEAD_BYTES.
404
+ */
405
+ function writerCheck(options, operation) {
406
+ if (options === undefined || options === null)
407
+ return {};
408
+ if (typeof options !== "object" || Array.isArray(options)) {
409
+ throw storageError("CAULDRON_STORAGE_INVALID_ARGUMENT", "Write options must be an object.", operation);
410
+ }
411
+ if (options.check === undefined)
412
+ return {};
413
+ const check = options.check;
414
+ if (!check || typeof check !== "object" || Array.isArray(check)) {
415
+ throw storageError("CAULDRON_STORAGE_INVALID_ARGUMENT", "A writer check needs a target and a writer.", operation);
416
+ }
417
+ const target = validateSaveTarget(check.target, true);
418
+ if (typeof check.writer !== "string" ||
419
+ check.writer.length === 0 ||
420
+ utf8Length(check.writer) > MAX_KEY_BYTES) {
421
+ throw storageError("CAULDRON_STORAGE_INVALID_ARGUMENT", "A writer check needs the writer from claim.", operation);
422
+ }
423
+ return { writerCheck: { target, writer: check.writer } };
424
+ }
397
425
  /**
398
426
  * Splits entries into requests that fit both limits: the platform's key count and the
399
427
  * channel's frame size.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-sdk",
3
- "version": "0.4.56",
3
+ "version": "0.4.58",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"