castle-web-cli 0.4.246 → 0.4.247

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.
@@ -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
 
@@ -450,7 +552,11 @@ overwrite each other, a counter can be added to safely from several
450
552
  places at once, and a deck can hold much more than `Storage` allows and
451
553
  read back a slice of it rather than the whole thing.
452
554
 
453
- 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()`.
454
560
 
455
561
  Scopes decide who owns a key:
456
562
 
@@ -460,7 +566,10 @@ Scopes decide who owns a key:
460
566
  - `Store.user(userId)` — another player's public data. Anyone can read
461
567
  it; only that player, or the deck's session server, can write it.
462
568
  - `Store.private` — the current player's own data. Nobody else can read
463
- 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`.
464
573
 
465
574
  ### `Store.<scope>.get<T>(keys): Promise<Record<string, T>>`
466
575
 
@@ -469,8 +578,11 @@ the result rather than present as `null`.
469
578
 
470
579
  ```js
471
580
  const { level = 1, name } = await Store.deck.get(["level", "name"]);
581
+ const { save } = await Store.private.get(["save"]); // { coins: 12, ... } or undefined
472
582
  ```
473
583
 
584
+ At most 32 keys in one call.
585
+
474
586
  ### `Store.<scope>.set(values): Promise<void>`
475
587
 
476
588
  Writes several keys. Nearby writes are grouped, so saving on every
@@ -478,13 +590,20 @@ change costs one request per burst. The promise resolves once the
478
590
  platform has the write, so a deck can tell whether saving worked.
479
591
 
480
592
  ```js
481
- await Store.deck.set({ level: 7, name: "Ada" });
593
+ await Store.me.set({ name: "Ada", outfit: { hat: "tophat", color: "#f80" } });
482
594
  ```
483
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
+
484
599
  ### `Store.<scope>.remove(keys): Promise<void>`
485
600
 
486
601
  Removes keys.
487
602
 
603
+ ```js
604
+ await Store.private.remove(["save"]);
605
+ ```
606
+
488
607
  ### `Store.<scope>.increment(key, delta?): Promise<number>`
489
608
 
490
609
  Adds `delta` (default `1`) to a number and returns the new total,
@@ -499,7 +618,11 @@ const plays = await Store.deck.increment("plays");
499
618
  ### `Store.<scope>.list(options?): Promise<{ entries, cursor }>`
500
619
 
501
620
  Reads a page of keys in order, optionally only those starting with
502
- `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`.
503
626
 
504
627
  ```js
505
628
  let cursor = null;
@@ -530,16 +653,22 @@ const top = await Store.board("highscores").top(10);
530
653
  const mine = await Store.board("highscores").get();
531
654
  ```
532
655
 
533
- - `submit(score)` records the current player's score. A later submission
534
- replaces an earlier one, so compare first if you only want to keep a
535
- personal best.
536
- - `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.
537
661
  - `get(userId?)` returns one player's score, defaulting to the current
538
662
  player, or `null` if they have none.
539
663
 
540
- A deck's session server can submit any player's score, which is how a
541
- leaderboard becomes something a player cannot fake. See the multiplayer
542
- 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).
543
672
 
544
673
  ### `Store.usage(): Promise<StoreUsage>`
545
674
 
@@ -562,11 +691,11 @@ if (player.byteCount > player.byteLimit * 0.9) {
562
691
  Each has `byteCount`, `byteLimit`, `keyCount` and `keyLimit`. A board
563
692
  score counts as a key. The answer includes the `set` and `remove` calls
564
693
  the page made before calling it, even ones still being batched; await an
565
- `increment` or a board `submit` first if the answer should include it. A player can only ever see their own usage, not
566
- 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.
567
696
 
568
- `rate` says how much of the per-second rate limits (the last two rows of
569
- 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
570
699
  off before a call is refused rather than after:
571
700
 
572
701
  ```js
