@ksaa-nlp/gamehub-sdk 4.2.0 → 4.5.0

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.
Files changed (44) hide show
  1. package/README.md +58 -1
  2. package/SPEC.md +82 -13
  3. package/dist/gamehub-sdk.js +204 -3
  4. package/dist/gamehub-sdk.js.map +4 -4
  5. package/dist/src/bot-driver.d.ts +53 -0
  6. package/dist/src/bot-driver.d.ts.map +1 -0
  7. package/dist/src/bot-driver.js +94 -0
  8. package/dist/src/bot-driver.js.map +1 -0
  9. package/dist/src/bridge.d.ts +0 -14
  10. package/dist/src/bridge.d.ts.map +1 -1
  11. package/dist/src/bridge.js +25 -0
  12. package/dist/src/bridge.js.map +1 -1
  13. package/dist/src/constants.d.ts +1 -1
  14. package/dist/src/constants.js +1 -1
  15. package/dist/src/init.d.ts +0 -14
  16. package/dist/src/init.d.ts.map +1 -1
  17. package/dist/src/init.js +7 -1
  18. package/dist/src/init.js.map +1 -1
  19. package/dist/src/main.d.ts +4 -13
  20. package/dist/src/main.d.ts.map +1 -1
  21. package/dist/src/main.js +8 -0
  22. package/dist/src/main.js.map +1 -1
  23. package/dist/src/multiplayer-session.d.ts +8 -0
  24. package/dist/src/multiplayer-session.d.ts.map +1 -0
  25. package/dist/src/multiplayer-session.js +220 -0
  26. package/dist/src/multiplayer-session.js.map +1 -0
  27. package/dist/src/server-entry.d.ts +10 -4
  28. package/dist/src/server-entry.d.ts.map +1 -1
  29. package/dist/src/server-entry.js +7 -5
  30. package/dist/src/server-entry.js.map +1 -1
  31. package/dist/src/session.d.ts.map +1 -1
  32. package/dist/src/session.js +5 -1
  33. package/dist/src/session.js.map +1 -1
  34. package/dist/src/state.d.ts +2 -0
  35. package/dist/src/state.d.ts.map +1 -1
  36. package/dist/src/state.js +1 -9
  37. package/dist/src/state.js.map +1 -1
  38. package/dist/types/bootstrap.d.ts +5 -0
  39. package/dist/types/bootstrap.d.ts.map +1 -1
  40. package/dist/types/multiplayer-session.d.ts +81 -0
  41. package/dist/types/multiplayer-session.d.ts.map +1 -0
  42. package/dist/types/multiplayer-session.js +2 -0
  43. package/dist/types/multiplayer-session.js.map +1 -0
  44. package/package.json +1 -1
