castle-web-sdk 0.4.51 → 0.4.53
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 +178 -7
- package/dist/analytics.d.ts +8 -0
- package/dist/analytics.js +92 -0
- package/dist/castle.d.ts +6 -2
- package/dist/castle.js +2 -0
- package/dist/commands.d.ts +79 -0
- package/dist/commands.js +1 -0
- package/dist/experiments.js +24 -1
- package/dist/hub.d.ts +20 -2
- package/dist/hub.js +51 -1
- package/dist/multiplayer.js +30 -0
- package/dist/reconnectBudget.d.ts +4 -0
- package/dist/reconnectBudget.js +37 -1
- package/dist/rooms.d.ts +11 -0
- package/dist/rooms.js +22 -0
- package/dist/server/hub.d.ts +19 -0
- package/dist/server/hub.js +12 -0
- package/dist/server/platformHandle.d.ts +1 -0
- package/dist/server/wrapper.d.ts +1 -1
- package/dist/server/wrapper.js +26 -1
- package/dist/store.d.ts +8 -2
- package/dist/store.js +5 -1
- package/dist/transport.d.ts +2 -1
- package/dist/transport.js +35 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -23,11 +23,13 @@ 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)
|
|
29
30
|
- [Portal](#portal)
|
|
30
31
|
- [Social](#social)
|
|
32
|
+
- [Rooms](#rooms)
|
|
31
33
|
- [Party](#party)
|
|
32
34
|
- [Hub](#hub)
|
|
33
35
|
- [Decks](#decks)
|
|
@@ -235,12 +237,27 @@ dev serve.
|
|
|
235
237
|
the third argument of `onPlayerJoin`.
|
|
236
238
|
- `session.hub.push` is optional, present only for a place declaring
|
|
237
239
|
`hub.push: { version: 1 }` on a capable runtime. Its
|
|
238
|
-
`visit(playerId, { userId, timezone })` reports
|
|
239
|
-
authenticated account and an IANA timezone.
|
|
240
|
+
`visit(playerId, { userId, timezone, phase? })` reports visit facts with the captured
|
|
241
|
+
authenticated account and an IANA timezone. Absent `phase` starts a visit as before;
|
|
242
|
+
its only optional value, `"end"` (v1.189), reports the end. The place server
|
|
243
|
+
remembers the account and timezone only after a start returns `true`, then sends
|
|
244
|
+
an end once from `leave` (at forget for a retained resume player, not backgrounding)
|
|
245
|
+
or for every remembered player at layer shutdown, and clears the entry.
|
|
246
|
+
It returns `true` only for `accepted === true`; errors and refusals return `false`.
|
|
247
|
+
Ignore `false` and never retry. An old host-agent or Ghost answers `false` for
|
|
248
|
+
an end, and Ghost derives from the start. Ghost keeps the latest end per user,
|
|
249
|
+
place and join generation, dropping an end older than the start or from an old
|
|
250
|
+
generation. Landing order: Ghost first, then the host-agent, then the deck save.
|
|
240
251
|
Ghost derives the three-day come-back reminder and checks consent, answered
|
|
241
252
|
age, experiments, quiet hours and delivery limits. Reporting a visit does not
|
|
242
253
|
opt the player in or promise a notification. No crop reporting or queue
|
|
243
|
-
reconciliation API is exposed.
|
|
254
|
+
reconciliation API is exposed. On a runtime with preferences it also has
|
|
255
|
+
`preference(playerId, change)`: `{}` reads, `{ enabled: boolean }` sets
|
|
256
|
+
consent and `{ declined: true }` records a declined prompt. It returns
|
|
257
|
+
`{ accepted: true, enabled, globalEnabled, touched, milestone, nextPromptAt }`
|
|
258
|
+
or `null` when refused or unavailable, and never throws. `touched` says the
|
|
259
|
+
player has ever set this place's preference; `nextPromptAt` is non-null once
|
|
260
|
+
they declined or disabled. Consent is checked again by Ghost on delivery.
|
|
244
261
|
- `session.hub.reportResult(playerId, { outcome?, score?, stats? })` records a
|
|
245
262
|
signed-in player's result for this visit, once. The host checks it against the
|
|
246
263
|
published shape and Castle keeps it only for a place behind a curated door;
|
|
@@ -321,6 +338,9 @@ arms the player's page reads and nothing a client can claim.
|
|
|
321
338
|
such experiment.
|
|
322
339
|
- `session.experiments(player)` is all of them, `{ name: variant }`.
|
|
323
340
|
|
|
341
|
+
The first `session.experiment` of each name for a player's join records an
|
|
342
|
+
exposure, as the client's first read does; `session.experiments` records none.
|
|
343
|
+
|
|
324
344
|
Both answer from `onPlayerJoin` until the player leaves, and `null` / `{}`
|
|
325
345
|
after. The variants are never on the player object, so a roster or state built
|
|
326
346
|
from `session.players` does not show one player's arm to another; send a variant
|
|
@@ -539,6 +559,28 @@ the page made before calling it, even ones still being batched; await an
|
|
|
539
559
|
`increment` or a board `submit` first if the answer should include it. A player can only ever see their own usage, not
|
|
540
560
|
another player's.
|
|
541
561
|
|
|
562
|
+
`rate` says how much of the per-second rate limits (the last two rows of
|
|
563
|
+
the table below) is spent right now, so a deck that writes often can back
|
|
564
|
+
off before a call is refused rather than after:
|
|
565
|
+
|
|
566
|
+
```js
|
|
567
|
+
const { rate } = await Store.usage();
|
|
568
|
+
if (rate && rate.caller.opsUsed > rate.caller.opsLimit * 0.8) {
|
|
569
|
+
// Close to this player's calls-per-second limit: batch or slow down.
|
|
570
|
+
}
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
- `rate.caller` is the current player's own limit, and `rate.deck` is the
|
|
574
|
+
one every player of the deck shares.
|
|
575
|
+
- Each has `opsUsed`, `opsLimit`, `bytesUsed` and `bytesLimit`, counted
|
|
576
|
+
over the current one-second window, and the `usage` call itself is
|
|
577
|
+
counted in them.
|
|
578
|
+
- `rate.callerClass` names which limit `caller` is: `"client"` for a
|
|
579
|
+
page.
|
|
580
|
+
|
|
581
|
+
`rate` is missing when the app is older than it, so check for it before
|
|
582
|
+
reading it.
|
|
583
|
+
|
|
542
584
|
An app too old to know `usage` rejects with a `CastleError` whose `code`
|
|
543
585
|
is `UNKNOWN_COMMAND`.
|
|
544
586
|
|
|
@@ -1073,9 +1115,14 @@ in no such experiment: the deck does not declare it, it was removed, or the host
|
|
|
1073
1115
|
is an older one that knows nothing of experiments. Always give `null` a
|
|
1074
1116
|
behavior, normally the one the deck had before the test.
|
|
1075
1117
|
|
|
1118
|
+
The first read of each name that returns a variant also records an exposure,
|
|
1119
|
+
the moment the player was shown that arm, for the deck's analytics. Read it
|
|
1120
|
+
where the variant changes what the player sees, not up front.
|
|
1121
|
+
|
|
1076
1122
|
### `experiments(): Record<string, string>`
|
|
1077
1123
|
|
|
1078
|
-
Every experiment this player is in on this deck, as `{ name: variant }`.
|
|
1124
|
+
Every experiment this player is in on this deck, as `{ name: variant }`. It
|
|
1125
|
+
records no exposure.
|
|
1079
1126
|
|
|
1080
1127
|
### `experimentsReady(): Promise<Record<string, string>>`
|
|
1081
1128
|
|
|
@@ -1093,10 +1140,64 @@ assigned to you exactly as they will be once the deck is saved. Add
|
|
|
1093
1140
|
experiment and one of its variants); it holds for the whole serve, client and
|
|
1094
1141
|
local server alike, until `?experiment.<name>=` clears it or the serve stops.
|
|
1095
1142
|
An open deck page keeps the arm it loaded with until it is reloaded.
|
|
1096
|
-
|
|
1143
|
+
On a published deck the same parameter on the deck's page forces an arm for the
|
|
1144
|
+
deck's owner only, for a day; see [docs/ab-tests.md](../docs/ab-tests.md#try-an-arm-on-the-published-deck).
|
|
1145
|
+
`devExperiments` in `castle.json`, a
|
|
1097
1146
|
`{ "name": "variant" }` map, answers for experiments the deck does not declare
|
|
1098
1147
|
itself (ones Castle runs across decks), on the serve only.
|
|
1099
1148
|
|
|
1149
|
+
## Analytics
|
|
1150
|
+
|
|
1151
|
+
A deck's own named events, recorded in its creator analytics beside Castle's
|
|
1152
|
+
built-in ones (plays, play time, players who come back).
|
|
1153
|
+
|
|
1154
|
+
```js
|
|
1155
|
+
import { Analytics } from "castle-web-sdk";
|
|
1156
|
+
|
|
1157
|
+
Analytics.event("level_complete", { level: 3, seconds: 41 });
|
|
1158
|
+
```
|
|
1159
|
+
|
|
1160
|
+
### `Analytics.event(name, properties?): void`
|
|
1161
|
+
|
|
1162
|
+
Records one event for the player. Synchronous and fire and forget: it returns
|
|
1163
|
+
nothing, and a host that cannot record it (an older one, or no network) drops
|
|
1164
|
+
it without the deck noticing.
|
|
1165
|
+
|
|
1166
|
+
- `name` is trimmed, then 1 to 64 characters of letters, digits, space and
|
|
1167
|
+
`_ . : / -`, starting with a letter or digit.
|
|
1168
|
+
- `properties` is optional: a plain object of at most 5 keys, each 1 to 32
|
|
1169
|
+
characters under the same rule, whose values are finite numbers. Castle stores
|
|
1170
|
+
each as a whole number (rounded).
|
|
1171
|
+
- A bad name or properties throws a `TypeError` at the call, so a mistake shows
|
|
1172
|
+
up while you build the deck.
|
|
1173
|
+
- At most 60 events a minute per page load; the rest are dropped, with one
|
|
1174
|
+
console warning the first time.
|
|
1175
|
+
|
|
1176
|
+
**An event has to be registered before players' events are kept.** Castle keeps
|
|
1177
|
+
a list of event types per creator, up to 100 across all of a creator's decks.
|
|
1178
|
+
When the deck's creator plays the published deck, each `Analytics.event` call
|
|
1179
|
+
registers its name, with its property keys in the order the call gives them;
|
|
1180
|
+
the creator's own plays are not counted. After that, players' events with that
|
|
1181
|
+
name are recorded, carrying the properties the type names. A player's event
|
|
1182
|
+
under a name the creator never registered is dropped, as are property keys the
|
|
1183
|
+
type does not name. So play every path that sends an event once, signed in as
|
|
1184
|
+
the deck's owner, after saving the deck.
|
|
1185
|
+
|
|
1186
|
+
Registration is limited: at most 20 registrations per creator per hour (a new
|
|
1187
|
+
name, or a property key added to an existing name, each counts as one), and at
|
|
1188
|
+
most 100 event types per creator. A call past either limit registers nothing,
|
|
1189
|
+
so the name stays unregistered and players' events under it are dropped until
|
|
1190
|
+
the creator plays it again after the hour has passed. To see what is registered, the `creatorEventTypes` query in Castle's API
|
|
1191
|
+
lists the creator's event types with their property names, in slot order;
|
|
1192
|
+
`createCreatorEventType` registers one directly.
|
|
1193
|
+
|
|
1194
|
+
Only a published deck records events: on `castle-web serve` of a deck that was
|
|
1195
|
+
never saved, `Analytics.event` validates its arguments and sends nothing.
|
|
1196
|
+
|
|
1197
|
+
Each event carries the player's experiment arms, like the built-in events, so
|
|
1198
|
+
`creatorEventStats` with `splitBy: EXPERIMENT` reads custom events per variant;
|
|
1199
|
+
see [Measure a variant with your own events](../docs/ab-tests.md#measure-a-variant-with-your-own-events).
|
|
1200
|
+
|
|
1100
1201
|
## Avatar
|
|
1101
1202
|
|
|
1102
1203
|
The player's platform avatar: one per account, worn in every hub place
|
|
@@ -1247,6 +1348,45 @@ const friends = await Social.friends();
|
|
|
1247
1348
|
const playingHere = await Social.presence();
|
|
1248
1349
|
```
|
|
1249
1350
|
|
|
1351
|
+
## Rooms
|
|
1352
|
+
|
|
1353
|
+
### `Rooms.list(): Promise<RoomsListResult | null>`
|
|
1354
|
+
|
|
1355
|
+
This deck's public multiplayer rooms and how many players are in each, for a
|
|
1356
|
+
lobby, a room picker or a "12 playing now" line. No room has to write its own
|
|
1357
|
+
count to `Store` for a menu to read.
|
|
1358
|
+
|
|
1359
|
+
```js
|
|
1360
|
+
import { Rooms } from "castle-web-sdk";
|
|
1361
|
+
|
|
1362
|
+
const list = await Rooms.list();
|
|
1363
|
+
if (list) {
|
|
1364
|
+
label.textContent = `${list.total} playing now`;
|
|
1365
|
+
for (const room of list.rooms) {
|
|
1366
|
+
// { sessionId, routeId?, slot?, players, maxPlayers }
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
```
|
|
1370
|
+
|
|
1371
|
+
- `total` is the players across every listed room; `rooms` is one entry per
|
|
1372
|
+
room, with `routeId` and `slot` as the deck passed them to
|
|
1373
|
+
`Multiplayer.joinDestination` (absent for a room `Multiplayer.join`
|
|
1374
|
+
opened).
|
|
1375
|
+
- It resolves `null` when Castle will not list the deck's rooms for this
|
|
1376
|
+
player. The deck's owner and Castle admins always get a list; whether
|
|
1377
|
+
other players do depends on how far Castle has rolled presence out, so
|
|
1378
|
+
handle `null` for any player. A player under 13, or one Castle keeps out
|
|
1379
|
+
of multiplayer, gets `null` even on their own deck. Treat `null` as "not available", never as "no
|
|
1380
|
+
rooms": a deck nobody is playing answers `{ total: 0, rooms: [] }`.
|
|
1381
|
+
- An app built before the call also resolves `null` rather than throwing
|
|
1382
|
+
`UNKNOWN_COMMAND`. An unsaved deck throws `MISSING_DECK_ID`.
|
|
1383
|
+
- Counts come from a rollup Castle refreshes about every 10 seconds, so a
|
|
1384
|
+
player who joined or left in the last few seconds may not show yet. Poll it
|
|
1385
|
+
no more than every 10 seconds; there is no event.
|
|
1386
|
+
- Only public rooms are listed. Private, party and named rooms are not.
|
|
1387
|
+
- A local `castle-web serve` lists the saved deck's rooms on Castle, not the
|
|
1388
|
+
rooms of the local serve.
|
|
1389
|
+
|
|
1250
1390
|
## Party
|
|
1251
1391
|
|
|
1252
1392
|
`Party` creates and drives Castle parties with the signed-in player's account.
|
|
@@ -1306,6 +1446,14 @@ With `canInvite: true`, newer hosts also name the account the links belong to
|
|
|
1306
1446
|
account is the player's own, and checks `User.getCurrent()` when a host names
|
|
1307
1447
|
none.
|
|
1308
1448
|
|
|
1449
|
+
`Hub.inviteAvailable()` takes no parameters and reads the authenticated viewer's
|
|
1450
|
+
invite gate through the trusted, invite-enabled hub visit. It answers
|
|
1451
|
+
`{ status: 'ok', available: boolean }`, or `{ status: 'unavailable' }` when the
|
|
1452
|
+
viewer is signed out or anonymous, the visit or invite opt-in is absent, the
|
|
1453
|
+
read fails, or the host predates the command. It creates no invite and exposes
|
|
1454
|
+
no gate map. The opt-in Character entry also requires `available: true`;
|
|
1455
|
+
pending, false and unavailable answers keep it hidden.
|
|
1456
|
+
|
|
1309
1457
|
The trusted host resolves the link after sign-in, retains its token, and requests
|
|
1310
1458
|
the inviter's layer when it has room. If resolution refuses the invite, the host
|
|
1311
1459
|
discards it for that visit and joins normally. Transient resolution failures
|
|
@@ -1345,6 +1493,19 @@ the signed-in account id. A new host without native sign-in support returns
|
|
|
1345
1493
|
`unavailable`; an older host that does not know this command rejects with
|
|
1346
1494
|
`UNKNOWN_COMMAND`.
|
|
1347
1495
|
|
|
1496
|
+
`Hub.pushPermission()` (hub contract v1.177) may ask the native host to request
|
|
1497
|
+
OS notification permission. Call it only from a deliberate tap after the player
|
|
1498
|
+
committed to something worth a reminder. It waits for the player's answer and
|
|
1499
|
+
resolves to `{ status: 'granted' | 'denied' | 'unavailable' }`.
|
|
1500
|
+
`Hub.pushDestination()` reads, once, the native push hint that opened the app
|
|
1501
|
+
into this town: `{ notificationId, townDeckId }` or `{ status: 'unavailable' }`.
|
|
1502
|
+
On mobile the SDK acknowledges a delivered hint back to the host as soon as it
|
|
1503
|
+
resolves the call; a deck does nothing extra. Both take no arguments and answer
|
|
1504
|
+
`unavailable` on web, for a signed-out player, outside a joined session, or
|
|
1505
|
+
where the host does not offer hub notifications. A host that predates them
|
|
1506
|
+
(`UNKNOWN_COMMAND`) or no reachable host (`CASTLE_HOST_UNAVAILABLE`) also reads
|
|
1507
|
+
as `unavailable`; any other failure rejects with its `CastleError`.
|
|
1508
|
+
|
|
1348
1509
|
- `Hub.doors()` reads the current place's doors and who is inside them:
|
|
1349
1510
|
`{ status: "ok", doors }` or `{ status: "unavailable", doors: null }`. A row has
|
|
1350
1511
|
`doorId`, `launcherKind` (`door`, `table`, `cabinet`, `gate`), `placementKind`
|
|
@@ -1408,6 +1569,14 @@ the signed-in account id. A new host without native sign-in support returns
|
|
|
1408
1569
|
`Hub.go(doorId)` (with `{ ownerUserId: owner }` when set) behind its door
|
|
1409
1570
|
animation. Hosts that never send it are the norm. Returns an unsubscribe
|
|
1410
1571
|
function.
|
|
1572
|
+
- `Hub.goFailed({ doorId, owner }, why)` tells the host that a Go it sent
|
|
1573
|
+
(`Hub.onGo`) ended without the player going through: `why` is `"refused"`
|
|
1574
|
+
(`Hub.go` gave no handoff), `"content"` (the destination's content would not
|
|
1575
|
+
load) or `"join"` (the join was never committed). Call it at most once per
|
|
1576
|
+
Go, and not for a join the host committed. A host that acquired the door
|
|
1577
|
+
from its own session may acquire it again there and send a fresh Go; do not
|
|
1578
|
+
ask `Hub.go` again yourself. One-way: nothing answers it, and older hosts
|
|
1579
|
+
ignore it.
|
|
1411
1580
|
|
|
1412
1581
|
A player Castle has barred from the hub is refused at every hub door and at the
|
|
1413
1582
|
town itself with `CastleError` code `CAULDRON_HUB_BANNED` (from `Hub.go`,
|
|
@@ -1951,8 +2120,10 @@ load its assets through the bundler instead.
|
|
|
1951
2120
|
A multiplayer socket closed before its first hello reports its WebSocket close
|
|
1952
2121
|
code in `error.extensions.closeCode` when available. Code `4404` means the
|
|
1953
2122
|
play proxy could not route the session (`not_running`); it does not prove the
|
|
1954
|
-
runtime ended. A
|
|
1955
|
-
a
|
|
2123
|
+
runtime ended. A hub join refused this way tries the same handoff again for a
|
|
2124
|
+
few seconds, since a session ghost has just started can briefly be unroutable;
|
|
2125
|
+
the error is reported only when those tries run out. A failed hub join cancels
|
|
2126
|
+
its handoff, so retrying a door after that requires a fresh `Hub.go` acquisition.
|
|
1956
2127
|
|
|
1957
2128
|
Every error the SDK throws is a `CastleError`. Check `code` to tell
|
|
1958
2129
|
the kinds apart.
|
|
@@ -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,9 @@ 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";
|
|
19
|
+
export { Rooms } from "./rooms";
|
|
20
|
+
export type { CastleRoomsApi, RoomSummary, RoomsListResult } from "./rooms";
|
|
17
21
|
export { Social } from "./social";
|
|
18
22
|
export type { CastleSocialApi, SocialFriend, SocialPresence } from "./social";
|
|
19
23
|
export { Party } from "./party";
|
|
@@ -46,7 +50,7 @@ export { LocalCache } from "./localCache";
|
|
|
46
50
|
export type { LocalCacheApi } from "./localCache";
|
|
47
51
|
export { SharedStorage, Storage } from "./storage";
|
|
48
52
|
export { Store } from "./store";
|
|
49
|
-
export type { CastleStoreApi, StoreBoardApi, StoreBoardScore, StoreListEntry, StoreListOptions, StoreListPage, StoreAllowance, StoreScopeApi, StoreUsage, } from "./store";
|
|
53
|
+
export type { CastleStoreApi, StoreBoardApi, StoreBoardScore, StoreListEntry, StoreListOptions, StoreListPage, StoreAllowance, StoreRateBudget, StoreRateUsage, StoreScopeApi, StoreUsage, } from "./store";
|
|
50
54
|
export { Time } from "./time";
|
|
51
55
|
export type { CastleClockZone, CastleDateParts, CastleTimeApi } from "./time";
|
|
52
56
|
export type { Json } from "./types";
|
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";
|
|
@@ -9,6 +10,7 @@ export { experiment, experiments, experimentsReady } from "./experiments";
|
|
|
9
10
|
export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckFile, } from "./files";
|
|
10
11
|
export { Haptics } from "./haptics";
|
|
11
12
|
export { Hub } from "./hub";
|
|
13
|
+
export { Rooms } from "./rooms";
|
|
12
14
|
export { Social } from "./social";
|
|
13
15
|
export { Party } from "./party";
|
|
14
16
|
export { Leaderboard } from "./leaderboard";
|
package/dist/commands.d.ts
CHANGED
|
@@ -19,9 +19,25 @@ export interface StoreAllowance {
|
|
|
19
19
|
byteCount: number;
|
|
20
20
|
byteLimit: number;
|
|
21
21
|
}
|
|
22
|
+
/** One storage rate window: what was spent in the current second, and its limits. */
|
|
23
|
+
export interface StoreRateBudget {
|
|
24
|
+
opsUsed: number;
|
|
25
|
+
opsLimit: number;
|
|
26
|
+
bytesUsed: number;
|
|
27
|
+
bytesLimit: number;
|
|
28
|
+
}
|
|
29
|
+
/** The storage rate windows a call is charged against. */
|
|
30
|
+
export interface StoreRateUsage {
|
|
31
|
+
/** Which caller bucket answered: "client", "server", "session" or "town-layer". */
|
|
32
|
+
callerClass: string;
|
|
33
|
+
caller: StoreRateBudget;
|
|
34
|
+
deck: StoreRateBudget;
|
|
35
|
+
}
|
|
22
36
|
export interface StoreAllowances {
|
|
23
37
|
player: StoreAllowance;
|
|
24
38
|
shared: StoreAllowance;
|
|
39
|
+
/** Absent from a host older than the rate field. */
|
|
40
|
+
rate?: StoreRateUsage;
|
|
25
41
|
}
|
|
26
42
|
export interface StoreBoardEntry {
|
|
27
43
|
subject: string;
|
|
@@ -96,6 +112,19 @@ export interface SocialPresence extends SocialFriend {
|
|
|
96
112
|
slot?: string;
|
|
97
113
|
updatedAt: string;
|
|
98
114
|
}
|
|
115
|
+
/** One public room of the current deck, as Castle last counted it. */
|
|
116
|
+
export interface RoomSummary {
|
|
117
|
+
sessionId: string;
|
|
118
|
+
routeId?: string;
|
|
119
|
+
slot?: string;
|
|
120
|
+
players: number;
|
|
121
|
+
maxPlayers: number;
|
|
122
|
+
}
|
|
123
|
+
export interface RoomsListResult {
|
|
124
|
+
/** Players across every room listed. */
|
|
125
|
+
total: number;
|
|
126
|
+
rooms: RoomSummary[];
|
|
127
|
+
}
|
|
99
128
|
export type PartyStatus = "invited" | "joined" | "rejected" | "left" | "party_closed" | "banned";
|
|
100
129
|
export interface PartySummary {
|
|
101
130
|
partyId: string;
|
|
@@ -209,6 +238,15 @@ export interface HubSignInResult {
|
|
|
209
238
|
status: "signedIn" | "dismissed" | "unavailable";
|
|
210
239
|
userId?: string;
|
|
211
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
|
+
};
|
|
212
250
|
export type HubFriendsResult = {
|
|
213
251
|
status: "ok";
|
|
214
252
|
friends: HubFriend[];
|
|
@@ -237,6 +275,13 @@ export type HubCanInviteResult = {
|
|
|
237
275
|
status: "unavailable";
|
|
238
276
|
canInvite: false;
|
|
239
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
|
+
};
|
|
240
285
|
export interface HubInviteArrivalResult {
|
|
241
286
|
status: "ok" | "unavailable" | "route";
|
|
242
287
|
doorId?: string;
|
|
@@ -364,6 +409,17 @@ export interface HubEventEnvelope {
|
|
|
364
409
|
castleSdk: typeof CASTLE_SDK_PROTOCOL;
|
|
365
410
|
hub: HubEvent;
|
|
366
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
|
+
}
|
|
367
423
|
export declare function hubEventFrom(value: unknown): HubEvent | null;
|
|
368
424
|
export type HapticStyle = "light" | "medium" | "heavy" | "selection" | "success" | "warning" | "error";
|
|
369
425
|
export type HapticsStatus = "triggered" | "unavailable";
|
|
@@ -614,6 +670,14 @@ export interface CommandParams {
|
|
|
614
670
|
userId: string;
|
|
615
671
|
};
|
|
616
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
|
+
};
|
|
617
681
|
"time.getServerTime": Record<string, never>;
|
|
618
682
|
"pass.has": {
|
|
619
683
|
passId: string;
|
|
@@ -676,6 +740,7 @@ export interface CommandParams {
|
|
|
676
740
|
crew?: boolean;
|
|
677
741
|
};
|
|
678
742
|
"hub.canInvite": Record<string, never>;
|
|
743
|
+
"hub.inviteAvailable": Record<string, never>;
|
|
679
744
|
"hub.inviteArrival": Record<string, never>;
|
|
680
745
|
"hub.undoInvite": {
|
|
681
746
|
userId: string;
|
|
@@ -685,6 +750,8 @@ export interface CommandParams {
|
|
|
685
750
|
doorIds: string[];
|
|
686
751
|
};
|
|
687
752
|
"hub.signIn": HubSignInParams;
|
|
753
|
+
"hub.pushPermission": Record<string, never>;
|
|
754
|
+
"hub.pushDestination": Record<string, never>;
|
|
688
755
|
"hub.jump": HubJumpParams;
|
|
689
756
|
"hub.report": HubReportParams;
|
|
690
757
|
"hub.chat": HubChatParams;
|
|
@@ -799,6 +866,7 @@ export interface CommandParams {
|
|
|
799
866
|
subject?: string | null;
|
|
800
867
|
};
|
|
801
868
|
"cauldronStorage.usage": Record<string, never>;
|
|
869
|
+
"rooms.list": Record<string, never>;
|
|
802
870
|
"lifecycle.restoreState": Record<string, never>;
|
|
803
871
|
"localCache.get": {
|
|
804
872
|
key: string;
|
|
@@ -848,6 +916,12 @@ export interface CommandResult {
|
|
|
848
916
|
"experiments.get": {
|
|
849
917
|
variants: Record<string, string>;
|
|
850
918
|
};
|
|
919
|
+
"experiments.exposed": {
|
|
920
|
+
recorded: boolean;
|
|
921
|
+
};
|
|
922
|
+
"analytics.event": {
|
|
923
|
+
recorded: boolean;
|
|
924
|
+
};
|
|
851
925
|
"time.getServerTime": {
|
|
852
926
|
timestamp: number;
|
|
853
927
|
timezoneOffset: number;
|
|
@@ -885,11 +959,14 @@ export interface CommandResult {
|
|
|
885
959
|
"hub.friends": HubFriendsResult;
|
|
886
960
|
"hub.invite": HubInviteResult;
|
|
887
961
|
"hub.canInvite": HubCanInviteResult;
|
|
962
|
+
"hub.inviteAvailable": HubInviteAvailableResult;
|
|
888
963
|
"hub.inviteArrival": HubInviteArrivalResult;
|
|
889
964
|
"hub.undoInvite": HubReportResult;
|
|
890
965
|
"hub.hearts": HubHeartsResult;
|
|
891
966
|
"hub.setHearts": HubHeartsResult;
|
|
892
967
|
"hub.signIn": HubSignInResult;
|
|
968
|
+
"hub.pushPermission": HubPushPermissionResult;
|
|
969
|
+
"hub.pushDestination": HubPushDestinationResult;
|
|
893
970
|
"hub.jump": HubJumpResult;
|
|
894
971
|
"hub.report": HubReportResult;
|
|
895
972
|
"hub.chat": HubChatResult;
|
|
@@ -956,6 +1033,7 @@ export interface CommandResult {
|
|
|
956
1033
|
"cauldronStorage.usage": {
|
|
957
1034
|
usage: StoreAllowances;
|
|
958
1035
|
};
|
|
1036
|
+
"rooms.list": RoomsListResult | null;
|
|
959
1037
|
"lifecycle.restoreState": LifecycleRestoreStateResult;
|
|
960
1038
|
"localCache.get": {
|
|
961
1039
|
value: ArrayBuffer | string | null;
|
|
@@ -1000,6 +1078,7 @@ export interface CommandResponseEnvelope {
|
|
|
1000
1078
|
ok: boolean;
|
|
1001
1079
|
data?: unknown;
|
|
1002
1080
|
error?: SerializedCommandError;
|
|
1081
|
+
hubPushReceipt?: string;
|
|
1003
1082
|
}
|
|
1004
1083
|
export declare function isResponseEnvelope(value: unknown): value is CommandResponseEnvelope;
|
|
1005
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,
|
package/dist/experiments.js
CHANGED
|
@@ -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
|
-
|
|
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) {
|
package/dist/multiplayer.js
CHANGED
|
@@ -75,6 +75,9 @@ async function join(options) {
|
|
|
75
75
|
// The host answers `unavailable` while ghost is busy with this player; the
|
|
76
76
|
// trip stays pending there, so asking again is safe.
|
|
77
77
|
const HUB_COMMIT_RETRY_MS = [1_000, 2_000, 4_000, 8_000];
|
|
78
|
+
// A hub join's tries of the same nonce while the proxy cannot route the new
|
|
79
|
+
// session yet (`openHubSocket`), well inside the nonce's unconsumed life.
|
|
80
|
+
const HUB_UNROUTED_RETRY_MS = [500, 1_000, 2_000];
|
|
78
81
|
async function commitHubTrip(nonce, sessionId) {
|
|
79
82
|
for (let attempt = 0;; attempt++) {
|
|
80
83
|
let status;
|
|
@@ -458,8 +461,35 @@ class MultiplayerConnectionImpl {
|
|
|
458
461
|
if (savedToken && await this.restoreDevReconnect(savedToken))
|
|
459
462
|
return;
|
|
460
463
|
this.assertOpen();
|
|
464
|
+
if (this.request.command === "hub") {
|
|
465
|
+
await this.openHubSocket(result.nonce);
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
461
468
|
await this.openSocket("nonce", result.nonce);
|
|
462
469
|
}
|
|
470
|
+
// A hub session ghost has just started can be refused by the play proxy
|
|
471
|
+
// before its route is readable there (4404, before any hello). The proxy
|
|
472
|
+
// refuses before the session sees the nonce, so the nonce is still good:
|
|
473
|
+
// try it again for a few seconds before the trip is given back.
|
|
474
|
+
async openHubSocket(nonce) {
|
|
475
|
+
for (let attempt = 0;; attempt++) {
|
|
476
|
+
try {
|
|
477
|
+
await this.openSocket("nonce", nonce);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
catch (error) {
|
|
481
|
+
const delay = HUB_UNROUTED_RETRY_MS[attempt];
|
|
482
|
+
if (!(error instanceof SocketClosedError) ||
|
|
483
|
+
error.code !== PROXY_SESSION_ENDED_CLOSE_CODE ||
|
|
484
|
+
delay === undefined) {
|
|
485
|
+
throw error;
|
|
486
|
+
}
|
|
487
|
+
this.assertOpen();
|
|
488
|
+
await pause(delay);
|
|
489
|
+
this.assertOpen();
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
463
493
|
async restoreDevReconnect(token) {
|
|
464
494
|
this.assertOpen();
|
|
465
495
|
const budget = this.reconnectBudget = new ReconnectBudget();
|
|
@@ -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;
|
package/dist/reconnectBudget.js
CHANGED
|
@@ -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
|
-
|
|
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/rooms.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { RoomsListResult } from "./commands";
|
|
2
|
+
export type { RoomSummary, RoomsListResult } from "./commands";
|
|
3
|
+
export interface CastleRoomsApi {
|
|
4
|
+
/**
|
|
5
|
+
* This deck's public rooms with their player counts, or null when Castle
|
|
6
|
+
* will not list them for this player or the app running the deck predates
|
|
7
|
+
* the call. Null is "not available", never "no rooms".
|
|
8
|
+
*/
|
|
9
|
+
list(): Promise<RoomsListResult | null>;
|
|
10
|
+
}
|
|
11
|
+
export declare const Rooms: CastleRoomsApi;
|
package/dist/rooms.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Rooms — the current deck's public multiplayer rooms and how many players are
|
|
2
|
+
// in each, for a lobby or a "players online" line. Castle always lists them
|
|
3
|
+
// to the deck's owner and Castle admins, to other players only as far as its
|
|
4
|
+
// presence rollout reaches, and never to a player under 13 or kept out of
|
|
5
|
+
// multiplayer; anyone it will not list them for gets null.
|
|
6
|
+
//
|
|
7
|
+
// Counts come from a rollup Castle refreshes about every 10 seconds, so a
|
|
8
|
+
// player who just joined or left may not show yet. Private, party and named
|
|
9
|
+
// rooms are not listed.
|
|
10
|
+
import { CastleError } from "./errors";
|
|
11
|
+
import { hostRequest } from "./transport";
|
|
12
|
+
async function list() {
|
|
13
|
+
try {
|
|
14
|
+
return await hostRequest("rooms.list", {});
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
if (error instanceof CastleError && error.code === "UNKNOWN_COMMAND")
|
|
18
|
+
return null;
|
|
19
|
+
throw error;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export const Rooms = Object.freeze({ list });
|
package/dist/server/hub.d.ts
CHANGED
|
@@ -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: {
|
package/dist/server/hub.js
CHANGED
|
@@ -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). */
|
package/dist/server/wrapper.d.ts
CHANGED
|
@@ -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;
|
package/dist/server/wrapper.js
CHANGED
|
@@ -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
|
-
|
|
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) };
|
package/dist/store.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { StoreAllowance } from "./commands";
|
|
1
|
+
import type { StoreAllowance, StoreRateBudget, StoreRateUsage } from "./commands";
|
|
2
2
|
import type { Json } from "./types";
|
|
3
3
|
import { type SaveApi, type SaveBucketApi } from "./save";
|
|
4
4
|
export interface StoreListOptions {
|
|
@@ -54,7 +54,7 @@ export interface StoreBoardApi {
|
|
|
54
54
|
/** One player's score, defaulting to the current player. Null if unset. */
|
|
55
55
|
get(userId?: string): Promise<StoreBoardScore | null>;
|
|
56
56
|
}
|
|
57
|
-
export type { StoreAllowance };
|
|
57
|
+
export type { StoreAllowance, StoreRateBudget, StoreRateUsage };
|
|
58
58
|
export interface StoreUsage {
|
|
59
59
|
/**
|
|
60
60
|
* The current player's own data in this deck: their `Store.me` and
|
|
@@ -63,6 +63,12 @@ export interface StoreUsage {
|
|
|
63
63
|
player: StoreAllowance;
|
|
64
64
|
/** `Store.deck`: one allowance shared by every player of the deck. */
|
|
65
65
|
shared: StoreAllowance;
|
|
66
|
+
/**
|
|
67
|
+
* How much of the current second's call and byte rate limits is spent, for
|
|
68
|
+
* the current player (`caller`) and for every player of the deck together
|
|
69
|
+
* (`deck`). Counts this usage call. Absent when the app is too old to report it.
|
|
70
|
+
*/
|
|
71
|
+
rate?: StoreRateUsage;
|
|
66
72
|
}
|
|
67
73
|
export interface CastleStoreApi extends SaveApi {
|
|
68
74
|
/** Shared by everyone playing the deck. */
|
package/dist/store.js
CHANGED
|
@@ -309,7 +309,11 @@ async function usage() {
|
|
|
309
309
|
// caller.
|
|
310
310
|
await Promise.all(Array.from(buckets.values(), (bucket) => flushBucket(bucket, false)));
|
|
311
311
|
const { usage: allowances } = await hostRequest("cauldronStorage.usage", {});
|
|
312
|
-
|
|
312
|
+
const result = { player: allowances.player, shared: allowances.shared };
|
|
313
|
+
// An app built before the rate field answers without it.
|
|
314
|
+
if (allowances.rate)
|
|
315
|
+
result.rate = allowances.rate;
|
|
316
|
+
return result;
|
|
313
317
|
}
|
|
314
318
|
// Saves skip the write coalescing above: each is one request, sent at once.
|
|
315
319
|
const saveApi = createSaveApi((verb, input) => hostRequest(`cauldronStorage.${verb}`, input));
|
package/dist/transport.d.ts
CHANGED
|
@@ -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) {
|