castle-web-sdk 0.4.53 → 0.4.55

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
@@ -38,6 +38,7 @@ import { setup, initCard, Store, Leaderboard } from "castle-web-sdk";
38
38
  - [Agent](#agent)
39
39
  - [Lifecycle](#lifecycle)
40
40
  - [Display](#display)
41
+ - [DebugConsole](#debugconsole)
41
42
  - [Multiplayer](#multiplayer)
42
43
  - [Setup](#setup)
43
44
  - [Saving files](#writefilepath-contents-promisevoid)
@@ -75,9 +76,13 @@ of foreground time; time while the page is hidden or frozen does not spend it,
75
76
  and a stall of the page's JavaScript (a debugger pause, an app pausing its web
76
77
  view) spends at most two seconds. After any return the SDK tries the reconnect
77
78
  credential at least once before giving up on it. Retries wait for the page to
78
- 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
79
82
  credential or confirming the session ended can still trigger a fresh join sooner.
80
83
 
84
+ `connection.reconnect()` starts recovery for a connected socket and returns `true`; otherwise it returns `false`, including in solo mode.
85
+
81
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.
82
87
 
83
88
  Experimental: `Multiplayer.join({ mode: "public", pongTimeoutMs: 10_000 })`
@@ -1975,6 +1980,44 @@ deck's preferred display orientation: `landscape`, `portrait`, or `any`.
1975
1980
  Missing or unrecognized preferences mean `any`; read the value as
1976
1981
  `display.orientation ?? "any"`.
1977
1982
 
1983
+ ## DebugConsole
1984
+
1985
+ A published deck's `console` output never reaches devtools: on
1986
+ castle.xyz the deck runs in a sandboxed frame of its own, and in the
1987
+ app it runs in a WebView. `DebugConsole` draws the deck's console as a
1988
+ panel along the bottom of the deck itself, so it can be read on the
1989
+ device the deck is running on.
1990
+
1991
+ - **`DebugConsole.show()`** — opens the panel. It holds the last 300
1992
+ lines of `console.log`, `console.warn` and `console.error`, plus
1993
+ uncaught errors and unhandled promise rejections. After
1994
+ [`setup()`](#setup) that includes everything since the deck started;
1995
+ in a deck that never calls `setup()`, only what comes after the first
1996
+ `show()`. The panel has **Clear** and **Hide** buttons.
1997
+ - **`DebugConsole.hide()`** — closes the panel. Lines keep being
1998
+ recorded.
1999
+ - **`DebugConsole.lines(): DebugConsoleLine[]`** — the recorded lines,
2000
+ oldest first, each `{ level: "log" | "warn" | "error", text, time }`
2001
+ with `time` from `Date.now()`, for a deck that draws its own.
2002
+
2003
+ The panel covers the bottom of the deck and takes touches there, so
2004
+ open it from a gesture or a debug option the deck controls, and remove
2005
+ that before the deck is for players:
2006
+
2007
+ ```js
2008
+ import { DebugConsole } from "castle-web-sdk";
2009
+
2010
+ // Three fingers on the card toggles the console.
2011
+ let open = false;
2012
+ window.addEventListener("touchstart", (event) => {
2013
+ if (event.touches.length === 3) {
2014
+ open = !open;
2015
+ if (open) DebugConsole.show();
2016
+ else DebugConsole.hide();
2017
+ }
2018
+ });
2019
+ ```
2020
+
1978
2021
  ## Setup
1979
2022
 
1980
2023
  Startup, editor-mode check, and a file-write call for editor UI.
@@ -1990,6 +2033,17 @@ While running locally with `castle-web serve`, it also forwards
1990
2033
  `console` output to the CLI and reloads the page when `castle-web
1991
2034
  restart` runs.
1992
2035
 
2036
+ `setup()` also keeps `history.pushState` and `history.replaceState`
2037
+ from throwing in a deck published on castle.xyz. There the deck's frame
2038
+ has no origin of its own, and a call that passes a URL throws a
2039
+ `SecurityError`; after
2040
+ `setup()` the call adds or replaces the history entry with its state
2041
+ but leaves the address as it was. A router that keeps its route in the
2042
+ address won't see it change; keep the route in the state or in the
2043
+ deck's own variables. `localStorage` throws there too; use
2044
+ [`LocalCache`](#localcache) for things the deck can rebuild and
2045
+ [`Store`](#store) for everything else.
2046
+
1993
2047
  ```js
1994
2048
  import { setup } from "castle-web-sdk";
1995
2049
 
@@ -2125,6 +2179,13 @@ few seconds, since a session ghost has just started can briefly be unroutable;
2125
2179
  the error is reported only when those tries run out. A failed hub join cancels
2126
2180
  its handoff, so retrying a door after that requires a fresh `Hub.go` acquisition.
2127
2181
 
2182
+ `Hub.go`, `Hub.back`, `Hub.jump`, `Multiplayer.join`'s session request and
2183
+ `Multiplayer.joinDestination` ask the host again when it fails in transit
2184
+ (`CASTLE_HOST_ERROR`, e.g. a 502 from Castle's API): after 1, 2, 4 and 8 s,
2185
+ then the last error is thrown. `Hub.cancel` ends that wait with `cancelled`, as
2186
+ does a newer destination join; a newer `Multiplayer.join` stops an older one's
2187
+ tries. Any other code (`FORBIDDEN`, `LOGIN_REQUIRED`, ...) fails at once.
2188
+
2128
2189
  Every error the SDK throws is a `CastleError`. Check `code` to tell
2129
2190
  the kinds apart.
2130
2191
 
package/dist/castle.d.ts CHANGED
@@ -46,6 +46,8 @@ export { cardUnit, fitStage, fovForAspect, getDisplay } from "./display";
46
46
  export type { DeckDisplay, DeckLayout, DeckOrientation } from "./display";
47
47
  export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
48
48
  export type { SaveState } from "./saveQueue";
49
+ export { DebugConsole } from "./debugConsole";
50
+ export type { DebugConsoleApi, DebugConsoleLevel, DebugConsoleLine } from "./debugConsole";
49
51
  export { LocalCache } from "./localCache";
50
52
  export type { LocalCacheApi } from "./localCache";
51
53
  export { SharedStorage, Storage } from "./storage";
package/dist/castle.js CHANGED
@@ -24,6 +24,7 @@ export { Portal } from "./portal";
24
24
  export { CARD_RATIO, deleteFile, fileUrl, initCard, onBeforeRestart, onFilesChanged, onSaveReloadState, openFile, renameFile, requestReload, setup, takeReloadState, writeFileOnce, } from "./runtime";
25
25
  export { cardUnit, fitStage, fovForAspect, getDisplay } from "./display";
26
26
  export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
27
+ export { DebugConsole } from "./debugConsole";
27
28
  export { LocalCache } from "./localCache";
28
29
  export { SharedStorage, Storage } from "./storage";
29
30
  export { Store } from "./store";
@@ -0,0 +1,17 @@
1
+ export type DebugConsoleLevel = "log" | "warn" | "error";
2
+ export interface DebugConsoleLine {
3
+ level: DebugConsoleLevel;
4
+ text: string;
5
+ /** `Date.now()` when the line was written. */
6
+ time: number;
7
+ }
8
+ export interface DebugConsoleApi {
9
+ show(): void;
10
+ hide(): void;
11
+ lines(): DebugConsoleLine[];
12
+ }
13
+ export declare function formatConsoleArgs(args: unknown[]): string;
14
+ export declare function recordConsoleLine(level: DebugConsoleLevel, text: string): void;
15
+ export declare function noteConsoleHooked(): void;
16
+ export declare function captureErrors(): void;
17
+ export declare const DebugConsole: DebugConsoleApi;
@@ -0,0 +1,154 @@
1
+ // A console drawn inside the deck's own frame, for debugging on a phone. A
2
+ // published deck runs in an opaque-origin frame (and in the app, a WebView), so
3
+ // the host page's devtools never see its console; this puts the lines where the
4
+ // person holding the device can read them. Off until the deck asks for it.
5
+ //
6
+ // `setup()` records every console line and uncaught error from the start, so
7
+ // `show()` reveals what happened before it was called. A deck that never calls
8
+ // `setup()` gets recording from its first `show()` on.
9
+ const MAX_LINES = 300;
10
+ const MAX_LINE_CHARS = 2000;
11
+ const COLORS = {
12
+ log: "#e8e8e8",
13
+ warn: "#ffd66b",
14
+ error: "#ff8a80",
15
+ };
16
+ const recorded = [];
17
+ let consoleHooked = false;
18
+ let errorsHooked = false;
19
+ let panel = null;
20
+ let list = null;
21
+ export function formatConsoleArgs(args) {
22
+ return args
23
+ .map((arg) => {
24
+ if (typeof arg === "string")
25
+ 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);
31
+ }
32
+ catch {
33
+ return String(arg);
34
+ }
35
+ })
36
+ .join(" ");
37
+ }
38
+ // runtime.ts's own console hook calls this, so the line is formatted once for
39
+ // both the dev serve and this buffer.
40
+ export function recordConsoleLine(level, text) {
41
+ const line = {
42
+ level,
43
+ text: text.length > MAX_LINE_CHARS ? `${text.slice(0, MAX_LINE_CHARS)}…` : text,
44
+ time: Date.now(),
45
+ };
46
+ recorded.push(line);
47
+ if (recorded.length > MAX_LINES) {
48
+ recorded.splice(0, recorded.length - MAX_LINES);
49
+ }
50
+ if (list) {
51
+ appendRow(line);
52
+ }
53
+ }
54
+ export function noteConsoleHooked() {
55
+ consoleHooked = true;
56
+ }
57
+ // Uncaught errors and rejections never pass through console.error, and they
58
+ // are what a deck that "just shows a black card" on a phone is hiding.
59
+ export function captureErrors() {
60
+ if (errorsHooked || typeof window === "undefined")
61
+ return;
62
+ errorsHooked = true;
63
+ window.addEventListener("error", (event) => {
64
+ const error = event.error;
65
+ const text = error instanceof Error ? error.stack || error.message : event.message;
66
+ recordConsoleLine("error", `Uncaught ${text || "error"}`);
67
+ });
68
+ window.addEventListener("unhandledrejection", (event) => {
69
+ recordConsoleLine("error", `Unhandled rejection ${formatConsoleArgs([event.reason])}`);
70
+ });
71
+ }
72
+ function hookConsole() {
73
+ if (consoleHooked)
74
+ return;
75
+ consoleHooked = true;
76
+ for (const level of ["log", "warn", "error"]) {
77
+ const original = console[level];
78
+ console[level] = (...args) => {
79
+ original(...args);
80
+ recordConsoleLine(level, formatConsoleArgs(args));
81
+ };
82
+ }
83
+ }
84
+ function button(label, onClick) {
85
+ const el = document.createElement("button");
86
+ el.type = "button";
87
+ el.textContent = label;
88
+ el.style.cssText =
89
+ "font: inherit; color: #fff; background: #333; border: 1px solid #555; border-radius: 4px; padding: 2px 8px; margin-left: 6px;";
90
+ el.addEventListener("click", onClick);
91
+ return el;
92
+ }
93
+ // Text only, never markup: a line is whatever the deck logged.
94
+ function appendRow(line) {
95
+ if (!list)
96
+ return;
97
+ const row = document.createElement("div");
98
+ row.textContent = line.text;
99
+ row.style.cssText = `color: ${COLORS[line.level]}; white-space: pre-wrap; word-break: break-word; border-bottom: 1px solid #222; padding: 1px 0;`;
100
+ const atBottom = list.scrollHeight - list.scrollTop - list.clientHeight < 8;
101
+ list.appendChild(row);
102
+ while (list.childElementCount > MAX_LINES) {
103
+ list.firstElementChild?.remove();
104
+ }
105
+ if (atBottom) {
106
+ list.scrollTop = list.scrollHeight;
107
+ }
108
+ }
109
+ function buildPanel() {
110
+ const root = document.createElement("div");
111
+ root.setAttribute("data-castle-debug-console", "");
112
+ root.style.cssText =
113
+ "position: fixed; left: 0; right: 0; bottom: 0; max-height: 40%; z-index: 2147483647; display: flex; flex-direction: column; background: rgba(0, 0, 0, 0.85); color: #e8e8e8; font: 11px/1.35 ui-monospace, Menlo, Consolas, monospace; pointer-events: auto; touch-action: pan-y;";
114
+ const header = document.createElement("div");
115
+ header.style.cssText =
116
+ "display: flex; align-items: center; padding: 4px 8px; border-bottom: 1px solid #444; flex: none;";
117
+ const title = document.createElement("span");
118
+ title.textContent = "Console";
119
+ title.style.cssText = "flex: 1; font-weight: bold;";
120
+ header.append(title, button("Clear", () => {
121
+ recorded.length = 0;
122
+ list?.replaceChildren();
123
+ }), button("Hide", hide));
124
+ list = document.createElement("div");
125
+ list.style.cssText = "overflow-y: auto; padding: 4px 8px; flex: 1; min-height: 0;";
126
+ root.append(header, list);
127
+ return root;
128
+ }
129
+ function show() {
130
+ if (typeof document === "undefined")
131
+ return;
132
+ hookConsole();
133
+ captureErrors();
134
+ if (panel)
135
+ return;
136
+ panel = buildPanel();
137
+ (document.body ?? document.documentElement).appendChild(panel);
138
+ for (const line of recorded) {
139
+ appendRow(line);
140
+ }
141
+ if (list) {
142
+ list.scrollTop = list.scrollHeight;
143
+ }
144
+ }
145
+ function hide() {
146
+ panel?.remove();
147
+ panel = null;
148
+ list = null;
149
+ }
150
+ export const DebugConsole = {
151
+ show,
152
+ hide,
153
+ lines: () => recorded.slice(),
154
+ };
@@ -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,5 +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
4
  import { cardUnit, fitStage, getDisplay } from "./display";
4
5
  import { appliedNotice, applyTunedParams, } from "./paramsRegistry";
5
6
  export const CARD_RATIO = 5 / 7;
@@ -27,6 +28,8 @@ const origError = console.error;
27
28
  const dynamicImport = new Function("u", "return import(u)");
28
29
  export function setup() {
29
30
  interceptConsole();
31
+ captureErrors();
32
+ initHistoryShim();
30
33
  connectLocal();
31
34
  initLocalWake();
32
35
  initHostCapture();
@@ -429,35 +432,49 @@ function resolveLocalRequest(msg) {
429
432
  return true;
430
433
  }
431
434
  function interceptConsole() {
435
+ noteConsoleHooked();
432
436
  console.log = (...args) => {
433
437
  origLog(...args);
434
- sendMsg({ type: "log", level: "log", msg: formatConsoleArgs(args) });
438
+ forwardConsoleLine("log", args);
435
439
  };
436
440
  console.warn = (...args) => {
437
441
  origWarn(...args);
438
- sendMsg({ type: "log", level: "warn", msg: formatConsoleArgs(args) });
442
+ forwardConsoleLine("warn", args);
439
443
  };
440
444
  console.error = (...args) => {
441
445
  origError(...args);
442
- sendMsg({ type: "log", level: "error", msg: formatConsoleArgs(args) });
446
+ forwardConsoleLine("error", args);
443
447
  };
444
448
  }
445
- function formatConsoleArgs(args) {
446
- return args
447
- .map((arg) => {
448
- if (typeof arg === "string")
449
- return arg;
450
- if (arg instanceof Error)
451
- return arg.stack || arg.message;
452
- try {
453
- const json = JSON.stringify(arg);
454
- return json ?? String(arg);
455
- }
456
- catch {
457
- return String(arg);
458
- }
459
- })
460
- .join(" ");
449
+ function forwardConsoleLine(level, args) {
450
+ const msg = formatConsoleArgs(args);
451
+ recordConsoleLine(level, msg);
452
+ sendMsg({ type: "log", level, msg });
453
+ }
454
+ // A published deck's frame has an opaque origin (about:srcdoc on the web), so
455
+ // pushState/replaceState throw a SecurityError the moment they are given a URL.
456
+ // Keep the state and drop the URL: the history entry still lands, and routers
457
+ // that read state rather than the address keep working. Calls without a URL
458
+ // never threw and pass straight through. Only an opaque origin gets this: with
459
+ // an origin of its own a URL that throws is a real error (a cross-origin URL a
460
+ // router may catch to navigate instead), and is left to throw.
461
+ function initHistoryShim() {
462
+ if (typeof history === "undefined" || location.origin !== "null")
463
+ return;
464
+ for (const name of ["pushState", "replaceState"]) {
465
+ const original = history[name];
466
+ history[name] = function (data, unused, url) {
467
+ try {
468
+ original.call(this, data, unused, url);
469
+ }
470
+ catch (error) {
471
+ const security = error instanceof DOMException && error.name === "SecurityError";
472
+ if (!security || url === undefined || url === null)
473
+ throw error;
474
+ original.call(this, data, unused);
475
+ }
476
+ };
477
+ }
461
478
  }
462
479
  // Compositing a card needs html2canvas, and where it comes from decides whether
463
480
  // a capture can fail for reasons that have nothing to do with the deck.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-sdk",
3
- "version": "0.4.53",
3
+ "version": "0.4.55",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"