package/README.md CHANGED
@@ -370,11 +370,35 @@ The full nested `Word` shape and its sub-interfaces (`WordSense`, `WordForm`, `L
370
370
 
371
371
  For games with authoritative server logic running in the Colyseus UGC sandbox, the SDK ships two extra subpaths, separate from the browser runtime:
372
372
 
373
- - `@ksaa-nlp/gamehub-sdk/server` — **types only** (`GuestModule`, `Ctx`, `PeerInfo`, …) for writing the guest module.
373
+ - `@ksaa-nlp/gamehub-sdk/server` — types (`GuestModule`, `Ctx`, `PeerInfo`, …) for writing the guest module, plus the optional `createBotDriver` helper.
374
374
  - `@ksaa-nlp/gamehub-sdk/server/dev` — `runLocal(guest, opts)`, a pure-Node harness to unit-test a guest bundle against a simulated room without `isolated-vm`.
375
375
 
376
376
  See [SPEC.md §21bis](./SPEC.md#21bis-ugc-server-bundle-subpath) for the full contract.
377
377
 
378
+ ### Bot players (SDK 4.5)
379
+
380
+ When the host adds bots, `opts.seededPlayers` contains `kind: 'bot'` rows with a
381
+ `botLevel` (`easy`/`medium`/`hard`). `createBotDriver` plays them from your rules:
382
+
383
+ ```ts
384
+ import { createBotDriver } from '@ksaa-nlp/gamehub-sdk/server';
385
+
386
+ const bots = createBotDriver<Move>({
387
+ legalMoves: (ctx, seatId) => movesFor(ctx.state, seatId),
388
+ apply: (ctx, seatId, move) => play(ctx, seatId, move), // same path as humans
389
+ isTurn: (ctx, seatId) => ctx.state.turn === seatId,
390
+ isOver: (ctx) => ctx.state.finished,
391
+ score: (ctx, seatId, move) => evaluate(ctx.state, seatId, move), // optional
392
+ });
393
+ // onCreate: bots.setBots(opts.seededPlayers)
394
+ // onStart and after every state change: bots.schedule(ctx)
395
+ // onMessage: ignore messages from bots.isBot(peer.peerId)
396
+ // onDispose: bots.cancel(ctx)
397
+ ```
398
+
399
+ Easy plays randomly, medium uses `score` half the time, hard always picks the
400
+ best-scored move. See SPEC "Bot driver (4.5.0)" and `examples/take-twenty-one`.
401
+
378
402
  ## Specification
379
403
 
380
404
  [SPEC.md](./SPEC.md) is the authoritative contract — postMessage taxonomy, state model, REST endpoints, error semantics, boundary rules, versioning policy. Read that before changing SDK internals or adding a new feature area.
@@ -423,3 +447,36 @@ state, clock and recovery lifecycle. The [Take Twenty-One starter](../../example
423
447
  contains a complete authoring/build/upload example. V1 bootstrap is unchanged;
424
448
  unsupported/native hosts do not advertise v2. Server-authoritative v2 rounds use
425
449
  ctx.endMatch version 2 instead of browser submitScore/submitMatchResult.
450
+
451
+ ## Create and join inside your game (SDK 4.3)
452
+
453
+ Declare `lobbyUi: "game"` in `gamehub.multiplayer.json`, then disable the game's
454
+ platform-lobby setting. Wait for bootstrap and implement the menu using typed
455
+ host controls. Hosts retain authentication and session ownership.
456
+
457
+ ```ts
458
+ await sdk.ready();
459
+ const off = sdk.onMultiplayerSessionChange(({ session, busy, error }) => {
460
+ // Render roster, ready/start controls and errors. Disable operations while busy.
461
+ });
462
+ await sdk.requestMultiplayerSession({ operation: 'create', type: 'player' });
463
+ // In another browser:
464
+ await sdk.requestMultiplayerSession({
465
+ operation: 'join',
466
+ roomCode: '123456',
467
+ displayName: 'Player',
468
+ type: 'player',
469
+ });
470
+ await sdk.requestMultiplayerSession({ operation: 'ready', ready: true });
471
+ // Current host only; all minimum human/player and readiness rules still apply.
472
+ await sdk.requestMultiplayerSession({ operation: 'start' });
473
+ off();
474
+ ```
475
+
476
+ Use `multiplayerEntry` to prefill invitation code and spectator intent. Public
477
+ session snapshots contain invitation URLs, limits, roster and current round
478
+ phase. Rematch availability follows terminal round phases, not only eventual
479
+ session retirement. Start transitions to a newly mounted pinned game document;
480
+ read `multiplayerLaunch` there and connect the multiplayer adapter. Lobby menus
481
+ cannot start/submit ordinary client scores. See the starter for ready/start,
482
+ bots, leave and rematch controls.
package/SPEC.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # GameHub SDK — Specification
2
2
 
3
- Version: 4.2.0
3
+ Version: 4.5.0
4
4
  Status: Authoritative. Supersedes README/MIGRATION/CHANGELOG where they conflict.
5
5
 
6
6
  This document is the single source of truth for the GameHub SDK. Code, tests, and consumer docs follow this spec; if a behaviour is observed in code but not described here, treat it as undocumented and revisit before relying on it.
@@ -32,14 +32,14 @@ The SDK is not coupled to any realtime transport. When the host attaches a multi
32
32
  - Surface a bootstrap snapshot (`getBootstrap()`) including the trusted
33
33
  `sessionMode` and opaque `multiplayer` block.
34
34
  - Forward player-visible host commands (`pause`, `resume`) to optional `window.onGameHubPause` / `onGameHubResume` callbacks.
35
- - Type definitions for authoring UGC server bundles (`./server` subpath, types-only at runtime).
35
+ - Type definitions for authoring UGC server bundles (`./server` subpath), plus the optional bundled `createBotDriver` helper.
36
36
  - Node-only dev harness (`./server/dev` subpath) for unit-testing a guest bundle against a simulated `ctx`.
37
37
 
38
38
  ### Out of scope
39
39
 
40
40
  - Opening or managing WebSocket / WebRTC / SSE connections.
41
41
  - Maintaining live realtime room state, peer rosters, message routing, or reconnection.
42
- - Server-side authority for **browser-side** game logic. The `./server` subpath is types-only; authoritative server logic for UGC games runs inside the colyseus UGC sandbox (`packages/colyseus/src/rooms/ugc/`).
42
+ - Server-side authority for **browser-side** game logic. The `./server` subpath holds types and the pure `createBotDriver` helper; authoritative server logic for UGC games runs inside the colyseus UGC sandbox (`packages/colyseus/src/rooms/ugc/`).
43
43
  - Persistent storage. The SDK keeps everything in memory; refresh resets it.
44
44
  - UI. The SDK never renders or injects DOM.
45
45
  - Analytics. `logEvent` forwards a payload to the host via postMessage; the SDK does not POST to any analytics endpoint itself.
@@ -62,7 +62,7 @@ The package is laid out flat under `src/` and `types/`. No subdirectories.
62
62
  | `src/session.ts` | `startSession`, `submitScore`, `submitMatchScore`, `submitMatchResult`, `getQuestions`, `getWords`. |
63
63
  | `src/match-context.ts` | `fetchMatchContext` (HTTP `/leagues/<id>/matches/<id>`). |
64
64
  | `src/api-client.ts` | `apiRequest`: thin `fetch` wrapper that prefixes the API base and attaches the Bearer token. |
65
- | `src/settings.ts` | Settings snapshots, validated merge and isolated subscriptions. |
65
+ | `src/settings.ts` | Settings snapshots, validated merge and isolated subscriptions. |
66
66
  | `src/state.ts` | `SdkState` interface + the singleton `state` object. All mutable state lives here. |
67
67
  | `src/constants.ts` | `SDK_VERSION`, `MESSAGE_PREFIX`, `PARENT_REQUEST_TIMEOUT_MS`, `QUESTIONS_LIMIT_CAP`, `WORDS_LIMIT_CAP`. |
68
68
  | `src/utils.ts` | `isBrowser`, `warn`, `error`, `unwrapResult`, `readQueryParam`. |
@@ -71,7 +71,7 @@ The package is laid out flat under `src/` and `types/`. No subdirectories.
71
71
  | `types/session.ts` | `Question`, `QuestionOptions`, `ScoreMetadata`, `EventData`, `GameCompleteData`, `StartSessionResult`, `SubmitScoreResult`, `WordOptions`, `ReportWordData`, `ReportableWord` (re-exports `Word`). |
72
72
  | `types/word.ts` | `Word` + sub-interfaces (`WordSense`, `WordForm`, `Lookup`, `Synset`, `FormRepresentation`, `DynamicProp`, …) — Words Bank feature. |
73
73
  | `types/match.ts` | `MatchParticipantMember`, `MatchParticipant`, `MatchContext`, `MatchResultPayload`. |
74
- | `src/server-entry.ts` | `./server` subpath. Types-only at runtime: `GuestModule`, `Ctx`, `PeerInfo`, `BroadcastOptions`, `EndMatchPayload`, `CreateOptions`. No imports from the browser SDK; safe for tooling that compiles the bundle on Node. |
74
+ | `src/server-entry.ts` | `./server` subpath. Types (`GuestModule`, `Ctx`, `PeerInfo`, `BroadcastOptions`, `EndMatchPayload`, `CreateOptions`) plus `createBotDriver` from `src/bot-driver.ts`, its only runtime code. No imports from the browser SDK; safe for tooling that compiles the bundle on Node. |
75
75
  | `src/server-dev-harness.ts` | `./server/dev` subpath. `runLocal(guest, opts)` returns a `LocalRoom` that simulates the colyseus host (`join`, `send`, `leave`, `advance`, etc.) and records every bridge call to `outbox`. Pure Node — does not import `isolated-vm` or anything browser. |
76
76
 
77
77
  ### 3.2 Singleton model
@@ -665,10 +665,10 @@ Two modes:
665
665
 
666
666
  ### 14.7a Game settings
667
667
 
668
- | Method | Returns | Notes |
669
- | --- | --- | --- |
670
- | `getSettings()` | `GameSettings` | Detached effective snapshot; default music off. |
671
- | `onSettingsChange(listener)` | `() => void` | Immediate snapshot, then changes; unsubscribe on game teardown. |
668
+ | Method | Returns | Notes |
669
+ | ---------------------------- | -------------- | --------------------------------------------------------------- |
670
+ | `getSettings()` | `GameSettings` | Detached effective snapshot; default music off. |
671
+ | `onSettingsChange(listener)` | `() => void` | Immediate snapshot, then changes; unsubscribe on game teardown. |
672
672
 
673
673
  ### 14.7 Read-only context
674
674
 
@@ -972,7 +972,7 @@ These rules exist because of a real prior regression where transport-related cle
972
972
 
973
973
  ### 20.3 Bundle budget
974
974
 
975
- The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **44 KiB raw** and **10 KiB gzip**, the latter being the figure that matters most on the wire. The raw budget was historically 25 KB; native transport and the reliable multi-round lifecycle deliberately exceed that historical target. SDK 4.2.0 combines account music settings and multiplayer v2: **43,567 bytes raw / 9,804 bytes gzip**. The merged features deliberately raise the raw limit from 42 KiB to 44 KiB while retaining the 10 KiB gzip limit. Further growth requires a deliberate release review.
975
+ The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **52 KiB raw** and **12 KiB gzip**. SDK 4.3 deliberately raises the previous 44/10 KiB limits to include bounded lobby-state validation, typed host controls and independent subscriptions. Runtime dependencies remain empty; the distribution test checks the built and served bytes and both budgets.
976
976
 
977
977
  ### 20.4 No runtime dependencies
978
978
 
@@ -1077,7 +1077,7 @@ The `./server` and `./server/dev` subpaths are separate from the browser SDK. Im
1077
1077
 
1078
1078
  ### 21bis.1 `./server` — types
1079
1079
 
1080
- `@ksaa-nlp/gamehub-sdk/server` exports types only at runtime; the `.js` artifact contains no runtime symbols. Authors use the types from TypeScript:
1080
+ `@ksaa-nlp/gamehub-sdk/server` exports types plus one runtime helper, `createBotDriver` (see "Bot driver (4.5.0)"), which bundlers include only when a guest calls it. Authors use the types from TypeScript:
1081
1081
 
1082
1082
  ```ts
1083
1083
  import type { GuestModule, Ctx, PeerInfo } from '@ksaa-nlp/gamehub-sdk/server';
@@ -1161,8 +1161,8 @@ and bounded metadata. The v2 room requires the v2 result shape and enriches it
1161
1161
  with trusted provenance. `ctx.endMatch` is a proposal, not a saved acknowledgement.
1162
1162
  Legacy endMatch payloads remain valid in legacy rooms.
1163
1163
 
1164
- SDK_VERSION, npm version and served JS/map are 4.2.0. The distribution gate is
1165
- 44 KiB raw / 10 KiB gzip (the raw increase covers v2 validation and game settings); runtime
1164
+ SDK_VERSION, npm version and served JS/map are 4.5.0. The distribution gate is
1165
+ 52 KiB raw / 12 KiB gzip (the raw increase covers v2 validation and game settings); runtime
1166
1166
  dependencies remain empty. Scanner version 3 includes requestMultiplayerLaunch,
1167
1167
  endMatch, seededPlayers and the static-only game-settings APIs; version-2 scans
1168
1168
  are stale after rebasing onto the game-settings release. A launch request
@@ -1172,3 +1172,72 @@ observation is not successful admission; see the
1172
1172
  ## Seeded participants (4.2.0)
1173
1173
 
1174
1174
  `SeededPlayer` adds optional `kind: human|bot`, `seatId` and `peerId`. Missing kind means human for legacy hosts. V2 always supplies these fields; userId/seatId/peerId are the same opaque stable seat ID, never a bot/account credential. Bots do not connect or receive `onJoin`; the UGC bundle owns their legal moves using normal state/rules and `ctx.setTimeout`. All roster players, including bots, belong in endMatch scores. No realtime dependency is introduced. SDK Usage scanner 3 represents the widened data capability as `seededPlayers`: static identifiers are possible evidence; a trusted first UGC round-start acknowledgement confirms roster delivery. It does not prove a game consumed the field or that its bot algorithm acted. See the report specification.
1175
+
1176
+ ## Bot driver (4.5.0)
1177
+
1178
+ `@ksaa-nlp/gamehub-sdk/server` exports `createBotDriver<Move>(options)`, the
1179
+ only runtime code in the server entry. It is plain JS bundled into the game's
1180
+ UGC server bundle and uses only the injected `ctx` (`setTimeout`,
1181
+ `clearTimeout`, seeded `random`), so it adds no sandbox surface or dependency
1182
+ and does not affect the browser IIFE bundle.
1183
+
1184
+ The game supplies its rules: `legalMoves(ctx, seatId)` and `apply(ctx, seatId,
1185
+ move)` (required; `apply` should use the same path as human messages), plus
1186
+ optional `isTurn` (default always; simultaneous games must return false once
1187
+ the bot has acted for the step), `isOver` (default never), `score` (higher is
1188
+ better), `choose` (replaces the default choice) and `delayMs` (fixed number or
1189
+ per-level `[min, max]`; defaults `DEFAULT_BOT_DELAYS`: easy 1.5–3 s, medium
1190
+ 0.9–1.8 s, hard 0.5–1 s).
1191
+
1192
+ The returned `BotDriver` has `setBots(opts.seededPlayers)` (bot seats with
1193
+ `botLevel`, missing → `medium`), `bots`, `isBot(seatId)`, `schedule(ctx)` and
1194
+ `cancel(ctx)`. Call `schedule` after `onStart` and after every state change; it
1195
+ keeps at most one pending timer per bot and, when a timer fires, re-checks
1196
+ `isOver`/`isTurn`, skips an empty move list, applies the chosen move and
1197
+ schedules again. Call `cancel` on finish or in `onDispose`. Default choice:
1198
+ easy is uniformly random; medium uses the best `score` half the time and is
1199
+ random otherwise; hard always takes the best `score` (ties broken randomly).
1200
+ Without `score` every level is random. `BotDriver.kind` is the stable literal
1201
+ `"gamehub-sdk:createBotDriver"` used by the SDK usage report (scanner 5,
1202
+ static-only, detected in the private server bundle). Take Twenty-One is the
1203
+ reference integration.
1204
+
1205
+ ## Bot levels (4.4.0)
1206
+
1207
+ `SeededPlayer.botLevel` (`easy|medium|hard`) is present on bot seats from v2 hosts; treat a bot without it as `medium` (older hosts). Humans never carry it. `MultiplayerSessionRequest` `add-bot` accepts an optional `level` (host default `medium`), and lobby roster seats expose `botLevel` on bots only; `parseLobbyState` rejects unknown levels or a level on a human seat. Games decide what each level means for their own rules. This widens existing capabilities (`seededPlayers`, lobby control) and adds no new usage-report feature.
1208
+
1209
+ ## Lobby control v2 (4.3.0)
1210
+
1211
+ The optional capability `multiplayer.lobby.v2` enables game-owned lobby UI.
1212
+ `requestMultiplayerSession(request: MultiplayerSessionRequest)` sends the typed
1213
+ discriminated request to the host's POST `/multiplayer/session` bridge and returns
1214
+ `{success:true,data:MultiplayerLobbyState}` or `{success:false,error:{code,message,
1215
+ retryable}}`. Operations and their fields are defined in
1216
+ `types/multiplayer-session.ts`: create (type/passcode), join (code/name/type/
1217
+ passcode), ready (boolean), remove-bot (seatId), read/start/leave/rematch/add-bot.
1218
+ There are no caller-supplied game, session, host, profile, key or revision fields.
1219
+ The host binds these and the server enforces its normal admission/authority.
1220
+ Native/legacy hosts without the capability return `PROTOCOL_UNSUPPORTED`.
1221
+
1222
+ `onMultiplayerSessionChange(listener)` returns an unsubscribe function and
1223
+ immediately emits a detached snapshot, then trusted host pushes and successful
1224
+ request results. Callback exceptions are isolated and registrations unsubscribe
1225
+ independently. SDK validates bounded fields and copies only public roster, limits,
1226
+ phase/reason, invitation URLs and errors, never host credentials or URLs used for
1227
+ content/reservations. Invalid snapshots are ignored. `getBootstrap()` includes
1228
+ `multiplayerSession` (empty when absent) and `multiplayerEntry` (null or trusted
1229
+ initial create/join intent, code, seat type). New host pushes use
1230
+ `GAMEHUB_SDK_MULTIPLAYER_SESSION` and retain direct-parent/origin pinning.
1231
+
1232
+ Before a round exists, the bootstrap uses `mode:multiplayer_lobby` and null
1233
+ `multiplayerLaunch`. Both lobby capability and a launch suppress auth exchange
1234
+ and prohibit ordinary session creation/submission, even with a stale cached solo
1235
+ token. A loading round is a new pinned document with the existing launch contract;
1236
+ `requestMultiplayerLaunch()` semantics remain unchanged. In-flight lobby replies
1237
+ are fenced against a changed slug/launch. Hosts retain all storage and sockets
1238
+ remain in the separate adapter.
1239
+
1240
+ SDK Usage scanner 4 includes both new APIs, with Arabic admin/filter/CSV support.
1241
+ Successful validated host lobby requests observe `requestMultiplayerSession`;
1242
+ `onMultiplayerSessionChange` is static-only because delivered state does not prove
1243
+ a subscription. Observations do not prove admission or a started round.
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  (() => {
3
3
  // src/constants.ts
4
- var SDK_VERSION = "4.2.0";
4
+ var SDK_VERSION = "4.5.0";
5
5
  var MESSAGE_PREFIX = "GAMEHUB_SDK";
6
6
  var PARENT_REQUEST_TIMEOUT_MS = 2e3;
7
7
  var HOST_API_TIMEOUT_MS = 15e3;
@@ -10,6 +10,7 @@
10
10
 
11
11
  // src/state.ts
12
12
  var state = {
13
+ multiplayerEntry: null,
13
14
  gameSettings: { musicEnabled: false },
14
15
  settingsListeners: /* @__PURE__ */ new Set(),
15
16
  bootstrapLaunch: null,
@@ -45,6 +46,171 @@
45
46
  matchContextPromise: null
46
47
  };
47
48
 
49
+ // src/multiplayer-session.ts
50
+ var listeners = /* @__PURE__ */ new Set();
51
+ var empty = {
52
+ session: null,
53
+ busy: false,
54
+ error: null,
55
+ disconnected: false
56
+ };
57
+ var current = empty;
58
+ var id = (value) => typeof value === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(value);
59
+ function parseLobbyState(value) {
60
+ if (!value || typeof value !== "object") return null;
61
+ const v = value;
62
+ if (typeof v.busy !== "boolean" || typeof v.disconnected !== "boolean")
63
+ return null;
64
+ const error2 = v.error;
65
+ if (error2 !== null && (!error2 || !id(error2.code) || typeof error2.message !== "string" || error2.message.length > 1e3 || typeof error2.retryable !== "boolean"))
66
+ return null;
67
+ const s = v.session;
68
+ if (s !== null) {
69
+ if (!s || ![s.multiplayerSessionId, s.hostSeatId, s.ownSeatId].every(id) || typeof s.gameSlug !== "string" || !/^[a-z0-9-]{1,100}$/.test(s.gameSlug) || !/^\d{6}$/.test(s.roomCode) || !["waiting", "in_round", "completed", "closed"].includes(s.phase) || !Number.isSafeInteger(s.revision) || s.revision < 0 || typeof s.rematchAllowed !== "boolean" || !Array.isArray(s.seats) || s.seats.length > 272)
70
+ return null;
71
+ for (const url of [s.invitationUrl, s.spectatorInvitationUrl]) {
72
+ if (url !== void 0 && (typeof url !== "string" || url.length > 2048 || !/^https?:\/\//.test(url)))
73
+ return null;
74
+ }
75
+ const p = s.playerPolicy;
76
+ if (!p || ![
77
+ p.minPlayers,
78
+ p.maxPlayers,
79
+ p.minHumanPlayers,
80
+ p.maxBots,
81
+ p.maxSpectators
82
+ ].every((n) => Number.isSafeInteger(n) && n >= 0 && n <= 256) || p.minPlayers < 1 || p.minHumanPlayers < 1 || p.maxPlayers < p.minPlayers || p.minHumanPlayers > p.maxPlayers || p.maxBots > p.maxPlayers - p.minHumanPlayers || p.maxSpectators > 16)
83
+ return null;
84
+ if (!s.seats.every(
85
+ (seat) => seat && id(seat.seatId) && typeof seat.displayName === "string" && seat.displayName.length <= 80 && ["human", "bot"].includes(seat.kind) && (seat.botLevel === void 0 || seat.kind === "bot" && ["easy", "medium", "hard"].includes(seat.botLevel)) && ["player", "spectator"].includes(seat.type) && typeof seat.ready === "boolean" && typeof seat.online === "boolean"
86
+ ))
87
+ return null;
88
+ if (s.round !== null && (!s.round || !id(s.round.roundId) || ![
89
+ "preparing",
90
+ "loading",
91
+ "playing",
92
+ "finishing",
93
+ "completed",
94
+ "aborted",
95
+ "interrupted"
96
+ ].includes(s.round.phase) || s.round.reason !== null && (typeof s.round.reason !== "string" || s.round.reason.length > 1e3)))
97
+ return null;
98
+ }
99
+ return {
100
+ busy: v.busy,
101
+ disconnected: v.disconnected,
102
+ error: error2 ? { code: error2.code, message: error2.message, retryable: error2.retryable } : null,
103
+ session: s ? {
104
+ ...s.invitationUrl ? { invitationUrl: s.invitationUrl } : {},
105
+ ...s.spectatorInvitationUrl ? { spectatorInvitationUrl: s.spectatorInvitationUrl } : {},
106
+ multiplayerSessionId: s.multiplayerSessionId,
107
+ gameSlug: s.gameSlug,
108
+ roomCode: s.roomCode,
109
+ phase: s.phase,
110
+ revision: s.revision,
111
+ hostSeatId: s.hostSeatId,
112
+ ownSeatId: s.ownSeatId,
113
+ rematchAllowed: s.rematchAllowed,
114
+ playerPolicy: {
115
+ minPlayers: s.playerPolicy.minPlayers,
116
+ maxPlayers: s.playerPolicy.maxPlayers,
117
+ minHumanPlayers: s.playerPolicy.minHumanPlayers,
118
+ maxBots: s.playerPolicy.maxBots,
119
+ maxSpectators: s.playerPolicy.maxSpectators
120
+ },
121
+ seats: s.seats.map((seat) => ({
122
+ seatId: seat.seatId,
123
+ displayName: seat.displayName,
124
+ kind: seat.kind,
125
+ ...seat.botLevel ? { botLevel: seat.botLevel } : {},
126
+ type: seat.type,
127
+ ready: seat.ready,
128
+ online: seat.online
129
+ })),
130
+ round: s.round ? {
131
+ roundId: s.round.roundId,
132
+ phase: s.round.phase,
133
+ reason: s.round.reason
134
+ } : null
135
+ } : null
136
+ };
137
+ }
138
+ function acceptLobbyState(value) {
139
+ const parsed = parseLobbyState(value);
140
+ if (!parsed) return;
141
+ current = parsed;
142
+ for (const listener of listeners) {
143
+ try {
144
+ listener(structuredClone(current));
145
+ } catch {
146
+ }
147
+ }
148
+ }
149
+ function lobbySnapshot() {
150
+ return structuredClone(current);
151
+ }
152
+ function onMultiplayerSessionChange(listener) {
153
+ const subscription = (value) => listener(value);
154
+ listeners.add(subscription);
155
+ try {
156
+ subscription(lobbySnapshot());
157
+ } catch {
158
+ }
159
+ return () => {
160
+ listeners.delete(subscription);
161
+ };
162
+ }
163
+ async function requestMultiplayerSession(request) {
164
+ if (!state.bootstrapCapabilities.includes("multiplayer.lobby.v2"))
165
+ return {
166
+ success: false,
167
+ error: {
168
+ code: "PROTOCOL_UNSUPPORTED",
169
+ message: "This host does not support multiplayer lobby controls",
170
+ retryable: false
171
+ }
172
+ };
173
+ const slug = state.gameSlug;
174
+ const launch = state.bootstrapLaunch;
175
+ try {
176
+ const response = await requestApiFromParent("/multiplayer/session", {
177
+ method: "POST",
178
+ body: request
179
+ });
180
+ if (slug !== state.gameSlug || launch !== state.bootstrapLaunch)
181
+ return {
182
+ success: false,
183
+ error: {
184
+ code: "STALE_ATTEMPT",
185
+ message: "The multiplayer context changed",
186
+ retryable: false
187
+ }
188
+ };
189
+ const parsed = response.success ? parseLobbyState(response.data) : null;
190
+ if (parsed && (!parsed.session || parsed.session.gameSlug === slug)) {
191
+ acceptLobbyState(parsed);
192
+ return { success: true, data: lobbySnapshot() };
193
+ }
194
+ return {
195
+ success: false,
196
+ error: {
197
+ code: response.error?.code ?? "UNAVAILABLE",
198
+ message: response.error?.message ?? "Lobby request failed",
199
+ retryable: response.error?.details?.terminal !== true
200
+ }
201
+ };
202
+ } catch {
203
+ return {
204
+ success: false,
205
+ error: {
206
+ code: "UNAVAILABLE",
207
+ message: "Lobby request timed out; refresh status before retrying",
208
+ retryable: true
209
+ }
210
+ };
211
+ }
212
+ }
213
+
48
214
  // src/settings.ts
49
215
  function getSettings() {
50
216
  return { ...state.gameSettings };
@@ -251,6 +417,24 @@
251
417
  function mergeBootstrapConfig(config = {}) {
252
418
  if (!config || typeof config !== "object" || Array.isArray(config)) return;
253
419
  mergeSettings(config.settings);
420
+ if (config.multiplayerSession !== void 0)
421
+ acceptLobbyState(
422
+ config.multiplayerSession ?? {
423
+ session: null,
424
+ busy: false,
425
+ error: null,
426
+ disconnected: false
427
+ }
428
+ );
429
+ if (config.multiplayerEntry === null) state.multiplayerEntry = null;
430
+ else if (config.multiplayerEntry && ["create", "join"].includes(config.multiplayerEntry.action)) {
431
+ const entry = config.multiplayerEntry;
432
+ state.multiplayerEntry = {
433
+ action: entry.action,
434
+ ...typeof entry.roomCode === "string" && /^\d{6}$/.test(entry.roomCode) ? { roomCode: entry.roomCode } : {},
435
+ ...entry.type === "player" || entry.type === "spectator" ? { type: entry.type } : {}
436
+ };
437
+ }
254
438
  const apply = (key, raw) => {
255
439
  const next = trimToNullable(raw);
256
440
  if (next === void 0) return;
@@ -298,6 +482,8 @@
298
482
  }
299
483
  function snapshotBootstrap() {
300
484
  return {
485
+ multiplayerEntry: state.multiplayerEntry,
486
+ multiplayerSession: lobbySnapshot(),
301
487
  settings: getSettings(),
302
488
  gameSlug: state.gameSlug,
303
489
  authToken: state.authToken,
@@ -653,7 +839,7 @@
653
839
  }
654
840
  }
655
841
  async function startSession() {
656
- if (state.bootstrapLaunch)
842
+ if (state.bootstrapLaunch || state.bootstrapCapabilities.includes("multiplayer.lobby.v2"))
657
843
  return { success: false, error: "Multiplayer rounds own their results" };
658
844
  if (state.sessionToken) return { success: true, token: state.sessionToken };
659
845
  if (state.sessionStartPromise) return await state.sessionStartPromise;
@@ -748,6 +934,12 @@
748
934
  }
749
935
  async function submitScore(score, meta = {}) {
750
936
  await ensureInitialized();
937
+ if (state.bootstrapLaunch || state.bootstrapCapabilities.includes("multiplayer.lobby.v2"))
938
+ return failedResult(
939
+ "FORBIDDEN",
940
+ "Multiplayer rounds own their results",
941
+ false
942
+ );
751
943
  if (!state.isInitialized) {
752
944
  return failedResult(
753
945
  "SDK_NOT_INITIALIZED",
@@ -968,7 +1160,7 @@
968
1160
  state.isAutoInitializing = false;
969
1161
  return false;
970
1162
  }
971
- if (!state.authToken && !state.bootstrapLaunch) {
1163
+ if (!state.authToken && !state.bootstrapLaunch && !state.bootstrapCapabilities.includes("multiplayer.lobby.v2")) {
972
1164
  state.authToken = await getAuthTokenFromParent();
973
1165
  }
974
1166
  state.isInitialized = true;
@@ -1011,6 +1203,8 @@
1011
1203
  state.bootstrapReceived = true;
1012
1204
  mergeBootstrapConfig(data.payload);
1013
1205
  }
1206
+ if (type === MESSAGE_PREFIX + "_MULTIPLAYER_SESSION" && state.bootstrapCapabilities.includes("multiplayer.lobby.v2"))
1207
+ acceptLobbyState(data.payload);
1014
1208
  if (type === MESSAGE_PREFIX + "_SET_AUTH") {
1015
1209
  state.authToken = data.token;
1016
1210
  if (state.gameSlug && !state.sessionToken && !state.sessionStartPromise && (state.authToken || state.leagueId && state.gameId && state.matchId)) {
@@ -1137,6 +1331,11 @@
1137
1331
  return !!state.sessionToken;
1138
1332
  },
1139
1333
  requestMultiplayerLaunch,
1334
+ requestMultiplayerSession,
1335
+ onMultiplayerSessionChange(listener) {
1336
+ installHostMessageListener();
1337
+ return onMultiplayerSessionChange(listener);
1338
+ },
1140
1339
  async startSession() {
1141
1340
  await ensureInitialized();
1142
1341
  if (state.sessionStartPromise) return await state.sessionStartPromise;
@@ -1205,6 +1404,8 @@
1205
1404
  },
1206
1405
  getBootstrap() {
1207
1406
  return {
1407
+ multiplayerEntry: state.multiplayerEntry,
1408
+ multiplayerSession: lobbySnapshot(),
1208
1409
  settings: getSettings(),
1209
1410
  gameSlug: state.gameSlug,
1210
1411
  authToken: state.authToken,