castle-web-sdk 0.4.47 → 0.4.49
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 +260 -3
- package/dist/castle.d.ts +7 -3
- package/dist/castle.js +2 -0
- package/dist/commands.d.ts +162 -1
- package/dist/commands.js +3 -0
- package/dist/display.d.ts +3 -0
- package/dist/display.js +9 -3
- package/dist/hub.d.ts +33 -6
- package/dist/hub.js +50 -4
- package/dist/multiplayer.d.ts +7 -1
- package/dist/multiplayer.js +140 -40
- package/dist/multiplayerProtocol.d.ts +2 -0
- package/dist/party.d.ts +23 -0
- package/dist/party.js +91 -0
- package/dist/reconnectBudget.d.ts +23 -0
- package/dist/reconnectBudget.js +96 -0
- package/dist/save.d.ts +38 -1
- package/dist/save.js +79 -6
- package/dist/server/hub.d.ts +31 -1
- package/dist/server/hub.js +50 -3
- package/dist/server/platformHandle.d.ts +13 -1
- package/dist/server/storage.d.ts +4 -0
- package/dist/server/storage.js +19 -3
- package/dist/server/wrapper.d.ts +7 -1
- package/dist/server/wrapper.js +10 -1
- package/dist/social.d.ts +9 -0
- package/dist/social.js +5 -0
- package/package.json +1 -1
package/dist/display.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
//
|
|
6
6
|
// <meta name="castle-display" content="layout=fill">
|
|
7
7
|
// <meta name="castle-display" content="layout=fill, min-aspect=9/16, max-aspect=16/9">
|
|
8
|
+
// <meta name="castle-display" content="layout=fill, orientation=landscape">
|
|
8
9
|
//
|
|
9
10
|
// With no tag the deck is a `card`: the classic 5:7 portrait card, exactly as
|
|
10
11
|
// before. A `fill` deck takes whatever box the host gives it, as long as the
|
|
@@ -42,13 +43,18 @@ export function parseDisplayContent(content) {
|
|
|
42
43
|
continue;
|
|
43
44
|
fields[part.slice(0, eq).trim().toLowerCase()] = part.slice(eq + 1).trim();
|
|
44
45
|
}
|
|
45
|
-
|
|
46
|
-
|
|
46
|
+
const declaredOrientation = fields.orientation?.toLowerCase();
|
|
47
|
+
const orientation = declaredOrientation === "landscape" || declaredOrientation === "portrait"
|
|
48
|
+
? declaredOrientation
|
|
49
|
+
: "any";
|
|
50
|
+
if (fields.layout?.toLowerCase() !== "fill") {
|
|
51
|
+
return orientation === "any" ? CARD_DISPLAY : { ...CARD_DISPLAY, orientation };
|
|
52
|
+
}
|
|
47
53
|
let minAspect = parseAspect(fields["min-aspect"] ?? "") ?? FILL_MIN_ASPECT;
|
|
48
54
|
let maxAspect = parseAspect(fields["max-aspect"] ?? "") ?? FILL_MAX_ASPECT;
|
|
49
55
|
if (minAspect > maxAspect)
|
|
50
56
|
[minAspect, maxAspect] = [maxAspect, minAspect];
|
|
51
|
-
return { layout: "fill", minAspect, maxAspect };
|
|
57
|
+
return { layout: "fill", orientation, minAspect, maxAspect };
|
|
52
58
|
}
|
|
53
59
|
let cached = null;
|
|
54
60
|
/** The display this deck declared in its index.html (a card when it declared none). */
|
package/dist/hub.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { HubBackResult, HubCancelResult, HubChatResult, HubDoorsResult, HubFriendsResult, HubHeartsResult, HubGoResult, HubJumpResult, HubReportResult, HubSayResult } from "./commands";
|
|
2
|
-
export type { HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubHeartsResult, HubGoParams, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, } 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,29 @@ export interface CastleHubApi {
|
|
|
35
39
|
* on hosts without hub support.
|
|
36
40
|
*/
|
|
37
41
|
friends(): Promise<HubFriendsResult>;
|
|
42
|
+
/** Create an expiring link from this hub session. Links admit up to five invitees by default. */
|
|
43
|
+
invite(options?: {
|
|
44
|
+
crew?: boolean;
|
|
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>;
|
|
53
|
+
/** Hub-kit arrival hook: the trusted host retains the invite token. */
|
|
54
|
+
inviteArrival(): Promise<HubInviteArrivalResult>;
|
|
55
|
+
/** Undo both follow directions for one pair from this host's invite arrival. */
|
|
56
|
+
undoInvite(userId: string): Promise<HubReportResult>;
|
|
38
57
|
/** Read this signed-in account's hub door hearts. */
|
|
39
58
|
hearts(): Promise<HubHeartsResult>;
|
|
40
59
|
/** Replace the hearts, oldest first, at most eight distinct door ids. */
|
|
41
60
|
setHearts(doorIds: string[]): Promise<HubHeartsResult>;
|
|
61
|
+
/** Ask the host to let an anonymous player sign in to a permanent account. */
|
|
62
|
+
signIn(options: {
|
|
63
|
+
reason: string;
|
|
64
|
+
}): Promise<HubSignInResult>;
|
|
42
65
|
/**
|
|
43
66
|
* Acquire the layer of this place a friend is in. The destination is this
|
|
44
67
|
* same place in another session; join it exactly like a door's
|
|
@@ -70,10 +93,14 @@ export interface CastleHubApi {
|
|
|
70
93
|
say(text: string): Promise<HubSayResult>;
|
|
71
94
|
/**
|
|
72
95
|
* Report a chat message this player was returned to Castle's moderators, by
|
|
73
|
-
* 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.
|
|
74
99
|
* `unavailable` on hosts without hub support or outside a hub session.
|
|
75
100
|
*/
|
|
76
|
-
reportChat(messageId: string
|
|
101
|
+
reportChat(messageId: string, options?: {
|
|
102
|
+
block?: boolean;
|
|
103
|
+
}): Promise<HubReportResult>;
|
|
77
104
|
/**
|
|
78
105
|
* Abandon an acquisition the deck will not join (its content failed to load,
|
|
79
106
|
* the player walked away). Optional: an unjoined one expires on its own.
|
package/dist/hub.js
CHANGED
|
@@ -5,8 +5,13 @@ export const Hub = {
|
|
|
5
5
|
back,
|
|
6
6
|
doors,
|
|
7
7
|
friends,
|
|
8
|
+
invite,
|
|
9
|
+
canInvite,
|
|
10
|
+
inviteArrival,
|
|
11
|
+
undoInvite,
|
|
8
12
|
hearts,
|
|
9
13
|
setHearts,
|
|
14
|
+
signIn,
|
|
10
15
|
jump,
|
|
11
16
|
report,
|
|
12
17
|
chat,
|
|
@@ -15,7 +20,7 @@ export const Hub = {
|
|
|
15
20
|
cancel,
|
|
16
21
|
onBack,
|
|
17
22
|
};
|
|
18
|
-
async function go(doorId) {
|
|
23
|
+
async function go(doorId, options = {}) {
|
|
19
24
|
if (typeof doorId !== "string" || doorId.length === 0) {
|
|
20
25
|
throw new CastleError({
|
|
21
26
|
code: "INVALID_ARGUMENT",
|
|
@@ -23,7 +28,15 @@ async function go(doorId) {
|
|
|
23
28
|
operation: "Hub.go",
|
|
24
29
|
});
|
|
25
30
|
}
|
|
26
|
-
|
|
31
|
+
const ownerUserId = options?.ownerUserId;
|
|
32
|
+
if (ownerUserId !== undefined && (typeof ownerUserId !== "string" || !/^[1-9]\d{0,9}$/.test(ownerUserId))) {
|
|
33
|
+
throw new CastleError({
|
|
34
|
+
code: "INVALID_ARGUMENT",
|
|
35
|
+
message: "Hub.go ownerUserId must be a user id.",
|
|
36
|
+
operation: "Hub.go",
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return hostRequest("hub.go", ownerUserId === undefined ? { doorId } : { doorId, ownerUserId });
|
|
27
40
|
}
|
|
28
41
|
async function back() {
|
|
29
42
|
return hostRequest("hub.back", {});
|
|
@@ -34,6 +47,22 @@ async function doors() {
|
|
|
34
47
|
async function friends() {
|
|
35
48
|
return hostRequest("hub.friends", {});
|
|
36
49
|
}
|
|
50
|
+
async function invite(options = {}) {
|
|
51
|
+
if (options.crew !== undefined && typeof options.crew !== "boolean")
|
|
52
|
+
throw new CastleError({ code: "INVALID_ARGUMENT", message: "Hub.invite crew must be a boolean.", operation: "Hub.invite" });
|
|
53
|
+
return hostRequest("hub.invite", options.crew !== false ? { crew: true } : {});
|
|
54
|
+
}
|
|
55
|
+
async function canInvite() {
|
|
56
|
+
return hostRequest("hub.canInvite", {});
|
|
57
|
+
}
|
|
58
|
+
async function inviteArrival() {
|
|
59
|
+
return hostRequest("hub.inviteArrival", {});
|
|
60
|
+
}
|
|
61
|
+
async function undoInvite(userId) {
|
|
62
|
+
if (!/^[1-9]\d{0,9}$/.test(userId))
|
|
63
|
+
throw new CastleError({ code: "INVALID_ARGUMENT", message: "Hub.undoInvite requires a userId.", operation: "Hub.undoInvite" });
|
|
64
|
+
return hostRequest("hub.undoInvite", { userId });
|
|
65
|
+
}
|
|
37
66
|
async function hearts() {
|
|
38
67
|
return hostRequest("hub.hearts", {});
|
|
39
68
|
}
|
|
@@ -45,6 +74,23 @@ async function setHearts(doorIds) {
|
|
|
45
74
|
}
|
|
46
75
|
return hostRequest("hub.setHearts", { doorIds });
|
|
47
76
|
}
|
|
77
|
+
const SIGN_IN_REASON_MAX_CHARACTERS = 200;
|
|
78
|
+
const SIGN_IN_REASON_MAX_BYTES = 512;
|
|
79
|
+
async function signIn(options) {
|
|
80
|
+
const reason = options?.reason;
|
|
81
|
+
if (typeof reason !== "string" ||
|
|
82
|
+
reason.length === 0 ||
|
|
83
|
+
reason.length > SIGN_IN_REASON_MAX_CHARACTERS ||
|
|
84
|
+
reason.includes("\0") ||
|
|
85
|
+
new TextEncoder().encode(reason).byteLength > SIGN_IN_REASON_MAX_BYTES) {
|
|
86
|
+
throw new CastleError({
|
|
87
|
+
code: "INVALID_ARGUMENT",
|
|
88
|
+
message: `Hub.signIn requires reason of at most ${SIGN_IN_REASON_MAX_CHARACTERS} characters and ${SIGN_IN_REASON_MAX_BYTES} bytes.`,
|
|
89
|
+
operation: "Hub.signIn",
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return hostRequest("hub.signIn", { reason });
|
|
93
|
+
}
|
|
48
94
|
async function jump(userId) {
|
|
49
95
|
if (typeof userId !== "string" || userId.length === 0) {
|
|
50
96
|
throw new CastleError({
|
|
@@ -78,7 +124,7 @@ async function say(text) {
|
|
|
78
124
|
}
|
|
79
125
|
return hostRequest("hub.say", { text });
|
|
80
126
|
}
|
|
81
|
-
async function reportChat(messageId) {
|
|
127
|
+
async function reportChat(messageId, options) {
|
|
82
128
|
if (typeof messageId !== "string" || messageId.length === 0) {
|
|
83
129
|
throw new CastleError({
|
|
84
130
|
code: "INVALID_ARGUMENT",
|
|
@@ -86,7 +132,7 @@ async function reportChat(messageId) {
|
|
|
86
132
|
operation: "Hub.reportChat",
|
|
87
133
|
});
|
|
88
134
|
}
|
|
89
|
-
return hostRequest("hub.reportChat", { messageId });
|
|
135
|
+
return hostRequest("hub.reportChat", { messageId, ...(options?.block === true ? { block: true } : {}) });
|
|
90
136
|
}
|
|
91
137
|
async function cancel() {
|
|
92
138
|
return hostRequest("hub.cancel", {});
|
package/dist/multiplayer.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { Json } from "./types";
|
|
|
4
4
|
import { type MultiplayerPlayer, type MultiplayerCharacterDisclosure, type MultiplayerCharacterTurnStatus } from "./multiplayerProtocol";
|
|
5
5
|
import { type MultiplayerVoice } from "./multiplayerVoice";
|
|
6
6
|
export type { MultiplayerJoinHint } from "./commands";
|
|
7
|
-
export type MultiplayerJoinOptions = {
|
|
7
|
+
export type MultiplayerJoinOptions = ({
|
|
8
8
|
mode: "named";
|
|
9
9
|
key: string;
|
|
10
10
|
} | {
|
|
@@ -14,6 +14,9 @@ export type MultiplayerJoinOptions = {
|
|
|
14
14
|
} | {
|
|
15
15
|
mode: "hub";
|
|
16
16
|
handoff: HubHandoffResult;
|
|
17
|
+
}) & {
|
|
18
|
+
/** Experimental opt-in: reconnect if a keepalive ping receives no pong. */
|
|
19
|
+
pongTimeoutMs?: number;
|
|
17
20
|
};
|
|
18
21
|
export interface MultiplayerDestinationOptions {
|
|
19
22
|
routeId: string;
|
|
@@ -184,6 +187,9 @@ export interface MultiplayerConnection {
|
|
|
184
187
|
readonly state: MultiplayerConnectionState;
|
|
185
188
|
readonly playerId: string;
|
|
186
189
|
readonly sessionId: string;
|
|
190
|
+
/** Current host publication diagnostics; null when unavailable or not connected. */
|
|
191
|
+
readonly serverBundleSha256: string | null;
|
|
192
|
+
readonly serverBundleId: string | null;
|
|
187
193
|
readonly isSolo: boolean;
|
|
188
194
|
/**
|
|
189
195
|
* Why the join fell back to solo; null while multiplayer is live.
|
package/dist/multiplayer.js
CHANGED
|
@@ -2,6 +2,7 @@ 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";
|
|
5
6
|
const KEEPALIVE_INTERVAL_MS = 25_000;
|
|
6
7
|
const HELLO_TIMEOUT_MS = 10_000;
|
|
7
8
|
const RECONNECT_BUDGET_MS = 30_000;
|
|
@@ -46,13 +47,17 @@ async function join(options) {
|
|
|
46
47
|
const request = hub
|
|
47
48
|
? { command: "hub", nonce: hub.nonce }
|
|
48
49
|
: { command: "multiplayer.getSession", params: joinParams(options) };
|
|
50
|
+
const pongTimeoutMs = options.pongTimeoutMs ?? 0;
|
|
51
|
+
if (!Number.isFinite(pongTimeoutMs) || pongTimeoutMs < 0 || pongTimeoutMs > 2_147_483_647) {
|
|
52
|
+
throw new RangeError("pongTimeoutMs must be between 0 and 2147483647 milliseconds");
|
|
53
|
+
}
|
|
49
54
|
latestJoinAttempt += 1;
|
|
50
55
|
cancelPendingDestinationJoin();
|
|
51
56
|
activeConnection?.leave();
|
|
52
57
|
const connection = new MultiplayerConnectionImpl(request, () => {
|
|
53
58
|
if (activeConnection === connection)
|
|
54
59
|
activeConnection = null;
|
|
55
|
-
});
|
|
60
|
+
}, null, pongTimeoutMs);
|
|
56
61
|
activeConnection = connection;
|
|
57
62
|
await connection.start(hub ?? undefined);
|
|
58
63
|
// The host moves its place (and every place-scoped command with it) when the
|
|
@@ -183,9 +188,12 @@ class MultiplayerConnectionImpl {
|
|
|
183
188
|
request;
|
|
184
189
|
onClosed;
|
|
185
190
|
destinationAudience;
|
|
191
|
+
pongTimeoutMs;
|
|
186
192
|
currentState = "acquiring";
|
|
187
193
|
currentPlayerId = "";
|
|
188
194
|
currentSessionId = "";
|
|
195
|
+
currentServerBundleSha256 = null;
|
|
196
|
+
currentServerBundleId = null;
|
|
189
197
|
solo = false;
|
|
190
198
|
currentSoloReason = null;
|
|
191
199
|
baseUrl = "";
|
|
@@ -194,8 +202,11 @@ class MultiplayerConnectionImpl {
|
|
|
194
202
|
socket = null;
|
|
195
203
|
socketAttempt = 0;
|
|
196
204
|
keepalive = null;
|
|
205
|
+
pongExtensionUsed = false;
|
|
206
|
+
pongDeadline = null;
|
|
197
207
|
reAcquisitionUsed = false;
|
|
198
208
|
recovering = false;
|
|
209
|
+
reconnectBudget = null;
|
|
199
210
|
hubSettled = false;
|
|
200
211
|
hubCommit = Promise.resolve(true);
|
|
201
212
|
roster = null;
|
|
@@ -219,10 +230,11 @@ class MultiplayerConnectionImpl {
|
|
|
219
230
|
players: () => this.roster?.players ?? [],
|
|
220
231
|
isSolo: () => this.solo,
|
|
221
232
|
});
|
|
222
|
-
constructor(request, onClosed, destinationAudience = null) {
|
|
233
|
+
constructor(request, onClosed, destinationAudience = null, pongTimeoutMs = 0) {
|
|
223
234
|
this.request = request;
|
|
224
235
|
this.onClosed = onClosed;
|
|
225
236
|
this.destinationAudience = destinationAudience;
|
|
237
|
+
this.pongTimeoutMs = pongTimeoutMs;
|
|
226
238
|
}
|
|
227
239
|
get state() {
|
|
228
240
|
return this.currentState;
|
|
@@ -233,6 +245,12 @@ class MultiplayerConnectionImpl {
|
|
|
233
245
|
get sessionId() {
|
|
234
246
|
return this.currentSessionId;
|
|
235
247
|
}
|
|
248
|
+
get serverBundleSha256() {
|
|
249
|
+
return this.currentState === "connected" && !this.solo ? this.currentServerBundleSha256 : null;
|
|
250
|
+
}
|
|
251
|
+
get serverBundleId() {
|
|
252
|
+
return this.currentState === "connected" && !this.solo ? this.currentServerBundleId : null;
|
|
253
|
+
}
|
|
236
254
|
get isSolo() {
|
|
237
255
|
return this.solo;
|
|
238
256
|
}
|
|
@@ -441,28 +459,39 @@ class MultiplayerConnectionImpl {
|
|
|
441
459
|
await this.openSocket("nonce", result.nonce);
|
|
442
460
|
}
|
|
443
461
|
async restoreDevReconnect(token) {
|
|
444
|
-
|
|
462
|
+
this.assertOpen();
|
|
463
|
+
const budget = this.reconnectBudget = new ReconnectBudget();
|
|
445
464
|
let attempt = 0;
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
465
|
+
try {
|
|
466
|
+
while (true) {
|
|
467
|
+
await budget.waitUntilActive();
|
|
468
|
+
this.assertOpen();
|
|
469
|
+
try {
|
|
470
|
+
budget.noteAttempt();
|
|
471
|
+
await this.openSocket("reconnect", token);
|
|
472
|
+
return true;
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
await budget.waitUntilActive();
|
|
476
|
+
this.assertOpen();
|
|
477
|
+
if (error instanceof SocketClosedError &&
|
|
478
|
+
error.code === INVALID_DEV_RECONNECT_CLOSE_CODE) {
|
|
479
|
+
clearDevReconnectToken(this.devReconnectStorageKey, token);
|
|
480
|
+
return false;
|
|
481
|
+
}
|
|
482
|
+
// A 503 during a server rebuild, network failure, or hello timeout
|
|
483
|
+
// does not prove the credential expired. Retain it if retries run out.
|
|
484
|
+
if (budget.exhausted(RECONNECT_BUDGET_MS))
|
|
485
|
+
throw error;
|
|
486
|
+
const delay = RECONNECT_DELAYS_MS[Math.min(attempt++, RECONNECT_DELAYS_MS.length - 1)];
|
|
487
|
+
await pause(delay);
|
|
457
488
|
}
|
|
458
|
-
// A 503 during a server rebuild, network failure, or hello timeout
|
|
459
|
-
// does not prove the credential expired. Retain it if retries run out.
|
|
460
|
-
if (Date.now() - startedAt >= RECONNECT_BUDGET_MS)
|
|
461
|
-
throw error;
|
|
462
|
-
const delay = RECONNECT_DELAYS_MS[Math.min(attempt++, RECONNECT_DELAYS_MS.length - 1)];
|
|
463
|
-
await pause(delay);
|
|
464
489
|
}
|
|
465
490
|
}
|
|
491
|
+
finally {
|
|
492
|
+
budget.dispose();
|
|
493
|
+
this.reconnectBudget = null;
|
|
494
|
+
}
|
|
466
495
|
}
|
|
467
496
|
connectSolo(result) {
|
|
468
497
|
this.solo = true;
|
|
@@ -553,6 +582,10 @@ class MultiplayerConnectionImpl {
|
|
|
553
582
|
acceptHello(frame) {
|
|
554
583
|
this.currentPlayerId = frame.playerId;
|
|
555
584
|
this.currentSessionId = frame.sessionId;
|
|
585
|
+
// Diagnostics never decide whether a hello is accepted. Missing or malformed
|
|
586
|
+
// metadata clears the previous host's identity on every reconnect.
|
|
587
|
+
this.currentServerBundleSha256 = typeof frame.serverBundleSha256 === "string" && /^[0-9a-f]{64}$/.test(frame.serverBundleSha256) ? frame.serverBundleSha256 : null;
|
|
588
|
+
this.currentServerBundleId = typeof frame.serverBundleId === "string" && /^[A-Za-z0-9_-]{10}$/.test(frame.serverBundleId) ? frame.serverBundleId : null;
|
|
556
589
|
this.reconnectToken = frame.reconnectToken;
|
|
557
590
|
this.sharedCharactersSupported = frame.capabilities?.sharedCharactersV1 === true;
|
|
558
591
|
if (this.devReconnectStorageKey)
|
|
@@ -587,6 +620,8 @@ class MultiplayerConnectionImpl {
|
|
|
587
620
|
this.acceptHello(frame);
|
|
588
621
|
break;
|
|
589
622
|
case "pong":
|
|
623
|
+
this.pongExtensionUsed = false;
|
|
624
|
+
this.clearPongDeadline();
|
|
590
625
|
break;
|
|
591
626
|
}
|
|
592
627
|
}
|
|
@@ -628,31 +663,48 @@ class MultiplayerConnectionImpl {
|
|
|
628
663
|
});
|
|
629
664
|
}
|
|
630
665
|
async recover() {
|
|
631
|
-
|
|
666
|
+
this.assertOpen();
|
|
667
|
+
const budget = this.reconnectBudget = new ReconnectBudget();
|
|
632
668
|
let attempt = 0;
|
|
633
669
|
let sessionEndedCloses = 0;
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
return;
|
|
642
|
-
}
|
|
643
|
-
catch (error) {
|
|
644
|
-
const code = error instanceof SocketClosedError ? error.code : null;
|
|
645
|
-
if (code === 1008 || code === PROXY_CREDENTIAL_REJECTED_CLOSE_CODE)
|
|
646
|
-
break;
|
|
647
|
-
// Retrying a session that is gone only spends the budget; ask for a fresh join.
|
|
648
|
-
// Any other failure in between means the two refusals were not in a row.
|
|
649
|
-
sessionEndedCloses = code === PROXY_SESSION_ENDED_CLOSE_CODE
|
|
650
|
-
? sessionEndedCloses + 1
|
|
651
|
-
: 0;
|
|
652
|
-
if (sessionEndedCloses >= SESSION_ENDED_CONFIRMATIONS)
|
|
670
|
+
try {
|
|
671
|
+
while (true) {
|
|
672
|
+
await budget.waitUntilActive();
|
|
673
|
+
this.assertOpen();
|
|
674
|
+
// A stall that spends the budget still leaves one try with the token,
|
|
675
|
+
// which keeps the player's identity while the host holds its lineage.
|
|
676
|
+
if (budget.exhausted(RECONNECT_BUDGET_MS))
|
|
653
677
|
break;
|
|
678
|
+
const delay = RECONNECT_DELAYS_MS[Math.min(attempt, RECONNECT_DELAYS_MS.length - 1)];
|
|
679
|
+
attempt += 1;
|
|
680
|
+
await pause(delay);
|
|
681
|
+
await budget.waitUntilActive();
|
|
682
|
+
this.assertOpen();
|
|
683
|
+
try {
|
|
684
|
+
budget.noteAttempt();
|
|
685
|
+
await this.openSocket("reconnect", this.reconnectToken);
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
catch (error) {
|
|
689
|
+
await budget.waitUntilActive();
|
|
690
|
+
this.assertOpen();
|
|
691
|
+
const code = error instanceof SocketClosedError ? error.code : null;
|
|
692
|
+
if (code === 1008 || code === PROXY_CREDENTIAL_REJECTED_CLOSE_CODE)
|
|
693
|
+
break;
|
|
694
|
+
// Retrying a session that is gone only spends the budget; ask for a fresh join.
|
|
695
|
+
// Any other failure in between means the two refusals were not in a row.
|
|
696
|
+
sessionEndedCloses = code === PROXY_SESSION_ENDED_CLOSE_CODE
|
|
697
|
+
? sessionEndedCloses + 1
|
|
698
|
+
: 0;
|
|
699
|
+
if (sessionEndedCloses >= SESSION_ENDED_CONFIRMATIONS)
|
|
700
|
+
break;
|
|
701
|
+
}
|
|
654
702
|
}
|
|
655
703
|
}
|
|
704
|
+
finally {
|
|
705
|
+
budget.dispose();
|
|
706
|
+
this.reconnectBudget = null;
|
|
707
|
+
}
|
|
656
708
|
await this.reacquireOnce();
|
|
657
709
|
}
|
|
658
710
|
async reacquireOnce() {
|
|
@@ -676,10 +728,14 @@ class MultiplayerConnectionImpl {
|
|
|
676
728
|
}
|
|
677
729
|
startKeepalive() {
|
|
678
730
|
this.stopKeepalive();
|
|
731
|
+
this.pongExtensionUsed = false;
|
|
679
732
|
this.keepalive = setInterval(() => {
|
|
680
733
|
if (this.socket?.readyState === WebSocket.OPEN) {
|
|
734
|
+
if (this.pongDeadline !== null)
|
|
735
|
+
return;
|
|
681
736
|
try {
|
|
682
737
|
this.socket.send('{"t":"ping"}');
|
|
738
|
+
this.expectPong(this.socket);
|
|
683
739
|
}
|
|
684
740
|
catch {
|
|
685
741
|
closeSocket(this.socket, 1000, "keepalive failed");
|
|
@@ -688,11 +744,46 @@ class MultiplayerConnectionImpl {
|
|
|
688
744
|
}, KEEPALIVE_INTERVAL_MS);
|
|
689
745
|
}
|
|
690
746
|
stopKeepalive() {
|
|
747
|
+
this.clearPongDeadline();
|
|
691
748
|
if (this.keepalive === null)
|
|
692
749
|
return;
|
|
693
750
|
clearInterval(this.keepalive);
|
|
694
751
|
this.keepalive = null;
|
|
695
752
|
}
|
|
753
|
+
clearPongDeadline() {
|
|
754
|
+
if (this.pongDeadline === null)
|
|
755
|
+
return;
|
|
756
|
+
clearTimeout(this.pongDeadline);
|
|
757
|
+
this.pongDeadline = null;
|
|
758
|
+
}
|
|
759
|
+
expectPong(socket) {
|
|
760
|
+
if (!this.pongTimeoutMs)
|
|
761
|
+
return;
|
|
762
|
+
const due = Date.now() + this.pongTimeoutMs;
|
|
763
|
+
this.pongDeadline = setTimeout(() => {
|
|
764
|
+
this.pongDeadline = null;
|
|
765
|
+
if (this.socket !== socket || this.currentState !== "connected")
|
|
766
|
+
return;
|
|
767
|
+
// A suspended page can run an overdue timer before queued socket events.
|
|
768
|
+
// Verify liveness with a fresh ping instead of condemning that socket.
|
|
769
|
+
if (!this.pongExtensionUsed && Date.now() - due > 1_000 && socket.readyState === WebSocket.OPEN) {
|
|
770
|
+
this.pongExtensionUsed = true;
|
|
771
|
+
try {
|
|
772
|
+
socket.send('{"t":"ping"}');
|
|
773
|
+
this.expectPong(socket);
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
catch { /* Fall through to recovery if the fresh probe cannot send. */ }
|
|
777
|
+
}
|
|
778
|
+
// A half-open transport may never emit close. Fence its queued callbacks
|
|
779
|
+
// and enter recovery directly rather than waiting for that close event.
|
|
780
|
+
this.socketAttempt += 1;
|
|
781
|
+
this.socket = null;
|
|
782
|
+
this.stopKeepalive();
|
|
783
|
+
closeSocket(socket, 1000, "pong timeout");
|
|
784
|
+
this.beginRecovery();
|
|
785
|
+
}, this.pongTimeoutMs);
|
|
786
|
+
}
|
|
696
787
|
transition(state, metadata) {
|
|
697
788
|
if (this.currentState === "closed" || this.currentState === state)
|
|
698
789
|
return;
|
|
@@ -710,6 +801,7 @@ class MultiplayerConnectionImpl {
|
|
|
710
801
|
(metadata.type === "left" || metadata.type === "bye" || metadata.type === "replaced"))
|
|
711
802
|
clearDevReconnectToken(this.devReconnectStorageKey, this.reconnectToken);
|
|
712
803
|
this.stopKeepalive();
|
|
804
|
+
this.reconnectBudget?.dispose();
|
|
713
805
|
this.rejectPendingCharacterRequests("MULTIPLAYER_CONNECTION_CLOSED", "The multiplayer connection closed before the shared character request completed.");
|
|
714
806
|
const socket = this.socket;
|
|
715
807
|
this.socket = null;
|
|
@@ -1227,5 +1319,13 @@ function multiplayerError(code, message, operation = "Multiplayer.join") {
|
|
|
1227
1319
|
function asCastleError(error) {
|
|
1228
1320
|
if (error instanceof CastleError)
|
|
1229
1321
|
return error;
|
|
1322
|
+
if (error instanceof SocketClosedError) {
|
|
1323
|
+
return new CastleError({
|
|
1324
|
+
code: "MULTIPLAYER_CONNECTION_FAILED",
|
|
1325
|
+
message: error.message,
|
|
1326
|
+
operation: "Multiplayer.join",
|
|
1327
|
+
extensions: { closeCode: error.code },
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1230
1330
|
return multiplayerError("MULTIPLAYER_CONNECTION_FAILED", error instanceof Error ? error.message : "The multiplayer connection failed.");
|
|
1231
1331
|
}
|
package/dist/party.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { PartyMember, PartyMessage, PartyMessagesResult, PartySummary } from './commands';
|
|
2
|
+
export type { PartyMember, PartyMessage, PartyMessagesResult, PartyStatus, PartySummary, } from './commands';
|
|
3
|
+
export interface CastlePartyApi {
|
|
4
|
+
/** The party this play was launched with, or null when it has none. */
|
|
5
|
+
current(): Promise<PartySummary | null>;
|
|
6
|
+
/** Create a party containing these users and the signed-in player. */
|
|
7
|
+
create(userIds: string[]): Promise<PartySummary>;
|
|
8
|
+
invite(partyId: string, userIds: string[]): Promise<{
|
|
9
|
+
ok: true;
|
|
10
|
+
}>;
|
|
11
|
+
respond(partyId: string, accept: boolean): Promise<{
|
|
12
|
+
ok: true;
|
|
13
|
+
}>;
|
|
14
|
+
members(partyId: string): Promise<PartyMember[]>;
|
|
15
|
+
leave(partyId: string): Promise<{
|
|
16
|
+
ok: true;
|
|
17
|
+
}>;
|
|
18
|
+
/** Newest first. Pass `cursor` to load older history. */
|
|
19
|
+
messages(partyId: string, cursor?: string): Promise<PartyMessagesResult>;
|
|
20
|
+
/** Send plain text; the host trims it to Castle's 1,000-character limit. */
|
|
21
|
+
say(partyId: string, text: string): Promise<PartyMessage>;
|
|
22
|
+
}
|
|
23
|
+
export declare const Party: CastlePartyApi;
|
package/dist/party.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { CastleError } from './errors';
|
|
2
|
+
import { hostRequest } from './transport';
|
|
3
|
+
export const Party = {
|
|
4
|
+
current,
|
|
5
|
+
create,
|
|
6
|
+
invite,
|
|
7
|
+
respond,
|
|
8
|
+
members,
|
|
9
|
+
leave,
|
|
10
|
+
messages,
|
|
11
|
+
say,
|
|
12
|
+
};
|
|
13
|
+
const ID_MAX = 128;
|
|
14
|
+
const CURSOR_MAX = 512;
|
|
15
|
+
const PARTY_USERS_MAX = 32;
|
|
16
|
+
function id(value, field, operation) {
|
|
17
|
+
return boundedText(value, field, operation, ID_MAX);
|
|
18
|
+
}
|
|
19
|
+
function boundedText(value, field, operation, max) {
|
|
20
|
+
if (typeof value === 'string' &&
|
|
21
|
+
value.length > 0 &&
|
|
22
|
+
value.length <= max &&
|
|
23
|
+
!value.includes('\0')) {
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
throw new CastleError({
|
|
27
|
+
code: 'INVALID_ARGUMENT',
|
|
28
|
+
message: `${operation} requires a valid ${field}.`,
|
|
29
|
+
operation,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function ids(value, operation) {
|
|
33
|
+
if (!Array.isArray(value) || value.length > PARTY_USERS_MAX) {
|
|
34
|
+
throw new CastleError({
|
|
35
|
+
code: 'INVALID_ARGUMENT',
|
|
36
|
+
message: `${operation} requires at most ${PARTY_USERS_MAX} user ids.`,
|
|
37
|
+
operation,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return value.map((value) => id(value, 'userId', operation));
|
|
41
|
+
}
|
|
42
|
+
async function current() {
|
|
43
|
+
return hostRequest('party.current', {});
|
|
44
|
+
}
|
|
45
|
+
async function create(userIds) {
|
|
46
|
+
return hostRequest('party.create', { userIds: ids(userIds, 'Party.create') });
|
|
47
|
+
}
|
|
48
|
+
async function invite(partyId, userIds) {
|
|
49
|
+
return hostRequest('party.invite', {
|
|
50
|
+
partyId: id(partyId, 'partyId', 'Party.invite'),
|
|
51
|
+
userIds: ids(userIds, 'Party.invite'),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
async function respond(partyId, accept) {
|
|
55
|
+
if (typeof accept !== 'boolean') {
|
|
56
|
+
throw new CastleError({
|
|
57
|
+
code: 'INVALID_ARGUMENT',
|
|
58
|
+
message: 'Party.respond requires accept to be a boolean.',
|
|
59
|
+
operation: 'Party.respond',
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return hostRequest('party.respond', {
|
|
63
|
+
partyId: id(partyId, 'partyId', 'Party.respond'),
|
|
64
|
+
accept,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
async function members(partyId) {
|
|
68
|
+
return hostRequest('party.members', { partyId: id(partyId, 'partyId', 'Party.members') });
|
|
69
|
+
}
|
|
70
|
+
async function leave(partyId) {
|
|
71
|
+
return hostRequest('party.leave', { partyId: id(partyId, 'partyId', 'Party.leave') });
|
|
72
|
+
}
|
|
73
|
+
async function messages(partyId, cursor) {
|
|
74
|
+
const params = {
|
|
75
|
+
partyId: id(partyId, 'partyId', 'Party.messages'),
|
|
76
|
+
};
|
|
77
|
+
if (cursor !== undefined) {
|
|
78
|
+
params.cursor = boundedText(cursor, 'cursor', 'Party.messages', CURSOR_MAX);
|
|
79
|
+
}
|
|
80
|
+
return hostRequest('party.messages', params);
|
|
81
|
+
}
|
|
82
|
+
async function say(partyId, text) {
|
|
83
|
+
if (typeof text !== 'string' || text.length === 0) {
|
|
84
|
+
throw new CastleError({
|
|
85
|
+
code: 'INVALID_ARGUMENT',
|
|
86
|
+
message: 'Party.say requires text.',
|
|
87
|
+
operation: 'Party.say',
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return hostRequest('party.say', { partyId: id(partyId, 'partyId', 'Party.say'), text });
|
|
91
|
+
}
|