castle-web-sdk 0.4.58 → 0.4.59
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 +42 -5
- package/dist/castle.d.ts +3 -0
- package/dist/castle.js +2 -0
- package/dist/commands.d.ts +37 -0
- package/dist/deckInvites.d.ts +31 -0
- package/dist/deckInvites.js +22 -0
- package/dist/save.d.ts +13 -2
- package/dist/save.js +7 -2
- package/dist/server/platformHandle.d.ts +2 -0
- package/dist/server/storage.d.ts +8 -2
- package/dist/server/storage.js +6 -4
- package/dist/server/wrapper.d.ts +4 -0
- package/dist/server/wrapper.js +29 -1
- package/dist/transport.d.ts +1 -0
- package/dist/transport.js +134 -12
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -155,6 +155,20 @@ is. `session.place` is the hub place the host started the session for (see
|
|
|
155
155
|
[`session.hub`](#sessionhub)), and `null` otherwise. It is never taken from a
|
|
156
156
|
client.
|
|
157
157
|
|
|
158
|
+
### `session.sessionSecret` and `session.assets.read`
|
|
159
|
+
|
|
160
|
+
Both are available in `onStart`. `session.sessionSecret` is the host-provided
|
|
161
|
+
signing key for this session, or `undefined` when the host supplies no key.
|
|
162
|
+
The key is read-only and omitted from object inspection, spread, and default JSON
|
|
163
|
+
serialization. Code that names the property, by reading it or by passing it in a
|
|
164
|
+
`JSON.stringify` property list, gets the key. Read it directly through `session.sessionSecret`.
|
|
165
|
+
Keep the key server-side and out of messages, logs, and storage.
|
|
166
|
+
|
|
167
|
+
`await session.assets.read(name)` returns the exact bytes of a mounted session
|
|
168
|
+
asset as a `Uint8Array`, or `null` if the name is absent. On older runtimes
|
|
169
|
+
without session asset support, the promise rejects with an unavailable error.
|
|
170
|
+
`session.assets` is omitted from object keys, spread, and JSON serialization.
|
|
171
|
+
|
|
158
172
|
### `session.storage`
|
|
159
173
|
|
|
160
174
|
A session ends when its last player leaves, and its memory goes with it.
|
|
@@ -202,6 +216,13 @@ the [atomic save API](#atomic-saves). A board has
|
|
|
202
216
|
game state. Its `resetGeneration` is present only after an administrator has
|
|
203
217
|
reset that player's progress for this deck. It is a monotonic reset marker,
|
|
204
218
|
separate from the handle's `generation`, which fences playthrough operations.
|
|
219
|
+
Its `set(values, { check: { target, writer } })` and `remove(keys, { check })`
|
|
220
|
+
take the same optional writer check as `session.storage.user(id).set`: the
|
|
221
|
+
platform applies each request only while `writer` (from `claim`) still holds
|
|
222
|
+
`target`, and otherwise fails it with `CAULDRON_STORAGE_WRITER_LOST`. The check
|
|
223
|
+
is per request: a `set` or `remove` too big for one request is split, and when
|
|
224
|
+
the claim is lost partway the earlier requests stay written and the rest are not
|
|
225
|
+
sent. Without the option the request is unchanged. castle-web serve refuses a checked write instead of emulating it.
|
|
205
226
|
Deck-scope storage writes are not fenced by either generation; a server using
|
|
206
227
|
`session.storage.deck` must discard its own stale queued writes and cached
|
|
207
228
|
per-player values when it observes a newer reset marker.
|
|
@@ -778,12 +799,24 @@ does not fit in one. Ship media with the deck instead.
|
|
|
778
799
|
expected revision creates only an absent target; an explicit `replace` also
|
|
779
800
|
supports importing unregistered legacy rows. `checks` are read-only target
|
|
780
801
|
checks with an expected revision and/or writer; they leave revisions intact.
|
|
781
|
-
- `claim({ operationId, expectedAccess?, target, initial?, load? })`
|
|
782
|
-
takes ownership of a target and returns `{ writer, receipt, snapshot }`.
|
|
802
|
+
- `claim({ operationId, expectedAccess?, target, expectedRevision?, initial?, load? })`
|
|
803
|
+
explicitly takes ownership of a target and returns `{ writer, receipt, snapshot }`.
|
|
783
804
|
`initial: [{ target, rows }]` initializes absent targets only. An absent
|
|
784
805
|
claimed target initializes empty if defaults were omitted. Claiming an
|
|
785
806
|
existing target leaves its data revision unchanged. The latest committed
|
|
786
807
|
claim wins; claimed targets require the current writer on every change.
|
|
808
|
+
With `expectedRevision` (the target's revision from a snapshot, or `null` for
|
|
809
|
+
a target never initialized) and `expectedAccess`, the claim is a
|
|
810
|
+
compare-and-set: it commits only while the target still has that revision and
|
|
811
|
+
then always moves it, so a claim made against the same observation fails with
|
|
812
|
+
`CAULDRON_STORAGE_REVISION_CONFLICT`, `committed: false`, and `current`
|
|
813
|
+
holding the target's revision (no rows). A claim sent late, after a newer
|
|
814
|
+
CAS claim or any change to the target, cannot take it back; a plain claim
|
|
815
|
+
leaves the revision alone, so every claimer of a CAS target must use CAS. Retry with `current`'s revision only while
|
|
816
|
+
the caller should still own it. A player progress reset returns the target
|
|
817
|
+
to never-initialized, so an old `null` observation matches again. Needs a
|
|
818
|
+
platform that knows the field; older ones refuse it with
|
|
819
|
+
`CAULDRON_STORAGE_INVALID_ARGUMENT`.
|
|
787
820
|
- `initialize({ operationId, expectedAccess?, initial, load? })` initializes
|
|
788
821
|
only absent targets and returns `{ receipt, snapshot }`. Concurrent defaults
|
|
789
822
|
are applied once. It never claims ownership or replaces existing data.
|
|
@@ -879,9 +912,13 @@ recovery must check current generations before adopting it. Clients cannot send
|
|
|
879
912
|
reset fences. Omitting them preserves the existing request.
|
|
880
913
|
|
|
881
914
|
One call changes up to eight targets, with up to eight explicit key changes
|
|
882
|
-
per target, across the same deck and at most two players. Every
|
|
883
|
-
its expected revision. A read-only `check` can use `expectedRevision: null`
|
|
884
|
-
to require absence without creating that target
|
|
915
|
+
per target, across the same deck and at most two players. Every changed
|
|
916
|
+
target needs its expected revision. A read-only `check` can use `expectedRevision: null`
|
|
917
|
+
to require absence without creating that target, or carry only a `writer`
|
|
918
|
+
(from `claim`) to commit only while that claim still holds its target, for
|
|
919
|
+
example a one-writer lease's empty user target fencing deck-scope changes.
|
|
920
|
+
A replaced claim fails with `CAULDRON_STORAGE_WRITER_LOST`. Checks count
|
|
921
|
+
toward the eight targets and two players. All changes commit together. Clients may address their
|
|
885
922
|
own user/private targets and writable deck targets; only the deck server can
|
|
886
923
|
condition on another player's user target. Servers cannot access private data.
|
|
887
924
|
Existing quota, byte and rate allowances still apply. A prefix replacement
|
package/dist/castle.d.ts
CHANGED
|
@@ -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";
|
package/dist/castle.js
CHANGED
|
@@ -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";
|
package/dist/commands.d.ts
CHANGED
|
@@ -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,31 @@
|
|
|
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
|
+
* castle.xyz answers these only for the document it inlined into its frame:
|
|
13
|
+
* a deck built before that check (or a page the frame navigated to) gets
|
|
14
|
+
* `{ status: "unavailable", reason: "DOCUMENT_MISMATCH" }`. Rebuild it.
|
|
15
|
+
*/
|
|
16
|
+
export interface CastleDeckInvitesApi {
|
|
17
|
+
/**
|
|
18
|
+
* Make an expiring link into the public session this player joined last.
|
|
19
|
+
* `unavailable` when there is none, on hosts without deck invites, or when
|
|
20
|
+
* Castle refuses (`reason` carries its code).
|
|
21
|
+
*/
|
|
22
|
+
invite(): Promise<DeckInviteResult>;
|
|
23
|
+
/**
|
|
24
|
+
* Once this play has joined a public session: if it opened from an invite
|
|
25
|
+
* link, follow the inviter (and be followed back) and return who. Safe to
|
|
26
|
+
* call again; `unavailable` when the play did not come from a link.
|
|
27
|
+
*/
|
|
28
|
+
inviteArrival(): Promise<DeckInviteArrivalResult>;
|
|
29
|
+
}
|
|
30
|
+
/** @experimental See {@link CastleDeckInvitesApi}. */
|
|
31
|
+
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 };
|
package/dist/save.d.ts
CHANGED
|
@@ -63,10 +63,14 @@ export interface SaveTransactionInput {
|
|
|
63
63
|
checks?: SaveCheck[];
|
|
64
64
|
changes: SaveChange[];
|
|
65
65
|
}
|
|
66
|
-
export
|
|
66
|
+
export type SaveConditionalCheck = (Omit<SaveCheck, "expectedRevision"> & {
|
|
67
67
|
/** Null checks absence without creating the target. */
|
|
68
68
|
expectedRevision: SaveRevision | null;
|
|
69
|
-
}
|
|
69
|
+
}) | (Omit<SaveCheck, "expectedRevision" | "writer"> & {
|
|
70
|
+
/** A writer alone fences on a claim, e.g. a one-writer lease's empty target. */
|
|
71
|
+
writer: SaveWriter;
|
|
72
|
+
expectedRevision?: undefined;
|
|
73
|
+
});
|
|
70
74
|
export interface SaveConditionalWriteInput extends Omit<SaveTransactionInput, "checks"> {
|
|
71
75
|
checks?: SaveConditionalCheck[];
|
|
72
76
|
/** Session servers only: atomically fence each affected player's progress reset. */
|
|
@@ -84,6 +88,12 @@ export interface SaveClaimInput {
|
|
|
84
88
|
operationId: string;
|
|
85
89
|
expectedAccess?: string;
|
|
86
90
|
target: SaveTarget;
|
|
91
|
+
/**
|
|
92
|
+
* Compare-and-set: claim only while `target`'s revision is still this one (null:
|
|
93
|
+
* never initialized). A claim carrying it always moves the revision, so another
|
|
94
|
+
* claim made against the same observation is refused with REVISION_CONFLICT.
|
|
95
|
+
*/
|
|
96
|
+
expectedRevision?: SaveRevision | null;
|
|
87
97
|
initial?: SaveInitial[];
|
|
88
98
|
/** Omitted loads the claimed and initial targets. */
|
|
89
99
|
load?: SaveReadTarget[];
|
|
@@ -156,6 +166,7 @@ export interface SaveBucketApi {
|
|
|
156
166
|
operationId: string;
|
|
157
167
|
expectedAccess?: string;
|
|
158
168
|
prefix: string;
|
|
169
|
+
expectedRevision?: SaveRevision | null;
|
|
159
170
|
initial?: {
|
|
160
171
|
prefix: string;
|
|
161
172
|
rows: SaveRows;
|
package/dist/save.js
CHANGED
|
@@ -251,8 +251,6 @@ function encodeChange(change, server) {
|
|
|
251
251
|
}
|
|
252
252
|
function encodeCheck(check, server, conditional = false) {
|
|
253
253
|
const target = validateSaveTarget(check.target, server);
|
|
254
|
-
if (conditional && check.expectedRevision === undefined)
|
|
255
|
-
invalid("Every conditional check needs an expected revision.");
|
|
256
254
|
if (check.expectedRevision === undefined && check.writer === undefined) {
|
|
257
255
|
invalid("A check needs an expected revision or a writer.");
|
|
258
256
|
}
|
|
@@ -350,6 +348,13 @@ export function encodeSaveInput(verb, input, server = false) {
|
|
|
350
348
|
...(verb === "claim"
|
|
351
349
|
? { target: validateSaveTarget(input.target, server) }
|
|
352
350
|
: {}),
|
|
351
|
+
...(verb === "claim" && input.expectedRevision !== undefined
|
|
352
|
+
? {
|
|
353
|
+
expectedRevision: input.expectedRevision === null
|
|
354
|
+
? null
|
|
355
|
+
: checkText(input.expectedRevision, "expected revision", MAX_KEY_BYTES),
|
|
356
|
+
}
|
|
357
|
+
: {}),
|
|
353
358
|
...(input.initial === undefined
|
|
354
359
|
? {}
|
|
355
360
|
: { initial: encodeInitial(input.initial, server) }),
|
|
@@ -41,6 +41,8 @@ export interface PlatformWorldTimeConfig {
|
|
|
41
41
|
advance: "wallClock";
|
|
42
42
|
}
|
|
43
43
|
export interface PlatformHandle {
|
|
44
|
+
readonly sessionSecret?: string;
|
|
45
|
+
readAsset?(name: string): Promise<Uint8Array | null>;
|
|
44
46
|
send(connId: string, text: string): void;
|
|
45
47
|
broadcast(text: string): void;
|
|
46
48
|
sendBinary?(connId: string, bytes: Uint8Array | ArrayBuffer): void;
|
package/dist/server/storage.d.ts
CHANGED
|
@@ -69,8 +69,14 @@ export interface ServerPlaythrough {
|
|
|
69
69
|
/** Explicit narrative changes for this same player and generation. */
|
|
70
70
|
readonly characters: ServerPlaythroughCharacters;
|
|
71
71
|
get<T extends Json = Json>(keys: string[]): Promise<Record<string, T>>;
|
|
72
|
-
|
|
73
|
-
|
|
72
|
+
/**
|
|
73
|
+
* With `{ check: { target, writer } }`, as on `session.storage.user(id).set`, the
|
|
74
|
+
* platform applies each request only while `writer` still holds `target`'s claim
|
|
75
|
+
* (CAULDRON_STORAGE_WRITER_LOST otherwise). A split write is checked per request:
|
|
76
|
+
* requests sent before the claim was lost stay written.
|
|
77
|
+
*/
|
|
78
|
+
set(values: Record<string, Json>, options?: ServerStorageWriteOptions): Promise<void>;
|
|
79
|
+
remove(keys: string[], options?: ServerStorageWriteOptions): Promise<void>;
|
|
74
80
|
reset(operationId: string): Promise<ServerPlaythrough>;
|
|
75
81
|
}
|
|
76
82
|
export interface RecordCharacterEventInput {
|
package/dist/server/storage.js
CHANGED
|
@@ -234,15 +234,17 @@ function createPlaythrough(call, subject, generation, resetGeneration) {
|
|
|
234
234
|
const entries = await call("playthroughGet", { subject, generation, keys: assertKeys(keys, "session.storage.playthrough.get") });
|
|
235
235
|
return decodeEntries(entries, "session.storage.playthrough.get");
|
|
236
236
|
},
|
|
237
|
-
async set(values) {
|
|
237
|
+
async set(values, options) {
|
|
238
|
+
const fence = writerCheck(options, "session.storage.playthrough.set");
|
|
238
239
|
const entries = encodeEntries(values, "session.storage.playthrough.set");
|
|
239
240
|
for (const chunk of batched(entries, "session.storage.playthrough.set")) {
|
|
240
|
-
await call("playthroughSet", { subject, generation, entries: chunk });
|
|
241
|
+
await call("playthroughSet", { subject, generation, entries: chunk, ...fence });
|
|
241
242
|
}
|
|
242
243
|
},
|
|
243
|
-
async remove(keys) {
|
|
244
|
+
async remove(keys, options) {
|
|
245
|
+
const fence = writerCheck(options, "session.storage.playthrough.remove");
|
|
244
246
|
for (const chunk of chunked(assertKeys(keys, "session.storage.playthrough.remove"), MAX_KEYS_PER_CALL)) {
|
|
245
|
-
await call("playthroughDelete", { subject, generation, keys: chunk });
|
|
247
|
+
await call("playthroughDelete", { subject, generation, keys: chunk, ...fence });
|
|
246
248
|
}
|
|
247
249
|
},
|
|
248
250
|
async reset(operationId) {
|
package/dist/server/wrapper.d.ts
CHANGED
|
@@ -22,6 +22,10 @@ export interface MultiplayerServerSession {
|
|
|
22
22
|
readonly sessionId: string;
|
|
23
23
|
readonly deckId: string;
|
|
24
24
|
readonly mode: MultiplayerSessionMode;
|
|
25
|
+
readonly sessionSecret?: string;
|
|
26
|
+
readonly assets: {
|
|
27
|
+
read(name: string): Promise<Uint8Array | null>;
|
|
28
|
+
};
|
|
25
29
|
/**
|
|
26
30
|
* The place the host started this session for (a hub door's destination, or
|
|
27
31
|
* the hub place ghost pinned the session to), or null when the host stamped
|
package/dist/server/wrapper.js
CHANGED
|
@@ -247,7 +247,7 @@ function createAuthorSession(platformHandle, players, arrivals, hidden, variants
|
|
|
247
247
|
return Boolean(hidden.get(a)?.has(userB) || hidden.get(b)?.has(userA));
|
|
248
248
|
});
|
|
249
249
|
const world = createServerWorld(platformHandle);
|
|
250
|
-
|
|
250
|
+
const session = {
|
|
251
251
|
get players() {
|
|
252
252
|
return Array.from(players.values());
|
|
253
253
|
},
|
|
@@ -257,6 +257,14 @@ function createAuthorSession(platformHandle, players, arrivals, hidden, variants
|
|
|
257
257
|
place: typeof platformHandle.config.place === "string"
|
|
258
258
|
? platformHandle.config.place
|
|
259
259
|
: hub?.place ?? null,
|
|
260
|
+
assets: {
|
|
261
|
+
async read(name) {
|
|
262
|
+
if (typeof platformHandle.readAsset !== "function") {
|
|
263
|
+
throw new TypeError("This Castle runtime does not support session assets yet.");
|
|
264
|
+
}
|
|
265
|
+
return platformHandle.readAsset(name);
|
|
266
|
+
},
|
|
267
|
+
},
|
|
260
268
|
storage: createServerStorage(platformHandle),
|
|
261
269
|
world,
|
|
262
270
|
characters: world?.characters ?? createPlaceCharacters(platformHandle),
|
|
@@ -308,6 +316,26 @@ function createAuthorSession(platformHandle, players, arrivals, hidden, variants
|
|
|
308
316
|
platformHandle.disconnect(playerId, reason ?? 1000);
|
|
309
317
|
},
|
|
310
318
|
};
|
|
319
|
+
Object.defineProperty(session, "assets", { enumerable: false });
|
|
320
|
+
// Inspectors can invoke getters. Keep the key in a closure off the inspected target.
|
|
321
|
+
const sessionSecret = platformHandle.sessionSecret;
|
|
322
|
+
return new Proxy(session, {
|
|
323
|
+
get(target, property, receiver) {
|
|
324
|
+
if (property === "sessionSecret")
|
|
325
|
+
return sessionSecret;
|
|
326
|
+
return Reflect.get(target, property, receiver);
|
|
327
|
+
},
|
|
328
|
+
set(target, property, value, receiver) {
|
|
329
|
+
if (property === "sessionSecret")
|
|
330
|
+
return false;
|
|
331
|
+
return Reflect.set(target, property, value, receiver);
|
|
332
|
+
},
|
|
333
|
+
defineProperty(target, property, descriptor) {
|
|
334
|
+
if (property === "sessionSecret")
|
|
335
|
+
return false;
|
|
336
|
+
return Reflect.defineProperty(target, property, descriptor);
|
|
337
|
+
},
|
|
338
|
+
});
|
|
311
339
|
}
|
|
312
340
|
const WORLD_OPERATION_ID_MAX_BYTES = 128;
|
|
313
341
|
const WORLD_OPERATION_ID_MAX_CHARACTERS = 120;
|
package/dist/transport.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ declare global {
|
|
|
14
14
|
__castleSdkHost?: {
|
|
15
15
|
receive: (message: unknown) => void;
|
|
16
16
|
};
|
|
17
|
+
__castleDocumentNonce?: unknown;
|
|
17
18
|
}
|
|
18
19
|
}
|
|
19
20
|
export declare function hostRequest<C extends CommandName>(command: C, params: CommandParams[C], stream?: HostStreamOptions): Promise<CommandResult[C]>;
|
package/dist/transport.js
CHANGED
|
@@ -28,6 +28,100 @@ const INTERACTIVE_COMMANDS = new Set([
|
|
|
28
28
|
"voice.requestJoin",
|
|
29
29
|
"hub.pushPermission",
|
|
30
30
|
]);
|
|
31
|
+
// The deck channel. A web host that inlines the deck into its frame writes a
|
|
32
|
+
// secret for that one document into its source, as
|
|
33
|
+
// `window.__castleDocumentNonce`, before any deck script. The SDK takes it once
|
|
34
|
+
// at load and deletes the global, makes a MessageChannel, and redeems the nonce
|
|
35
|
+
// once, sending it with one port to window.parent (a `deck.channel` request).
|
|
36
|
+
// A host that accepts answers on that port and keeps it; from then on the
|
|
37
|
+
// commands below go only over it, and so do their answers. The frame keeps the
|
|
38
|
+
// other port in this document's memory, so a document the frame navigates to
|
|
39
|
+
// in place (same window, different document) never holds it, and nothing
|
|
40
|
+
// tied to it is ever posted to the frame's window. Opaque to the SDK.
|
|
41
|
+
const DECK_CHANNEL_COMMANDS = new Set([
|
|
42
|
+
"deck.invite",
|
|
43
|
+
"deck.inviteArrival",
|
|
44
|
+
"multiplayer.getSession",
|
|
45
|
+
"multiplayer.joinDestination",
|
|
46
|
+
]);
|
|
47
|
+
const DECK_CHANNEL_HANDSHAKE_MS = 5000;
|
|
48
|
+
let deckPort = null;
|
|
49
|
+
let deckHandshake = null;
|
|
50
|
+
function openDeckChannel(nonce) {
|
|
51
|
+
if (!nonce || typeof MessageChannel === "undefined" || resolveChannel() !== "web") {
|
|
52
|
+
return Promise.resolve();
|
|
53
|
+
}
|
|
54
|
+
return new Promise((resolve) => {
|
|
55
|
+
const { port1, port2 } = new MessageChannel();
|
|
56
|
+
const requestId = `${requestIdPrefix}deckChannel`;
|
|
57
|
+
let settled = false;
|
|
58
|
+
const done = (port) => {
|
|
59
|
+
if (settled)
|
|
60
|
+
return;
|
|
61
|
+
settled = true;
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
deckHandshake = null;
|
|
64
|
+
if (port)
|
|
65
|
+
deckPort = port;
|
|
66
|
+
else
|
|
67
|
+
port1.close();
|
|
68
|
+
resolve();
|
|
69
|
+
};
|
|
70
|
+
const timer = setTimeout(() => done(null), DECK_CHANNEL_HANDSHAKE_MS);
|
|
71
|
+
deckHandshake = { requestId, done };
|
|
72
|
+
port1.onmessage = (event) => receiveFromPort(port1, event.data);
|
|
73
|
+
installHostListener();
|
|
74
|
+
try {
|
|
75
|
+
window.parent.postMessage({ castleSdk: CASTLE_SDK_PROTOCOL, requestId, command: "deck.channel", params: {}, documentNonce: nonce }, "*", [port2]);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
done(null);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
function receiveFromPort(port, message) {
|
|
83
|
+
const handshake = deckHandshake;
|
|
84
|
+
if (handshake && isResponseEnvelope(message) && message.requestId === handshake.requestId) {
|
|
85
|
+
const data = message.data;
|
|
86
|
+
handshake.done(message.ok && data?.status === "ok" ? port : null);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (port !== deckPort)
|
|
90
|
+
return;
|
|
91
|
+
// The host ended the channel (the frame's document or the deck's page
|
|
92
|
+
// changed): what was sent on it is not answered, and later commands go to
|
|
93
|
+
// window.parent. Each pending one fails as CASTLE_HOST_ERROR, a failure in
|
|
94
|
+
// transit, so a join asks again (hostRetry.ts), now on the window.
|
|
95
|
+
if (message?.castleSdk === CASTLE_SDK_PROTOCOL &&
|
|
96
|
+
message.deckChannelClosed === true) {
|
|
97
|
+
deckPort = null;
|
|
98
|
+
port.close();
|
|
99
|
+
for (const [requestId, entry] of [...pending]) {
|
|
100
|
+
if (entry.port !== port)
|
|
101
|
+
continue;
|
|
102
|
+
forget(requestId);
|
|
103
|
+
entry.reject(new CastleError({
|
|
104
|
+
code: "CASTLE_HOST_ERROR",
|
|
105
|
+
message: `Castle host ended the channel for ${entry.command}.`,
|
|
106
|
+
operation: entry.command,
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
receive(message, port);
|
|
112
|
+
}
|
|
113
|
+
function takeDocumentNonce() {
|
|
114
|
+
if (typeof window === "undefined")
|
|
115
|
+
return null;
|
|
116
|
+
try {
|
|
117
|
+
const value = window.__castleDocumentNonce;
|
|
118
|
+
delete window.__castleDocumentNonce;
|
|
119
|
+
return typeof value === "string" && value.length > 0 && value.length <= 256 ? value : null;
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
31
125
|
// Request ids carry a per-page prefix so that a host serving several decks at
|
|
32
126
|
// once can key a cancel by requestId alone.
|
|
33
127
|
const requestIdPrefix = `csdk_${Math.random().toString(36).slice(2, 10)}_`;
|
|
@@ -39,7 +133,13 @@ let voiceEventHandler = null;
|
|
|
39
133
|
let hubEventHandler = null;
|
|
40
134
|
export async function hostRequest(command, params, stream = {}) {
|
|
41
135
|
try {
|
|
42
|
-
const
|
|
136
|
+
const channel = resolveChannel();
|
|
137
|
+
const viaDeckChannel = channel === "web" && DECK_CHANNEL_COMMANDS.has(command);
|
|
138
|
+
// Only while the channel request is unanswered: otherwise this sends at once, as ever.
|
|
139
|
+
if (viaDeckChannel && deckHandshake)
|
|
140
|
+
await deckChannelReady;
|
|
141
|
+
const port = viaDeckChannel ? deckPort : null;
|
|
142
|
+
const env = await sendCommand(channel, command, params, stream, port);
|
|
43
143
|
return interpretResponse(command, env);
|
|
44
144
|
}
|
|
45
145
|
catch (error) {
|
|
@@ -136,7 +236,7 @@ function resolveChannel() {
|
|
|
136
236
|
// local dev server (top-level page served by `castle-web serve`).
|
|
137
237
|
return window.parent && window.parent !== window ? "web" : "local";
|
|
138
238
|
}
|
|
139
|
-
function sendCommand(channel, command, params, stream) {
|
|
239
|
+
function sendCommand(channel, command, params, stream, port = null) {
|
|
140
240
|
const requestId = `${requestIdPrefix}${nextRequestId++}`;
|
|
141
241
|
return new Promise((resolve, reject) => {
|
|
142
242
|
if (stream.signal?.aborted) {
|
|
@@ -144,18 +244,21 @@ function sendCommand(channel, command, params, stream) {
|
|
|
144
244
|
return;
|
|
145
245
|
}
|
|
146
246
|
const entry = { command, channel, resolve, reject, onStream: stream.onStream };
|
|
247
|
+
if (port)
|
|
248
|
+
entry.port = port;
|
|
147
249
|
pending.set(requestId, entry);
|
|
148
250
|
restartTimeout(requestId, entry, COMMAND_TIMEOUTS_MS[command] ?? REQUEST_TIMEOUT_MS);
|
|
149
251
|
watchAbort(requestId, entry, stream.signal);
|
|
150
252
|
if (channel === "local") {
|
|
151
|
-
sendLocalCommand(requestId, command, params, receive).catch((error) => {
|
|
253
|
+
sendLocalCommand(requestId, command, params, (message) => receive(message)).catch((error) => {
|
|
152
254
|
forget(requestId);
|
|
153
255
|
reject(error instanceof Error ? error : new Error(String(error)));
|
|
154
256
|
});
|
|
155
257
|
return;
|
|
156
258
|
}
|
|
157
259
|
installHostListener();
|
|
158
|
-
|
|
260
|
+
const envelope = { castleSdk: CASTLE_SDK_PROTOCOL, requestId, command, params };
|
|
261
|
+
postToHost(entry, envelope, stream.transfer);
|
|
159
262
|
});
|
|
160
263
|
}
|
|
161
264
|
// Interactive commands have no timeout; they resolve only when the host replies.
|
|
@@ -186,7 +289,7 @@ function watchAbort(requestId, entry, signal) {
|
|
|
186
289
|
requestId,
|
|
187
290
|
cancel: true,
|
|
188
291
|
};
|
|
189
|
-
|
|
292
|
+
postToHost(entry, envelope);
|
|
190
293
|
}
|
|
191
294
|
entry.reject(cancelledError(entry.command));
|
|
192
295
|
};
|
|
@@ -214,6 +317,12 @@ function cancelledError(command) {
|
|
|
214
317
|
operation: command,
|
|
215
318
|
});
|
|
216
319
|
}
|
|
320
|
+
function postToHost(entry, envelope, transfer = []) {
|
|
321
|
+
if (entry.port)
|
|
322
|
+
entry.port.postMessage(envelope, transfer);
|
|
323
|
+
else if (entry.channel !== "local")
|
|
324
|
+
sendEnvelope(entry.channel, envelope, transfer);
|
|
325
|
+
}
|
|
217
326
|
function sendEnvelope(channel, envelope, transfer = []) {
|
|
218
327
|
if (channel === "mobile") {
|
|
219
328
|
window.ReactNativeWebView?.postMessage(JSON.stringify(envelope));
|
|
@@ -237,15 +346,26 @@ export function installHostListener() {
|
|
|
237
346
|
receive(event.data);
|
|
238
347
|
});
|
|
239
348
|
}
|
|
240
|
-
|
|
349
|
+
// `viaPort`: the deck channel port it came on; null for the window (and the
|
|
350
|
+
// mobile and dev hosts). A request is settled or streamed to only from the
|
|
351
|
+
// channel it was sent on, so a window message naming a port request's id, or
|
|
352
|
+
// the reverse, is ignored.
|
|
353
|
+
function receive(message, viaPort = null) {
|
|
354
|
+
// An answer to the deck channel request on the window is a host without it.
|
|
355
|
+
if (!viaPort && deckHandshake && isResponseEnvelope(message) && message.requestId === deckHandshake.requestId) {
|
|
356
|
+
deckHandshake.done(null);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
241
359
|
if (isResponseEnvelope(message)) {
|
|
242
|
-
settle(message);
|
|
360
|
+
settle(message, viaPort);
|
|
243
361
|
return;
|
|
244
362
|
}
|
|
245
363
|
if (isStreamEnvelope(message)) {
|
|
246
|
-
deliverStream(message.requestId, message.stream);
|
|
364
|
+
deliverStream(message.requestId, message.stream, viaPort);
|
|
247
365
|
return;
|
|
248
366
|
}
|
|
367
|
+
if (viaPort)
|
|
368
|
+
return;
|
|
249
369
|
const voiceEvent = voiceEventFrom(message);
|
|
250
370
|
if (voiceEvent) {
|
|
251
371
|
voiceEventHandler?.(voiceEvent);
|
|
@@ -260,9 +380,9 @@ function receive(message) {
|
|
|
260
380
|
if (unloadId !== null)
|
|
261
381
|
unloadHandler?.(unloadId);
|
|
262
382
|
}
|
|
263
|
-
function settle(message) {
|
|
383
|
+
function settle(message, viaPort) {
|
|
264
384
|
const entry = pending.get(message.requestId);
|
|
265
|
-
if (!entry) {
|
|
385
|
+
if (!entry || (entry.port ?? null) !== viaPort) {
|
|
266
386
|
return;
|
|
267
387
|
}
|
|
268
388
|
forget(message.requestId);
|
|
@@ -292,9 +412,9 @@ function settle(message) {
|
|
|
292
412
|
}
|
|
293
413
|
}
|
|
294
414
|
// A throwing onStream is logged, and the stream goes on.
|
|
295
|
-
function deliverStream(requestId, event) {
|
|
415
|
+
function deliverStream(requestId, event, viaPort) {
|
|
296
416
|
const entry = pending.get(requestId);
|
|
297
|
-
if (!entry) {
|
|
417
|
+
if (!entry || (entry.port ?? null) !== viaPort) {
|
|
298
418
|
return;
|
|
299
419
|
}
|
|
300
420
|
restartTimeout(requestId, entry, STREAM_IDLE_TIMEOUT_MS);
|
|
@@ -318,3 +438,5 @@ function fromSerializedError(error, command) {
|
|
|
318
438
|
extensions: error?.extensions,
|
|
319
439
|
});
|
|
320
440
|
}
|
|
441
|
+
// Last, once every binding above exists: the deck channel opens at load.
|
|
442
|
+
const deckChannelReady = openDeckChannel(takeDocumentNonce());
|