castle-web-sdk 0.4.48 → 0.4.50
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 +75 -9
- package/dist/castle.d.ts +1 -1
- package/dist/commands.d.ts +34 -0
- package/dist/hub.d.ts +22 -7
- package/dist/hub.js +35 -6
- package/dist/hubRejoin.d.ts +4 -0
- package/dist/hubRejoin.js +15 -0
- package/dist/multiplayer.js +84 -38
- package/dist/reconnectBudget.d.ts +23 -0
- package/dist/reconnectBudget.js +96 -0
- package/dist/save.d.ts +12 -0
- package/dist/save.js +27 -0
- package/dist/server/hub.d.ts +7 -0
- package/dist/server/hub.js +17 -2
- package/dist/server/platformHandle.d.ts +4 -0
- package/dist/server/storage.d.ts +2 -0
- package/dist/server/storage.js +8 -0
- package/dist/server/wrapper.d.ts +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -67,7 +67,13 @@ Named rooms use `{ mode: "named", key: "room-name" }`; party sessions use
|
|
|
67
67
|
reconnects temporary socket drops automatically. `onStateChange` reports
|
|
68
68
|
`acquiring`, `connecting`, `connected`, `reconnecting`, and `closed`; its optional
|
|
69
69
|
metadata distinguishes a server `bye`, a replaced server version, an explicit
|
|
70
|
-
`leave`, and connection failures.
|
|
70
|
+
`leave`, and connection failures. The reconnect retry budget counts 30 seconds
|
|
71
|
+
of foreground time; time while the page is hidden or frozen does not spend it,
|
|
72
|
+
and a stall of the page's JavaScript (a debugger pause, an app pausing its web
|
|
73
|
+
view) spends at most two seconds. After any return the SDK tries the reconnect
|
|
74
|
+
credential at least once before giving up on it. Retries wait for the page to
|
|
75
|
+
become visible and resume. A server rejecting the
|
|
76
|
+
credential or confirming the session ended can still trigger a fresh join sooner.
|
|
71
77
|
|
|
72
78
|
`connection.serverBundleId` and `connection.serverBundleSha256` identify the server publication running the connected session. These read-only diagnostics are `null` before a live connection, while disconnected, in solo mode, or when the host does not provide them. The ID identifies a publication; the SHA-256 identifies its code bytes, so two publications can share a hash. Read the values again after a reconnect or a destination join. They describe the running server, not the client bundle or the deck’s newest save.
|
|
73
79
|
|
|
@@ -226,6 +232,14 @@ dev serve.
|
|
|
226
232
|
through a hub door: `{ fromDeckId, doorId }` (`doorId` is `null` when the door
|
|
227
233
|
names none), else `null`. It is Castle's word, never a client's, and it is also
|
|
228
234
|
the third argument of `onPlayerJoin`.
|
|
235
|
+
- `session.hub.push` is optional, present only for a place declaring
|
|
236
|
+
`hub.push: { version: 1 }` on a capable runtime. Its
|
|
237
|
+
`visit(playerId, { userId, timezone })` reports a visit with the captured
|
|
238
|
+
authenticated account and an IANA timezone. It returns a boolean acknowledgement.
|
|
239
|
+
Ghost derives the three-day come-back reminder and checks consent, answered
|
|
240
|
+
age, experiments, quiet hours and delivery limits. Reporting a visit does not
|
|
241
|
+
opt the player in or promise a notification. No crop reporting or queue
|
|
242
|
+
reconciliation API is exposed.
|
|
229
243
|
- `session.hub.reportResult(playerId, { outcome?, score?, stats? })` records a
|
|
230
244
|
signed-in player's result for this visit, once. The host checks it against the
|
|
231
245
|
published shape and Castle keeps it only for a place behind a curated door;
|
|
@@ -669,6 +683,17 @@ Older hosts and the dev memory store do not support it. Keep a dependent
|
|
|
669
683
|
feature off when the API is unavailable; never fall back to ordinary writes.
|
|
670
684
|
Existing `get`, `set` and save methods keep their behavior.
|
|
671
685
|
|
|
686
|
+
Session servers can read `session.storage.resetGeneration(userId)` (zero before
|
|
687
|
+
the first reset) and pass `resetFences: [{ playerId, resetGeneration }]` to
|
|
688
|
+
`conditionalWrite`. Supply one or two unique numeric account IDs and integer
|
|
689
|
+
generations from 0 through 2147483647. Read generations before the snapshot used
|
|
690
|
+
to build the write. A reset that commits first refuses the write with
|
|
691
|
+
`CAULDRON_STORAGE_STALE_RESET_GENERATION`, `committed: false`, and
|
|
692
|
+
`playerId`, `expectedResetGeneration`, and current `resetGeneration` on the
|
|
693
|
+
`SaveError` and its `extensions`. A write that commits first retains its receipt;
|
|
694
|
+
recovery must check current generations before adopting it. Clients cannot send
|
|
695
|
+
reset fences. Omitting them preserves the existing request.
|
|
696
|
+
|
|
672
697
|
One call changes up to eight targets, with up to eight explicit key changes
|
|
673
698
|
per target, across the same deck and at most two players. Every target needs
|
|
674
699
|
its expected revision. A read-only `check` can use `expectedRevision: null`
|
|
@@ -1226,12 +1251,28 @@ if (party) {
|
|
|
1226
1251
|
|
|
1227
1252
|
Hub contract v1.95 adds optional invites. A place declaring `hub.invite: true`
|
|
1228
1253
|
can call `hub.invite(playerId)` on its server to offer **Invite a friend**.
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1254
|
+
As of contract v1.124, `Hub.invite()` makes one link for up to five friends,
|
|
1255
|
+
expiring within 24 hours. The kit opens it directly with native Share when
|
|
1256
|
+
supported and an explicit Copy link action. `Hub.invite({ crew: false })`
|
|
1257
|
+
retains the one-use option for callers that need it. Hosts without invite
|
|
1258
|
+
support return `unavailable`.
|
|
1259
|
+
|
|
1260
|
+
`Hub.canInvite()` answers `{ status: 'ok', canInvite }`: whether the host will
|
|
1261
|
+
make a link for this player, by Castle's invite rule for the account (signed
|
|
1262
|
+
in, over 13, in the invite audience). The kit offers **Invite a friend** only on
|
|
1263
|
+
`canInvite: true`. Hosts without hub support answer `unavailable`, and a host
|
|
1264
|
+
older than the command rejects it, so treat anything else as no.
|
|
1265
|
+
With `canInvite: true`, newer hosts also name the account the links belong to
|
|
1266
|
+
(`userId`, a guest's included); the kit offers the action only while that
|
|
1267
|
+
account is the player's own, and checks `User.getCurrent()` when a host names
|
|
1268
|
+
none.
|
|
1232
1269
|
|
|
1233
1270
|
The trusted host resolves the link after sign-in, retains its token, and requests
|
|
1234
|
-
the inviter's layer when it has room.
|
|
1271
|
+
the inviter's layer when it has room. If resolution refuses the invite, the host
|
|
1272
|
+
discards it for that visit and joins normally. Transient resolution failures
|
|
1273
|
+
retry with backoff; after five failures the host also discards the invite.
|
|
1274
|
+
Anonymous players join normally without using the invite.
|
|
1275
|
+
An invite can also route through the
|
|
1235
1276
|
existing `Hub.inviteArrival()` result `{ status: 'route', doorId }` to the
|
|
1236
1277
|
inviter's house or active run behind a curated door that allows late joins.
|
|
1237
1278
|
Contract v1.113 active-run routing requires root `hub.bringFriend: true`
|
|
@@ -1241,8 +1282,9 @@ the invite capability;
|
|
|
1241
1282
|
it admits only to the matching live run while the inviter is present. A full,
|
|
1242
1283
|
ended or unavailable run is refused rather than recreated. The kit calls
|
|
1243
1284
|
`Hub.inviteArrival()` after joining that destination. Ghost verifies arrival
|
|
1244
|
-
before creating mutual follows
|
|
1245
|
-
over-13
|
|
1285
|
+
before creating mutual follows between each eligible
|
|
1286
|
+
over-13 arrival and the inviter. New arrivals do not follow one another;
|
|
1287
|
+
existing pairs from earlier links remain available for Undo. Under-13 arrivals create no follows. The arrival
|
|
1246
1288
|
surface shows an authored now-friends line and `Hub.undoInvite(userId)` removes
|
|
1247
1289
|
both follow directions for that pair. No player-entered message travels with a link.
|
|
1248
1290
|
These operations retain the existing hub access gates. Link creation and arrival
|
|
@@ -1272,6 +1314,10 @@ the signed-in account id. A new host without native sign-in support returns
|
|
|
1272
1314
|
- `Hub.go(doorId)` acquires the destination behind a door of the current place.
|
|
1273
1315
|
A door used within seconds of arriving can take up to 15 seconds to answer
|
|
1274
1316
|
while Castle catches up with the arrival.
|
|
1317
|
+
`Hub.go(doorId, { ownerUserId })` on a House door visits that friend's House
|
|
1318
|
+
(the `ownerUserId` `Hub.friends()` gives a friend at home); Castle admits it
|
|
1319
|
+
only while the two are connected and the owner is home. A host that predates
|
|
1320
|
+
it ignores `ownerUserId` and acquires the player's own House.
|
|
1275
1321
|
- `Hub.back()` acquires the way back through the door the player came in by: the
|
|
1276
1322
|
layer they left if it has room, else their party's, else the usual pick. The
|
|
1277
1323
|
deck cannot choose where it leads; `not_found` when there is no way back.
|
|
@@ -1280,7 +1326,9 @@ the signed-in account id. A new host without native sign-in support returns
|
|
|
1280
1326
|
20): `{ status: "ok", friends: [{ userId, username, here, door }] }` or
|
|
1281
1327
|
`{ status: "unavailable", friends: null }`. `here` is true for a friend in the
|
|
1282
1328
|
player's own layer; `door` is set instead for a friend inside the place behind
|
|
1283
|
-
one of this place's doors (that door's id), and null otherwise.
|
|
1329
|
+
one of this place's doors (that door's id), and null otherwise. A friend
|
|
1330
|
+
inside their own House behind that door also has `home: true` and
|
|
1331
|
+
`ownerUserId`, which `Hub.go` takes to visit them.
|
|
1284
1332
|
- `Hub.jump(userId)` acquires the layer of the current place that friend is in:
|
|
1285
1333
|
the same place in another session, joined exactly like a door's. The way back
|
|
1286
1334
|
does not change. `not_found` when the friend is not in another layer of it.
|
|
@@ -1301,7 +1349,13 @@ the signed-in account id. A new host without native sign-in support returns
|
|
|
1301
1349
|
send it to), `refused`, `limited` (said too fast) or `unavailable`.
|
|
1302
1350
|
- `Hub.reportChat(messageId)` reports a chat message the player was returned to
|
|
1303
1351
|
Castle's moderators. The host names the place and session. `{ status: "ok" }`
|
|
1304
|
-
or `unavailable`.
|
|
1352
|
+
or `unavailable`. Pass `{ block: true }` as a second argument to also block
|
|
1353
|
+
the sender of that stored message. The host asks for confirmation naming the
|
|
1354
|
+
sender; dismissing it, or using a host without confirmation support, reports
|
|
1355
|
+
the message without blocking. Hosts limit confirmation prompts to one per
|
|
1356
|
+
minute; another request during that window reports without blocking. Only `{ status: "ok", blocked: true }`
|
|
1357
|
+
confirms both actions; older hosts can report without confirming a block.
|
|
1358
|
+
Blocks prevent chat between the pair in either direction. Hub chrome only.
|
|
1305
1359
|
- `Hub.cancel()` gives back an acquisition the deck will not join. Optional: one
|
|
1306
1360
|
that is never joined expires within two minutes.
|
|
1307
1361
|
- `Hub.onBack(listener)` hears the host's Back control, which a game cannot hide.
|
|
@@ -1318,6 +1372,12 @@ destination session's content pack hash) and `contentUrl` (that pack's immutable
|
|
|
1318
1372
|
URL, or null when the destination has none), or `cancelled`, `full`,
|
|
1319
1373
|
`unavailable`, `not_found`, `forbidden` or `party_required` with those fields null.
|
|
1320
1374
|
|
|
1375
|
+
Castle lists a player at a door only once it has seen them in the place's
|
|
1376
|
+
session, which can take up to 15 seconds after they arrive or after their
|
|
1377
|
+
connection comes back from a break (an app switch, a network drop). In that
|
|
1378
|
+
window `go` and `jump` keep asking and answer once the player is listed, so a
|
|
1379
|
+
`forbidden` they return is final.
|
|
1380
|
+
|
|
1321
1381
|
A door can also lead to a cabinet: a classic Castle deck the host plays itself.
|
|
1322
1382
|
`Hub.go` then answers `status: "ok"` with `kind: "classic"` and null `url`, `nonce`
|
|
1323
1383
|
and `sessionId`: there is no session to join, and the trip is already committed.
|
|
@@ -1841,6 +1901,12 @@ load its assets through the bundler instead.
|
|
|
1841
1901
|
|
|
1842
1902
|
## CastleError
|
|
1843
1903
|
|
|
1904
|
+
A multiplayer socket closed before its first hello reports its WebSocket close
|
|
1905
|
+
code in `error.extensions.closeCode` when available. Code `4404` means the
|
|
1906
|
+
play proxy could not route the session (`not_running`); it does not prove the
|
|
1907
|
+
runtime ended. A failed hub join cancels its handoff, so retrying a door requires
|
|
1908
|
+
a fresh `Hub.go` acquisition.
|
|
1909
|
+
|
|
1844
1910
|
Every error the SDK throws is a `CastleError`. Check `code` to tell
|
|
1845
1911
|
the kinds apart.
|
|
1846
1912
|
|
package/dist/castle.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ 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, 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, HubSignInParams, HubSignInResult, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, } from "./hub";
|
|
17
17
|
export { Social } from "./social";
|
|
18
18
|
export type { CastleSocialApi, SocialFriend, SocialPresence } from "./social";
|
|
19
19
|
export { Party } from "./party";
|
package/dist/commands.d.ts
CHANGED
|
@@ -121,6 +121,12 @@ export interface PartyMessagesResult {
|
|
|
121
121
|
}
|
|
122
122
|
export interface HubGoParams {
|
|
123
123
|
doorId: string;
|
|
124
|
+
/**
|
|
125
|
+
* A House door only: visit this owner's House instead of the player's own.
|
|
126
|
+
* Ghost admits it only when the two are connected and the owner is home;
|
|
127
|
+
* a host that predates it ignores it and acquires the player's own House.
|
|
128
|
+
*/
|
|
129
|
+
ownerUserId?: string;
|
|
124
130
|
}
|
|
125
131
|
export type HubPlacementKind = "layer" | "pad" | "exact";
|
|
126
132
|
export type HubHandoffStatus = "ok" | "cancelled" | "full" | "unavailable" | "not_found" | "forbidden" | "party_required";
|
|
@@ -176,6 +182,12 @@ export interface HubFriend {
|
|
|
176
182
|
* of its doors: that door's id. Null for a friend in a layer of this place.
|
|
177
183
|
*/
|
|
178
184
|
door: string | null;
|
|
185
|
+
/**
|
|
186
|
+
* Present only for a friend inside their own House behind `door`: `home` is
|
|
187
|
+
* true and `ownerUserId` is the owner to pass to `Hub.go` to visit them.
|
|
188
|
+
*/
|
|
189
|
+
home?: true;
|
|
190
|
+
ownerUserId?: string;
|
|
179
191
|
}
|
|
180
192
|
/** Hub.report: another player, by user id, and an optional short reason. */
|
|
181
193
|
export interface HubReportParams {
|
|
@@ -185,6 +197,8 @@ export interface HubReportParams {
|
|
|
185
197
|
/** `unavailable` on hosts without hub support or outside a hub session. */
|
|
186
198
|
export interface HubReportResult {
|
|
187
199
|
status: "ok" | "unavailable";
|
|
200
|
+
/** Present only when a chat sender was also blocked successfully. */
|
|
201
|
+
blocked?: true;
|
|
188
202
|
}
|
|
189
203
|
/** Why the hub is asking the player to replace an anonymous account. */
|
|
190
204
|
export interface HubSignInParams {
|
|
@@ -207,6 +221,22 @@ export interface HubInviteResult {
|
|
|
207
221
|
url?: string;
|
|
208
222
|
expiresAt?: string;
|
|
209
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Whether the host will make invite links for this player: Castle's invite
|
|
226
|
+
* rule for the account (signed in, over 13, in the invite audience), as the
|
|
227
|
+
* host resolved it. `unavailable` on hosts without hub support. With
|
|
228
|
+
* `canInvite: true`, `userId` names the account the links belong to (a guest's
|
|
229
|
+
* included), so a deck offers them only to the player that account plays as;
|
|
230
|
+
* older hosts leave it out.
|
|
231
|
+
*/
|
|
232
|
+
export type HubCanInviteResult = {
|
|
233
|
+
status: "ok";
|
|
234
|
+
canInvite: boolean;
|
|
235
|
+
userId?: string;
|
|
236
|
+
} | {
|
|
237
|
+
status: "unavailable";
|
|
238
|
+
canInvite: false;
|
|
239
|
+
};
|
|
210
240
|
export interface HubInviteArrivalResult {
|
|
211
241
|
status: "ok" | "unavailable" | "route";
|
|
212
242
|
doorId?: string;
|
|
@@ -280,6 +310,8 @@ export interface HubSayResult {
|
|
|
280
310
|
/** Hub.reportChat: a message this player was returned, by its id. */
|
|
281
311
|
export interface HubReportChatParams {
|
|
282
312
|
messageId: string;
|
|
313
|
+
/** Also block the sender identified by the stored message. */
|
|
314
|
+
block?: boolean;
|
|
283
315
|
}
|
|
284
316
|
/** Public door row; destination identity and return tickets stay host-owned. */
|
|
285
317
|
export interface HubDoor {
|
|
@@ -634,6 +666,7 @@ export interface CommandParams {
|
|
|
634
666
|
"hub.invite": {
|
|
635
667
|
crew?: boolean;
|
|
636
668
|
};
|
|
669
|
+
"hub.canInvite": Record<string, never>;
|
|
637
670
|
"hub.inviteArrival": Record<string, never>;
|
|
638
671
|
"hub.undoInvite": {
|
|
639
672
|
userId: string;
|
|
@@ -832,6 +865,7 @@ export interface CommandResult {
|
|
|
832
865
|
"hub.doors": HubDoorsResult;
|
|
833
866
|
"hub.friends": HubFriendsResult;
|
|
834
867
|
"hub.invite": HubInviteResult;
|
|
868
|
+
"hub.canInvite": HubCanInviteResult;
|
|
835
869
|
"hub.inviteArrival": HubInviteArrivalResult;
|
|
836
870
|
"hub.undoInvite": HubReportResult;
|
|
837
871
|
"hub.hearts": HubHeartsResult;
|
package/dist/hub.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { HubBackResult, HubCancelResult, HubChatResult, HubDoorsResult, HubFriendsResult, HubInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoResult, HubJumpResult, HubReportResult, HubSayResult, HubSignInResult } from "./commands";
|
|
2
|
-
export type { HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoParams, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, HubSignInParams, HubSignInResult, } from "./commands";
|
|
1
|
+
import type { HubBackResult, HubCancelResult, HubChatResult, HubDoorsResult, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoResult, HubJumpResult, HubReportResult, HubSayResult, HubSignInResult } from "./commands";
|
|
2
|
+
export type { HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoParams, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, HubSignInParams, HubSignInResult, } from "./commands";
|
|
3
3
|
/**
|
|
4
4
|
* Doors between hub places. Every hub-kit deck is a place; ghost's door table
|
|
5
5
|
* is the allowlist, and the host supplies real authentication and the current
|
|
@@ -17,9 +17,13 @@ export interface CastleHubApi {
|
|
|
17
17
|
/**
|
|
18
18
|
* Acquire the destination behind a door of the current place. A door used
|
|
19
19
|
* within seconds of arriving may take up to 15 s while ghost catches up with
|
|
20
|
-
* the arrival. `unavailable` on hosts without hub support.
|
|
20
|
+
* the arrival. `unavailable` on hosts without hub support. `ownerUserId`
|
|
21
|
+
* (a House door only) visits that friend's House, as `Hub.friends()` names
|
|
22
|
+
* it; a host that predates it acquires the player's own House instead.
|
|
21
23
|
*/
|
|
22
|
-
go(doorId: string
|
|
24
|
+
go(doorId: string, options?: {
|
|
25
|
+
ownerUserId?: string;
|
|
26
|
+
}): Promise<HubGoResult>;
|
|
23
27
|
/**
|
|
24
28
|
* Acquire the way back through the door this player came in by: the layer
|
|
25
29
|
* left behind if it has room, else the party's, else the usual pick. The deck
|
|
@@ -35,10 +39,17 @@ export interface CastleHubApi {
|
|
|
35
39
|
* on hosts without hub support.
|
|
36
40
|
*/
|
|
37
41
|
friends(): Promise<HubFriendsResult>;
|
|
38
|
-
/** Create an expiring link from this hub session.
|
|
42
|
+
/** Create an expiring link from this hub session. Links admit up to five invitees by default. */
|
|
39
43
|
invite(options?: {
|
|
40
44
|
crew?: boolean;
|
|
41
45
|
}): Promise<HubInviteResult>;
|
|
46
|
+
/**
|
|
47
|
+
* Whether `invite` can make a link for this player: Castle's invite rule for
|
|
48
|
+
* the account, as the host resolved it. Ask before offering an invite;
|
|
49
|
+
* `unavailable` on hosts without hub support, and a host older than this
|
|
50
|
+
* command rejects it, so treat anything but `canInvite: true` as no.
|
|
51
|
+
*/
|
|
52
|
+
canInvite(): Promise<HubCanInviteResult>;
|
|
42
53
|
/** Hub-kit arrival hook: the trusted host retains the invite token. */
|
|
43
54
|
inviteArrival(): Promise<HubInviteArrivalResult>;
|
|
44
55
|
/** Undo both follow directions for one pair from this host's invite arrival. */
|
|
@@ -82,10 +93,14 @@ export interface CastleHubApi {
|
|
|
82
93
|
say(text: string): Promise<HubSayResult>;
|
|
83
94
|
/**
|
|
84
95
|
* Report a chat message this player was returned to Castle's moderators, by
|
|
85
|
-
* its id.
|
|
96
|
+
* its id. Pass `{ block: true }` to also block the stored sender; only a
|
|
97
|
+
* result with `blocked: true` confirms that block. Hub chrome only:
|
|
98
|
+
* the host fills in the place and session.
|
|
86
99
|
* `unavailable` on hosts without hub support or outside a hub session.
|
|
87
100
|
*/
|
|
88
|
-
reportChat(messageId: string
|
|
101
|
+
reportChat(messageId: string, options?: {
|
|
102
|
+
block?: boolean;
|
|
103
|
+
}): Promise<HubReportResult>;
|
|
89
104
|
/**
|
|
90
105
|
* Abandon an acquisition the deck will not join (its content failed to load,
|
|
91
106
|
* the player walked away). Optional: an unjoined one expires on its own.
|
package/dist/hub.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { CastleError } from "./errors";
|
|
2
2
|
import { hostRequest, setHubEventHandler } from "./transport";
|
|
3
|
+
import { HUB_FORBIDDEN_RETRY_MS, rejoinedRecently } from "./hubRejoin";
|
|
3
4
|
export const Hub = {
|
|
4
5
|
go,
|
|
5
6
|
back,
|
|
6
7
|
doors,
|
|
7
8
|
friends,
|
|
8
9
|
invite,
|
|
10
|
+
canInvite,
|
|
9
11
|
inviteArrival,
|
|
10
12
|
undoInvite,
|
|
11
13
|
hearts,
|
|
@@ -19,7 +21,7 @@ export const Hub = {
|
|
|
19
21
|
cancel,
|
|
20
22
|
onBack,
|
|
21
23
|
};
|
|
22
|
-
async function go(doorId) {
|
|
24
|
+
async function go(doorId, options = {}) {
|
|
23
25
|
if (typeof doorId !== "string" || doorId.length === 0) {
|
|
24
26
|
throw new CastleError({
|
|
25
27
|
code: "INVALID_ARGUMENT",
|
|
@@ -27,7 +29,30 @@ async function go(doorId) {
|
|
|
27
29
|
operation: "Hub.go",
|
|
28
30
|
});
|
|
29
31
|
}
|
|
30
|
-
|
|
32
|
+
const ownerUserId = options?.ownerUserId;
|
|
33
|
+
if (ownerUserId !== undefined && (typeof ownerUserId !== "string" || !/^[1-9]\d{0,9}$/.test(ownerUserId))) {
|
|
34
|
+
throw new CastleError({
|
|
35
|
+
code: "INVALID_ARGUMENT",
|
|
36
|
+
message: "Hub.go ownerUserId must be a user id.",
|
|
37
|
+
operation: "Hub.go",
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return untilListed(() => hostRequest("hub.go", ownerUserId === undefined ? { doorId } : { doorId, ownerUserId }));
|
|
41
|
+
}
|
|
42
|
+
// Right after the socket rejoined its session ghost may not list the player
|
|
43
|
+
// yet, and answers `forbidden` until it does. `Hub.cancel` ends the wait.
|
|
44
|
+
let cancels = 0;
|
|
45
|
+
async function untilListed(ask) {
|
|
46
|
+
const asked = cancels;
|
|
47
|
+
for (;;) {
|
|
48
|
+
const result = await ask();
|
|
49
|
+
if (result.status !== "forbidden" || !rejoinedRecently())
|
|
50
|
+
return result;
|
|
51
|
+
await new Promise((resolve) => setTimeout(resolve, HUB_FORBIDDEN_RETRY_MS));
|
|
52
|
+
if (cancels !== asked) {
|
|
53
|
+
return { status: "cancelled", url: null, nonce: null, sessionId: null, bundleHash: null, contentUrl: null };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
31
56
|
}
|
|
32
57
|
async function back() {
|
|
33
58
|
return hostRequest("hub.back", {});
|
|
@@ -41,7 +66,10 @@ async function friends() {
|
|
|
41
66
|
async function invite(options = {}) {
|
|
42
67
|
if (options.crew !== undefined && typeof options.crew !== "boolean")
|
|
43
68
|
throw new CastleError({ code: "INVALID_ARGUMENT", message: "Hub.invite crew must be a boolean.", operation: "Hub.invite" });
|
|
44
|
-
return hostRequest("hub.invite", options.crew
|
|
69
|
+
return hostRequest("hub.invite", options.crew !== false ? { crew: true } : {});
|
|
70
|
+
}
|
|
71
|
+
async function canInvite() {
|
|
72
|
+
return hostRequest("hub.canInvite", {});
|
|
45
73
|
}
|
|
46
74
|
async function inviteArrival() {
|
|
47
75
|
return hostRequest("hub.inviteArrival", {});
|
|
@@ -87,7 +115,7 @@ async function jump(userId) {
|
|
|
87
115
|
operation: "Hub.jump",
|
|
88
116
|
});
|
|
89
117
|
}
|
|
90
|
-
return hostRequest("hub.jump", { userId });
|
|
118
|
+
return untilListed(() => hostRequest("hub.jump", { userId }));
|
|
91
119
|
}
|
|
92
120
|
async function report(userId, reason) {
|
|
93
121
|
if (typeof userId !== "string" || userId.length === 0) {
|
|
@@ -112,7 +140,7 @@ async function say(text) {
|
|
|
112
140
|
}
|
|
113
141
|
return hostRequest("hub.say", { text });
|
|
114
142
|
}
|
|
115
|
-
async function reportChat(messageId) {
|
|
143
|
+
async function reportChat(messageId, options) {
|
|
116
144
|
if (typeof messageId !== "string" || messageId.length === 0) {
|
|
117
145
|
throw new CastleError({
|
|
118
146
|
code: "INVALID_ARGUMENT",
|
|
@@ -120,9 +148,10 @@ async function reportChat(messageId) {
|
|
|
120
148
|
operation: "Hub.reportChat",
|
|
121
149
|
});
|
|
122
150
|
}
|
|
123
|
-
return hostRequest("hub.reportChat", { messageId });
|
|
151
|
+
return hostRequest("hub.reportChat", { messageId, ...(options?.block === true ? { block: true } : {}) });
|
|
124
152
|
}
|
|
125
153
|
async function cancel() {
|
|
154
|
+
cancels += 1;
|
|
126
155
|
return hostRequest("hub.cancel", {});
|
|
127
156
|
}
|
|
128
157
|
const backListeners = new Set();
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Ghost's source check for a door reads the session's heartbeat roster, which
|
|
2
|
+
// drops a player who was away and takes up to 15 s to list them again. The host
|
|
3
|
+
// waits that out after an arrival it saw; a socket that reconnected to the same
|
|
4
|
+
// session is one only the deck sees, so the deck waits it out itself.
|
|
5
|
+
export const HUB_ROSTER_LAG_MS = 16_000;
|
|
6
|
+
export const HUB_FORBIDDEN_RETRY_MS = 1_000;
|
|
7
|
+
let rejoinedAt = null;
|
|
8
|
+
// Monotonic where there is one: a wall-clock correction must not stretch or cut the wait.
|
|
9
|
+
const now = () => globalThis.performance?.now() ?? Date.now();
|
|
10
|
+
export function noteSessionRejoined() {
|
|
11
|
+
rejoinedAt = now();
|
|
12
|
+
}
|
|
13
|
+
export function rejoinedRecently() {
|
|
14
|
+
return rejoinedAt !== null && now() - rejoinedAt < HUB_ROSTER_LAG_MS;
|
|
15
|
+
}
|
package/dist/multiplayer.js
CHANGED
|
@@ -2,6 +2,8 @@ import { CastleError } from "./errors";
|
|
|
2
2
|
import { BINARY_MESSAGE_TAG, isBinaryPayload, MAX_CLIENT_FRAME_BYTES, toUint8Array, } from "./multiplayerProtocol";
|
|
3
3
|
import { hostRequest } from "./transport";
|
|
4
4
|
import { MultiplayerVoiceImpl } from "./multiplayerVoice";
|
|
5
|
+
import { ReconnectBudget } from "./reconnectBudget";
|
|
6
|
+
import { noteSessionRejoined } from "./hubRejoin";
|
|
5
7
|
const KEEPALIVE_INTERVAL_MS = 25_000;
|
|
6
8
|
const HELLO_TIMEOUT_MS = 10_000;
|
|
7
9
|
const RECONNECT_BUDGET_MS = 30_000;
|
|
@@ -204,7 +206,9 @@ class MultiplayerConnectionImpl {
|
|
|
204
206
|
pongExtensionUsed = false;
|
|
205
207
|
pongDeadline = null;
|
|
206
208
|
reAcquisitionUsed = false;
|
|
209
|
+
greeted = false;
|
|
207
210
|
recovering = false;
|
|
211
|
+
reconnectBudget = null;
|
|
208
212
|
hubSettled = false;
|
|
209
213
|
hubCommit = Promise.resolve(true);
|
|
210
214
|
roster = null;
|
|
@@ -457,28 +461,39 @@ class MultiplayerConnectionImpl {
|
|
|
457
461
|
await this.openSocket("nonce", result.nonce);
|
|
458
462
|
}
|
|
459
463
|
async restoreDevReconnect(token) {
|
|
460
|
-
|
|
464
|
+
this.assertOpen();
|
|
465
|
+
const budget = this.reconnectBudget = new ReconnectBudget();
|
|
461
466
|
let attempt = 0;
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
467
|
+
try {
|
|
468
|
+
while (true) {
|
|
469
|
+
await budget.waitUntilActive();
|
|
470
|
+
this.assertOpen();
|
|
471
|
+
try {
|
|
472
|
+
budget.noteAttempt();
|
|
473
|
+
await this.openSocket("reconnect", token);
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
catch (error) {
|
|
477
|
+
await budget.waitUntilActive();
|
|
478
|
+
this.assertOpen();
|
|
479
|
+
if (error instanceof SocketClosedError &&
|
|
480
|
+
error.code === INVALID_DEV_RECONNECT_CLOSE_CODE) {
|
|
481
|
+
clearDevReconnectToken(this.devReconnectStorageKey, token);
|
|
482
|
+
return false;
|
|
483
|
+
}
|
|
484
|
+
// A 503 during a server rebuild, network failure, or hello timeout
|
|
485
|
+
// does not prove the credential expired. Retain it if retries run out.
|
|
486
|
+
if (budget.exhausted(RECONNECT_BUDGET_MS))
|
|
487
|
+
throw error;
|
|
488
|
+
const delay = RECONNECT_DELAYS_MS[Math.min(attempt++, RECONNECT_DELAYS_MS.length - 1)];
|
|
489
|
+
await pause(delay);
|
|
473
490
|
}
|
|
474
|
-
// A 503 during a server rebuild, network failure, or hello timeout
|
|
475
|
-
// does not prove the credential expired. Retain it if retries run out.
|
|
476
|
-
if (Date.now() - startedAt >= RECONNECT_BUDGET_MS)
|
|
477
|
-
throw error;
|
|
478
|
-
const delay = RECONNECT_DELAYS_MS[Math.min(attempt++, RECONNECT_DELAYS_MS.length - 1)];
|
|
479
|
-
await pause(delay);
|
|
480
491
|
}
|
|
481
492
|
}
|
|
493
|
+
finally {
|
|
494
|
+
budget.dispose();
|
|
495
|
+
this.reconnectBudget = null;
|
|
496
|
+
}
|
|
482
497
|
}
|
|
483
498
|
connectSolo(result) {
|
|
484
499
|
this.solo = true;
|
|
@@ -567,6 +582,11 @@ class MultiplayerConnectionImpl {
|
|
|
567
582
|
});
|
|
568
583
|
}
|
|
569
584
|
acceptHello(frame) {
|
|
585
|
+
// A later hello is a rejoin the host never hears of; doors wait out the
|
|
586
|
+
// roster lag after it (hubRejoin.ts).
|
|
587
|
+
if (this.greeted)
|
|
588
|
+
noteSessionRejoined();
|
|
589
|
+
this.greeted = true;
|
|
570
590
|
this.currentPlayerId = frame.playerId;
|
|
571
591
|
this.currentSessionId = frame.sessionId;
|
|
572
592
|
// Diagnostics never decide whether a hello is accepted. Missing or malformed
|
|
@@ -650,31 +670,48 @@ class MultiplayerConnectionImpl {
|
|
|
650
670
|
});
|
|
651
671
|
}
|
|
652
672
|
async recover() {
|
|
653
|
-
|
|
673
|
+
this.assertOpen();
|
|
674
|
+
const budget = this.reconnectBudget = new ReconnectBudget();
|
|
654
675
|
let attempt = 0;
|
|
655
676
|
let sessionEndedCloses = 0;
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
return;
|
|
664
|
-
}
|
|
665
|
-
catch (error) {
|
|
666
|
-
const code = error instanceof SocketClosedError ? error.code : null;
|
|
667
|
-
if (code === 1008 || code === PROXY_CREDENTIAL_REJECTED_CLOSE_CODE)
|
|
668
|
-
break;
|
|
669
|
-
// Retrying a session that is gone only spends the budget; ask for a fresh join.
|
|
670
|
-
// Any other failure in between means the two refusals were not in a row.
|
|
671
|
-
sessionEndedCloses = code === PROXY_SESSION_ENDED_CLOSE_CODE
|
|
672
|
-
? sessionEndedCloses + 1
|
|
673
|
-
: 0;
|
|
674
|
-
if (sessionEndedCloses >= SESSION_ENDED_CONFIRMATIONS)
|
|
677
|
+
try {
|
|
678
|
+
while (true) {
|
|
679
|
+
await budget.waitUntilActive();
|
|
680
|
+
this.assertOpen();
|
|
681
|
+
// A stall that spends the budget still leaves one try with the token,
|
|
682
|
+
// which keeps the player's identity while the host holds its lineage.
|
|
683
|
+
if (budget.exhausted(RECONNECT_BUDGET_MS))
|
|
675
684
|
break;
|
|
685
|
+
const delay = RECONNECT_DELAYS_MS[Math.min(attempt, RECONNECT_DELAYS_MS.length - 1)];
|
|
686
|
+
attempt += 1;
|
|
687
|
+
await pause(delay);
|
|
688
|
+
await budget.waitUntilActive();
|
|
689
|
+
this.assertOpen();
|
|
690
|
+
try {
|
|
691
|
+
budget.noteAttempt();
|
|
692
|
+
await this.openSocket("reconnect", this.reconnectToken);
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
catch (error) {
|
|
696
|
+
await budget.waitUntilActive();
|
|
697
|
+
this.assertOpen();
|
|
698
|
+
const code = error instanceof SocketClosedError ? error.code : null;
|
|
699
|
+
if (code === 1008 || code === PROXY_CREDENTIAL_REJECTED_CLOSE_CODE)
|
|
700
|
+
break;
|
|
701
|
+
// Retrying a session that is gone only spends the budget; ask for a fresh join.
|
|
702
|
+
// Any other failure in between means the two refusals were not in a row.
|
|
703
|
+
sessionEndedCloses = code === PROXY_SESSION_ENDED_CLOSE_CODE
|
|
704
|
+
? sessionEndedCloses + 1
|
|
705
|
+
: 0;
|
|
706
|
+
if (sessionEndedCloses >= SESSION_ENDED_CONFIRMATIONS)
|
|
707
|
+
break;
|
|
708
|
+
}
|
|
676
709
|
}
|
|
677
710
|
}
|
|
711
|
+
finally {
|
|
712
|
+
budget.dispose();
|
|
713
|
+
this.reconnectBudget = null;
|
|
714
|
+
}
|
|
678
715
|
await this.reacquireOnce();
|
|
679
716
|
}
|
|
680
717
|
async reacquireOnce() {
|
|
@@ -771,6 +808,7 @@ class MultiplayerConnectionImpl {
|
|
|
771
808
|
(metadata.type === "left" || metadata.type === "bye" || metadata.type === "replaced"))
|
|
772
809
|
clearDevReconnectToken(this.devReconnectStorageKey, this.reconnectToken);
|
|
773
810
|
this.stopKeepalive();
|
|
811
|
+
this.reconnectBudget?.dispose();
|
|
774
812
|
this.rejectPendingCharacterRequests("MULTIPLAYER_CONNECTION_CLOSED", "The multiplayer connection closed before the shared character request completed.");
|
|
775
813
|
const socket = this.socket;
|
|
776
814
|
this.socket = null;
|
|
@@ -1288,5 +1326,13 @@ function multiplayerError(code, message, operation = "Multiplayer.join") {
|
|
|
1288
1326
|
function asCastleError(error) {
|
|
1289
1327
|
if (error instanceof CastleError)
|
|
1290
1328
|
return error;
|
|
1329
|
+
if (error instanceof SocketClosedError) {
|
|
1330
|
+
return new CastleError({
|
|
1331
|
+
code: "MULTIPLAYER_CONNECTION_FAILED",
|
|
1332
|
+
message: error.message,
|
|
1333
|
+
operation: "Multiplayer.join",
|
|
1334
|
+
extensions: { closeCode: error.code },
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1291
1337
|
return multiplayerError("MULTIPLAYER_CONNECTION_FAILED", error instanceof Error ? error.message : "The multiplayer connection failed.");
|
|
1292
1338
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export declare class ReconnectBudget {
|
|
2
|
+
private elapsed;
|
|
3
|
+
private lastSeen;
|
|
4
|
+
private heartbeat;
|
|
5
|
+
private wokeSinceAttempt;
|
|
6
|
+
private gapGraceUsed;
|
|
7
|
+
private frozen;
|
|
8
|
+
private disposed;
|
|
9
|
+
private readonly waiters;
|
|
10
|
+
private readonly page;
|
|
11
|
+
constructor();
|
|
12
|
+
get elapsedMs(): number;
|
|
13
|
+
noteAttempt(): void;
|
|
14
|
+
exhausted(limitMs: number): boolean;
|
|
15
|
+
waitUntilActive(): Promise<void>;
|
|
16
|
+
dispose(): void;
|
|
17
|
+
private readonly freeze;
|
|
18
|
+
private readonly resume;
|
|
19
|
+
private readonly update;
|
|
20
|
+
private readonly observe;
|
|
21
|
+
private stop;
|
|
22
|
+
private wakeWaiters;
|
|
23
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Recovery gets foreground time to retry. A phone can suspend JavaScript for
|
|
2
|
+
// minutes, so a wall-clock deadline would already be spent when it returns.
|
|
3
|
+
// Not every suspension is announced (a debugger pause, a native app pausing
|
|
4
|
+
// its web view while the document stays visible), so active time accrues in
|
|
5
|
+
// heartbeat steps and a gap longer than one step counts only that step.
|
|
6
|
+
const HEARTBEAT_MS = 1_000;
|
|
7
|
+
const MAX_STEP_MS = 2_000;
|
|
8
|
+
export class ReconnectBudget {
|
|
9
|
+
elapsed = 0;
|
|
10
|
+
lastSeen = null;
|
|
11
|
+
heartbeat = null;
|
|
12
|
+
// Set on every return to the foreground, announced or not; cleared by an attempt.
|
|
13
|
+
wokeSinceAttempt = false;
|
|
14
|
+
// A detected gap earns that try once per outage: a slow phone dropping
|
|
15
|
+
// frames for minutes would otherwise renew it forever.
|
|
16
|
+
gapGraceUsed = false;
|
|
17
|
+
frozen = false;
|
|
18
|
+
disposed = false;
|
|
19
|
+
waiters = new Set();
|
|
20
|
+
page = typeof document === "undefined" ? null : document;
|
|
21
|
+
constructor() {
|
|
22
|
+
this.page?.addEventListener("visibilitychange", this.update);
|
|
23
|
+
this.page?.addEventListener("freeze", this.freeze);
|
|
24
|
+
this.page?.addEventListener("resume", this.resume);
|
|
25
|
+
this.update();
|
|
26
|
+
}
|
|
27
|
+
get elapsedMs() {
|
|
28
|
+
this.observe();
|
|
29
|
+
return this.elapsed;
|
|
30
|
+
}
|
|
31
|
+
noteAttempt() {
|
|
32
|
+
this.wokeSinceAttempt = false;
|
|
33
|
+
}
|
|
34
|
+
// Spent only once an attempt has run since the page last came back, so a
|
|
35
|
+
// stall at the edge of the budget still gets one try with what it holds.
|
|
36
|
+
exhausted(limitMs) {
|
|
37
|
+
return this.elapsedMs >= limitMs && !this.wokeSinceAttempt;
|
|
38
|
+
}
|
|
39
|
+
waitUntilActive() {
|
|
40
|
+
if (this.disposed || this.lastSeen !== null)
|
|
41
|
+
return Promise.resolve();
|
|
42
|
+
return new Promise((resolve) => this.waiters.add(resolve));
|
|
43
|
+
}
|
|
44
|
+
dispose() {
|
|
45
|
+
this.disposed = true;
|
|
46
|
+
this.stop();
|
|
47
|
+
this.page?.removeEventListener("visibilitychange", this.update);
|
|
48
|
+
this.page?.removeEventListener("freeze", this.freeze);
|
|
49
|
+
this.page?.removeEventListener("resume", this.resume);
|
|
50
|
+
this.wakeWaiters();
|
|
51
|
+
}
|
|
52
|
+
freeze = () => {
|
|
53
|
+
this.frozen = true;
|
|
54
|
+
this.update();
|
|
55
|
+
};
|
|
56
|
+
resume = () => {
|
|
57
|
+
this.frozen = false;
|
|
58
|
+
this.update();
|
|
59
|
+
};
|
|
60
|
+
update = () => {
|
|
61
|
+
const active = !this.disposed && !this.frozen && this.page?.visibilityState !== "hidden";
|
|
62
|
+
if (active && this.lastSeen === null) {
|
|
63
|
+
this.lastSeen = Date.now();
|
|
64
|
+
this.heartbeat = setInterval(this.observe, HEARTBEAT_MS);
|
|
65
|
+
this.wokeSinceAttempt = true;
|
|
66
|
+
this.wakeWaiters();
|
|
67
|
+
}
|
|
68
|
+
else if (!active && this.lastSeen !== null) {
|
|
69
|
+
this.stop();
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
observe = () => {
|
|
73
|
+
if (this.lastSeen === null)
|
|
74
|
+
return;
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
const gap = now - this.lastSeen;
|
|
77
|
+
if (gap > MAX_STEP_MS && !this.gapGraceUsed) {
|
|
78
|
+
this.gapGraceUsed = true;
|
|
79
|
+
this.wokeSinceAttempt = true;
|
|
80
|
+
}
|
|
81
|
+
this.elapsed += Math.min(Math.max(gap, 0), MAX_STEP_MS);
|
|
82
|
+
this.lastSeen = now;
|
|
83
|
+
};
|
|
84
|
+
stop() {
|
|
85
|
+
this.observe();
|
|
86
|
+
this.lastSeen = null;
|
|
87
|
+
if (this.heartbeat !== null)
|
|
88
|
+
clearInterval(this.heartbeat);
|
|
89
|
+
this.heartbeat = null;
|
|
90
|
+
}
|
|
91
|
+
wakeWaiters() {
|
|
92
|
+
for (const resolve of this.waiters)
|
|
93
|
+
resolve();
|
|
94
|
+
this.waiters.clear();
|
|
95
|
+
}
|
|
96
|
+
}
|
package/dist/save.d.ts
CHANGED
|
@@ -69,6 +69,12 @@ export interface SaveConditionalCheck extends Omit<SaveCheck, "expectedRevision"
|
|
|
69
69
|
}
|
|
70
70
|
export interface SaveConditionalWriteInput extends Omit<SaveTransactionInput, "checks"> {
|
|
71
71
|
checks?: SaveConditionalCheck[];
|
|
72
|
+
/** Session servers only: atomically fence each affected player's progress reset. */
|
|
73
|
+
resetFences?: SaveResetFence[];
|
|
74
|
+
}
|
|
75
|
+
export interface SaveResetFence {
|
|
76
|
+
playerId: string;
|
|
77
|
+
resetGeneration: number;
|
|
72
78
|
}
|
|
73
79
|
export interface SaveInitial {
|
|
74
80
|
target: SaveTarget;
|
|
@@ -180,6 +186,9 @@ export interface SaveErrorEnvelope {
|
|
|
180
186
|
retryAfterMs?: number;
|
|
181
187
|
target?: SaveTarget;
|
|
182
188
|
current?: SaveSnapshot;
|
|
189
|
+
playerId?: string;
|
|
190
|
+
expectedResetGeneration?: number;
|
|
191
|
+
resetGeneration?: number;
|
|
183
192
|
[detail: string]: unknown;
|
|
184
193
|
}
|
|
185
194
|
export declare class SaveError extends CastleError {
|
|
@@ -190,6 +199,9 @@ export declare class SaveError extends CastleError {
|
|
|
190
199
|
readonly retryAfterMs?: number;
|
|
191
200
|
readonly target?: SaveTarget;
|
|
192
201
|
readonly current?: SaveSnapshot;
|
|
202
|
+
readonly playerId?: string;
|
|
203
|
+
readonly expectedResetGeneration?: number;
|
|
204
|
+
readonly resetGeneration?: number;
|
|
193
205
|
constructor(envelope: SaveErrorEnvelope);
|
|
194
206
|
}
|
|
195
207
|
/**
|
package/dist/save.js
CHANGED
|
@@ -8,6 +8,9 @@ export class SaveError extends CastleError {
|
|
|
8
8
|
retryAfterMs;
|
|
9
9
|
target;
|
|
10
10
|
current;
|
|
11
|
+
playerId;
|
|
12
|
+
expectedResetGeneration;
|
|
13
|
+
resetGeneration;
|
|
11
14
|
constructor(envelope) {
|
|
12
15
|
super({
|
|
13
16
|
code: envelope.code,
|
|
@@ -22,6 +25,9 @@ export class SaveError extends CastleError {
|
|
|
22
25
|
this.retryAfterMs = envelope.retryAfterMs;
|
|
23
26
|
this.target = envelope.target;
|
|
24
27
|
this.current = envelope.current;
|
|
28
|
+
this.playerId = envelope.playerId;
|
|
29
|
+
this.expectedResetGeneration = envelope.expectedResetGeneration;
|
|
30
|
+
this.resetGeneration = envelope.resetGeneration;
|
|
25
31
|
}
|
|
26
32
|
}
|
|
27
33
|
/**
|
|
@@ -272,6 +278,9 @@ function encodeTransaction(input, server, conditional = false) {
|
|
|
272
278
|
return {
|
|
273
279
|
operationId: input.operationId,
|
|
274
280
|
expectedAccess: checkText(input.expectedAccess, "expected access"),
|
|
281
|
+
...(input.resetFences === undefined
|
|
282
|
+
? {}
|
|
283
|
+
: { resetFences: encodeResetFences(input.resetFences, server && conditional) }),
|
|
275
284
|
...(input.checks === undefined
|
|
276
285
|
? {}
|
|
277
286
|
: {
|
|
@@ -280,6 +289,24 @@ function encodeTransaction(input, server, conditional = false) {
|
|
|
280
289
|
changes,
|
|
281
290
|
};
|
|
282
291
|
}
|
|
292
|
+
function encodeResetFences(value, allowed) {
|
|
293
|
+
if (!allowed || !Array.isArray(value) || value.length < 1 || value.length > 2)
|
|
294
|
+
invalid("resetFences requires one or two players on a server conditional write.");
|
|
295
|
+
const seen = new Set();
|
|
296
|
+
return value.map((entry) => {
|
|
297
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry) ||
|
|
298
|
+
Reflect.ownKeys(entry).length !== 2 ||
|
|
299
|
+
!Object.hasOwn(entry, "playerId") || !Object.hasOwn(entry, "resetGeneration"))
|
|
300
|
+
invalid("Invalid reset fence.");
|
|
301
|
+
const fence = entry;
|
|
302
|
+
if (typeof fence.playerId !== "string" || !/^[1-9][0-9]{0,19}$/.test(fence.playerId) ||
|
|
303
|
+
seen.has(fence.playerId) || !Number.isInteger(fence.resetGeneration) ||
|
|
304
|
+
fence.resetGeneration < 0 || fence.resetGeneration > 2147483647)
|
|
305
|
+
invalid("Invalid reset fence player or generation.");
|
|
306
|
+
seen.add(fence.playerId);
|
|
307
|
+
return { playerId: fence.playerId, resetGeneration: fence.resetGeneration };
|
|
308
|
+
});
|
|
309
|
+
}
|
|
283
310
|
/** Validates and copies a request; the result is what goes on the wire. */
|
|
284
311
|
export function encodeSaveInput(verb, input, server = false) {
|
|
285
312
|
if (!input || typeof input !== "object" || Array.isArray(input)) {
|
package/dist/server/hub.d.ts
CHANGED
|
@@ -184,6 +184,13 @@ export interface MultiplayerHubResultsRead {
|
|
|
184
184
|
* and for a deck that declares no hub block.
|
|
185
185
|
*/
|
|
186
186
|
export interface MultiplayerServerHub {
|
|
187
|
+
/** Present only for an enabled place on a capable runtime. Reports visits; Ghost owns comeback delivery. */
|
|
188
|
+
readonly push?: {
|
|
189
|
+
visit(playerId: string, visit: {
|
|
190
|
+
userId: string;
|
|
191
|
+
timezone: string;
|
|
192
|
+
}): Promise<boolean>;
|
|
193
|
+
};
|
|
187
194
|
/** Durably appends NPC words to a private platform archive. No read operation. */
|
|
188
195
|
archiveText(playerId: string, entry: {
|
|
189
196
|
npcId: string;
|
package/dist/server/hub.js
CHANGED
|
@@ -78,11 +78,11 @@ export function createServerHub(platformHandle, arrivals, hiddenPair = () => fal
|
|
|
78
78
|
return parsed;
|
|
79
79
|
};
|
|
80
80
|
const hub = {
|
|
81
|
+
...pushCapability(platformHandle),
|
|
81
82
|
async archiveText(playerId, entry) {
|
|
82
83
|
if (platformHandle.hubTextArchiveEnabled !== true || typeof platformHandle.storage !== "function")
|
|
83
84
|
throw unavailable("archiveText", "archive NPC transcripts");
|
|
84
|
-
|
|
85
|
-
if (JSON.parse(raw)?.recorded !== true)
|
|
85
|
+
if (JSON.parse(await platformHandle.storage("hubTextArchive", JSON.stringify({ ...entry, playerId })))?.recorded !== true)
|
|
86
86
|
throw unavailable("archiveText", "archive NPC transcripts");
|
|
87
87
|
},
|
|
88
88
|
place: typeof pinned.place === "string" ? pinned.place : null,
|
|
@@ -225,3 +225,18 @@ export function createServerHub(platformHandle, arrivals, hiddenPair = () => fal
|
|
|
225
225
|
Object.defineProperty(hub, "archiveText", { enumerable: false });
|
|
226
226
|
return Object.freeze(hub);
|
|
227
227
|
}
|
|
228
|
+
async function pushVisitCall(call, playerId, args) {
|
|
229
|
+
try {
|
|
230
|
+
return JSON.parse(await call(JSON.stringify({ ...args, playerId })))?.accepted === true;
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function pushCapability(handle) {
|
|
237
|
+
if (handle.hub?.push?.version !== 1 || typeof handle.hubPushVisit !== "function")
|
|
238
|
+
return {};
|
|
239
|
+
return { push: {
|
|
240
|
+
visit: (playerId, visit) => pushVisitCall((raw) => handle.hubPushVisit(raw), playerId, visit),
|
|
241
|
+
} };
|
|
242
|
+
}
|
|
@@ -99,6 +99,7 @@ export interface PlatformHandle {
|
|
|
99
99
|
hubResultsRead?(argsJson: string): Promise<string>;
|
|
100
100
|
/** Friends among candidates (hub contract v1.36); older images use storage. */
|
|
101
101
|
hubFriendsAmong?(argsJson: string): Promise<string>;
|
|
102
|
+
hubPushVisit?(argsJson: string): Promise<string>;
|
|
102
103
|
/** Absent on a runtime older than wearables (contract v1.4). */
|
|
103
104
|
hubWear?(argsJson: string): Promise<string>;
|
|
104
105
|
/** Absent on a runtime older than earned items (contract v1.53). */
|
|
@@ -120,6 +121,9 @@ export interface PlatformHubResultShape {
|
|
|
120
121
|
stats: Record<string, "number" | "string">;
|
|
121
122
|
}
|
|
122
123
|
export interface PlatformHubPlace {
|
|
124
|
+
push?: {
|
|
125
|
+
version: 1;
|
|
126
|
+
};
|
|
123
127
|
owner?: string;
|
|
124
128
|
reconnectWindowMs?: number;
|
|
125
129
|
place?: string;
|
package/dist/server/storage.d.ts
CHANGED
|
@@ -267,6 +267,8 @@ export interface ServerCharacterHistoryOptions {
|
|
|
267
267
|
cursor?: string | null;
|
|
268
268
|
}
|
|
269
269
|
export interface ServerStorage extends SaveApi {
|
|
270
|
+
/** Reads the authoritative progress-reset generation, including never-reset zero. */
|
|
271
|
+
resetGeneration(userId: string): Promise<number>;
|
|
270
272
|
/** Shared by everyone playing the deck, and owned by this server. */
|
|
271
273
|
readonly deck: ServerStorageScope;
|
|
272
274
|
/** One player's public data. Readable by anyone; writable by them or by this server. */
|
package/dist/server/storage.js
CHANGED
|
@@ -76,6 +76,14 @@ export function createServerStorage(platformHandle) {
|
|
|
76
76
|
}, true);
|
|
77
77
|
return {
|
|
78
78
|
...saveApi,
|
|
79
|
+
async resetGeneration(userId) {
|
|
80
|
+
const subject = assertUserId(userId, "session.storage.resetGeneration");
|
|
81
|
+
const value = await call("resetGeneration", { subject });
|
|
82
|
+
if (!Number.isInteger(value) || value < 0 || value > MAX_GENERATION) {
|
|
83
|
+
throw storageError("CAULDRON_STORAGE_INVALID_RESPONSE", "The platform returned an invalid progress reset generation.", "session.storage.resetGeneration");
|
|
84
|
+
}
|
|
85
|
+
return value;
|
|
86
|
+
},
|
|
79
87
|
deck: createScope(call, "DECK", null, saveApi),
|
|
80
88
|
user(userId) {
|
|
81
89
|
// A bad id poisons the scope rather than throwing here, so the failure arrives
|
package/dist/server/wrapper.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export type { MultiplayerSessionMode, PlatformHandle, PlatformSessionConfig, Pla
|
|
|
7
7
|
export { createSaveCoordinator } from "../saveCoordinator";
|
|
8
8
|
export type { CoordinatedChange, CoordinatedSave, SaveCoordinator, SaveStatus, } from "../saveCoordinator";
|
|
9
9
|
export { SaveError } from "../save";
|
|
10
|
-
export type { SaveApi, SaveBucketApi, SaveBucketRead, SaveChange, SaveCheck, SaveConditionalCheck, SaveConditionalWriteInput, SaveClaimed, SaveClaimInput, SaveErrorEnvelope, SaveInitial, SaveInitializeInput, SaveOpened, SaveOperation, SaveReadTarget, SaveReceipt, SaveRecentOperationsInput, SaveRecentOperationsPage, SaveRevision, SaveRows, SaveScope, SaveSelection, SaveSnapshot, SaveTarget, SaveTransactionInput, SaveWriter, } from "../save";
|
|
10
|
+
export type { SaveApi, SaveBucketApi, SaveBucketRead, SaveChange, SaveCheck, SaveConditionalCheck, SaveConditionalWriteInput, SaveResetFence, SaveClaimed, SaveClaimInput, SaveErrorEnvelope, SaveInitial, SaveInitializeInput, SaveOpened, SaveOperation, SaveReadTarget, SaveReceipt, SaveRecentOperationsInput, SaveRecentOperationsPage, SaveRevision, SaveRows, SaveScope, SaveSelection, SaveSnapshot, SaveTarget, SaveTransactionInput, SaveWriter, } from "../save";
|
|
11
11
|
export type { MultiplayerHubArrival, MultiplayerHubBoard, MultiplayerHubOutcome, MultiplayerHubPadUpdateInput, MultiplayerHubPadUpdateResult, MultiplayerHubPlayerResults, MultiplayerHubRecord, MultiplayerHubReportReceipt, MultiplayerHubResultInput, MultiplayerHubResultRow, MultiplayerHubResultShape, MultiplayerHubResultsRead, MultiplayerHubResultsReadInput, MultiplayerHubWearable, MultiplayerHubWearReceipt, MultiplayerHubEarnedClass, MultiplayerHubEarnedItem, MultiplayerHubHomeClass, MultiplayerHubHomeItem, MultiplayerHubUnlockReceipt, MultiplayerHubUnlocksRead, MultiplayerHubWearEarnedReceipt, MultiplayerServerHub, } from "./hub";
|
|
12
12
|
export type { CharacterActionNotice, CharacterGameStateOperation, CharacterGameStateResult, CharacterKnowledgeDeliveryOperation, CharacterKnowledgeDeliveryResult, CharacterKnowledgeSource, CompleteCharacterBeatInput, DeliverCharacterKnowledgeInput, RecordCharacterEventInput, SetCharacterGameStateInput, ShareCharacterClaimInput, ServerStorage, ServerStorageBoard, ServerStorageBoardScore, ServerStorageListEntry, ServerStorageListOptions, ServerStorageListPage, ServerPlaythrough, ServerPlaythroughCharacters, ServerCharacterHistoryOptions, ServerStorageScope, ServerTownStorage, } from "./storage";
|
|
13
13
|
export interface MultiplayerServerPlayer extends PlayerIdentity {
|