castle-web-sdk 0.4.50 → 0.4.52
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 +113 -2
- package/dist/castle.d.ts +6 -2
- package/dist/castle.js +2 -0
- package/dist/commands.d.ts +56 -1
- package/dist/commands.js +29 -1
- package/dist/hub.d.ts +17 -0
- package/dist/hub.js +33 -9
- package/dist/localCache.d.ts +27 -0
- package/dist/localCache.js +115 -0
- package/dist/localCacheStore.d.ts +15 -0
- package/dist/localCacheStore.js +358 -0
- package/dist/multiplayer.js +30 -0
- package/dist/rooms.d.ts +11 -0
- package/dist/rooms.js +22 -0
- package/dist/store.d.ts +8 -2
- package/dist/store.js +5 -1
- package/dist/transport.d.ts +1 -0
- package/dist/transport.js +4 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,6 +18,7 @@ import { setup, initCard, Store, Leaderboard } from "castle-web-sdk";
|
|
|
18
18
|
- [Store](#store)
|
|
19
19
|
- [Storage](#storage)
|
|
20
20
|
- [SharedStorage](#sharedstorage)
|
|
21
|
+
- [LocalCache](#localcache)
|
|
21
22
|
- [Leaderboard](#leaderboard)
|
|
22
23
|
- [Time](#time)
|
|
23
24
|
- [User](#user)
|
|
@@ -27,6 +28,7 @@ import { setup, initCard, Store, Leaderboard } from "castle-web-sdk";
|
|
|
27
28
|
- [Snapshot](#snapshot)
|
|
28
29
|
- [Portal](#portal)
|
|
29
30
|
- [Social](#social)
|
|
31
|
+
- [Rooms](#rooms)
|
|
30
32
|
- [Party](#party)
|
|
31
33
|
- [Hub](#hub)
|
|
32
34
|
- [Decks](#decks)
|
|
@@ -538,6 +540,28 @@ the page made before calling it, even ones still being batched; await an
|
|
|
538
540
|
`increment` or a board `submit` first if the answer should include it. A player can only ever see their own usage, not
|
|
539
541
|
another player's.
|
|
540
542
|
|
|
543
|
+
`rate` says how much of the per-second rate limits (the last two rows of
|
|
544
|
+
the table below) is spent right now, so a deck that writes often can back
|
|
545
|
+
off before a call is refused rather than after:
|
|
546
|
+
|
|
547
|
+
```js
|
|
548
|
+
const { rate } = await Store.usage();
|
|
549
|
+
if (rate && rate.caller.opsUsed > rate.caller.opsLimit * 0.8) {
|
|
550
|
+
// Close to this player's calls-per-second limit: batch or slow down.
|
|
551
|
+
}
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
- `rate.caller` is the current player's own limit, and `rate.deck` is the
|
|
555
|
+
one every player of the deck shares.
|
|
556
|
+
- Each has `opsUsed`, `opsLimit`, `bytesUsed` and `bytesLimit`, counted
|
|
557
|
+
over the current one-second window, and the `usage` call itself is
|
|
558
|
+
counted in them.
|
|
559
|
+
- `rate.callerClass` names which limit `caller` is: `"client"` for a
|
|
560
|
+
page.
|
|
561
|
+
|
|
562
|
+
`rate` is missing when the app is older than it, so check for it before
|
|
563
|
+
reading it.
|
|
564
|
+
|
|
541
565
|
An app too old to know `usage` rejects with a `CastleError` whose `code`
|
|
542
566
|
is `UNKNOWN_COMMAND`.
|
|
543
567
|
|
|
@@ -853,6 +877,44 @@ const { color } = await Store.user(otherUserId).get(["color"]);
|
|
|
853
877
|
await Store.me.set({ color: "red" });
|
|
854
878
|
```
|
|
855
879
|
|
|
880
|
+
## LocalCache
|
|
881
|
+
|
|
882
|
+
`LocalCache` keeps bytes and text on the player's device, for things the
|
|
883
|
+
deck can rebuild: downloaded or unpacked assets, compiled data. Entries
|
|
884
|
+
belong to the deck whose code is running. A hub town's doors change the
|
|
885
|
+
place but not the code, so the games played through them use the town's
|
|
886
|
+
entries. In the app, decks loaded from the same web address share entries.
|
|
887
|
+
|
|
888
|
+
Any entry can be gone at any time. Each deck has 20 MB; past that, its own
|
|
889
|
+
least recently used entries are evicted. On the web all decks
|
|
890
|
+
together have 300 MB; past that, the least recently used entries of any
|
|
891
|
+
deck are evicted. Both are less when the device is short of space. The
|
|
892
|
+
browser or app may also clear the whole cache. Never keep anything here
|
|
893
|
+
that the deck cannot make again; use [`Store`](#store) for that.
|
|
894
|
+
|
|
895
|
+
- **`LocalCache.getBinary(key): Promise<ArrayBuffer | null>`** — the bytes
|
|
896
|
+
at `key`, or `null` if there are none. A text entry comes back as UTF-8.
|
|
897
|
+
- **`LocalCache.getText(key): Promise<string | null>`** — the text at
|
|
898
|
+
`key`. A bytes entry is decoded as UTF-8.
|
|
899
|
+
- **`LocalCache.set(key, value): Promise<void>`** — stores an
|
|
900
|
+
`ArrayBuffer`, a `Uint8Array` or a string. An `ArrayBuffer` is moved, not
|
|
901
|
+
copied, and is empty (detached) once `set` returns; pass `buffer.slice(0)`
|
|
902
|
+
to keep one. A `Uint8Array` that covers its whole buffer moves that buffer
|
|
903
|
+
the same way; one over part of a buffer is copied.
|
|
904
|
+
- **`LocalCache.remove(key): Promise<void>`** — removes `key`.
|
|
905
|
+
|
|
906
|
+
Keys are 1 to 1024 characters, without NUL; a bad key or value throws.
|
|
907
|
+
Nothing else does: a get that cannot read returns `null`, and a set that
|
|
908
|
+
cannot write stores nothing.
|
|
909
|
+
|
|
910
|
+
```js
|
|
911
|
+
let bytes = await LocalCache.getBinary("town-v3");
|
|
912
|
+
if (!bytes) {
|
|
913
|
+
bytes = await unpackTown();
|
|
914
|
+
LocalCache.set("town-v3", bytes.slice(0));
|
|
915
|
+
}
|
|
916
|
+
```
|
|
917
|
+
|
|
856
918
|
## Leaderboard
|
|
857
919
|
|
|
858
920
|
`Leaderboard` ranks players by a numeric score, per deck and per
|
|
@@ -1208,6 +1270,45 @@ const friends = await Social.friends();
|
|
|
1208
1270
|
const playingHere = await Social.presence();
|
|
1209
1271
|
```
|
|
1210
1272
|
|
|
1273
|
+
## Rooms
|
|
1274
|
+
|
|
1275
|
+
### `Rooms.list(): Promise<RoomsListResult | null>`
|
|
1276
|
+
|
|
1277
|
+
This deck's public multiplayer rooms and how many players are in each, for a
|
|
1278
|
+
lobby, a room picker or a "12 playing now" line. No room has to write its own
|
|
1279
|
+
count to `Store` for a menu to read.
|
|
1280
|
+
|
|
1281
|
+
```js
|
|
1282
|
+
import { Rooms } from "castle-web-sdk";
|
|
1283
|
+
|
|
1284
|
+
const list = await Rooms.list();
|
|
1285
|
+
if (list) {
|
|
1286
|
+
label.textContent = `${list.total} playing now`;
|
|
1287
|
+
for (const room of list.rooms) {
|
|
1288
|
+
// { sessionId, routeId?, slot?, players, maxPlayers }
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
```
|
|
1292
|
+
|
|
1293
|
+
- `total` is the players across every listed room; `rooms` is one entry per
|
|
1294
|
+
room, with `routeId` and `slot` as the deck passed them to
|
|
1295
|
+
`Multiplayer.joinDestination` (absent for a room `Multiplayer.join`
|
|
1296
|
+
opened).
|
|
1297
|
+
- It resolves `null` when Castle will not list the deck's rooms for this
|
|
1298
|
+
player. The deck's owner and Castle admins always get a list; whether
|
|
1299
|
+
other players do depends on how far Castle has rolled presence out, so
|
|
1300
|
+
handle `null` for any player. A player under 13, or one Castle keeps out
|
|
1301
|
+
of multiplayer, gets `null` even on their own deck. Treat `null` as "not available", never as "no
|
|
1302
|
+
rooms": a deck nobody is playing answers `{ total: 0, rooms: [] }`.
|
|
1303
|
+
- An app built before the call also resolves `null` rather than throwing
|
|
1304
|
+
`UNKNOWN_COMMAND`. An unsaved deck throws `MISSING_DECK_ID`.
|
|
1305
|
+
- Counts come from a rollup Castle refreshes about every 10 seconds, so a
|
|
1306
|
+
player who joined or left in the last few seconds may not show yet. Poll it
|
|
1307
|
+
no more than every 10 seconds; there is no event.
|
|
1308
|
+
- Only public rooms are listed. Private, party and named rooms are not.
|
|
1309
|
+
- A local `castle-web serve` lists the saved deck's rooms on Castle, not the
|
|
1310
|
+
rooms of the local serve.
|
|
1311
|
+
|
|
1211
1312
|
## Party
|
|
1212
1313
|
|
|
1213
1314
|
`Party` creates and drives Castle parties with the signed-in player's account.
|
|
@@ -1361,6 +1462,14 @@ the signed-in account id. A new host without native sign-in support returns
|
|
|
1361
1462
|
- `Hub.onBack(listener)` hears the host's Back control, which a game cannot hide.
|
|
1362
1463
|
Answer it with `Hub.back()` behind the door animation; a host that hears
|
|
1363
1464
|
nothing takes the player home itself. Returns an unsubscribe function.
|
|
1465
|
+
- `Hub.onGo(listener)` hears the host ask to take the player through a door,
|
|
1466
|
+
e.g. a trip begun outside this page. The listener gets
|
|
1467
|
+
`{ doorId, owner, title, party }`: `owner` is whose House a House door leads
|
|
1468
|
+
to (or null), `title` the host's name for the door (or null), `party` how many
|
|
1469
|
+
travel (1 when the host does not say). A hub kit answers it like a fired pad:
|
|
1470
|
+
`Hub.go(doorId)` (with `{ ownerUserId: owner }` when set) behind its door
|
|
1471
|
+
animation. Hosts that never send it are the norm. Returns an unsubscribe
|
|
1472
|
+
function.
|
|
1364
1473
|
|
|
1365
1474
|
A player Castle has barred from the hub is refused at every hub door and at the
|
|
1366
1475
|
town itself with `CastleError` code `CAULDRON_HUB_BANNED` (from `Hub.go`,
|
|
@@ -1904,8 +2013,10 @@ load its assets through the bundler instead.
|
|
|
1904
2013
|
A multiplayer socket closed before its first hello reports its WebSocket close
|
|
1905
2014
|
code in `error.extensions.closeCode` when available. Code `4404` means the
|
|
1906
2015
|
play proxy could not route the session (`not_running`); it does not prove the
|
|
1907
|
-
runtime ended. A
|
|
1908
|
-
a
|
|
2016
|
+
runtime ended. A hub join refused this way tries the same handoff again for a
|
|
2017
|
+
few seconds, since a session ghost has just started can briefly be unroutable;
|
|
2018
|
+
the error is reported only when those tries run out. A failed hub join cancels
|
|
2019
|
+
its handoff, so retrying a door after that requires a fresh `Hub.go` acquisition.
|
|
1909
2020
|
|
|
1910
2021
|
Every error the SDK throws is a `CastleError`. Check `code` to tell
|
|
1911
2022
|
the kinds apart.
|
package/dist/castle.d.ts
CHANGED
|
@@ -13,7 +13,9 @@ export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckF
|
|
|
13
13
|
export { Haptics } from "./haptics";
|
|
14
14
|
export type { CastleHapticsApi, HapticsResult, HapticsStatus, HapticStyle } from "./haptics";
|
|
15
15
|
export { Hub } from "./hub";
|
|
16
|
-
export type { CastleHubApi, HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoParams, HubSignInParams, HubSignInResult, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, } from "./hub";
|
|
16
|
+
export type { CastleHubApi, HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoParams, HubGoRequest, HubSignInParams, HubSignInResult, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, } from "./hub";
|
|
17
|
+
export { Rooms } from "./rooms";
|
|
18
|
+
export type { CastleRoomsApi, RoomSummary, RoomsListResult } from "./rooms";
|
|
17
19
|
export { Social } from "./social";
|
|
18
20
|
export type { CastleSocialApi, SocialFriend, SocialPresence } from "./social";
|
|
19
21
|
export { Party } from "./party";
|
|
@@ -42,9 +44,11 @@ export { cardUnit, fitStage, fovForAspect, getDisplay } from "./display";
|
|
|
42
44
|
export type { DeckDisplay, DeckLayout, DeckOrientation } from "./display";
|
|
43
45
|
export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
|
|
44
46
|
export type { SaveState } from "./saveQueue";
|
|
47
|
+
export { LocalCache } from "./localCache";
|
|
48
|
+
export type { LocalCacheApi } from "./localCache";
|
|
45
49
|
export { SharedStorage, Storage } from "./storage";
|
|
46
50
|
export { Store } from "./store";
|
|
47
|
-
export type { CastleStoreApi, StoreBoardApi, StoreBoardScore, StoreListEntry, StoreListOptions, StoreListPage, StoreAllowance, StoreScopeApi, StoreUsage, } from "./store";
|
|
51
|
+
export type { CastleStoreApi, StoreBoardApi, StoreBoardScore, StoreListEntry, StoreListOptions, StoreListPage, StoreAllowance, StoreRateBudget, StoreRateUsage, StoreScopeApi, StoreUsage, } from "./store";
|
|
48
52
|
export { Time } from "./time";
|
|
49
53
|
export type { CastleClockZone, CastleDateParts, CastleTimeApi } from "./time";
|
|
50
54
|
export type { Json } from "./types";
|
package/dist/castle.js
CHANGED
|
@@ -9,6 +9,7 @@ export { experiment, experiments, experimentsReady } from "./experiments";
|
|
|
9
9
|
export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckFile, } from "./files";
|
|
10
10
|
export { Haptics } from "./haptics";
|
|
11
11
|
export { Hub } from "./hub";
|
|
12
|
+
export { Rooms } from "./rooms";
|
|
12
13
|
export { Social } from "./social";
|
|
13
14
|
export { Party } from "./party";
|
|
14
15
|
export { Leaderboard } from "./leaderboard";
|
|
@@ -22,6 +23,7 @@ export { Portal } from "./portal";
|
|
|
22
23
|
export { CARD_RATIO, deleteFile, fileUrl, initCard, onBeforeRestart, onFilesChanged, onSaveReloadState, openFile, renameFile, requestReload, setup, takeReloadState, writeFileOnce, } from "./runtime";
|
|
23
24
|
export { cardUnit, fitStage, fovForAspect, getDisplay } from "./display";
|
|
24
25
|
export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
|
|
26
|
+
export { LocalCache } from "./localCache";
|
|
25
27
|
export { SharedStorage, Storage } from "./storage";
|
|
26
28
|
export { Store } from "./store";
|
|
27
29
|
export { Time } from "./time";
|
package/dist/commands.d.ts
CHANGED
|
@@ -19,9 +19,25 @@ export interface StoreAllowance {
|
|
|
19
19
|
byteCount: number;
|
|
20
20
|
byteLimit: number;
|
|
21
21
|
}
|
|
22
|
+
/** One storage rate window: what was spent in the current second, and its limits. */
|
|
23
|
+
export interface StoreRateBudget {
|
|
24
|
+
opsUsed: number;
|
|
25
|
+
opsLimit: number;
|
|
26
|
+
bytesUsed: number;
|
|
27
|
+
bytesLimit: number;
|
|
28
|
+
}
|
|
29
|
+
/** The storage rate windows a call is charged against. */
|
|
30
|
+
export interface StoreRateUsage {
|
|
31
|
+
/** Which caller bucket answered: "client", "server", "session" or "town-layer". */
|
|
32
|
+
callerClass: string;
|
|
33
|
+
caller: StoreRateBudget;
|
|
34
|
+
deck: StoreRateBudget;
|
|
35
|
+
}
|
|
22
36
|
export interface StoreAllowances {
|
|
23
37
|
player: StoreAllowance;
|
|
24
38
|
shared: StoreAllowance;
|
|
39
|
+
/** Absent from a host older than the rate field. */
|
|
40
|
+
rate?: StoreRateUsage;
|
|
25
41
|
}
|
|
26
42
|
export interface StoreBoardEntry {
|
|
27
43
|
subject: string;
|
|
@@ -96,6 +112,19 @@ export interface SocialPresence extends SocialFriend {
|
|
|
96
112
|
slot?: string;
|
|
97
113
|
updatedAt: string;
|
|
98
114
|
}
|
|
115
|
+
/** One public room of the current deck, as Castle last counted it. */
|
|
116
|
+
export interface RoomSummary {
|
|
117
|
+
sessionId: string;
|
|
118
|
+
routeId?: string;
|
|
119
|
+
slot?: string;
|
|
120
|
+
players: number;
|
|
121
|
+
maxPlayers: number;
|
|
122
|
+
}
|
|
123
|
+
export interface RoomsListResult {
|
|
124
|
+
/** Players across every room listed. */
|
|
125
|
+
total: number;
|
|
126
|
+
rooms: RoomSummary[];
|
|
127
|
+
}
|
|
99
128
|
export type PartyStatus = "invited" | "joined" | "rejected" | "left" | "party_closed" | "banned";
|
|
100
129
|
export interface PartySummary {
|
|
101
130
|
partyId: string;
|
|
@@ -348,9 +377,18 @@ export type HubCancelStatus = "cancelled" | "expired" | "none" | "unavailable";
|
|
|
348
377
|
export interface HubCancelResult {
|
|
349
378
|
status: HubCancelStatus;
|
|
350
379
|
}
|
|
351
|
-
export type
|
|
380
|
+
export type HubBackEvent = {
|
|
352
381
|
type: "back";
|
|
353
382
|
};
|
|
383
|
+
export type HubGoEvent = {
|
|
384
|
+
type: "go";
|
|
385
|
+
doorId: string;
|
|
386
|
+
owner?: string;
|
|
387
|
+
title?: string;
|
|
388
|
+
party?: number;
|
|
389
|
+
};
|
|
390
|
+
export type HubEvent = HubBackEvent | HubGoEvent;
|
|
391
|
+
export declare const HUB_GO_DOOR_ID_MAX = 128;
|
|
354
392
|
export interface HubEventEnvelope {
|
|
355
393
|
castleSdk: typeof CASTLE_SDK_PROTOCOL;
|
|
356
394
|
hub: HubEvent;
|
|
@@ -790,7 +828,18 @@ export interface CommandParams {
|
|
|
790
828
|
subject?: string | null;
|
|
791
829
|
};
|
|
792
830
|
"cauldronStorage.usage": Record<string, never>;
|
|
831
|
+
"rooms.list": Record<string, never>;
|
|
793
832
|
"lifecycle.restoreState": Record<string, never>;
|
|
833
|
+
"localCache.get": {
|
|
834
|
+
key: string;
|
|
835
|
+
};
|
|
836
|
+
"localCache.set": {
|
|
837
|
+
key: string;
|
|
838
|
+
value: ArrayBuffer | string;
|
|
839
|
+
};
|
|
840
|
+
"localCache.remove": {
|
|
841
|
+
key: string;
|
|
842
|
+
};
|
|
794
843
|
}
|
|
795
844
|
export interface CommandResult {
|
|
796
845
|
"agent.chat": AgentChatResult;
|
|
@@ -937,7 +986,13 @@ export interface CommandResult {
|
|
|
937
986
|
"cauldronStorage.usage": {
|
|
938
987
|
usage: StoreAllowances;
|
|
939
988
|
};
|
|
989
|
+
"rooms.list": RoomsListResult | null;
|
|
940
990
|
"lifecycle.restoreState": LifecycleRestoreStateResult;
|
|
991
|
+
"localCache.get": {
|
|
992
|
+
value: ArrayBuffer | string | null;
|
|
993
|
+
};
|
|
994
|
+
"localCache.set": Record<string, never>;
|
|
995
|
+
"localCache.remove": Record<string, never>;
|
|
941
996
|
}
|
|
942
997
|
export interface UserPayload {
|
|
943
998
|
userId: string;
|
package/dist/commands.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// Marker + protocol version. Doubles as a discriminator so host messages can't
|
|
7
7
|
// be confused with embed.js `castlexyz:` strings or RN console messages.
|
|
8
8
|
export const CASTLE_SDK_PROTOCOL = 1;
|
|
9
|
+
export const HUB_GO_DOOR_ID_MAX = 128;
|
|
9
10
|
export function hubEventFrom(value) {
|
|
10
11
|
if (typeof value !== "object" || value === null)
|
|
11
12
|
return null;
|
|
@@ -15,7 +16,29 @@ export function hubEventFrom(value) {
|
|
|
15
16
|
const event = record.hub;
|
|
16
17
|
if (typeof event !== "object" || event === null)
|
|
17
18
|
return null;
|
|
18
|
-
|
|
19
|
+
if (event.type === "back")
|
|
20
|
+
return { type: "back" };
|
|
21
|
+
if (event.type === "go")
|
|
22
|
+
return hubGoEventFrom(event);
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
function hubGoEventFrom(event) {
|
|
26
|
+
const { doorId, owner, title, party } = event;
|
|
27
|
+
if (typeof doorId !== "string" || doorId.length === 0 || doorId.length > HUB_GO_DOOR_ID_MAX)
|
|
28
|
+
return null;
|
|
29
|
+
const go = { type: "go", doorId };
|
|
30
|
+
// A bad owner refuses the whole event: a trip to the wrong House is worse
|
|
31
|
+
// than none.
|
|
32
|
+
if (owner !== undefined && owner !== null) {
|
|
33
|
+
if (typeof owner !== "string" || !/^[1-9]\d{0,9}$/.test(owner))
|
|
34
|
+
return null;
|
|
35
|
+
go.owner = owner;
|
|
36
|
+
}
|
|
37
|
+
if (typeof title === "string")
|
|
38
|
+
go.title = title;
|
|
39
|
+
if (typeof party === "number" && Number.isInteger(party) && party > 0)
|
|
40
|
+
go.party = party;
|
|
41
|
+
return go;
|
|
19
42
|
}
|
|
20
43
|
// How long the deck waits for a reply to these commands, in place of the
|
|
21
44
|
// data-command timeout. A deck list fetches every cover on the list. A host
|
|
@@ -32,6 +55,11 @@ export const COMMAND_TIMEOUTS_MS = {
|
|
|
32
55
|
// Native auth may include a provider handoff, but it must not leave a deck
|
|
33
56
|
// waiting forever if the host loses the completion callback.
|
|
34
57
|
"hub.signIn": 120_000,
|
|
58
|
+
// A large entry is an IndexedDB read or write plus a copy into the other
|
|
59
|
+
// frame, and can wait behind other tabs' writes to the same store.
|
|
60
|
+
"localCache.get": 60_000,
|
|
61
|
+
"localCache.set": 60_000,
|
|
62
|
+
"localCache.remove": 60_000,
|
|
35
63
|
};
|
|
36
64
|
// Once a host streams a command, each stream envelope restarts the wait at this
|
|
37
65
|
// length instead. The deck-agent service sends a heartbeat every 15 seconds, and the host
|
package/dist/hub.d.ts
CHANGED
|
@@ -112,5 +112,22 @@ export interface CastleHubApi {
|
|
|
112
112
|
* takes the player home itself. Returns an unsubscribe function.
|
|
113
113
|
*/
|
|
114
114
|
onBack(listener: () => void): () => void;
|
|
115
|
+
/**
|
|
116
|
+
* The host asked to take the player through a door, e.g. a trip begun
|
|
117
|
+
* outside this page. A hub kit answers it like a fired pad: `go(doorId)`
|
|
118
|
+
* behind its door animation, passing `owner` as `ownerUserId` when set.
|
|
119
|
+
* `owner` names whose House a House door leads to, or null; `title` is the
|
|
120
|
+
* host's name for the door, or null; `party` is how many travel (1 when
|
|
121
|
+
* the host does not say). Hosts
|
|
122
|
+
* that never send it are the norm. Returns an unsubscribe function.
|
|
123
|
+
*/
|
|
124
|
+
onGo(listener: (go: HubGoRequest) => void): () => void;
|
|
125
|
+
}
|
|
126
|
+
/** A host's request to go through a door (see `Hub.onGo`). */
|
|
127
|
+
export interface HubGoRequest {
|
|
128
|
+
doorId: string;
|
|
129
|
+
owner: string | null;
|
|
130
|
+
title: string | null;
|
|
131
|
+
party: number;
|
|
115
132
|
}
|
|
116
133
|
export declare const Hub: CastleHubApi;
|
package/dist/hub.js
CHANGED
|
@@ -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:
|
|
163
|
-
operation
|
|
172
|
+
message: `${operation} requires a function.`,
|
|
173
|
+
operation,
|
|
164
174
|
});
|
|
165
175
|
}
|
|
166
|
-
|
|
176
|
+
listeners.add(listener);
|
|
167
177
|
setHubEventHandler(dispatchHubEvent);
|
|
168
178
|
return () => {
|
|
169
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
+
}
|
package/dist/multiplayer.js
CHANGED
|
@@ -75,6 +75,9 @@ async function join(options) {
|
|
|
75
75
|
// The host answers `unavailable` while ghost is busy with this player; the
|
|
76
76
|
// trip stays pending there, so asking again is safe.
|
|
77
77
|
const HUB_COMMIT_RETRY_MS = [1_000, 2_000, 4_000, 8_000];
|
|
78
|
+
// A hub join's tries of the same nonce while the proxy cannot route the new
|
|
79
|
+
// session yet (`openHubSocket`), well inside the nonce's unconsumed life.
|
|
80
|
+
const HUB_UNROUTED_RETRY_MS = [500, 1_000, 2_000];
|
|
78
81
|
async function commitHubTrip(nonce, sessionId) {
|
|
79
82
|
for (let attempt = 0;; attempt++) {
|
|
80
83
|
let status;
|
|
@@ -458,8 +461,35 @@ class MultiplayerConnectionImpl {
|
|
|
458
461
|
if (savedToken && await this.restoreDevReconnect(savedToken))
|
|
459
462
|
return;
|
|
460
463
|
this.assertOpen();
|
|
464
|
+
if (this.request.command === "hub") {
|
|
465
|
+
await this.openHubSocket(result.nonce);
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
461
468
|
await this.openSocket("nonce", result.nonce);
|
|
462
469
|
}
|
|
470
|
+
// A hub session ghost has just started can be refused by the play proxy
|
|
471
|
+
// before its route is readable there (4404, before any hello). The proxy
|
|
472
|
+
// refuses before the session sees the nonce, so the nonce is still good:
|
|
473
|
+
// try it again for a few seconds before the trip is given back.
|
|
474
|
+
async openHubSocket(nonce) {
|
|
475
|
+
for (let attempt = 0;; attempt++) {
|
|
476
|
+
try {
|
|
477
|
+
await this.openSocket("nonce", nonce);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
catch (error) {
|
|
481
|
+
const delay = HUB_UNROUTED_RETRY_MS[attempt];
|
|
482
|
+
if (!(error instanceof SocketClosedError) ||
|
|
483
|
+
error.code !== PROXY_SESSION_ENDED_CLOSE_CODE ||
|
|
484
|
+
delay === undefined) {
|
|
485
|
+
throw error;
|
|
486
|
+
}
|
|
487
|
+
this.assertOpen();
|
|
488
|
+
await pause(delay);
|
|
489
|
+
this.assertOpen();
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
463
493
|
async restoreDevReconnect(token) {
|
|
464
494
|
this.assertOpen();
|
|
465
495
|
const budget = this.reconnectBudget = new ReconnectBudget();
|
package/dist/rooms.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { RoomsListResult } from "./commands";
|
|
2
|
+
export type { RoomSummary, RoomsListResult } from "./commands";
|
|
3
|
+
export interface CastleRoomsApi {
|
|
4
|
+
/**
|
|
5
|
+
* This deck's public rooms with their player counts, or null when Castle
|
|
6
|
+
* will not list them for this player or the app running the deck predates
|
|
7
|
+
* the call. Null is "not available", never "no rooms".
|
|
8
|
+
*/
|
|
9
|
+
list(): Promise<RoomsListResult | null>;
|
|
10
|
+
}
|
|
11
|
+
export declare const Rooms: CastleRoomsApi;
|
package/dist/rooms.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Rooms — the current deck's public multiplayer rooms and how many players are
|
|
2
|
+
// in each, for a lobby or a "players online" line. Castle always lists them
|
|
3
|
+
// to the deck's owner and Castle admins, to other players only as far as its
|
|
4
|
+
// presence rollout reaches, and never to a player under 13 or kept out of
|
|
5
|
+
// multiplayer; anyone it will not list them for gets null.
|
|
6
|
+
//
|
|
7
|
+
// Counts come from a rollup Castle refreshes about every 10 seconds, so a
|
|
8
|
+
// player who just joined or left may not show yet. Private, party and named
|
|
9
|
+
// rooms are not listed.
|
|
10
|
+
import { CastleError } from "./errors";
|
|
11
|
+
import { hostRequest } from "./transport";
|
|
12
|
+
async function list() {
|
|
13
|
+
try {
|
|
14
|
+
return await hostRequest("rooms.list", {});
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
if (error instanceof CastleError && error.code === "UNKNOWN_COMMAND")
|
|
18
|
+
return null;
|
|
19
|
+
throw error;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export const Rooms = Object.freeze({ list });
|
package/dist/store.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { StoreAllowance } from "./commands";
|
|
1
|
+
import type { StoreAllowance, StoreRateBudget, StoreRateUsage } from "./commands";
|
|
2
2
|
import type { Json } from "./types";
|
|
3
3
|
import { type SaveApi, type SaveBucketApi } from "./save";
|
|
4
4
|
export interface StoreListOptions {
|
|
@@ -54,7 +54,7 @@ export interface StoreBoardApi {
|
|
|
54
54
|
/** One player's score, defaulting to the current player. Null if unset. */
|
|
55
55
|
get(userId?: string): Promise<StoreBoardScore | null>;
|
|
56
56
|
}
|
|
57
|
-
export type { StoreAllowance };
|
|
57
|
+
export type { StoreAllowance, StoreRateBudget, StoreRateUsage };
|
|
58
58
|
export interface StoreUsage {
|
|
59
59
|
/**
|
|
60
60
|
* The current player's own data in this deck: their `Store.me` and
|
|
@@ -63,6 +63,12 @@ export interface StoreUsage {
|
|
|
63
63
|
player: StoreAllowance;
|
|
64
64
|
/** `Store.deck`: one allowance shared by every player of the deck. */
|
|
65
65
|
shared: StoreAllowance;
|
|
66
|
+
/**
|
|
67
|
+
* How much of the current second's call and byte rate limits is spent, for
|
|
68
|
+
* the current player (`caller`) and for every player of the deck together
|
|
69
|
+
* (`deck`). Counts this usage call. Absent when the app is too old to report it.
|
|
70
|
+
*/
|
|
71
|
+
rate?: StoreRateUsage;
|
|
66
72
|
}
|
|
67
73
|
export interface CastleStoreApi extends SaveApi {
|
|
68
74
|
/** Shared by everyone playing the deck. */
|
package/dist/store.js
CHANGED
|
@@ -309,7 +309,11 @@ async function usage() {
|
|
|
309
309
|
// caller.
|
|
310
310
|
await Promise.all(Array.from(buckets.values(), (bucket) => flushBucket(bucket, false)));
|
|
311
311
|
const { usage: allowances } = await hostRequest("cauldronStorage.usage", {});
|
|
312
|
-
|
|
312
|
+
const result = { player: allowances.player, shared: allowances.shared };
|
|
313
|
+
// An app built before the rate field answers without it.
|
|
314
|
+
if (allowances.rate)
|
|
315
|
+
result.rate = allowances.rate;
|
|
316
|
+
return result;
|
|
313
317
|
}
|
|
314
318
|
// Saves skip the write coalescing above: each is one request, sent at once.
|
|
315
319
|
const saveApi = createSaveApi((verb, input) => hostRequest(`cauldronStorage.${verb}`, input));
|
package/dist/transport.d.ts
CHANGED
package/dist/transport.js
CHANGED
|
@@ -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(
|
|
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
|