castle-web-sdk 0.4.52 → 0.4.54

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
@@ -23,6 +23,7 @@ import { setup, initCard, Store, Leaderboard } from "castle-web-sdk";
23
23
  - [Time](#time)
24
24
  - [User](#user)
25
25
  - [Experiments](#experiments)
26
+ - [Analytics](#analytics)
26
27
  - [Avatar](#avatar)
27
28
  - [Pass](#pass)
28
29
  - [Snapshot](#snapshot)
@@ -37,6 +38,7 @@ import { setup, initCard, Store, Leaderboard } from "castle-web-sdk";
37
38
  - [Agent](#agent)
38
39
  - [Lifecycle](#lifecycle)
39
40
  - [Display](#display)
41
+ - [DebugConsole](#debugconsole)
40
42
  - [Multiplayer](#multiplayer)
41
43
  - [Setup](#setup)
42
44
  - [Saving files](#writefilepath-contents-promisevoid)
@@ -236,12 +238,27 @@ dev serve.
236
238
  the third argument of `onPlayerJoin`.
237
239
  - `session.hub.push` is optional, present only for a place declaring
238
240
  `hub.push: { version: 1 }` on a capable runtime. Its
239
- `visit(playerId, { userId, timezone })` reports a visit with the captured
240
- authenticated account and an IANA timezone. It returns a boolean acknowledgement.
241
+ `visit(playerId, { userId, timezone, phase? })` reports visit facts with the captured
242
+ authenticated account and an IANA timezone. Absent `phase` starts a visit as before;
243
+ its only optional value, `"end"` (v1.189), reports the end. The place server
244
+ remembers the account and timezone only after a start returns `true`, then sends
245
+ an end once from `leave` (at forget for a retained resume player, not backgrounding)
246
+ or for every remembered player at layer shutdown, and clears the entry.
247
+ It returns `true` only for `accepted === true`; errors and refusals return `false`.
248
+ Ignore `false` and never retry. An old host-agent or Ghost answers `false` for
249
+ an end, and Ghost derives from the start. Ghost keeps the latest end per user,
250
+ place and join generation, dropping an end older than the start or from an old
251
+ generation. Landing order: Ghost first, then the host-agent, then the deck save.
241
252
  Ghost derives the three-day come-back reminder and checks consent, answered
242
253
  age, experiments, quiet hours and delivery limits. Reporting a visit does not
243
254
  opt the player in or promise a notification. No crop reporting or queue
244
- reconciliation API is exposed.
255
+ reconciliation API is exposed. On a runtime with preferences it also has
256
+ `preference(playerId, change)`: `{}` reads, `{ enabled: boolean }` sets
257
+ consent and `{ declined: true }` records a declined prompt. It returns
258
+ `{ accepted: true, enabled, globalEnabled, touched, milestone, nextPromptAt }`
259
+ or `null` when refused or unavailable, and never throws. `touched` says the
260
+ player has ever set this place's preference; `nextPromptAt` is non-null once
261
+ they declined or disabled. Consent is checked again by Ghost on delivery.
245
262
  - `session.hub.reportResult(playerId, { outcome?, score?, stats? })` records a
246
263
  signed-in player's result for this visit, once. The host checks it against the
247
264
  published shape and Castle keeps it only for a place behind a curated door;
@@ -322,6 +339,9 @@ arms the player's page reads and nothing a client can claim.
322
339
  such experiment.
323
340
  - `session.experiments(player)` is all of them, `{ name: variant }`.
324
341
 
342
+ The first `session.experiment` of each name for a player's join records an
343
+ exposure, as the client's first read does; `session.experiments` records none.
344
+
325
345
  Both answer from `onPlayerJoin` until the player leaves, and `null` / `{}`
326
346
  after. The variants are never on the player object, so a roster or state built
327
347
  from `session.players` does not show one player's arm to another; send a variant
@@ -1096,9 +1116,14 @@ in no such experiment: the deck does not declare it, it was removed, or the host
1096
1116
  is an older one that knows nothing of experiments. Always give `null` a
1097
1117
  behavior, normally the one the deck had before the test.
1098
1118
 
1119
+ The first read of each name that returns a variant also records an exposure,
1120
+ the moment the player was shown that arm, for the deck's analytics. Read it
1121
+ where the variant changes what the player sees, not up front.
1122
+
1099
1123
  ### `experiments(): Record<string, string>`
1100
1124
 
1101
- Every experiment this player is in on this deck, as `{ name: variant }`.
1125
+ Every experiment this player is in on this deck, as `{ name: variant }`. It
1126
+ records no exposure.
1102
1127
 
1103
1128
  ### `experimentsReady(): Promise<Record<string, string>>`
1104
1129
 
@@ -1116,10 +1141,64 @@ assigned to you exactly as they will be once the deck is saved. Add
1116
1141
  experiment and one of its variants); it holds for the whole serve, client and
1117
1142
  local server alike, until `?experiment.<name>=` clears it or the serve stops.
1118
1143
  An open deck page keeps the arm it loaded with until it is reloaded.
1119
- Nothing published reads that parameter. `devExperiments` in `castle.json`, a
1144
+ On a published deck the same parameter on the deck's page forces an arm for the
1145
+ deck's owner only, for a day; see [docs/ab-tests.md](../docs/ab-tests.md#try-an-arm-on-the-published-deck).
1146
+ `devExperiments` in `castle.json`, a
1120
1147
  `{ "name": "variant" }` map, answers for experiments the deck does not declare
1121
1148
  itself (ones Castle runs across decks), on the serve only.
1122
1149
 
1150
+ ## Analytics
1151
+
1152
+ A deck's own named events, recorded in its creator analytics beside Castle's
1153
+ built-in ones (plays, play time, players who come back).
1154
+
1155
+ ```js
1156
+ import { Analytics } from "castle-web-sdk";
1157
+
1158
+ Analytics.event("level_complete", { level: 3, seconds: 41 });
1159
+ ```
1160
+
1161
+ ### `Analytics.event(name, properties?): void`
1162
+
1163
+ Records one event for the player. Synchronous and fire and forget: it returns
1164
+ nothing, and a host that cannot record it (an older one, or no network) drops
1165
+ it without the deck noticing.
1166
+
1167
+ - `name` is trimmed, then 1 to 64 characters of letters, digits, space and
1168
+ `_ . : / -`, starting with a letter or digit.
1169
+ - `properties` is optional: a plain object of at most 5 keys, each 1 to 32
1170
+ characters under the same rule, whose values are finite numbers. Castle stores
1171
+ each as a whole number (rounded).
1172
+ - A bad name or properties throws a `TypeError` at the call, so a mistake shows
1173
+ up while you build the deck.
1174
+ - At most 60 events a minute per page load; the rest are dropped, with one
1175
+ console warning the first time.
1176
+
1177
+ **An event has to be registered before players' events are kept.** Castle keeps
1178
+ a list of event types per creator, up to 100 across all of a creator's decks.
1179
+ When the deck's creator plays the published deck, each `Analytics.event` call
1180
+ registers its name, with its property keys in the order the call gives them;
1181
+ the creator's own plays are not counted. After that, players' events with that
1182
+ name are recorded, carrying the properties the type names. A player's event
1183
+ under a name the creator never registered is dropped, as are property keys the
1184
+ type does not name. So play every path that sends an event once, signed in as
1185
+ the deck's owner, after saving the deck.
1186
+
1187
+ Registration is limited: at most 20 registrations per creator per hour (a new
1188
+ name, or a property key added to an existing name, each counts as one), and at
1189
+ most 100 event types per creator. A call past either limit registers nothing,
1190
+ so the name stays unregistered and players' events under it are dropped until
1191
+ the creator plays it again after the hour has passed. To see what is registered, the `creatorEventTypes` query in Castle's API
1192
+ lists the creator's event types with their property names, in slot order;
1193
+ `createCreatorEventType` registers one directly.
1194
+
1195
+ Only a published deck records events: on `castle-web serve` of a deck that was
1196
+ never saved, `Analytics.event` validates its arguments and sends nothing.
1197
+
1198
+ Each event carries the player's experiment arms, like the built-in events, so
1199
+ `creatorEventStats` with `splitBy: EXPERIMENT` reads custom events per variant;
1200
+ see [Measure a variant with your own events](../docs/ab-tests.md#measure-a-variant-with-your-own-events).
1201
+
1123
1202
  ## Avatar
1124
1203
 
1125
1204
  The player's platform avatar: one per account, worn in every hub place
@@ -1368,6 +1447,14 @@ With `canInvite: true`, newer hosts also name the account the links belong to
1368
1447
  account is the player's own, and checks `User.getCurrent()` when a host names
1369
1448
  none.
1370
1449
 
1450
+ `Hub.inviteAvailable()` takes no parameters and reads the authenticated viewer's
1451
+ invite gate through the trusted, invite-enabled hub visit. It answers
1452
+ `{ status: 'ok', available: boolean }`, or `{ status: 'unavailable' }` when the
1453
+ viewer is signed out or anonymous, the visit or invite opt-in is absent, the
1454
+ read fails, or the host predates the command. It creates no invite and exposes
1455
+ no gate map. The opt-in Character entry also requires `available: true`;
1456
+ pending, false and unavailable answers keep it hidden.
1457
+
1371
1458
  The trusted host resolves the link after sign-in, retains its token, and requests
1372
1459
  the inviter's layer when it has room. If resolution refuses the invite, the host
1373
1460
  discards it for that visit and joins normally. Transient resolution failures
@@ -1407,6 +1494,19 @@ the signed-in account id. A new host without native sign-in support returns
1407
1494
  `unavailable`; an older host that does not know this command rejects with
1408
1495
  `UNKNOWN_COMMAND`.
1409
1496
 
1497
+ `Hub.pushPermission()` (hub contract v1.177) may ask the native host to request
1498
+ OS notification permission. Call it only from a deliberate tap after the player
1499
+ committed to something worth a reminder. It waits for the player's answer and
1500
+ resolves to `{ status: 'granted' | 'denied' | 'unavailable' }`.
1501
+ `Hub.pushDestination()` reads, once, the native push hint that opened the app
1502
+ into this town: `{ notificationId, townDeckId }` or `{ status: 'unavailable' }`.
1503
+ On mobile the SDK acknowledges a delivered hint back to the host as soon as it
1504
+ resolves the call; a deck does nothing extra. Both take no arguments and answer
1505
+ `unavailable` on web, for a signed-out player, outside a joined session, or
1506
+ where the host does not offer hub notifications. A host that predates them
1507
+ (`UNKNOWN_COMMAND`) or no reachable host (`CASTLE_HOST_UNAVAILABLE`) also reads
1508
+ as `unavailable`; any other failure rejects with its `CastleError`.
1509
+
1410
1510
  - `Hub.doors()` reads the current place's doors and who is inside them:
1411
1511
  `{ status: "ok", doors }` or `{ status: "unavailable", doors: null }`. A row has
1412
1512
  `doorId`, `launcherKind` (`door`, `table`, `cabinet`, `gate`), `placementKind`
@@ -1470,6 +1570,14 @@ the signed-in account id. A new host without native sign-in support returns
1470
1570
  `Hub.go(doorId)` (with `{ ownerUserId: owner }` when set) behind its door
1471
1571
  animation. Hosts that never send it are the norm. Returns an unsubscribe
1472
1572
  function.
1573
+ - `Hub.goFailed({ doorId, owner }, why)` tells the host that a Go it sent
1574
+ (`Hub.onGo`) ended without the player going through: `why` is `"refused"`
1575
+ (`Hub.go` gave no handoff), `"content"` (the destination's content would not
1576
+ load) or `"join"` (the join was never committed). Call it at most once per
1577
+ Go, and not for a join the host committed. A host that acquired the door
1578
+ from its own session may acquire it again there and send a fresh Go; do not
1579
+ ask `Hub.go` again yourself. One-way: nothing answers it, and older hosts
1580
+ ignore it.
1473
1581
 
1474
1582
  A player Castle has barred from the hub is refused at every hub door and at the
1475
1583
  town itself with `CastleError` code `CAULDRON_HUB_BANNED` (from `Hub.go`,
@@ -1868,6 +1976,44 @@ deck's preferred display orientation: `landscape`, `portrait`, or `any`.
1868
1976
  Missing or unrecognized preferences mean `any`; read the value as
1869
1977
  `display.orientation ?? "any"`.
1870
1978
 
1979
+ ## DebugConsole
1980
+
1981
+ A published deck's `console` output never reaches devtools: on
1982
+ castle.xyz the deck runs in a sandboxed frame of its own, and in the
1983
+ app it runs in a WebView. `DebugConsole` draws the deck's console as a
1984
+ panel along the bottom of the deck itself, so it can be read on the
1985
+ device the deck is running on.
1986
+
1987
+ - **`DebugConsole.show()`** — opens the panel. It holds the last 300
1988
+ lines of `console.log`, `console.warn` and `console.error`, plus
1989
+ uncaught errors and unhandled promise rejections. After
1990
+ [`setup()`](#setup) that includes everything since the deck started;
1991
+ in a deck that never calls `setup()`, only what comes after the first
1992
+ `show()`. The panel has **Clear** and **Hide** buttons.
1993
+ - **`DebugConsole.hide()`** — closes the panel. Lines keep being
1994
+ recorded.
1995
+ - **`DebugConsole.lines(): DebugConsoleLine[]`** — the recorded lines,
1996
+ oldest first, each `{ level: "log" | "warn" | "error", text, time }`
1997
+ with `time` from `Date.now()`, for a deck that draws its own.
1998
+
1999
+ The panel covers the bottom of the deck and takes touches there, so
2000
+ open it from a gesture or a debug option the deck controls, and remove
2001
+ that before the deck is for players:
2002
+
2003
+ ```js
2004
+ import { DebugConsole } from "castle-web-sdk";
2005
+
2006
+ // Three fingers on the card toggles the console.
2007
+ let open = false;
2008
+ window.addEventListener("touchstart", (event) => {
2009
+ if (event.touches.length === 3) {
2010
+ open = !open;
2011
+ if (open) DebugConsole.show();
2012
+ else DebugConsole.hide();
2013
+ }
2014
+ });
2015
+ ```
2016
+
1871
2017
  ## Setup
1872
2018
 
1873
2019
  Startup, editor-mode check, and a file-write call for editor UI.
@@ -1883,6 +2029,17 @@ While running locally with `castle-web serve`, it also forwards
1883
2029
  `console` output to the CLI and reloads the page when `castle-web
1884
2030
  restart` runs.
1885
2031
 
2032
+ `setup()` also keeps `history.pushState` and `history.replaceState`
2033
+ from throwing in a deck published on castle.xyz. There the deck's frame
2034
+ has no origin of its own, and a call that passes a URL throws a
2035
+ `SecurityError`; after
2036
+ `setup()` the call adds or replaces the history entry with its state
2037
+ but leaves the address as it was. A router that keeps its route in the
2038
+ address won't see it change; keep the route in the state or in the
2039
+ deck's own variables. `localStorage` throws there too; use
2040
+ [`LocalCache`](#localcache) for things the deck can rebuild and
2041
+ [`Store`](#store) for everything else.
2042
+
1886
2043
  ```js
1887
2044
  import { setup } from "castle-web-sdk";
1888
2045
 
@@ -0,0 +1,8 @@
1
+ export interface CastleAnalyticsApi {
2
+ /**
3
+ * Records one named event, with up to five numeric properties, for the deck's
4
+ * creator analytics. Synchronous and fire and forget.
5
+ */
6
+ event(name: string, properties?: Record<string, number>): void;
7
+ }
8
+ export declare const Analytics: CastleAnalyticsApi;
@@ -0,0 +1,92 @@
1
+ // Analytics — a deck's own named events, recorded in its creator analytics.
2
+ //
3
+ // Analytics.event("level_complete", { level: 3, seconds: 41 });
4
+ //
5
+ // Fire and forget: the call validates its arguments synchronously (a bad name
6
+ // or properties shape is a coding error, so it throws a TypeError the author
7
+ // sees in dev) and then tells the host, which records the event for a published
8
+ // deck's real players. Nothing is returned and nothing is awaited: an older host
9
+ // refuses the unknown command and a failed report never reaches the deck.
10
+ //
11
+ // Castle keeps a registry per creator: the deck's creator playing the deck
12
+ // registers each event name with its property keys, and a player's event under
13
+ // a name that is not registered is dropped. Each row carries the player's
14
+ // experiment arms, so creator analytics can split custom events by experiment.
15
+ import { hostRequest } from "./transport";
16
+ export const Analytics = {
17
+ event,
18
+ };
19
+ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 _.:/-]*$/;
20
+ const MAX_NAME_LENGTH = 64;
21
+ const MAX_KEY_LENGTH = 32;
22
+ const MAX_PROPERTIES = 5;
23
+ const RATE_LIMIT = 60;
24
+ const RATE_WINDOW_MS = 60_000;
25
+ // When each recent event was sent, oldest first, for the rolling-minute limit.
26
+ const sentAt = [];
27
+ let warnedRateLimit = false;
28
+ function event(name, properties) {
29
+ const trimmed = checkName(name);
30
+ const props = checkProperties(properties);
31
+ if (!admit())
32
+ return;
33
+ try {
34
+ void hostRequest("analytics.event", { name: trimmed, properties: props }).catch(() => { });
35
+ }
36
+ catch {
37
+ // No host to tell.
38
+ }
39
+ }
40
+ function checkName(name) {
41
+ if (typeof name !== "string") {
42
+ throw new TypeError("Analytics.event name must be a string.");
43
+ }
44
+ const trimmed = name.trim();
45
+ if (trimmed.length === 0 || trimmed.length > MAX_NAME_LENGTH || !NAME_PATTERN.test(trimmed)) {
46
+ throw new TypeError(`Analytics.event name must be 1 to ${MAX_NAME_LENGTH} characters of letters, digits, ` +
47
+ "space, _ . : / and -, starting with a letter or digit.");
48
+ }
49
+ return trimmed;
50
+ }
51
+ function checkProperties(properties) {
52
+ if (properties === undefined || properties === null)
53
+ return {};
54
+ if (typeof properties !== "object" || Array.isArray(properties)) {
55
+ throw new TypeError("Analytics.event properties must be a plain object of numbers.");
56
+ }
57
+ const proto = Object.getPrototypeOf(properties);
58
+ if (proto !== Object.prototype && proto !== null) {
59
+ throw new TypeError("Analytics.event properties must be a plain object of numbers.");
60
+ }
61
+ const entries = Object.entries(properties);
62
+ if (entries.length > MAX_PROPERTIES) {
63
+ throw new TypeError(`Analytics.event takes at most ${MAX_PROPERTIES} properties.`);
64
+ }
65
+ for (const [key, value] of entries) {
66
+ if (key.length > MAX_KEY_LENGTH || !NAME_PATTERN.test(key)) {
67
+ throw new TypeError(`Analytics.event property "${key}" must be 1 to ${MAX_KEY_LENGTH} characters, ` +
68
+ "following the same rule as an event name.");
69
+ }
70
+ if (typeof value !== "number" || !Number.isFinite(value)) {
71
+ throw new TypeError(`Analytics.event property "${key}" must be a finite number.`);
72
+ }
73
+ }
74
+ return Object.fromEntries(entries);
75
+ }
76
+ // At most RATE_LIMIT events in any rolling RATE_WINDOW_MS per page load; the
77
+ // rest are dropped, with one warning the first time.
78
+ function admit() {
79
+ const now = Date.now();
80
+ while (sentAt.length > 0 && now - sentAt[0] >= RATE_WINDOW_MS)
81
+ sentAt.shift();
82
+ if (sentAt.length >= RATE_LIMIT) {
83
+ if (!warnedRateLimit) {
84
+ warnedRateLimit = true;
85
+ console.warn(`Castle Analytics.event is limited to ${RATE_LIMIT} events a minute; ` +
86
+ "events past that are dropped.");
87
+ }
88
+ return false;
89
+ }
90
+ sentAt.push(now);
91
+ return true;
92
+ }
package/dist/castle.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { isEdit } from "./context";
2
2
  export { Agent } from "./agent";
3
3
  export type { AgentChatDelta, AgentChatParams, AgentChatResult, AgentMessage, AgentReasoning, AgentTool, AgentToolCall, AgentToolChoice, AgentUsage, CastleAgentApi, } from "./agent";
4
+ export { Analytics } from "./analytics";
5
+ export type { CastleAnalyticsApi } from "./analytics";
4
6
  export { Avatar } from "./avatar";
5
7
  export type { AvatarResult, CastleAvatarApi } from "./avatar";
6
8
  export { Characters } from "./characters";
@@ -13,7 +15,7 @@ export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckF
13
15
  export { Haptics } from "./haptics";
14
16
  export type { CastleHapticsApi, HapticsResult, HapticsStatus, HapticStyle } from "./haptics";
15
17
  export { Hub } from "./hub";
16
- export type { CastleHubApi, HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoParams, HubGoRequest, HubSignInParams, HubSignInResult, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, } from "./hub";
18
+ export type { CastleHubApi, HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteAvailableResult, HubInviteArrivalResult, HubHeartsResult, HubGoParams, HubGoFailedWhy, HubGoRequest, HubSignInParams, HubSignInResult, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, } from "./hub";
17
19
  export { Rooms } from "./rooms";
18
20
  export type { CastleRoomsApi, RoomSummary, RoomsListResult } from "./rooms";
19
21
  export { Social } from "./social";
@@ -44,6 +46,8 @@ export { cardUnit, fitStage, fovForAspect, getDisplay } from "./display";
44
46
  export type { DeckDisplay, DeckLayout, DeckOrientation } from "./display";
45
47
  export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
46
48
  export type { SaveState } from "./saveQueue";
49
+ export { DebugConsole } from "./debugConsole";
50
+ export type { DebugConsoleApi, DebugConsoleLevel, DebugConsoleLine } from "./debugConsole";
47
51
  export { LocalCache } from "./localCache";
48
52
  export type { LocalCacheApi } from "./localCache";
49
53
  export { SharedStorage, Storage } from "./storage";
package/dist/castle.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Castle Web SDK
2
2
  export { isEdit } from "./context";
3
3
  export { Agent } from "./agent";
4
+ export { Analytics } from "./analytics";
4
5
  export { Avatar } from "./avatar";
5
6
  export { Characters } from "./characters";
6
7
  export { Decks } from "./decks";
@@ -23,6 +24,7 @@ export { Portal } from "./portal";
23
24
  export { CARD_RATIO, deleteFile, fileUrl, initCard, onBeforeRestart, onFilesChanged, onSaveReloadState, openFile, renameFile, requestReload, setup, takeReloadState, writeFileOnce, } from "./runtime";
24
25
  export { cardUnit, fitStage, fovForAspect, getDisplay } from "./display";
25
26
  export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
27
+ export { DebugConsole } from "./debugConsole";
26
28
  export { LocalCache } from "./localCache";
27
29
  export { SharedStorage, Storage } from "./storage";
28
30
  export { Store } from "./store";
@@ -238,6 +238,15 @@ export interface HubSignInResult {
238
238
  status: "signedIn" | "dismissed" | "unavailable";
239
239
  userId?: string;
240
240
  }
241
+ export interface HubPushPermissionResult {
242
+ status: "granted" | "denied" | "unavailable";
243
+ }
244
+ export type HubPushDestinationResult = {
245
+ notificationId: string;
246
+ townDeckId: string;
247
+ } | {
248
+ status: "unavailable";
249
+ };
241
250
  export type HubFriendsResult = {
242
251
  status: "ok";
243
252
  friends: HubFriend[];
@@ -266,6 +275,13 @@ export type HubCanInviteResult = {
266
275
  status: "unavailable";
267
276
  canInvite: false;
268
277
  };
278
+ /** Viewer invite-gate availability, without exposing the gate map. */
279
+ export type HubInviteAvailableResult = {
280
+ status: "ok";
281
+ available: boolean;
282
+ } | {
283
+ status: "unavailable";
284
+ };
269
285
  export interface HubInviteArrivalResult {
270
286
  status: "ok" | "unavailable" | "route";
271
287
  doorId?: string;
@@ -393,6 +409,17 @@ export interface HubEventEnvelope {
393
409
  castleSdk: typeof CASTLE_SDK_PROTOCOL;
394
410
  hub: HubEvent;
395
411
  }
412
+ export type HubGoFailedWhy = "refused" | "content" | "join";
413
+ export type HubGoFailedEvent = {
414
+ type: "goFailed";
415
+ doorId: string;
416
+ owner?: string;
417
+ why: HubGoFailedWhy;
418
+ };
419
+ export interface HubGoFailedEnvelope {
420
+ castleSdk: typeof CASTLE_SDK_PROTOCOL;
421
+ hub: HubGoFailedEvent;
422
+ }
396
423
  export declare function hubEventFrom(value: unknown): HubEvent | null;
397
424
  export type HapticStyle = "light" | "medium" | "heavy" | "selection" | "success" | "warning" | "error";
398
425
  export type HapticsStatus = "triggered" | "unavailable";
@@ -643,6 +670,14 @@ export interface CommandParams {
643
670
  userId: string;
644
671
  };
645
672
  "experiments.get": Record<string, never>;
673
+ "experiments.exposed": {
674
+ name: string;
675
+ variant: string;
676
+ };
677
+ "analytics.event": {
678
+ name: string;
679
+ properties: Record<string, number>;
680
+ };
646
681
  "time.getServerTime": Record<string, never>;
647
682
  "pass.has": {
648
683
  passId: string;
@@ -705,6 +740,7 @@ export interface CommandParams {
705
740
  crew?: boolean;
706
741
  };
707
742
  "hub.canInvite": Record<string, never>;
743
+ "hub.inviteAvailable": Record<string, never>;
708
744
  "hub.inviteArrival": Record<string, never>;
709
745
  "hub.undoInvite": {
710
746
  userId: string;
@@ -714,6 +750,8 @@ export interface CommandParams {
714
750
  doorIds: string[];
715
751
  };
716
752
  "hub.signIn": HubSignInParams;
753
+ "hub.pushPermission": Record<string, never>;
754
+ "hub.pushDestination": Record<string, never>;
717
755
  "hub.jump": HubJumpParams;
718
756
  "hub.report": HubReportParams;
719
757
  "hub.chat": HubChatParams;
@@ -878,6 +916,12 @@ export interface CommandResult {
878
916
  "experiments.get": {
879
917
  variants: Record<string, string>;
880
918
  };
919
+ "experiments.exposed": {
920
+ recorded: boolean;
921
+ };
922
+ "analytics.event": {
923
+ recorded: boolean;
924
+ };
881
925
  "time.getServerTime": {
882
926
  timestamp: number;
883
927
  timezoneOffset: number;
@@ -915,11 +959,14 @@ export interface CommandResult {
915
959
  "hub.friends": HubFriendsResult;
916
960
  "hub.invite": HubInviteResult;
917
961
  "hub.canInvite": HubCanInviteResult;
962
+ "hub.inviteAvailable": HubInviteAvailableResult;
918
963
  "hub.inviteArrival": HubInviteArrivalResult;
919
964
  "hub.undoInvite": HubReportResult;
920
965
  "hub.hearts": HubHeartsResult;
921
966
  "hub.setHearts": HubHeartsResult;
922
967
  "hub.signIn": HubSignInResult;
968
+ "hub.pushPermission": HubPushPermissionResult;
969
+ "hub.pushDestination": HubPushDestinationResult;
923
970
  "hub.jump": HubJumpResult;
924
971
  "hub.report": HubReportResult;
925
972
  "hub.chat": HubChatResult;
@@ -1031,6 +1078,7 @@ export interface CommandResponseEnvelope {
1031
1078
  ok: boolean;
1032
1079
  data?: unknown;
1033
1080
  error?: SerializedCommandError;
1081
+ hubPushReceipt?: string;
1034
1082
  }
1035
1083
  export declare function isResponseEnvelope(value: unknown): value is CommandResponseEnvelope;
1036
1084
  export interface CommandStreamEnvelope {
package/dist/commands.js CHANGED
@@ -55,6 +55,7 @@ export const COMMAND_TIMEOUTS_MS = {
55
55
  // Native auth may include a provider handoff, but it must not leave a deck
56
56
  // waiting forever if the host loses the completion callback.
57
57
  "hub.signIn": 120_000,
58
+ "hub.pushPermission": 120_000,
58
59
  // A large entry is an IndexedDB read or write plus a copy into the other
59
60
  // frame, and can wait behind other tabs' writes to the same store.
60
61
  "localCache.get": 60_000,
@@ -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
+ };
@@ -10,12 +10,18 @@
10
10
  //
11
11
  // `null` is a normal answer: no such experiment, one that has ended, a player
12
12
  // who is not in it, or a host that predates experiments. Always handle it.
13
+ //
14
+ // The first `experiment(name)` that answers a variant also tells the host, once
15
+ // per name per page load, which records the exposure (the player was shown this
16
+ // arm) for the deck's analytics. `experiments()` reports nothing: a deck reading
17
+ // the whole map has not shown the player any one arm.
13
18
  import { getCastleEmbed } from "./context";
14
19
  import { hostRequest } from "./transport";
15
20
  const NONE = Object.freeze({});
16
21
  let variants = null;
17
22
  let loading = null;
18
23
  let warnedEarlyRead = false;
24
+ const exposed = new Set();
19
25
  /**
20
26
  * The variant this player has in `name`, or `null` when they are in no such
21
27
  * experiment. Synchronous; see `experimentsReady` for the one case where a read
@@ -23,7 +29,24 @@ let warnedEarlyRead = false;
23
29
  */
24
30
  export function experiment(name) {
25
31
  const known = current();
26
- return Object.hasOwn(known, name) ? known[name] : null;
32
+ if (!Object.hasOwn(known, name))
33
+ return null;
34
+ const variant = known[name];
35
+ reportExposure(name, variant);
36
+ return variant;
37
+ }
38
+ // Fire and forget: a host from before exposures does not know the command, and
39
+ // a failed report must never change what the deck reads.
40
+ function reportExposure(name, variant) {
41
+ if (exposed.has(name))
42
+ return;
43
+ exposed.add(name);
44
+ try {
45
+ void hostRequest("experiments.exposed", { name, variant }).catch(() => { });
46
+ }
47
+ catch {
48
+ // No host to tell.
49
+ }
27
50
  }
28
51
  /** Every experiment this player is in on this deck, `{ name: variant }`. */
29
52
  export function experiments() {
package/dist/hub.d.ts CHANGED
@@ -1,5 +1,5 @@
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";
1
+ import type { HubBackResult, HubCancelResult, HubChatResult, HubDoorsResult, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteAvailableResult, HubInviteArrivalResult, HubHeartsResult, HubGoResult, HubJumpResult, HubReportResult, HubSayResult, HubSignInResult, HubPushPermissionResult, HubPushDestinationResult, HubGoFailedWhy } from "./commands";
2
+ export type { HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteAvailableResult, HubInviteArrivalResult, HubHeartsResult, HubGoFailedWhy, HubGoParams, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, HubSignInParams, HubSignInResult, HubPushPermissionResult, HubPushDestinationResult, } 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
@@ -14,6 +14,10 @@ export type { HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, H
14
14
  * ticket is written. A failure before then leaves the player where they were.
15
15
  */
16
16
  export interface CastleHubApi {
17
+ /** Deliberate user action after a committed personal promise; native hosts may ask OS permission. */
18
+ pushPermission(): Promise<HubPushPermissionResult>;
19
+ /** One-time native push hint after authenticated town join. */
20
+ pushDestination(): Promise<HubPushDestinationResult>;
17
21
  /**
18
22
  * Acquire the destination behind a door of the current place. A door used
19
23
  * within seconds of arriving may take up to 15 s while ghost catches up with
@@ -50,6 +54,8 @@ export interface CastleHubApi {
50
54
  * command rejects it, so treat anything but `canInvite: true` as no.
51
55
  */
52
56
  canInvite(): Promise<HubCanInviteResult>;
57
+ /** Read the authenticated viewer's invite gate; old hosts answer unavailable. */
58
+ inviteAvailable(): Promise<HubInviteAvailableResult>;
53
59
  /** Hub-kit arrival hook: the trusted host retains the invite token. */
54
60
  inviteArrival(): Promise<HubInviteArrivalResult>;
55
61
  /** Undo both follow directions for one pair from this host's invite arrival. */
@@ -122,6 +128,18 @@ export interface CastleHubApi {
122
128
  * that never send it are the norm. Returns an unsubscribe function.
123
129
  */
124
130
  onGo(listener: (go: HubGoRequest) => void): () => void;
131
+ /**
132
+ * Tell the host that a Go it sent (`onGo`) ended without the player going
133
+ * through the door: `why` is `"refused"` (`go` gave no handoff),
134
+ * `"content"` (the destination's content would not load) or `"join"` (the
135
+ * join was never committed). A host that acquired the door from its own
136
+ * session may acquire it again there and send a fresh Go. One-way: nothing
137
+ * answers it, and hosts that predate it ignore it.
138
+ */
139
+ goFailed(go: {
140
+ doorId: string;
141
+ owner?: string | null;
142
+ }, why: HubGoFailedWhy): void;
125
143
  }
126
144
  /** A host's request to go through a door (see `Hub.onGo`). */
127
145
  export interface HubGoRequest {
package/dist/hub.js CHANGED
@@ -1,13 +1,36 @@
1
+ import { HUB_GO_DOOR_ID_MAX } from "./commands";
1
2
  import { CastleError } from "./errors";
2
- import { hostRequest, setHubEventHandler } from "./transport";
3
+ import { hostNotifyHub, hostRequest, setHubEventHandler } from "./transport";
3
4
  import { HUB_FORBIDDEN_RETRY_MS, rejoinedRecently } from "./hubRejoin";
5
+ // Hub contract v1.177: a host that predates these commands answers
6
+ // UNKNOWN_COMMAND, and no host at all (no bridge, an unreachable dev server, a
7
+ // timeout) surfaces CASTLE_HOST_UNAVAILABLE. Both read as unavailable to a
8
+ // deck; every other failure still rejects.
9
+ const HUB_PUSH_UNAVAILABLE_CODES = new Set([
10
+ "UNKNOWN_COMMAND",
11
+ "CASTLE_HOST_UNAVAILABLE",
12
+ ]);
13
+ async function hubPushRequest(command) {
14
+ try {
15
+ return await hostRequest(command, {});
16
+ }
17
+ catch (error) {
18
+ if (error instanceof CastleError && HUB_PUSH_UNAVAILABLE_CODES.has(error.code)) {
19
+ return { status: "unavailable" };
20
+ }
21
+ throw error;
22
+ }
23
+ }
4
24
  export const Hub = {
25
+ pushPermission: () => hubPushRequest("hub.pushPermission"),
26
+ pushDestination: () => hubPushRequest("hub.pushDestination"),
5
27
  go,
6
28
  back,
7
29
  doors,
8
30
  friends,
9
31
  invite,
10
32
  canInvite,
33
+ inviteAvailable,
11
34
  inviteArrival,
12
35
  undoInvite,
13
36
  hearts,
@@ -21,6 +44,7 @@ export const Hub = {
21
44
  cancel,
22
45
  onBack,
23
46
  onGo,
47
+ goFailed,
24
48
  };
25
49
  async function go(doorId, options = {}) {
26
50
  if (typeof doorId !== "string" || doorId.length === 0) {
@@ -72,6 +96,17 @@ async function invite(options = {}) {
72
96
  async function canInvite() {
73
97
  return hostRequest("hub.canInvite", {});
74
98
  }
99
+ async function inviteAvailable() {
100
+ try {
101
+ const answer = await hostRequest("hub.inviteAvailable", {});
102
+ return answer?.status === "ok" && typeof answer.available === "boolean"
103
+ ? { status: "ok", available: answer.available }
104
+ : { status: "unavailable" };
105
+ }
106
+ catch {
107
+ return { status: "unavailable" };
108
+ }
109
+ }
75
110
  async function inviteArrival() {
76
111
  return hostRequest("hub.inviteArrival", {});
77
112
  }
@@ -155,6 +190,21 @@ async function cancel() {
155
190
  cancels += 1;
156
191
  return hostRequest("hub.cancel", {});
157
192
  }
193
+ const GO_FAILED_WHYS = ["refused", "content", "join"];
194
+ function goFailed(go, why) {
195
+ const doorId = go?.doorId;
196
+ const owner = go?.owner ?? undefined;
197
+ if (typeof doorId !== "string" || doorId.length === 0 || doorId.length > HUB_GO_DOOR_ID_MAX ||
198
+ (owner !== undefined && (typeof owner !== "string" || !/^[1-9]\d{0,9}$/.test(owner))) ||
199
+ !GO_FAILED_WHYS.includes(why)) {
200
+ throw new CastleError({
201
+ code: "INVALID_ARGUMENT",
202
+ message: "Hub.goFailed requires a Go's doorId, its owner if any, and why it failed.",
203
+ operation: "Hub.goFailed",
204
+ });
205
+ }
206
+ hostNotifyHub({ type: "goFailed", doorId, ...(owner !== undefined ? { owner } : {}), why });
207
+ }
158
208
  const backListeners = new Set();
159
209
  const goListeners = new Set();
160
210
  function onBack(listener) {
@@ -5,9 +5,11 @@ export declare class ReconnectBudget {
5
5
  private wokeSinceAttempt;
6
6
  private gapGraceUsed;
7
7
  private frozen;
8
+ private offline;
8
9
  private disposed;
9
10
  private readonly waiters;
10
11
  private readonly page;
12
+ private readonly host;
11
13
  constructor();
12
14
  get elapsedMs(): number;
13
15
  noteAttempt(): void;
@@ -16,6 +18,8 @@ export declare class ReconnectBudget {
16
18
  dispose(): void;
17
19
  private readonly freeze;
18
20
  private readonly resume;
21
+ private readonly goOffline;
22
+ private readonly goOnline;
19
23
  private readonly update;
20
24
  private readonly observe;
21
25
  private stop;
@@ -3,6 +3,15 @@
3
3
  // Not every suspension is announced (a debugger pause, a native app pausing
4
4
  // its web view while the document stays visible), so active time accrues in
5
5
  // heartbeat steps and a gap longer than one step counts only that step.
6
+ //
7
+ // Time the browser reports offline does not accrue either: a network drop
8
+ // with the page visible would otherwise spend the whole budget on attempts
9
+ // that fail instantly, and the player rejoins fresh while the host still
10
+ // holds their identity. Offline only pauses the clock; attempts continue at
11
+ // the normal backoff, because navigator.onLine can be wrong (some WebViews
12
+ // and captive networks report false while sockets work) and a wrong flag must
13
+ // never stop a reconnect. If the player stays away past the host's hold, the
14
+ // host refuses the token and recovery ends on that, not on this budget.
6
15
  const HEARTBEAT_MS = 1_000;
7
16
  const MAX_STEP_MS = 2_000;
8
17
  export class ReconnectBudget {
@@ -15,13 +24,24 @@ export class ReconnectBudget {
15
24
  // frames for minutes would otherwise renew it forever.
16
25
  gapGraceUsed = false;
17
26
  frozen = false;
27
+ offline = false;
18
28
  disposed = false;
19
29
  waiters = new Set();
20
30
  page = typeof document === "undefined" ? null : document;
31
+ // Where online/offline arrive: the window, or a worker's own global. With
32
+ // neither, a change of navigator.onLine cannot be seen, so it is not trusted.
33
+ host = typeof window !== "undefined"
34
+ ? window
35
+ : typeof globalThis.addEventListener === "function"
36
+ ? globalThis
37
+ : null;
21
38
  constructor() {
22
39
  this.page?.addEventListener("visibilitychange", this.update);
23
40
  this.page?.addEventListener("freeze", this.freeze);
24
41
  this.page?.addEventListener("resume", this.resume);
42
+ this.host?.addEventListener?.("offline", this.goOffline);
43
+ this.host?.addEventListener?.("online", this.goOnline);
44
+ this.offline = this.host !== null && typeof navigator !== "undefined" && navigator?.onLine === false;
25
45
  this.update();
26
46
  }
27
47
  get elapsedMs() {
@@ -47,6 +67,8 @@ export class ReconnectBudget {
47
67
  this.page?.removeEventListener("visibilitychange", this.update);
48
68
  this.page?.removeEventListener("freeze", this.freeze);
49
69
  this.page?.removeEventListener("resume", this.resume);
70
+ this.host?.removeEventListener?.("offline", this.goOffline);
71
+ this.host?.removeEventListener?.("online", this.goOnline);
50
72
  this.wakeWaiters();
51
73
  }
52
74
  freeze = () => {
@@ -57,6 +79,19 @@ export class ReconnectBudget {
57
79
  this.frozen = false;
58
80
  this.update();
59
81
  };
82
+ // Each edge settles the time before it at the old state.
83
+ goOffline = () => {
84
+ this.observe();
85
+ this.offline = true;
86
+ };
87
+ // Coming back online is a return like the foreground: one try with the token.
88
+ goOnline = () => {
89
+ if (!this.offline)
90
+ return;
91
+ this.observe();
92
+ this.offline = false;
93
+ this.wokeSinceAttempt = true;
94
+ };
60
95
  update = () => {
61
96
  const active = !this.disposed && !this.frozen && this.page?.visibilityState !== "hidden";
62
97
  if (active && this.lastSeen === null) {
@@ -78,7 +113,8 @@ export class ReconnectBudget {
78
113
  this.gapGraceUsed = true;
79
114
  this.wokeSinceAttempt = true;
80
115
  }
81
- this.elapsed += Math.min(Math.max(gap, 0), MAX_STEP_MS);
116
+ if (!this.offline)
117
+ this.elapsed += Math.min(Math.max(gap, 0), MAX_STEP_MS);
82
118
  this.lastSeen = now;
83
119
  };
84
120
  stop() {
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.
@@ -178,6 +178,21 @@ export interface MultiplayerHubResultsRead {
178
178
  players: Record<string, MultiplayerHubPlayerResults>;
179
179
  boards: Record<string, MultiplayerHubBoard>;
180
180
  }
181
+ export type MultiplayerHubPushPreferenceChange = Record<string, never> | {
182
+ enabled: boolean;
183
+ } | {
184
+ declined: true;
185
+ };
186
+ export interface MultiplayerHubPushPreference {
187
+ accepted: true;
188
+ enabled: boolean;
189
+ globalEnabled: boolean;
190
+ /** The player has ever set this place's reminder preference. */
191
+ touched: boolean;
192
+ milestone?: unknown;
193
+ /** Non-null once the player declined or disabled. */
194
+ nextPromptAt: number | null;
195
+ }
181
196
  /**
182
197
  * The hub place this session runs, as ghost pinned it from the deck's published
183
198
  * castle.json `hub` block. `session.hub` is null on a host without hub support
@@ -186,10 +201,14 @@ export interface MultiplayerHubResultsRead {
186
201
  export interface MultiplayerServerHub {
187
202
  /** Present only for an enabled place on a capable runtime. Reports visits; Ghost owns comeback delivery. */
188
203
  readonly push?: {
204
+ /** Absent phase starts a visit; `end` reports its end once, without retry. */
189
205
  visit(playerId: string, visit: {
190
206
  userId: string;
191
207
  timezone: string;
208
+ phase?: "end";
192
209
  }): Promise<boolean>;
210
+ /** Present only on a runtime with preferences. `{}` reads; null when refused or unavailable. */
211
+ preference?(playerId: string, change: MultiplayerHubPushPreferenceChange): Promise<MultiplayerHubPushPreference | null>;
193
212
  };
194
213
  /** Durably appends NPC words to a private platform archive. No read operation. */
195
214
  archiveText(playerId: string, entry: {
@@ -233,10 +233,22 @@ async function pushVisitCall(call, playerId, args) {
233
233
  return false;
234
234
  }
235
235
  }
236
+ async function pushPreferenceCall(call, playerId, args) {
237
+ try {
238
+ const answer = JSON.parse(await call(JSON.stringify({ ...args, playerId })));
239
+ return answer?.accepted === true ? answer : null;
240
+ }
241
+ catch {
242
+ return null;
243
+ }
244
+ }
236
245
  function pushCapability(handle) {
237
246
  if (handle.hub?.push?.version !== 1 || typeof handle.hubPushVisit !== "function")
238
247
  return {};
239
248
  return { push: {
240
249
  visit: (playerId, visit) => pushVisitCall((raw) => handle.hubPushVisit(raw), playerId, visit),
250
+ ...(typeof handle.hubPushPreference === "function"
251
+ ? { preference: (playerId, change) => pushPreferenceCall((raw) => handle.hubPushPreference(raw), playerId, change) }
252
+ : {}),
241
253
  } };
242
254
  }
@@ -100,6 +100,7 @@ export interface PlatformHandle {
100
100
  /** Friends among candidates (hub contract v1.36); older images use storage. */
101
101
  hubFriendsAmong?(argsJson: string): Promise<string>;
102
102
  hubPushVisit?(argsJson: string): Promise<string>;
103
+ hubPushPreference?(argsJson: string): Promise<string>;
103
104
  /** Absent on a runtime older than wearables (contract v1.4). */
104
105
  hubWear?(argsJson: string): Promise<string>;
105
106
  /** Absent on a runtime older than earned items (contract v1.53). */
@@ -8,7 +8,7 @@ export { createSaveCoordinator } from "../saveCoordinator";
8
8
  export type { CoordinatedChange, CoordinatedSave, SaveCoordinator, SaveStatus, } from "../saveCoordinator";
9
9
  export { SaveError } from "../save";
10
10
  export type { SaveApi, SaveBucketApi, SaveBucketRead, SaveChange, SaveCheck, SaveConditionalCheck, SaveConditionalWriteInput, SaveResetFence, SaveClaimed, SaveClaimInput, SaveErrorEnvelope, SaveInitial, SaveInitializeInput, SaveOpened, SaveOperation, SaveReadTarget, SaveReceipt, SaveRecentOperationsInput, SaveRecentOperationsPage, SaveRevision, SaveRows, SaveScope, SaveSelection, SaveSnapshot, SaveTarget, SaveTransactionInput, SaveWriter, } from "../save";
11
- export type { MultiplayerHubArrival, MultiplayerHubBoard, MultiplayerHubOutcome, MultiplayerHubPadUpdateInput, MultiplayerHubPadUpdateResult, MultiplayerHubPlayerResults, MultiplayerHubRecord, MultiplayerHubReportReceipt, MultiplayerHubResultInput, MultiplayerHubResultRow, MultiplayerHubResultShape, MultiplayerHubResultsRead, MultiplayerHubResultsReadInput, MultiplayerHubWearable, MultiplayerHubWearReceipt, MultiplayerHubEarnedClass, MultiplayerHubEarnedItem, MultiplayerHubHomeClass, MultiplayerHubHomeItem, MultiplayerHubUnlockReceipt, MultiplayerHubUnlocksRead, MultiplayerHubWearEarnedReceipt, MultiplayerServerHub, } from "./hub";
11
+ export type { MultiplayerHubArrival, MultiplayerHubBoard, MultiplayerHubOutcome, MultiplayerHubPadUpdateInput, MultiplayerHubPadUpdateResult, MultiplayerHubPlayerResults, MultiplayerHubPushPreference, MultiplayerHubPushPreferenceChange, MultiplayerHubRecord, MultiplayerHubReportReceipt, MultiplayerHubResultInput, MultiplayerHubResultRow, MultiplayerHubResultShape, MultiplayerHubResultsRead, MultiplayerHubResultsReadInput, MultiplayerHubWearable, MultiplayerHubWearReceipt, MultiplayerHubEarnedClass, MultiplayerHubEarnedItem, MultiplayerHubHomeClass, MultiplayerHubHomeItem, MultiplayerHubUnlockReceipt, MultiplayerHubUnlocksRead, MultiplayerHubWearEarnedReceipt, MultiplayerServerHub, } from "./hub";
12
12
  export type { CharacterActionNotice, CharacterGameStateOperation, CharacterGameStateResult, CharacterKnowledgeDeliveryOperation, CharacterKnowledgeDeliveryResult, CharacterKnowledgeSource, CompleteCharacterBeatInput, DeliverCharacterKnowledgeInput, RecordCharacterEventInput, SetCharacterGameStateInput, ShareCharacterClaimInput, ServerStorage, ServerStorageBoard, ServerStorageBoardScore, ServerStorageListEntry, ServerStorageListOptions, ServerStorageListPage, ServerPlaythrough, ServerPlaythroughCharacters, ServerCharacterHistoryOptions, ServerStorageScope, ServerTownStorage, } from "./storage";
13
13
  export interface MultiplayerServerPlayer extends PlayerIdentity {
14
14
  playerId: string;
@@ -210,6 +210,28 @@ async function bootSession(platformHandle, callbacks) {
210
210
  }
211
211
  }
212
212
  function createAuthorSession(platformHandle, players, arrivals, hidden, variants) {
213
+ // Each join's arms -> the names already reported for it, so a rejoin reports
214
+ // again and a leave needs no cleanup.
215
+ const exposed = new WeakMap();
216
+ // The first read of `name` for one join tells the host, which stamps the
217
+ // player and records the exposure (the arm the player was shown) for the deck's
218
+ // analytics. Fire and forget: a host from before exposures refuses the unknown
219
+ // operation, and a report must never change what the deck reads.
220
+ const reportExposure = (player, known, name) => {
221
+ let names = exposed.get(known);
222
+ if (!names)
223
+ exposed.set(known, (names = new Set()));
224
+ if (names.has(name) || typeof platformHandle.storage !== "function")
225
+ return;
226
+ names.add(name);
227
+ const playerId = typeof player === "string" ? player : player.playerId;
228
+ try {
229
+ void Promise.resolve(platformHandle.storage("experimentExposure", JSON.stringify({ playerId, experiment: name, variant: known[name] }))).catch(() => { });
230
+ }
231
+ catch {
232
+ // Same as a refusal.
233
+ }
234
+ };
213
235
  // Lenient about what it is handed: an unknown player is in no experiment.
214
236
  const variantsOf = (player) => variants.get(typeof player === "string"
215
237
  ? player
@@ -241,7 +263,10 @@ function createAuthorSession(platformHandle, players, arrivals, hidden, variants
241
263
  hub,
242
264
  experiment(player, name) {
243
265
  const known = variantsOf(player);
244
- return known && Object.hasOwn(known, name) ? known[name] : null;
266
+ if (!known || !Object.hasOwn(known, name))
267
+ return null;
268
+ reportExposure(player, known, name);
269
+ return known[name];
245
270
  },
246
271
  experiments(player) {
247
272
  return { ...variantsOf(player) };
@@ -1,4 +1,4 @@
1
- import { type CommandName, type CommandParams, type CommandResult, type HubEvent, type LifecycleEvent, type VoiceEvent } from "./commands";
1
+ import { type CommandName, type CommandParams, type CommandResult, type HubEvent, type HubGoFailedEvent, type LifecycleEvent, type VoiceEvent } from "./commands";
2
2
  type PostChannel = "mobile" | "web";
3
3
  export interface HostStreamOptions {
4
4
  onStream?: (event: unknown) => void;
@@ -19,6 +19,7 @@ declare global {
19
19
  export declare function hostRequest<C extends CommandName>(command: C, params: CommandParams[C], stream?: HostStreamOptions): Promise<CommandResult[C]>;
20
20
  export declare function getCommandChannel(): PostChannel | "local";
21
21
  export declare function hostNotify(event: LifecycleEvent): void;
22
+ export declare function hostNotifyHub(event: HubGoFailedEvent): void;
22
23
  export declare function postUnloadDone(unloadId: string, state?: string): void;
23
24
  export declare function setUnloadHandler(handler: (unloadId: string) => void): void;
24
25
  export declare function setVoiceEventHandler(handler: ((event: VoiceEvent) => void) | null): void;
package/dist/transport.js CHANGED
@@ -26,6 +26,7 @@ const INTERACTIVE_COMMANDS = new Set([
26
26
  "multiplayer.joinDestination",
27
27
  // The host's voice prompt and the browser's microphone permission.
28
28
  "voice.requestJoin",
29
+ "hub.pushPermission",
29
30
  ]);
30
31
  // Request ids carry a per-page prefix so that a host serving several decks at
31
32
  // once can key a cancel by requestId alone.
@@ -78,6 +79,17 @@ export function hostNotify(event) {
78
79
  };
79
80
  sendEnvelope(channel, envelope);
80
81
  }
82
+ // A deck's word to the host about a hub event (Hub.goFailed). One-way like
83
+ // hostNotify; the dev server has no host session to act on it.
84
+ export function hostNotifyHub(event) {
85
+ if (typeof window === "undefined")
86
+ return;
87
+ const channel = resolveChannel();
88
+ if (channel === "local")
89
+ return;
90
+ const envelope = { castleSdk: CASTLE_SDK_PROTOCOL, hub: event };
91
+ sendEnvelope(channel, envelope);
92
+ }
81
93
  // Reply to a host unload request. One-way like hostNotify, but it carries the
82
94
  // handshake's whole point, so it posts even with no state: the host is holding
83
95
  // its teardown open until this arrives or its cap runs out.
@@ -255,6 +267,29 @@ function settle(message) {
255
267
  }
256
268
  forget(message.requestId);
257
269
  entry.resolve(message);
270
+ // Only the mobile destination response for this still-pending SDK command
271
+ // may acknowledge delivery. The native host uses the receipt to consume a
272
+ // reserved push hint; ordinary commands and older hosts keep their bytes.
273
+ const receipt = message.hubPushReceipt;
274
+ const destination = message.data;
275
+ if (entry.channel === "mobile" &&
276
+ entry.command === "hub.pushDestination" &&
277
+ message.ok &&
278
+ typeof destination?.notificationId === "string" &&
279
+ typeof destination?.townDeckId === "string" &&
280
+ typeof receipt === "string" &&
281
+ /^[0-9a-f]{32}$/.test(receipt)) {
282
+ try {
283
+ sendEnvelope("mobile", {
284
+ castleSdk: CASTLE_SDK_PROTOCOL,
285
+ hubPushReceipt: { requestId: message.requestId, token: receipt },
286
+ });
287
+ }
288
+ catch {
289
+ // The response has been accepted, but a missing native bridge leaves
290
+ // the reservation to expire without consuming the destination.
291
+ }
292
+ }
258
293
  }
259
294
  // A throwing onStream is logged, and the stream goes on.
260
295
  function deliverStream(requestId, event) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-sdk",
3
- "version": "0.4.52",
3
+ "version": "0.4.54",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"