castle-web-sdk 0.4.54 → 0.4.56

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 CHANGED
@@ -76,9 +76,13 @@ of foreground time; time while the page is hidden or frozen does not spend it,
76
76
  and a stall of the page's JavaScript (a debugger pause, an app pausing its web
77
77
  view) spends at most two seconds. After any return the SDK tries the reconnect
78
78
  credential at least once before giving up on it. Retries wait for the page to
79
- become visible and resume. A server rejecting the
79
+ become visible and resume. A drop found as the page comes back from being
80
+ hidden, frozen or suspended is retried at once; one met while the page is
81
+ running waits a short backoff first. A server rejecting the
80
82
  credential or confirming the session ended can still trigger a fresh join sooner.
81
83
 
84
+ `connection.reconnect()` starts recovery for a connected socket and returns `true`; otherwise it returns `false`, including in solo mode.
85
+
82
86
  `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.
83
87
 
84
88
  Experimental: `Multiplayer.join({ mode: "public", pongTimeoutMs: 10_000 })`
@@ -2014,6 +2018,13 @@ window.addEventListener("touchstart", (event) => {
2014
2018
  });
2015
2019
  ```
2016
2020
 
2021
+ To open it without changing the deck, the deck's owner adds `?debug=1`
2022
+ to the deck's address on castle.xyz (`https://castle.xyz/d/<deck id>?debug=1`).
2023
+ The page checks that the signed-in viewer owns the deck, and only then
2024
+ opens the console as the deck starts; anyone else gets the deck as
2025
+ usual. It needs a deck saved with SDK 0.4.56 or later, and it works on
2026
+ the website only. In the Castle app, use `DebugConsole.show()`.
2027
+
2017
2028
  ## Setup
2018
2029
 
2019
2030
  Startup, editor-mode check, and a file-write call for editor UI.
@@ -2175,6 +2186,13 @@ few seconds, since a session ghost has just started can briefly be unroutable;
2175
2186
  the error is reported only when those tries run out. A failed hub join cancels
2176
2187
  its handoff, so retrying a door after that requires a fresh `Hub.go` acquisition.
2177
2188
 