@@ -580,7 +709,7 @@ if (rate && rate.caller.opsUsed > rate.caller.opsLimit * 0.8) {
580
709
  one every player of the deck shares.
581
710
  - Each has `opsUsed`, `opsLimit`, `bytesUsed` and `bytesLimit`, counted
582
711
  over the current one-second window, and the `usage` call itself is
583
- counted in them.
712
+ counted in them. The session server's own limit is not reported here.
584
713
  - `rate.callerClass` names which limit `caller` is: `"client"` for a
585
714
  page.
586
715
 
@@ -596,7 +725,8 @@ The platform caps key length, value size, how many keys one read may
596
725
  name, and how much each player may store, and it limits how fast a
597
726
  player may read and write. Going over one of these rejects with a
598
727
  `CastleError` whose `code` says which, so a deck can tell a player it is
599
- 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:
600
730
 
601
731
  | limit | value |
602
732
  |---|---|
@@ -605,18 +735,23 @@ saving too fast apart from a player who is out of space:
605
735
  | keys in one `get` | 32 |
606
736
  | one player's data in a deck | 50 MB, 50,000 keys |
607
737
  | the deck's shared data (`Store.deck`) | 500 MB, 1,000,000 keys |
738
+ | a board name, a `list` prefix | 128 bytes |
608
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 |
609
741
  | every player of a deck together | 500 calls a second, 8 MB a second |
610
742
 
611
743
  These do not reject. `set` and `remove` with more than 32 keys are split
612
744
  into several calls by the SDK (each still counts against the rate above).
613
745
  A `list` page holds at most 1,000 entries (a larger `limit` is lowered to
614
746
  it) and ends early once it reaches 1 MB; take the next page with its
615
- `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.
616
749
 
617
750
  A player's data is everything stored for them: their `Store.private`
618
751
  keys, their `Store.user(id)` keys, their scores on every board, and
619
- 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.
620
755
  Each player has their own allowance, so a deck with more
621
756
  players can hold more, and one player filling theirs does not stop
622
757
  anyone else. A write that shrinks what a player stores always succeeds,
@@ -8,6 +8,9 @@ export type { AvatarResult, CastleAvatarApi } from "./avatar";
8
8
  export { Characters } from "./characters";
9
9
  export type { CastleCharactersApi, CharacterHandle, CharacterHistoryOptions, CharacterSendInput, } from "./characters";
10
10
  export { Decks } from "./decks";
11
+ /** @experimental Deck invites are not available to every player yet. */
12
+ export { DeckInvites } from "./deckInvites";
13
+ export type { CastleDeckInvitesApi, DeckInviteArrivalResult, DeckInviteResult, DeckInviteUser, } from "./deckInvites";
11
14
  export type { CastleDecksApi, DeckSummary, DecksListParams, DecksListResult } from "./decks";
12
15
  export { CastleError } from "./errors";
13
16
  export { experiment, experiments, experimentsReady } from "./experiments";
@@ -5,6 +5,8 @@ export { Analytics } from "./analytics";
5
5
  export { Avatar } from "./avatar";
6
6
  export { Characters } from "./characters";
7
7
  export { Decks } from "./decks";
8
+ /** @experimental Deck invites are not available to every player yet. */
9
+ export { DeckInvites } from "./deckInvites";
8
10
  export { CastleError } from "./errors";
9
11
  export { experiment, experiments, experimentsReady } from "./experiments";
10
12
  export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckFile, } from "./files";
@@ -305,6 +305,39 @@ export interface HubHeartsResult {
305
305
  status: "ok" | "unavailable";
306
306
  hearts: string[];
307
307
  }
308
+ /**
309
+ * @experimental Deck invites are not available to every player yet, and only
310
+ * a deck whose server config sets `invites: true` can mint them. `reason` is
311
+ * Ghost's refusal code (`FEATURE_NOT_ENABLED`, `CAULDRON_DECK_INVITE_*`) when it
312
+ * gave one, or `UNSUPPORTED_HOST` from a host older than deck invites; it is
313
+ * absent on hosts without deck invites.
314
+ */
315
+ export type DeckInviteResult = {
316
+ status: "ok";
317
+ url: string;
318
+ expiresAt: string;
319
+ } | {
320
+ status: "unavailable";
321
+ reason?: string;
322
+ };
323
+ /** @experimental The friend who sent the link this play opened with. */
324
+ export interface DeckInviteUser {
325
+ userId: string;
326
+ username: string;
327
+ }
328
+ /**
329
+ * @experimental What arriving through a deck invite link did: the players this
330
+ * one now follows (and who follow back). `unavailable` when the play did not
331
+ * open from a link, is not in a session yet, or the host has no deck invites.
332
+ */
333
+ export type DeckInviteArrivalResult = {
334
+ status: "ok";
335
+ inviter: DeckInviteUser | null;
336
+ friends: DeckInviteUser[];
337
+ } | {
338
+ status: "unavailable";
339
+ reason?: string;
340
+ };
308
341
  /** Hub.chat: only the messages after a cursor an earlier answer returned. */
309
342
  export interface HubChatParams {
310
343
  after?: string;
@@ -749,6 +782,8 @@ export interface CommandParams {
749
782
  "hub.setHearts": {
750
783
  doorIds: string[];
751
784
  };
785
+ "deck.invite": Record<string, never>;
786
+ "deck.inviteArrival": Record<string, never>;
752
787
  "hub.signIn": HubSignInParams;
753
788
  "hub.pushPermission": Record<string, never>;
754
789
  "hub.pushDestination": Record<string, never>;
@@ -964,6 +999,8 @@ export interface CommandResult {
964
999
  "hub.undoInvite": HubReportResult;
965
1000
  "hub.hearts": HubHeartsResult;
966
1001
  "hub.setHearts": HubHeartsResult;
1002
+ "deck.invite": DeckInviteResult;
1003
+ "deck.inviteArrival": DeckInviteArrivalResult;
967
1004
  "hub.signIn": HubSignInResult;
968
1005
  "hub.pushPermission": HubPushPermissionResult;
969
1006
  "hub.pushDestination": HubPushDestinationResult;
@@ -0,0 +1,27 @@
1
+ import type { DeckInviteArrivalResult, DeckInviteResult } from "./commands";
2
+ export type { DeckInviteArrivalResult, DeckInviteResult, DeckInviteUser, } from "./commands";
3
+ /**
4
+ * @experimental Not available to every player yet, and only for a deck whose
5
+ * server config opts in with `invites: true`; the API may still change.
6
+ *
7
+ * Invite links for an ordinary deck: a player in a public multiplayer session
8
+ * makes a link, and a friend who opens it joins that player's public shard and
9
+ * the two follow each other. The host owns the deck, the session and the link's
10
+ * token; a deck never passes any of them.
11
+ */
12
+ export interface CastleDeckInvitesApi {
13
+ /**
14
+ * Make an expiring link into the public session this player joined last.
15
+ * `unavailable` when there is none, on hosts without deck invites, or when
16
+ * Castle refuses (`reason` carries its code).
17
+ */
18
+ invite(): Promise<DeckInviteResult>;
19
+ /**
20
+ * Once this play has joined a public session: if it opened from an invite
21
+ * link, follow the inviter (and be followed back) and return who. Safe to
22
+ * call again; `unavailable` when the play did not come from a link.
23
+ */
24
+ inviteArrival(): Promise<DeckInviteArrivalResult>;
25
+ }
26
+ /** @experimental See {@link CastleDeckInvitesApi}. */
27
+ export declare const DeckInvites: CastleDeckInvitesApi;
@@ -0,0 +1,22 @@
1
+ import { CastleError } from "./errors";
2
+ import { hostRequest } from "./transport";
3
+ const UNSUPPORTED_HOST = { status: "unavailable", reason: "UNSUPPORTED_HOST" };
4
+ // A host older than deck invites does not know the command.
5
+ async function supported(ask) {
6
+ try {
7
+ return await ask();
8
+ }
9
+ catch (error) {
10
+ if (error instanceof CastleError && error.code === "UNKNOWN_COMMAND")
11
+ return UNSUPPORTED_HOST;
12
+ throw error;
13
+ }
14
+ }
15
+ async function invite() {
16
+ return supported(() => hostRequest("deck.invite", {}));
17
+ }
18
+ async function inviteArrival() {
19
+ return supported(() => hostRequest("deck.inviteArrival", {}));
20
+ }
21
+ /** @experimental See {@link CastleDeckInvitesApi}. */
22
+ export const DeckInvites = { invite, inviteArrival };
@@ -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
  }
@@ -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.