2189
+ `Hub.go`, `Hub.back`, `Hub.jump`, `Multiplayer.join`'s session request and
2190
+ `Multiplayer.joinDestination` ask the host again when it fails in transit
2191
+ (`CASTLE_HOST_ERROR`, e.g. a 502 from Castle's API): after 1, 2, 4 and 8 s,
2192
+ then the last error is thrown. `Hub.cancel` ends that wait with `cancelled`, as
2193
+ does a newer destination join; a newer `Multiplayer.join` stops an older one's
2194
+ tries. Any other code (`FORBIDDEN`, `LOGIN_REQUIRED`, ...) fails at once.
2195
+
2178
2196
  Every error the SDK throws is a `CastleError`. Check `code` to tell
2179
2197
  the kinds apart.
2180
2198
 
package/dist/context.d.ts CHANGED
@@ -13,6 +13,11 @@ export interface CastleEmbed {
13
13
  * `experiments.get` command instead (experiments.ts).
14
14
  */
15
15
  experiments?: Record<string, string>;
16
+ /**
17
+ * Opens `DebugConsole` as the deck starts. castle.xyz sets it only for the
18
+ * deck's owner, when they add `?debug=1` to the deck's URL.
19
+ */
20
+ debugConsole?: boolean;
16
21
  }
17
22
  declare global {
18
23
  interface Window {
@@ -10,6 +10,7 @@ export interface DebugConsoleApi {
10
10
  hide(): void;
11
11
  lines(): DebugConsoleLine[];
12
12
  }
13
+ export declare const originalConsole: Record<DebugConsoleLevel, (...args: unknown[]) => void>;
13
14
  export declare function formatConsoleArgs(args: unknown[]): string;
14
15
  export declare function recordConsoleLine(level: DebugConsoleLevel, text: string): void;
15
16
  export declare function noteConsoleHooked(): void;
@@ -6,6 +6,10 @@
6
6
  // `setup()` records every console line and uncaught error from the start, so
7
7
  // `show()` reveals what happened before it was called. A deck that never calls
8
8
  // `setup()` gets recording from its first `show()` on.
9
+ //
10
+ // The host can also open it without any deck code (`openForHost` below): on
11
+ // castle.xyz the deck's owner adds `?debug=1` to the deck's URL.
12
+ import { getCastleEmbed } from "./context";
9
13
  const MAX_LINES = 300;
10
14
  const MAX_LINE_CHARS = 2000;
11
15
  const COLORS = {
@@ -13,27 +17,49 @@ const COLORS = {
13
17
  warn: "#ffd66b",
14
18
  error: "#ff8a80",
15
19
  };
20
+ // The console as it was before anything here or in runtime.ts wrapped it.
21
+ // runtime.ts writes through these, so a line is never recorded twice when the
22
+ // host opened the console before the deck called `setup()`.
23
+ export const originalConsole = {
24
+ log: console.log,
25
+ warn: console.warn,
26
+ error: console.error,
27
+ };
16
28
  const recorded = [];
17
29
  let consoleHooked = false;
18
30
  let errorsHooked = false;
19
31
  let panel = null;
20
32
  let list = null;
21
- export function formatConsoleArgs(args) {
22
- return args
23
- .map((arg) => {
33
+ // Never throws, and always a string: a console call the deck makes must not
34
+ // fail because of what it logged (a cyclic object with no prototype, a revoked
35
+ // proxy, an Error whose stack is not a string).
36
+ const UNPRINTABLE = "[unprintable]";
37
+ function formatConsoleArg(arg) {
38
+ try {
24
39
  if (typeof arg === "string")
25
40
  return arg;
26
- if (arg instanceof Error)
27
- return arg.stack || arg.message;
28
- try {
29
- const json = JSON.stringify(arg);
30
- return json ?? String(arg);
41
+ if (arg instanceof Error) {
42
+ const text = arg.stack || arg.message;
43
+ if (typeof text === "string")
44
+ return text;
31
45
  }
32
- catch {
33
- return String(arg);
34
- }
35
- })
36
- .join(" ");
46
+ const json = JSON.stringify(arg);
47
+ if (typeof json === "string")
48
+ return json;
49
+ }
50
+ catch {
51
+ // fall through to String()
52
+ }
53
+ try {
54
+ const text = String(arg);
55
+ return typeof text === "string" ? text : UNPRINTABLE;
56
+ }
57
+ catch {
58
+ return UNPRINTABLE;
59
+ }
60
+ }
61
+ export function formatConsoleArgs(args) {
62
+ return args.map(formatConsoleArg).join(" ");
37
63
  }
38
64
  // runtime.ts's own console hook calls this, so the line is formatted once for
39
65
  // both the dev serve and this buffer.
@@ -74,6 +100,8 @@ function hookConsole() {
74
100
  return;
75
101
  consoleHooked = true;
76
102
  for (const level of ["log", "warn", "error"]) {
103
+ // The console as it is now, so a wrapper the deck installed before
104
+ // calling show() keeps getting its lines.
77
105
  const original = console[level];
78
106
  console[level] = (...args) => {
79
107
  original(...args);
@@ -131,8 +159,12 @@ function show() {
131
159
  return;
132
160
  hookConsole();
133
161
  captureErrors();
134
- if (panel)
162
+ if (panel?.isConnected)
135
163
  return;
164
+ // A deck that replaces the body (innerHTML, replaceChildren) takes the
165
+ // panel with it; draw a new one.
166
+ panel?.remove();
167
+ panel = null;
136
168
  panel = buildPanel();
137
169
  (document.body ?? document.documentElement).appendChild(panel);
138
170
  for (const line of recorded) {
@@ -143,6 +175,7 @@ function show() {
143
175
  }
144
176
  }
145
177
  function hide() {
178
+ stopKeepingOpen();
146
179
  panel?.remove();
147
180
  panel = null;
148
181
  list = null;
@@ -152,3 +185,43 @@ export const DebugConsole = {
152
185
  hide,
153
186
  lines: () => recorded.slice(),
154
187
  };
188
+ // The host decides who sees the console: castle.xyz sets
189
+ // `CastleEmbed.debugConsole` only when the viewer who added `?debug=1` owns the
190
+ // deck (castle-www DeckPlayer). It is in the document before any deck script,
191
+ // so recording starts with the deck. Nothing here reads the deck's own URL:
192
+ // anyone can add a query string, only the host knows who is watching. A deck
193
+ // that sets the flag itself only shows its own console to its own players.
194
+ //
195
+ // Opened this way, the panel comes back when the deck's own startup clears the
196
+ // body (or replaces it), until the owner presses Hide.
197
+ let keepOpen = null;
198
+ function stopKeepingOpen() {
199
+ keepOpen?.disconnect();
200
+ keepOpen = null;
201
+ }
202
+ function openForHost() {
203
+ if (typeof document === "undefined" || getCastleEmbed()?.debugConsole !== true)
204
+ return;
205
+ hookConsole();
206
+ captureErrors();
207
+ const open = () => {
208
+ show();
209
+ if (keepOpen || typeof MutationObserver === "undefined")
210
+ return;
211
+ keepOpen = new MutationObserver(() => {
212
+ if (panel && !panel.isConnected)
213
+ show();
214
+ });
215
+ keepOpen.observe(document.documentElement, { childList: true, subtree: true });
216
+ };
217
+ // A classic script in the head runs before there is a body to draw into.
218
+ // A module deck runs once the document is parsed, still ahead of its own
219
+ // first pass over the body: the observer puts the panel back after that.
220
+ if (document.readyState === "loading") {
221
+ document.addEventListener("DOMContentLoaded", open, { once: true });
222
+ }
223
+ else {
224
+ open();
225
+ }
226
+ }
227
+ openForHost();
@@ -0,0 +1,7 @@
1
+ export declare const HOST_TRANSPORT_RETRY_MS: readonly [1000, 2000, 4000, 8000];
2
+ export interface HostRetryOptions {
3
+ signal?: AbortSignal;
4
+ stopped?: () => boolean;
5
+ }
6
+ export declare function isHostTransportFailure(error: unknown): boolean;
7
+ export declare function retryHostTransport<T>(command: string, ask: () => Promise<T>, options?: HostRetryOptions): Promise<T>;
@@ -0,0 +1,57 @@
1
+ // Re-asking a join-path host command whose request failed in transit.
2
+ //
3
+ // The host runs these commands against Castle's API with its own fetch. When
4
+ // the load balancer in front of the API answers a 502 (an HTML page, in bursts
5
+ // while app servers are replaced), the host cannot read the reply and the deck
6
+ // gets CASTLE_HOST_ERROR: the request never reached ghost, or reached it and
7
+ // its answer was lost. Ghost lets a newer acquisition supersede an earlier
8
+ // pending one, so asking again is safe for the acquisitions that use this
9
+ // (Hub.go/back/jump, multiplayer.getSession, multiplayer.joinDestination).
10
+ //
11
+ // Only CASTLE_HOST_ERROR is asked again. Every error ghost itself answered
12
+ // carries its own code (FORBIDDEN, LOGIN_REQUIRED, ...) and is final, and
13
+ // CASTLE_HOST_UNAVAILABLE is mostly the deck's own timeout, where the request
14
+ // may still be running and another wait would outlast the caller's deadline.
15
+ import { CastleError } from "./errors";
16
+ // The wait before each ask after the first: five asks over about 15 s, inside
17
+ // the 30 s the deck gives one hub.go/back/jump and the hub kit's door limit.
18
+ export const HOST_TRANSPORT_RETRY_MS = [1_000, 2_000, 4_000, 8_000];
19
+ export function isHostTransportFailure(error) {
20
+ return error instanceof CastleError && error.code === "CASTLE_HOST_ERROR";
21
+ }
22
+ export async function retryHostTransport(command, ask, options = {}) {
23
+ for (let attempt = 0;; attempt++) {
24
+ try {
25
+ return await ask();
26
+ }
27
+ catch (error) {
28
+ const delay = HOST_TRANSPORT_RETRY_MS[attempt];
29
+ if (!isHostTransportFailure(error) || delay === undefined || isStopped(options)) {
30
+ throw error;
31
+ }
32
+ console.warn(`Castle ${command} failed in transit; asking again in ${delay} ms ` +
33
+ `(attempt ${attempt + 2} of ${HOST_TRANSPORT_RETRY_MS.length + 1}).`);
34
+ await wait(delay, options.signal);
35
+ if (isStopped(options))
36
+ throw error;
37
+ }
38
+ }
39
+ }
40
+ function isStopped(options) {
41
+ return options.signal?.aborted === true || options.stopped?.() === true;
42
+ }
43
+ function wait(milliseconds, signal) {
44
+ return new Promise((resolve) => {
45
+ if (signal?.aborted) {
46
+ resolve();
47
+ return;
48
+ }
49
+ const done = () => {
50
+ clearTimeout(timer);
51
+ signal?.removeEventListener("abort", done);
52
+ resolve();
53
+ };
54
+ const timer = setTimeout(done, milliseconds);
55
+ signal?.addEventListener("abort", done, { once: true });
56
+ });
57
+ }
package/dist/hub.js CHANGED
@@ -2,6 +2,7 @@ import { HUB_GO_DOOR_ID_MAX } from "./commands";
2
2
  import { CastleError } from "./errors";
3
3
  import { hostNotifyHub, hostRequest, setHubEventHandler } from "./transport";
4
4
  import { HUB_FORBIDDEN_RETRY_MS, rejoinedRecently } from "./hubRejoin";
5
+ import { isHostTransportFailure, retryHostTransport } from "./hostRetry";
5
6
  // Hub contract v1.177: a host that predates these commands answers
6
7
  // UNKNOWN_COMMAND, and no host at all (no bridge, an unreachable dev server, a
7
8
  // timeout) surfaces CASTLE_HOST_UNAVAILABLE. Both read as unavailable to a
@@ -62,25 +63,59 @@ async function go(doorId, options = {}) {
62
63
  operation: "Hub.go",
63
64
  });
64
65
  }
65
- return untilListed(() => hostRequest("hub.go", ownerUserId === undefined ? { doorId } : { doorId, ownerUserId }));
66
+ return untilListed("hub.go", () => hostRequest("hub.go", ownerUserId === undefined ? { doorId } : { doorId, ownerUserId }));
67
+ }
68
+ // Aborted, and dropped, by every `Hub.cancel`: it ends any wait below. Made
69
+ // on first use, so loading the SDK needs no AbortController.
70
+ let cancelWaits = null;
71
+ function cancelSignal() {
72
+ return (cancelWaits ??= new AbortController()).signal;
73
+ }
74
+ const CANCELLED_HANDOFF = {
75
+ status: "cancelled", url: null, nonce: null, sessionId: null, bundleHash: null, contentUrl: null,
76
+ };
77
+ // Every go/back/jump takes the next generation. Ghost lets the newest pending
78
+ // acquisition supersede the others, so an older one asked again after a newer
79
+ // one began would replace it: only the newest is asked again.
80
+ let hubAcquisitions = 0;
81
+ function startAcquisition() {
82
+ return { signal: cancelSignal(), generation: ++hubAcquisitions };
83
+ }
84
+ function isSuperseded(acquisition) {
85
+ return acquisition.generation !== hubAcquisitions;
86
+ }
87
+ // An acquisition whose request failed in transit is asked again
88
+ // (`retryHostTransport`) until `Hub.cancel` or a newer acquisition, either of
89
+ // which answers `cancelled`.
90
+ async function handoff(command, ask, acquisition) {
91
+ const superseded = () => isSuperseded(acquisition);
92
+ try {
93
+ return await retryHostTransport(command, ask, { signal: acquisition.signal, stopped: superseded });
94
+ }
95
+ catch (error) {
96
+ if ((acquisition.signal.aborted || superseded()) && isHostTransportFailure(error)) {
97
+ return { ...CANCELLED_HANDOFF };
98
+ }
99
+ throw error;
100
+ }
66
101
  }
67
102
  // Right after the socket rejoined its session ghost may not list the player
68
- // yet, and answers `forbidden` until it does. `Hub.cancel` ends the wait.
69
- let cancels = 0;
70
- async function untilListed(ask) {
71
- const asked = cancels;
103
+ // yet, and answers `forbidden` until it does. `Hub.cancel` or a newer
104
+ // acquisition ends the wait, and nothing more is asked.
105
+ async function untilListed(command, ask) {
106
+ const acquisition = startAcquisition();
107
+ const signal = acquisition.signal;
72
108
  for (;;) {
73
- const result = await ask();
109
+ const result = await handoff(command, ask, acquisition);
74
110
  if (result.status !== "forbidden" || !rejoinedRecently())
75
111
  return result;
76
112
  await new Promise((resolve) => setTimeout(resolve, HUB_FORBIDDEN_RETRY_MS));
77
- if (cancels !== asked) {
78
- return { status: "cancelled", url: null, nonce: null, sessionId: null, bundleHash: null, contentUrl: null };
79
- }
113
+ if (signal.aborted || isSuperseded(acquisition))
114
+ return { ...CANCELLED_HANDOFF };
80
115
  }
81
116
  }
82
117
  async function back() {
83
- return hostRequest("hub.back", {});
118
+ return handoff("hub.back", () => hostRequest("hub.back", {}), startAcquisition());
84
119
  }
85
120
  async function doors() {
86
121
  return hostRequest("hub.doors", {});
@@ -151,7 +186,7 @@ async function jump(userId) {
151
186
  operation: "Hub.jump",
152
187
  });
153
188
  }
154
- return untilListed(() => hostRequest("hub.jump", { userId }));
189
+ return untilListed("hub.jump", () => hostRequest("hub.jump", { userId }));
155
190
  }
156
191
  async function report(userId, reason) {
157
192
  if (typeof userId !== "string" || userId.length === 0) {
@@ -187,7 +222,8 @@ async function reportChat(messageId, options) {
187
222
  return hostRequest("hub.reportChat", { messageId, ...(options?.block === true ? { block: true } : {}) });
188
223
  }
189
224
  async function cancel() {
190
- cancels += 1;
225
+ cancelWaits?.abort();
226
+ cancelWaits = null;
191
227
  return hostRequest("hub.cancel", {});
192
228
  }
193
229
  const GO_FAILED_WHYS = ["refused", "content", "join"];
@@ -205,6 +205,8 @@ export interface MultiplayerConnection {
205
205
  readonly sharedCharacters: boolean;
206
206
  /** Sends byte payloads as binary frames and all other payloads as JSON. */
207
207
  send(data: unknown): void;
208
+ /** Starts recovery for a connected socket; false when there is none. */
209
+ reconnect(): boolean;
208
210
  /** Requests one billed character turn through this authenticated world socket. */
209
211
  requestCharacterTurn(request: MultiplayerCharacterTurnRequest): Promise<MultiplayerCharacterTurnAdmission>;
210
212
  /** Recovers the durable status of a prior operation after reconnecting. */
@@ -1,6 +1,7 @@
1
1
  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
+ import { retryHostTransport } from "./hostRetry";
4
5
  import { MultiplayerVoiceImpl } from "./multiplayerVoice";
5
6
  import { ReconnectBudget } from "./reconnectBudget";
6
7
  import { noteSessionRejoined } from "./hubRejoin";
@@ -8,6 +9,20 @@ const KEEPALIVE_INTERVAL_MS = 25_000;
8
9
  const HELLO_TIMEOUT_MS = 10_000;
9
10
  const RECONNECT_BUDGET_MS = 30_000;
10
11
  const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
12
+ // A connected socket hears something at least once a keepalive (the pong, or
13
+ // the tick that sends the ping). Silence well past that means the page was not
14
+ // running: hidden, frozen or suspended. A connection lost across such a gap is
15
+ // found on the page's return, and its first try goes at once instead of after
16
+ // the first backoff step: the backoff is for a failing network, and an outage
17
+ // found on return has not failed a single try yet. A hidden page whose timers
18
+ // and frames kept running is away too: each sign of life notes whether the
19
+ // page was hidden, and the first one seen visible after that is a return. A
20
+ // resumed page can run an overdue keepalive tick or deliver buffered frames
21
+ // before the socket's close (or a pong deadline's fresh probe can outlast
22
+ // them), so a return stands until a socket frame arrives RETURN_GRACE_MS or
23
+ // more after it, which shows the socket carried on past the return.
24
+ const AWAY_SILENCE_MS = KEEPALIVE_INTERVAL_MS + 5_000;
25
+ const RETURN_GRACE_MS = 5_000;
11
26
  const INVALID_DEV_RECONNECT_CLOSE_CODE = 4003;
12
27
  // The play proxy closes a handshake it refuses with a reason (cauldron-game-server
13
28
  // shared/src/constants.ts). The host that owns the session rejecting the credential is
@@ -27,6 +42,18 @@ let nextCharacterStatusRequestId = 1;
27
42
  let activeConnection = null;
28
43
  let latestJoinAttempt = 0;
29
44
  let pendingDestinationJoin = null;
45
+ // Connections waiting for a newer join to settle (`whenJoinOwner`), woken when
46
+ // a destination join settles or a connection closes, to look again.
47
+ let joinSettledWaiters = [];
48
+ function nextJoinSettled() {
49
+ return new Promise((resolve) => joinSettledWaiters.push(resolve));
50
+ }
51
+ function wakeJoinWaiters() {
52
+ const waiters = joinSettledWaiters;
53
+ joinSettledWaiters = [];
54
+ for (const wake of waiters)
55
+ wake();
56
+ }
30
57
  export const Multiplayer = {
31
58
  placeCharacters: true,
32
59
  join,
@@ -52,10 +79,14 @@ async function join(options) {
52
79
  if (!Number.isFinite(pongTimeoutMs) || pongTimeoutMs < 0 || pongTimeoutMs > 2_147_483_647) {
53
80
  throw new RangeError("pongTimeoutMs must be between 0 and 2147483647 milliseconds");
54
81
  }
55
- latestJoinAttempt += 1;
82
+ const attempt = ++latestJoinAttempt;
83
+ // Leaving runs the deck's state listeners, which may begin a newer join:
84
+ // then this one is superseded before it asks for anything.
56
85
  cancelPendingDestinationJoin();
57
86
  activeConnection?.leave();
58
- const connection = new MultiplayerConnectionImpl(request, () => {
87
+ if (attempt !== latestJoinAttempt)
88
+ throw supersededJoinError();
89
+ const connection = new MultiplayerConnectionImpl(request, attempt, () => {
59
90
  if (activeConnection === connection)
60
91
  activeConnection = null;
61
92
  }, null, pongTimeoutMs);
@@ -119,8 +150,15 @@ function hubJoin(options) {
119
150
  async function joinDestination(options) {
120
151
  const params = destinationParams(options);
121
152
  const attempt = ++latestJoinAttempt;
153
+ // Cancelling a pending destination join leaves its connection, whose state
154
+ // listeners may begin a newer join: then this one is superseded already.
122
155
  cancelPendingDestinationJoin();
156
+ if (attempt !== latestJoinAttempt)
157
+ return { status: "cancelled" };
123
158
  if (activeConnection?.matchesDestination(params)) {
159
+ // This join is the connection's own join now, for its fence.
160
+ activeConnection.adoptJoinAttempt(attempt);
161
+ wakeJoinWaiters();
124
162
  return {
125
163
  status: "joined",
126
164
  connection: activeConnection,
@@ -128,14 +166,26 @@ async function joinDestination(options) {
128
166
  };
129
167
  }
130
168
  const previousConnection = activeConnection;
169
+ try {
170
+ return await joinNewDestination(params, attempt, previousConnection);
171
+ }
172
+ finally {
173
+ // The newest join ended without replacing the connection it found: that
174
+ // connection is the player's again, and may ask for its session again.
175
+ if (attempt === latestJoinAttempt && previousConnection && activeConnection === previousConnection) {
176
+ previousConnection.adoptJoinAttempt(attempt);
177
+ }
178
+ wakeJoinWaiters();
179
+ }
180
+ }
181
+ async function joinNewDestination(params, attempt, previousConnection) {
131
182
  const controller = new AbortController();
132
183
  const pending = { controller, connection: null };
133
184
  pendingDestinationJoin = pending;
134
185
  let acquired;
135
186
  try {
136
- acquired = await hostRequest("multiplayer.joinDestination", params, {
137
- signal: controller.signal,
138
- });
187
+ // A request lost in transit is asked again until a newer join or a cancel.
188
+ acquired = await retryHostTransport("multiplayer.joinDestination", () => hostRequest("multiplayer.joinDestination", params, { signal: controller.signal }), { signal: controller.signal, stopped: () => attempt !== latestJoinAttempt });
139
189
  }
140
190
  catch (error) {
141
191
  if (pendingDestinationJoin === pending)
@@ -160,7 +210,7 @@ async function joinDestination(options) {
160
210
  pendingDestinationJoin = null;
161
211
  return { status: "unavailable" };
162
212
  }
163
- const connection = new MultiplayerConnectionImpl({ command: "multiplayer.joinDestination", params }, () => {
213
+ const connection = new MultiplayerConnectionImpl({ command: "multiplayer.joinDestination", params }, attempt, () => {
164
214
  if (activeConnection === connection)
165
215
  activeConnection = null;
166
216
  }, acquired.audience);
@@ -183,6 +233,11 @@ async function joinDestination(options) {
183
233
  return { status: "cancelled" };
184
234
  }
185
235
  previousConnection?.leave();
236
+ // The previous connection's state listeners may have begun a newer join.
237
+ if (attempt !== latestJoinAttempt) {
238
+ connection.leave();
239
+ return { status: "cancelled" };
240
+ }
186
241
  activeConnection = connection;
187
242
  return { status: "joined", connection, audience: acquired.audience };
188
243
  }
@@ -190,6 +245,7 @@ async function joinDestination(options) {
190
245
  const EARLY_MESSAGES_MAX = 512;
191
246
  class MultiplayerConnectionImpl {
192
247
  request;
248
+ joinAttempt;
193
249
  onClosed;
194
250
  destinationAudience;
195
251
  pongTimeoutMs;
@@ -212,6 +268,11 @@ class MultiplayerConnectionImpl {
212
268
  greeted = false;
213
269
  recovering = false;
214
270
  reconnectBudget = null;
271
+ // Wall clock, not monotonic: the gap it measures is a suspension, which a
272
+ // paused page's monotonic clock may not count.
273
+ lastHeardAt = 0;
274
+ returnedAt = null;
275
+ heardHidden = false;
215
276
  hubSettled = false;
216
277
  hubCommit = Promise.resolve(true);
217
278
  roster = null;
@@ -235,8 +296,13 @@ class MultiplayerConnectionImpl {
235
296
  players: () => this.roster?.players ?? [],
236
297
  isSolo: () => this.solo,
237
298
  });
238
- constructor(request, onClosed, destinationAudience = null, pongTimeoutMs = 0) {
299
+ constructor(request,
300
+ // The join (Multiplayer.join or joinDestination) this connection belongs
301
+ // to, the attempt it took. While a newer join is pending, this connection
302
+ // asks for no session (`whenJoinOwner`).
303
+ joinAttempt, onClosed, destinationAudience = null, pongTimeoutMs = 0) {
239
304
  this.request = request;
305
+ this.joinAttempt = joinAttempt;
240
306
  this.onClosed = onClosed;
241
307
  this.destinationAudience = destinationAudience;
242
308
  this.pongTimeoutMs = pongTimeoutMs;
@@ -299,6 +365,12 @@ class MultiplayerConnectionImpl {
299
365
  return;
300
366
  this.socket.send(payload);
301
367
  }
368
+ reconnect() {
369
+ if (this.currentState !== "connected" || this.recovering || this.solo || !this.socket)
370
+ return false;
371
+ this.recoverSocket(this.socket, "reconnect");
372
+ return true;
373
+ }
302
374
  requestCharacterTurn(request) {
303
375
  const normalized = normalizeCharacterTurnRequest(request, this.currentPlayerId);
304
376
  return this.sendCharacterRequest(normalized.requestId, normalized.operationId, "admission", JSON.stringify({ t: "worldCharacterTurn", ...normalized }));
@@ -427,6 +499,9 @@ class MultiplayerConnectionImpl {
427
499
  hubCommitted() {
428
500
  return this.hubCommit;
429
501
  }
502
+ adoptJoinAttempt(attempt) {
503
+ this.joinAttempt = attempt;
504
+ }
430
505
  matchesDestination(params) {
431
506
  return (this.currentState !== "closed" &&
432
507
  this.request.command === "multiplayer.joinDestination" &&
@@ -434,9 +509,28 @@ class MultiplayerConnectionImpl {
434
509
  this.request.params.slot === params.slot &&
435
510
  this.destinationAudience !== null);
436
511
  }
512
+ // Sends an acquisition once this connection owns the newest join attempt,
513
+ // or rejects once it is closed. A destination join keeps this connection
514
+ // open until its own socket connects; an acquisition asked meanwhile would
515
+ // supersede the newer one at the host, so it waits for that join to settle:
516
+ // one that replaced this connection closed it, one that did not handed it
517
+ // the attempt. The check and the send run in the same synchronous callback,
518
+ // so no join can begin between them; after any wake the gate is entered again.
519
+ whenJoinOwner(send) {
520
+ if (this.currentState === "closed")
521
+ return Promise.reject(this.closedError());
522
+ if (this.joinAttempt === latestJoinAttempt)
523
+ return send();
524
+ return nextJoinSettled().then(() => this.whenJoinOwner(send));
525
+ }
526
+ closedError() {
527
+ return multiplayerError("MULTIPLAYER_CONNECTION_CLOSED", "The multiplayer connection is closed.");
528
+ }
437
529
  async acquire(initial) {
438
530
  this.transition("acquiring");
439
- const result = initial ?? await requestAcquisition(this.request);
531
+ // Every ask, the first and each retry, waits until this connection owns
532
+ // the newest join (`whenJoinOwner`); a retry wait ends once it closes.
533
+ const result = initial ?? await requestAcquisition(this.request, (send) => this.whenJoinOwner(send), () => this.currentState === "closed");
440
534
  this.assertOpen();
441
535
  if (result.status === "solo") {
442
536
  this.connectSolo(result);
@@ -558,6 +652,8 @@ class MultiplayerConnectionImpl {
558
652
  closeSocket(socket, 1000, "hello timeout");
559
653
  }, HELLO_TIMEOUT_MS);
560
654
  socket.onmessage = (event) => {
655
+ if (this.socketAttempt === attempt)
656
+ this.hear(true);
561
657
  const data = event.data;
562
658
  inbound = inbound
563
659
  .then(async () => {
@@ -704,6 +800,11 @@ class MultiplayerConnectionImpl {
704
800
  const budget = this.reconnectBudget = new ReconnectBudget();
705
801
  let attempt = 0;
706
802
  let sessionEndedCloses = 0;
803
+ // Lost while the page was away (AWAY_SILENCE_MS), or found while it still
804
+ // is: the first try goes as soon as the page is back. It is still a try
805
+ // with the token, which is the only way to learn whether the host kept the
806
+ // player; the backoff resumes from its first step after it.
807
+ let immediate = !budget.active || this.heardHidden || this.cameBack();
707
808
  try {
708
809
  while (true) {
709
810
  await budget.waitUntilActive();
@@ -712,11 +813,16 @@ class MultiplayerConnectionImpl {
712
813
  // which keeps the player's identity while the host holds its lineage.
713
814
  if (budget.exhausted(RECONNECT_BUDGET_MS))
714
815
  break;
715
- const delay = RECONNECT_DELAYS_MS[Math.min(attempt, RECONNECT_DELAYS_MS.length - 1)];
716
- attempt += 1;
717
- await pause(delay);
718
- await budget.waitUntilActive();
719
- this.assertOpen();
816
+ if (immediate) {
817
+ immediate = false;
818
+ }
819
+ else {
820
+ const delay = RECONNECT_DELAYS_MS[Math.min(attempt, RECONNECT_DELAYS_MS.length - 1)];
821
+ attempt += 1;
822
+ await pause(delay);
823
+ await budget.waitUntilActive();
824
+ this.assertOpen();
825
+ }
720
826
  try {
721
827
  budget.noteAttempt();
722
828
  await this.openSocket("reconnect", this.reconnectToken);
@@ -744,6 +850,23 @@ class MultiplayerConnectionImpl {
744
850
  }
745
851
  await this.reacquireOnce();
746
852
  }
853
+ // A sign the page is running: a frame from the socket or a keepalive tick.
854
+ hear(fromSocket = false) {
855
+ const now = Date.now();
856
+ const hidden = typeof document !== "undefined" && document.visibilityState === "hidden";
857
+ if (now - this.lastHeardAt > AWAY_SILENCE_MS || (this.heardHidden && !hidden)) {
858
+ this.returnedAt = now;
859
+ }
860
+ else if (fromSocket && this.returnedAt !== null && now - this.returnedAt >= RETURN_GRACE_MS) {
861
+ this.returnedAt = null;
862
+ }
863
+ this.heardHidden = hidden;
864
+ this.lastHeardAt = now;
865
+ }
866
+ cameBack() {
867
+ const now = Date.now();
868
+ return now - this.lastHeardAt > AWAY_SILENCE_MS || this.returnedAt !== null;
869
+ }
747
870
  async reacquireOnce() {
748
871
  if (this.reAcquisitionUsed) {
749
872
  throw this.closeAfterRecovery();
@@ -766,7 +889,11 @@ class MultiplayerConnectionImpl {
766
889
  startKeepalive() {
767
890
  this.stopKeepalive();
768
891
  this.pongExtensionUsed = false;
892
+ this.lastHeardAt = Date.now();
893
+ this.returnedAt = null;
894
+ this.heardHidden = false;
769
895
  this.keepalive = setInterval(() => {
896
+ this.hear();
770
897
  if (this.socket?.readyState === WebSocket.OPEN) {
771
898
  if (this.pongDeadline !== null)
772
899
  return;
@@ -812,15 +939,18 @@ class MultiplayerConnectionImpl {
812
939
  }
813
940
  catch { /* Fall through to recovery if the fresh probe cannot send. */ }
814
941
  }
815
- // A half-open transport may never emit close. Fence its queued callbacks
816
- // and enter recovery directly rather than waiting for that close event.
817
- this.socketAttempt += 1;
818
- this.socket = null;
819
- this.stopKeepalive();
820
- closeSocket(socket, 1000, "pong timeout");
821
- this.beginRecovery();
942
+ this.recoverSocket(socket, "pong timeout");
822
943
  }, this.pongTimeoutMs);
823
944
  }
945
+ recoverSocket(socket, reason) {
946
+ // A half-open transport may never emit close. Fence its queued callbacks
947
+ // and enter recovery directly rather than waiting for that close event.
948
+ this.socketAttempt += 1;
949
+ this.socket = null;
950
+ this.stopKeepalive();
951
+ closeSocket(socket, 1000, reason);
952
+ this.beginRecovery();
953
+ }
824
954
  transition(state, metadata) {
825
955
  if (this.currentState === "closed" || this.currentState === state)
826
956
  return;
@@ -850,11 +980,11 @@ class MultiplayerConnectionImpl {
850
980
  for (const callback of this.states)
851
981
  callStateListener(callback, "closed", metadata);
852
982
  this.onClosed();
983
+ wakeJoinWaiters();
853
984
  }
854
985
  assertOpen() {
855
- if (this.currentState === "closed") {
856
- throw multiplayerError("MULTIPLAYER_CONNECTION_CLOSED", "The multiplayer connection is closed.");
857
- }
986
+ if (this.currentState === "closed")
987
+ throw this.closedError();
858
988
  }
859
989
  acceptWorldCharacterResult(frame) {
860
990
  const pending = this.pendingCharacterRequests.get(frame.requestId);
@@ -955,22 +1085,34 @@ function destinationParams(options) {
955
1085
  }
956
1086
  return { routeId: options.routeId, slot: options.slot };
957
1087
  }
1088
+ // What a join superseded by a newer one before it had a connection rejects
1089
+ // with: the same code as one whose connection the newer join closed.
1090
+ function supersededJoinError() {
1091
+ return multiplayerError("MULTIPLAYER_CONNECTION_CLOSED", "A newer join began; this one was superseded.", "Multiplayer.join");
1092
+ }
958
1093
  function cancelPendingDestinationJoin() {
959
1094
  const pending = pendingDestinationJoin;
960
1095
  pendingDestinationJoin = null;
961
1096
  pending?.controller.abort();
962
1097
  pending?.connection?.leave();
963
1098
  }
964
- async function requestAcquisition(request) {
1099
+ async function requestAcquisition(request,
1100
+ // Sends one ask, when the connection may (`whenJoinOwner`).
1101
+ gate, closed) {
965
1102
  if (request.command === "hub") {
966
1103
  // The nonce was single-use and the trip is the host's; a hub session that
967
1104
  // cannot be reconnected to is left by going back through the door.
968
1105
  throw multiplayerError("MULTIPLAYER_CONNECTION_LOST", "A hub session cannot be acquired again. Go back through the door.");
969
1106
  }
1107
+ // A request lost in transit is asked again until the connection closes; the
1108
+ // wait under way runs out first. Each ask goes through `gate`.
1109
+ const ask = (send) => () => gate(send);
970
1110
  if (request.command === "multiplayer.getSession") {
971
- return hostRequest(request.command, request.params);
1111
+ const params = request.params;
1112
+ return retryHostTransport(request.command, ask(() => hostRequest("multiplayer.getSession", params)), { stopped: closed });
972
1113
  }
973
- return hostRequest(request.command, request.params);
1114
+ const params = request.params;
1115
+ return retryHostTransport(request.command, ask(() => hostRequest("multiplayer.joinDestination", params)), { stopped: closed });
974
1116
  }
975
1117
  function destinationStatusFromError(error) {
976
1118
  if (!(error instanceof CastleError))
@@ -11,6 +11,8 @@ export declare class ReconnectBudget {
11
11
  private readonly page;
12
12
  private readonly host;
13
13
  constructor();
14
+ /** Whether the page is running now: visible, not frozen, not disposed. */
15
+ get active(): boolean;
14
16
  get elapsedMs(): number;
15
17
  noteAttempt(): void;
16
18
  exhausted(limitMs: number): boolean;
@@ -44,6 +44,10 @@ export class ReconnectBudget {
44
44
  this.offline = this.host !== null && typeof navigator !== "undefined" && navigator?.onLine === false;
45
45
  this.update();
46
46
  }
47
+ /** Whether the page is running now: visible, not frozen, not disposed. */
48
+ get active() {
49
+ return this.lastSeen !== null;
50
+ }
47
51
  get elapsedMs() {
48
52
  this.observe();
49
53
  return this.elapsed;
package/dist/runtime.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CASTLE_SDK_PROTOCOL, } from "./commands";
2
2
  import { getCastleEmbed, isEdit } from "./context";
3
- import { captureErrors, formatConsoleArgs, noteConsoleHooked, recordConsoleLine } from "./debugConsole";
3
+ import { captureErrors, formatConsoleArgs, noteConsoleHooked, originalConsole, recordConsoleLine, } from "./debugConsole";
4
4
  import { cardUnit, fitStage, getDisplay } from "./display";
5
5
  import { appliedNotice, applyTunedParams, } from "./paramsRegistry";
6
6
  export const CARD_RATIO = 5 / 7;
@@ -20,9 +20,10 @@ const pendingRequests = new Map();
20
20
  // screenshot/write_file request map above. transport.ts owns the timeouts.
21
21
  const SOCKET_WAIT_TIMEOUT_MS = 10000;
22
22
  const localCommandListeners = new Map();
23
- const origLog = console.log;
24
- const origWarn = console.warn;
25
- const origError = console.error;
23
+ // Not `console.log` itself: the host may have had debugConsole.ts wrap it already.
24
+ const origLog = originalConsole.log;
25
+ const origWarn = originalConsole.warn;
26
+ const origError = originalConsole.error;
26
27
  // Indirected dynamic import so deck bundlers don't statically rewrite it.
27
28
  // eslint-disable-next-line @typescript-eslint/no-implied-eval
28
29
  const dynamicImport = new Function("u", "return import(u)");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-sdk",
3
- "version": "0.4.54",
3
+ "version": "0.4.56",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"