@ksaa-nlp/gamehub-sdk 0.9.0 → 3.6.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 (74) hide show
  1. package/README.md +158 -373
  2. package/SPEC.md +869 -0
  3. package/dist/gamehub-sdk.js +168 -1191
  4. package/dist/gamehub-sdk.js.map +3 -3
  5. package/dist/src/api-client.d.ts +15 -5
  6. package/dist/src/api-client.d.ts.map +1 -1
  7. package/dist/src/api-client.js +21 -5
  8. package/dist/src/api-client.js.map +1 -1
  9. package/dist/src/bridge.d.ts +31 -14
  10. package/dist/src/bridge.d.ts.map +1 -1
  11. package/dist/src/bridge.js +148 -159
  12. package/dist/src/bridge.js.map +1 -1
  13. package/dist/src/constants.d.ts +8 -6
  14. package/dist/src/constants.d.ts.map +1 -1
  15. package/dist/src/constants.js +8 -6
  16. package/dist/src/constants.js.map +1 -1
  17. package/dist/src/init.d.ts +18 -12
  18. package/dist/src/init.d.ts.map +1 -1
  19. package/dist/src/init.js +23 -156
  20. package/dist/src/init.js.map +1 -1
  21. package/dist/src/main.d.ts +45 -85
  22. package/dist/src/main.d.ts.map +1 -1
  23. package/dist/src/main.js +33 -52
  24. package/dist/src/main.js.map +1 -1
  25. package/dist/src/match-context.d.ts.map +1 -1
  26. package/dist/src/match-context.js +0 -14
  27. package/dist/src/match-context.js.map +1 -1
  28. package/dist/src/server-dev-harness.d.ts +85 -0
  29. package/dist/src/server-dev-harness.d.ts.map +1 -0
  30. package/dist/src/server-dev-harness.js +233 -0
  31. package/dist/src/server-dev-harness.js.map +1 -0
  32. package/dist/src/server-entry.d.ts +127 -0
  33. package/dist/src/server-entry.d.ts.map +1 -0
  34. package/dist/src/server-entry.js +26 -0
  35. package/dist/src/server-entry.js.map +1 -0
  36. package/dist/src/session.d.ts +16 -9
  37. package/dist/src/session.d.ts.map +1 -1
  38. package/dist/src/session.js +38 -27
  39. package/dist/src/session.js.map +1 -1
  40. package/dist/src/state.d.ts +17 -55
  41. package/dist/src/state.d.ts.map +1 -1
  42. package/dist/src/state.js +13 -32
  43. package/dist/src/state.js.map +1 -1
  44. package/dist/src/utils.d.ts +3 -14
  45. package/dist/src/utils.d.ts.map +1 -1
  46. package/dist/src/utils.js +3 -31
  47. package/dist/src/utils.js.map +1 -1
  48. package/dist/types/bootstrap.d.ts +56 -36
  49. package/dist/types/bootstrap.d.ts.map +1 -1
  50. package/dist/types/question.d.ts +36 -0
  51. package/dist/types/question.d.ts.map +1 -0
  52. package/dist/types/question.js +21 -0
  53. package/dist/types/question.js.map +1 -0
  54. package/dist/types/session.d.ts +46 -20
  55. package/dist/types/session.d.ts.map +1 -1
  56. package/package.json +14 -4
  57. package/CHANGELOG.md +0 -545
  58. package/MIGRATION.md +0 -322
  59. package/dist/src/multiplayer-match.d.ts +0 -42
  60. package/dist/src/multiplayer-match.d.ts.map +0 -1
  61. package/dist/src/multiplayer-match.js +0 -551
  62. package/dist/src/multiplayer-match.js.map +0 -1
  63. package/dist/src/multiplayer.d.ts +0 -96
  64. package/dist/src/multiplayer.d.ts.map +0 -1
  65. package/dist/src/multiplayer.js +0 -536
  66. package/dist/src/multiplayer.js.map +0 -1
  67. package/dist/types/multiplayer-match.d.ts +0 -204
  68. package/dist/types/multiplayer-match.d.ts.map +0 -1
  69. package/dist/types/multiplayer-match.js +0 -15
  70. package/dist/types/multiplayer-match.js.map +0 -1
  71. package/dist/types/multiplayer.d.ts +0 -194
  72. package/dist/types/multiplayer.d.ts.map +0 -1
  73. package/dist/types/multiplayer.js +0 -2
  74. package/dist/types/multiplayer.js.map +0 -1
package/CHANGELOG.md DELETED
@@ -1,545 +0,0 @@
1
- # Changelog
2
-
3
- ## 0.9.0 — 2026-05-03
4
-
5
- Tier-2 / Tier-3 multiplayer features. The headline change is **server-enforced host-only events** (E) — a guest can no longer forge authoritative state by hand-crafting a wire frame. Also: **opt-in host migration** (G), **per-room realtime rate limits** (F), `lastSeenAt` on peers (J), and a structured `ROOM_FULL` error frame (I).
6
-
7
- Existing games that don't enable `autoMigrateHost` keep current behaviour. Existing `multiplayer.broadcast` callers are silently upgraded — the SDK now stamps `hostOnly: true` on every broadcast, and a non-host trying to bypass `multiplayer.broadcast` and call `multiplayer.send` with `hostOnly: true` will be dropped server-side. Game code does not need to change.
8
-
9
- ### Server-enforced `hostOnly` (E) — security
10
-
11
- Wire frames may now carry `hostOnly: true`. The realtime server drops such a frame and replies with `{ type: 'system', eventName: 'error', payload: { code: 'HOST_ONLY', eventName } }` when the sender's role is not `host`. The SDK's `multiplayer.broadcast` and the match-API's `ctx.broadcast` / start-event paths set the flag automatically, so authoritative game state can no longer be forged by a guest. Application code does not need to set `hostOnly` directly.
12
-
13
- ```ts
14
- sdk.multiplayer.broadcast('cell_opened', { id: 7 });
15
- // wire: { eventName: 'cell_opened', payload: ..., hostOnly: true }
16
- // — server enforces; a guest sending the same frame gets HOST_ONLY back.
17
- ```
18
-
19
- ### Configurable per-room rate limits (F)
20
-
21
- `RoomOptions` accepts `rateBurst` and `rateWindowMs`. Defaults remain 20 frames per 1000ms — fine for turn-based play. Real-time games (movement, drawing, fast input) raise the burst:
22
-
23
- ```ts
24
- sdk.multiplayer.createRoom({ rateBurst: 100, rateWindowMs: 1000 });
25
- ```
26
-
27
- Cached on `wsMeta` at connect time so the message hot path doesn't re-read the room doc per frame. The HTTP `/multiplayer/rooms/create` endpoint validates and persists both fields.
28
-
29
- ### Host migration on host-disconnect (G) — opt-in
30
-
31
- `RoomOptions.autoMigrateHost: true` flips host-disconnect from "close the room after the grace window" to "promote the earliest-joined remaining peer." Server-side flow on timer expiry:
32
-
33
- 1. Pick the earliest-joined active peer (via `getPeers()`, now `joinedAt`-ordered — see H).
34
- 2. Update its peer doc role to `host`, demote the previous host's peer doc to `player`, and update the room's `hostPeerId`.
35
- 3. Flip `wsMeta.role` for the new host's live socket so its next `broadcast` passes the `hostOnly` check immediately.
36
- 4. Publish `{ type: 'system', eventName: 'host_changed', payload: { newHostPeerId, previousHostPeerId } }` to the room.
37
-
38
- The SDK listens for `host_changed`: if the local peer is the promotee, `state.mpRoom.role` flips to `host` and subsequent `multiplayer.isHost()` / `multiplayer.broadcast` route correctly without a reconnect. The match-API picks this up via `Multiplayer.isHost()` (already dynamic), so a mid-match migration doesn't require re-running `buildStart` — the new host just becomes responsible for `ctx.broadcast` going forward.
39
-
40
- A new upgrade-path guard rejects WebSocket upgrades whose JWT claims `role: 'host'` when the room's current `hostPeerId` doesn't match the token's `peerId`, closing a small race where the original host's stale token could re-claim host after migration.
41
-
42
- ```ts
43
- // Lobby / casual co-op: keep playing if host drops.
44
- sdk.multiplayer.createRoom({ autoMigrateHost: true });
45
-
46
- sdk.multiplayer.on('host_changed', ({ newHostPeerId, previousHostPeerId }) => {
47
- if (sdk.multiplayer.getMyPeerId() === newHostPeerId) {
48
- // we are now responsible for authoritative state
49
- }
50
- });
51
- ```
52
-
53
- **Default off.** Most match-style games (link-game, quizzes) should leave it off — losing the host mid-match is correctly fatal because the host owns authoritative state. Suitable for relay / lobby / casual co-op games where any peer can keep play going.
54
-
55
- ### `getPeers` ordered by `joinedAt` (H)
56
-
57
- `getPeers()` now sorts by `joinedAt` ascending. This makes seat-assignment deterministic on first reference (no more lex-sort fallback by peerId), and is a prerequisite for G's "earliest-joined first" promotion. No game-visible behaviour change beyond ordering stability.
58
-
59
- ### `ROOM_FULL` system frame (I)
60
-
61
- Previously, a WS upgrade past `maxPlayers + overbook` was rejected with a raw `socket.destroy()` — the SDK saw a connection refused and the game showed a generic error. The server now completes the WS handshake just long enough to deliver `{ type: 'system', eventName: 'error', payload: { code: 'ROOM_FULL', maxPlayers } }` and then closes with code 4001. The HTTP `/joinRoom` path still pre-checks capacity, so this matters mainly for the WS-upgrade race when two peers try to claim the last seat simultaneously.
62
-
63
- ### `lastSeenAt` on peers (J)
64
-
65
- `Peer.lastSeenAt` (ms since epoch) is now populated in the `room_joined` peers list and on every `peer_joined` payload. Refreshed on every inbound frame and on the WS heartbeat. Lets games render "last seen 3s ago" badges or dim flaky peers without extra plumbing.
66
-
67
- ```ts
68
- const peers = sdk.multiplayer.getPeers();
69
- peers.forEach((p) => {
70
- const stale = Date.now() - (p.lastSeenAt ?? 0) > 5_000;
71
- // dim avatar, show spinner, etc.
72
- });
73
- ```
74
-
75
- ### Migration notes
76
-
77
- - **Server config**: a new optional env knob `MULTIPLAYER_HOST_CLOSE_GRACE_MS` decouples the host-close timer from `RECONNECT_GRACE_MS` (production default still 30s). Used by integration tests so the migration path doesn't take 30s to fire.
78
- - **Mongo schema**: `multiplayer_rooms` gains optional `rateBurst`, `rateWindowMs`, `autoMigrateHost` fields. All optional — existing room docs work unchanged.
79
- - **Client semantics**: a non-host calling `multiplayer.send(name, payload, { hostOnly: true })` will now be dropped server-side with a `HOST_ONLY` error frame. This was effectively impossible before (the SDK didn't accept the option), so this is only a hazard for hand-crafted wire frames or custom clients.
80
-
81
- ## 0.7.0 — 2026-04-30
82
-
83
- Three Tier-1 transport features completing the multiplayer roadmap: targeted send, per-peer seq continuity across reconnect, and a server-clock helper. All three are additive — existing `multiplayer.send` / `broadcast` / `match` calls keep their current semantics.
84
-
85
- ### Targeted send (`SendOptions.to`)
86
-
87
- `multiplayer.send(name, payload, { to: peerId | peerId[] })` and the matching `MatchBroadcastOptions.to` route a frame to a specific subset of peers in the room instead of fanning out. Use cases: a private host→guest hint, per-player power-up effects that shouldn't leak to a spectator, host correcting one guest's view.
88
-
89
- ```ts
90
- sdk.multiplayer.send('private_hint', payload, { to: guestPeerId });
91
- ctx.broadcast('reveal_for_winner', payload, { to: [winnerId] });
92
- ```
93
-
94
- Server-side semantics:
95
- - The sender does NOT receive their own frame as an echo unless their id is explicitly in the `to` list.
96
- - Unknown peerIds are silently skipped (no error frame).
97
- - `to` and `retain` are mutually exclusive — a targeted frame is per-definition not a room-wide snapshot, so the server drops `retain` when `to` is set. The match-API mirrors this client-side and also skips the local `apply` step on targeted broadcasts (targeting means "send state to specific peers", not "this is the new authoritative state").
98
-
99
- ### Per-peer seq continuity across reconnect
100
-
101
- A peer's outbound `seq` counter now survives a disconnect+reconnect within `RECONNECT_GRACE_MS` (30s). Previously the counter reset to 0 on every new socket because it lived in `wsMeta` (a `WeakMap` keyed by socket); a reconnecting peer's first new message would have `seq=1`, which the SDK's `mpLastSeqByPeer` dedupe at the receiver would compare against the last value seen pre-disconnect (e.g. `seq=12`) and silently drop.
102
-
103
- Server changes that fix this:
104
- - The `multiplayer_peers` collection now stores `seq` per peer doc.
105
- - `storePeer()` (called on every connect) reads the existing seq and seeds `wsMeta.state.seq` from it before any message is processed.
106
- - The message handler captures `state.seq` into a local immediately after incrementing, then awaits `touchPeer(peerId, seq)` (persists seq + lastSeenAt) BEFORE publishing — so a crash between persist and publish leaves the DB at-least-as-recent as what receivers observed.
107
- - The `ws.on('close')` handler no longer deletes the peer doc; it sets `lastSeenAt: 0` so `getPeers` immediately filters the peer out, but the `seq` value stays around for a reconnect to pick up.
108
-
109
- Race fix as part of this: previously, three concurrent message handlers on the same socket could yield on `await touchPeer` interleaved, all read `state.seq` at the end, and emit identical seqs. The seq is now snapshotted into a local before any `await`.
110
-
111
- ### Server clock helper (`multiplayer.serverNow()`)
112
-
113
- `sdk.multiplayer.serverNow()` returns a server-anchored timestamp in milliseconds. Use it — not `Date.now()` — for any timer math compared across peers (countdowns, deadlines, replay times). Peer device clocks routinely drift seconds apart; without this, two peers running the same `maxTimeSec - (Date.now() - serverStartMs)/1000` countdown can show different remaining times.
114
-
115
- Implementation: every incoming frame's `sentAt - Date.now()` becomes a sample. The first sample sets the offset wholesale; subsequent samples blend via a 0.85 / 0.15 EMA so a single high-latency packet doesn't yank the clock around. Retained replays are excluded from offset updates (their `sentAt` is when the host originally pinned them, not the current network).
116
-
117
- ```ts
118
- // Old: brittle across clock skew
119
- const remaining = maxTimeSec - (Date.now() - serverStartMs) / 1000;
120
-
121
- // New: stable
122
- const remaining = maxTimeSec - (sdk.multiplayer.serverNow() - serverStartMs) / 1000;
123
- ```
124
-
125
- Returns `Date.now()` exactly until the first frame arrives, so games can call it during boot without special-casing.
126
-
127
- ### Verified
128
-
129
- - 23/23 realtime tests green (14 unit + 9 integration). New tests cover: targeted single-peer delivery, targeted multi-peer delivery, targeted-strips-retain, seq continuity across reconnect, peer-doc preserved on disconnect.
130
- - SDK type-check + build clean.
131
-
132
- ### Wire format
133
-
134
- Strictly additive on the wire. Inbound (client → server):
135
- - `to?: string | string[]` — targeted recipients.
136
-
137
- Server → client: unchanged. The server-stamped `sentAt` was already on every frame; v0.7 just consumes it on the SDK side.
138
-
139
- ### Unchanged
140
-
141
- - `Sdk` interface beyond the new `multiplayer.serverNow()` method and the new `to` field on `SendOptions` / `MatchBroadcastOptions` (both optional).
142
- - `BootstrapData`, `MpMessage`.
143
- - All other multiplayer methods.
144
- - The match API — adding retain/seq features here doesn't touch its semantics.
145
-
146
- ---
147
-
148
- ## 0.6.1 — 2026-04-30
149
-
150
- Three small, additive fixes that surfaced while porting link-game to the `multiplayer.match` API.
151
-
152
- - **`MatchCtx.retained: boolean`.** Added a `retained` flag on the context passed into `apply` and `onStart` handlers. It's `true` only when the handler is running for a server-replayed retained frame (a peer reconnecting / joining late catching up on past state) and `false` for live broadcasts and host-initiated calls. Game code uses this to suppress one-shot side effects — sounds, confetti, win animations, draw dialogs on a delay — that would otherwise re-fire for state the peer didn't see live. Also: retained replays no longer trigger a host's `hostHandle` (the host already authored that frame; re-validating against its own snapshot is at best wasteful, at worst incorrect).
153
-
154
- - **`Peer` identity fields.** The wire payload from the realtime server (`displayName`, `avatar`, `userId`, `guestId`) was already populated from JWT claims, but the public `Peer` type only exposed `peerId`/`role`/`metadata`. Adding the rest as optional fields lets games access player-name and avatar info without an `as any` cast. Optional because anonymous / passcode-joined peers may not carry all four.
155
-
156
- - **`MatchEventMap` constraint relaxed to a self-mapped form.** `match<TMap, TStart>(...)` previously required `TMap extends Record<string, MatchScopedPayload>`, which TypeScript silently rejects for an `interface LinkMatchMap { ... }` declaration because interfaces with concrete keys don't have an index signature. Switched the constraint everywhere (the `match()` factory, `MatchOptions`, the `Sdk['multiplayer'].match` signature) to the self-mapped pattern `<TMap extends { [K in keyof TMap]: MatchScopedPayload }>`, which accepts both interface-shaped and type-alias-shaped event maps while still enforcing per-key payload safety. The `MatchEventMap` alias is retained as documentation; its docstring now explains why the actual generics use the self-mapped form.
157
-
158
- ### Why these are 0.6.1 rather than 0.6.0
159
-
160
- These shipped together with the original `multiplayer.match` API (0.6.0) but emerged only when a real game tried to consume it. Bumping a patch version makes the relationship explicit: 0.6.0 is the API as designed; 0.6.1 is the API as a real game actually uses it.
161
-
162
- ### Verified
163
-
164
- - SDK type-check + build clean (53.3 KB IIFE).
165
- - link-game (Angular, `@ksaa-nlp/gamehub-sdk@0.6.x` consumer) builds clean against the new types.
166
- - 18/18 realtime tests still green.
167
-
168
- ### Unchanged
169
-
170
- - Wire protocol with the realtime server.
171
- - `Sdk` interface beyond the new `MatchCtx.retained` / `Peer.{userId,guestId,displayName,avatar}` fields and the loosened `match<>` constraint (purely a relaxation, no existing code breaks).
172
- - `BootstrapData`, `MpMessage`, `multiplayer.send` / `broadcast` / `on` semantics.
173
-
174
- ---
175
-
176
- ## 0.6.0 — 2026-04-30
177
-
178
- Adds **`multiplayer.match()`** — a host-authoritative match coordinator that owns the lifecycle every multiplayer game otherwise reinvents: peer-ready handshake, host-elected match start, intent → resolve routing, matchId scoping, and idempotent reapply of broadcasts (live and retained replay alike). Plus two helpers (`assignSeats`, `waitForPeers`) that complete the picture.
179
-
180
- ### Why
181
-
182
- Surveying the in-tree multiplayer game (link-game) showed that ~700 lines of its component file were transport plumbing, not gameplay: a `readyPeerIds` set, a `currentMatchId`, an `appliedEventKeys` set, manual `if (!this.isHostPeer()) return;` guards on every intent path, manual `if (p.matchId !== this.currentMatchId) return;` filters on every applier, and an ad-hoc switch dispatcher fanning the SDK's `'message'` channel into per-event handlers.
183
-
184
- All of that is generic — every host-authoritative game needs the same machinery — so it belongs in the SDK.
185
-
186
- ### What changed
187
-
188
- - **`Sdk.multiplayer.match<TMap, TStart>(options)`**. Build a Match by declaring (a) a typed event map, (b) per-event `hostHandle` / `apply` pairs, and (c) a host-only `buildStart`. Everything else lives in the reducer.
189
-
190
- ```ts
191
- const match = sdk.multiplayer.match<LinkMap, MatchStartPayload>({
192
- expectedPeers: 2,
193
- buildStart: async (peers) => ({
194
- greenPeerId: seats.bySeat.green,
195
- navyPeerId: seats.bySeat.navy,
196
- cellAssignments: makeGrid(),
197
- startedAtMs: Date.now(),
198
- }),
199
- onStart: (ctx, p) => applyMatchStart(p),
200
- events: {
201
- 'link:cell_click_request': {
202
- hostHandle: (ctx, p, from) => ctx.broadcast('link:cell_opened', resolve(p, from)),
203
- },
204
- 'link:cell_opened': {
205
- apply: (ctx, p) => applyCellOpened(p),
206
- idKey: (p) => `cell:${p.cellId}`,
207
- retain: true,
208
- retainKey: (p) => `cell:${p.cellId}`,
209
- },
210
- },
211
- onWaitingForPeers: (waiting) => /* show overlay */,
212
- onPeerLeft: (ctx, peerId) => /* show disconnect dialog */,
213
- onAborted: (reason) => /* show retry/back */,
214
- });
215
- ```
216
-
217
- What the SDK enforces, so games stop writing it:
218
- - `peer_ready` handshake fires automatically (or on an explicit `match.markReady()` when `autoReady: false`).
219
- - Host elects start once `expectedPeers` are present and ready, calls `buildStart`, broadcasts the result with `retain: true` so reconnecting peers receive it.
220
- - **`matchId` auto-injection on send + auto-verification on receive.** Frames from a previous match are dropped before user code runs.
221
- - **`idKey` dedupe** — same logical event applied at most once per match. Defaults to `${event}:${matchId}:${seq}`; override per-event when retained replays need to dedupe against live frames the peer already saw (e.g. `cell:${cellId}`).
222
- - **Host short-circuit** — `match.intent(...)` from the host runs `hostHandle` directly without a WS roundtrip.
223
- - **`hostOnly` guarding** — `ctx.broadcast` no-ops on guests with a warning.
224
- - **Lifecycle states** — `waiting | starting | active | aborted | ended`. Subscribe via `match.onStateChange(handler)`.
225
- - **Reconnect resilience** — re-announces ready on every `connected`/`room_joined`, replays retained match-start + per-event snapshots automatically, idKey dedupe catches the overlap.
226
-
227
- - **`Sdk.multiplayer.assignSeats(peers, seatNames, hostPeerId)`** — generalises link-game's `assignColors` to N seats and N peers. Sorts as `host first, then lex-asc by peerId`, returns both `bySeat` and `byPeer` maps.
228
-
229
- - **`Sdk.multiplayer.waitForPeers(n, timeoutMs?)`** — promise-based barrier for "don't render until everyone's here".
230
-
231
- - The match-start broadcast is **always retained** under `match:start`. Per-event retain is opt-in via `MatchEventDef.retain` / `retainKey`. The `retain` defaults are baked into the reducer so games that follow the standard pattern get transparent reconnect for free.
232
-
233
- - New exported types: [`Match`, `MatchOptions`, `MatchCtx`, `MatchHostCtx`, `MatchEventDef`, `MatchEventMap`, `MatchScopedPayload`, `MatchBroadcastOptions`, `MatchState`, `MatchAbortReason`](./types/multiplayer-match.ts).
234
-
235
- ### Migration
236
-
237
- The match API is purely additive — existing `multiplayer.send` / `broadcast` / `on` paths are unchanged. Games can adopt it incrementally; mixing match-managed events with raw `multiplayer.on` listeners is fine.
238
-
239
- A typical port (link-game): the per-event switch in [link.component.ts:491](https://github.com/...) becomes the `events` map, `readyPeerIds` / `appliedEventKeys` / `currentMatchId` are deleted, every `if (p.matchId !== this.currentMatchId)` and `if (this.isHostPeer())` guard is deleted. Estimated 60–70% reduction in multiplayer-related code.
240
-
241
- ### What's verified
242
-
243
- - TypeScript: full type-check passes; a smoke test exercises the public generics end-to-end against a realistic game-shaped event map (typed `hostHandle`, `apply`, `idKey`, `retainKey`, `assignSeats` literal-tuple inference, `match.intent`/`match.broadcast`).
244
- - Build: `npm run build` ships a 53.1 KB IIFE (up from 39.8 KB at 0.5).
245
-
246
- ### Unchanged
247
-
248
- - Wire protocol with the realtime server (the match reducer just uses the existing `send`/`broadcast` + retained-events transport from 0.5).
249
- - Public `Sdk` interface beyond the three new methods.
250
- - `BootstrapData` shape, `MpMessage` shape, all other multiplayer methods.
251
-
252
- ---
253
-
254
- ## 0.5.0 — 2026-04-30
255
-
256
- Adds **retained ("sticky") multiplayer events** so peers that join or reconnect mid-match automatically receive the latest authoritative state before any live traffic — without games having to write a custom resync intent.
257
-
258
- ### Why
259
-
260
- Every multiplayer game using the SDK has the same gap: when a guest peer drops and reconnects (or a viewer joins late), they have no idea what `match_start` said, which cells/turns/positions are filled, or whose turn it is. Today the only fix is per-game: a custom `request_state_sync` intent and a `state_snapshot` response, with all the bespoke serialisation and dedupe logic that implies. The SDK couldn't ship the upcoming `multiplayer.match` reducer's "transparent reconnect" guarantee without solving this.
261
-
262
- Retained frames put the fix at the transport layer where it belongs. The host pins the latest broadcast for a given key; the realtime server replays the pinned set to every newcomer in original insertion order, before any live frame for that key reaches the new socket. Borrowed semantics from MQTT retained messages — a small, well-understood primitive.
263
-
264
- ### What changed
265
-
266
- - **`SendOptions { retain?: boolean; retainKey?: string }`** is a new optional third argument on `multiplayer.send` and `multiplayer.broadcast`. Defaults preserve the old behaviour exactly.
267
- - **`MpMessage.retained?: boolean`** marks frames replayed by the server. Game code can usually treat retained and live frames identically (apply both via the same handler); games that play sounds or animations on a state change typically suppress them when `retained` is true.
268
- - **Per-peer seq dedupe now skips retained frames** and does not advance the per-peer high-water mark when one arrives. Replays carry their original `seq` (intentionally older than any live frame the receiver may already have seen), so the dedupe at [src/multiplayer.ts](./src/multiplayer.ts) would otherwise drop them. Live ordering is unaffected because `mpLastSeqByPeer` continues to advance only on live frames.
269
- - **`SendOptions` is re-exported** from the package entry alongside the other multiplayer types.
270
-
271
- ### Wire format
272
-
273
- Outbound (sender → server):
274
-
275
- ```jsonc
276
- {
277
- "eventName": "link:match_start",
278
- "payload": { ... },
279
- "retain": true, // host-only on the server side
280
- "retainKey": "match_start" // optional; defaults to eventName
281
- }
282
- ```
283
-
284
- Inbound (server → all peers, replay or live):
285
-
286
- ```jsonc
287
- {
288
- "type": "game_event",
289
- "roomCode": "...",
290
- "fromPeerId": "...",
291
- "eventName": "...",
292
- "payload": { ... },
293
- "seq": 7,
294
- "sentAt": 1714378900000,
295
- "retained": true // present on replays only
296
- }
297
- ```
298
-
299
- ### Server requirements
300
-
301
- This release pairs with realtime-server changes that:
302
-
303
- - Store retained frames per room (memory + MongoDB), capped at 64 keys per room with FIFO eviction at the cap.
304
- - Replay them to every new socket immediately after `room_joined` and before any live frame can reach that socket.
305
- - Drop the `retain` flag silently from non-host senders so a guest can't forge long-lived state for late joiners.
306
- - TTL retained docs in MongoDB at 24 hours (orphan cleanup for rooms closed via the HTTP API rather than via host disconnect).
307
-
308
- The wire format is a strict superset of v0.4 — older clients connecting to a server with retain support keep working unchanged (they just don't see the new fields). Older servers connecting from v0.5 clients ignore the `retain`/`retainKey` fields harmlessly.
309
-
310
- ### How games use it
311
-
312
- ```ts
313
- // Host-authoritative match start — replays for every reconnecting peer
314
- sdk.multiplayer.broadcast('link:match_start', payload, {
315
- retain: true,
316
- retainKey: 'match_start',
317
- });
318
-
319
- // Per-cell board state, replayed cell-by-cell on reconnect
320
- sdk.multiplayer.broadcast('link:answer_resolved', payload, {
321
- retain: true,
322
- retainKey: `cell:${payload.cellId}`,
323
- });
324
- ```
325
-
326
- Game-side dedupe (e.g. an `appliedEventKeys` set keyed by the same logical id) is still required: the same logical event can arrive once live and once retained on a reconnect-during-match. The upcoming `multiplayer.match` reducer formalises this via its `idKey` callback.
327
-
328
- ### Unchanged
329
-
330
- - Public `Sdk` interface beyond the new `SendOptions` parameter.
331
- - `BootstrapData` shape.
332
- - `MpMessage` for live frames (the `retained` flag is opt-in and absent on every existing path).
333
- - All other multiplayer methods (`createRoom`, `joinRoom`, `leaveRoom`, `getRoom`, `getPeers`, …).
334
-
335
- ---
336
-
337
- ## 0.4.0 — 2026-04-28
338
-
339
- ESM-only npm package shape with proper `exports`, retired hand-written shim, and a separate IIFE bundle for the `<script>`-tag flow. The package now installs cleanly and imports correctly under Node's native ESM loader, Angular, Vite, webpack, and esbuild — no bundler-specific workarounds.
340
-
341
- ### Why
342
-
343
- v0.3.0 made the source SSR-safe but left the package shape unfinished: `package.json` still pointed at `./dist/gamehub-sdk.js` and `./dist/index.mjs` (paths that no longer existed after the namespace conversion), there was no proper `exports` map, and the `scripts/emit-module-entry.mjs` shim was still hand-writing a fake module wrapper around the IIFE. This release replaces all of that with a real dual-output build.
344
-
345
- ### What changed
346
-
347
- - **ESM-only.** `"type": "module"` in [package.json](./package.json). No CJS condition in the `exports` map — modern Node (≥18), Angular CLI, Vite, webpack, esbuild, Bun, and Rollup all consume ESM natively.
348
- - **Source uses `.js` extensions in relative imports** (e.g. `import { state } from './state.js'`), matching Node's native ESM resolution. TypeScript with `moduleResolution: NodeNext` resolves these to the source `.ts` at compile time and preserves the `.js` extension in the emitted output.
349
- - **`tsconfig.json`** switched to `module: NodeNext` / `moduleResolution: NodeNext` (was `Bundler`). Stricter — catches missing extensions at type-check time.
350
- - **New `package.json` `exports` map** with three subpaths:
351
- - `.` → `./dist/src/main.js` (the npm/Angular/Node ESM entry; no side effects on import).
352
- - `./browser` → `./dist/src/browser-entry.js` (subpath import for consumers who want the IIFE side effects without the `<script>` tag, e.g. inside a bundler that's targeting a browser-only build).
353
- - `./gamehub-sdk.js` → `./dist/gamehub-sdk.js` (so a CDN or app server can serve `node_modules/@ksaa-nlp/gamehub-sdk/dist/gamehub-sdk.js` directly).
354
- - **`sideEffects`: `["./dist/src/browser-entry.js", "./dist/gamehub-sdk.js"]`** so bundlers tree-shake the pure ESM entry but never strip the IIFE side effect from the script-tag bundle.
355
- - **New build pipeline.** `tsc` does per-file ESM emit + declarations into `dist/src/` and `dist/types/`. `esbuild` bundles [src/browser-entry.ts](./src/browser-entry.ts) into a single 40 KB IIFE at `dist/gamehub-sdk.js` for the script-tag distribution channel. Both run from `npm run build` (and via `prepack` so `npm pack` / `npm publish` always rebuild).
356
- - **Retired `scripts/emit-module-entry.mjs`** and its hand-written `dist/index.mjs` / `dist/index.d.ts`. The whole `scripts/` directory is gone.
357
- - **Trimmed `files`** to ship only `dist/**/*`, `README.md`, `CHANGELOG.md`, `MIGRATION.md`. No more leaking source `.ts`, `tsconfig.json`, or build scripts to consumers.
358
- - **`SDK_VERSION` constant** is now in sync with `package.json`.
359
-
360
- ### Breaking change for module consumers
361
-
362
- `import sdk from '@ksaa-nlp/gamehub-sdk'` (default import) no longer resolves — the previous shim that re-exposed the global as a fake default is gone. Use the named factory:
363
-
364
- ```ts
365
- import { createSdk } from '@ksaa-nlp/gamehub-sdk';
366
- const sdk = createSdk();
367
- await sdk.ready();
368
- ```
369
-
370
- CJS `require()` is no longer supported. Tooling that needs CJS interop (older Jest, some Mocha configs) needs a transpile step or to use the dynamic `import()`.
371
-
372
- ### What's verified
373
-
374
- - `npm pack --dry-run` ships a 41 KB tarball with a single `dist/` tree, no source leakage. `npm audit` clean.
375
- - Locally-installed package via `npm install <path>` resolves through the `exports` map under Node's native ESM loader (no bundler), `import { createSdk } from '@ksaa-nlp/gamehub-sdk'` works, every method is SSR-safe.
376
- - `dist/gamehub-sdk.js` IIFE attaches `window.GameHubSDK`, picks up the slug from the script-tag path, reports `version: 0.4.0`.
377
-
378
- ### Unchanged
379
-
380
- - Wire protocol with the host.
381
- - `<script>`-tag end-user URLs and behaviour.
382
- - Public `Sdk` interface and every method's signature/semantics.
383
- - `BootstrapData` shape from v0.1.
384
-
385
- ---
386
-
387
- ## 0.3.0 — 2026-04-28
388
-
389
- Makes the package safe to import under Node and Angular SSR, and splits the script-tag bootstrap into its own entry. Importing the module entry (`./main`) no longer touches `window`, `document`, or runs `autoInit()` as a side effect. The legacy `<script>`-tag flow is unchanged from a consumer's perspective — the IIFE just lives in a separate file now.
390
-
391
- ### Why
392
-
393
- After the v0.2.0 namespace→ESM conversion, the public `Sdk` shape was already correct, but importing the package still had two SSR-incompatible side effects:
394
-
395
- - A top-of-module IIFE that read `window.location`, scanned `document.getElementsByTagName('script')`, and registered a `window.addEventListener('message', ...)` handler.
396
- - A few `Sdk` methods (`isInIframe()`, `notifyComplete()`, `requestClose()`, `logEvent()`) that touched `window` directly with no guard.
397
-
398
- Either was enough to crash an Angular Universal / Node module load with `ReferenceError: window is not defined`. This release closes that gap.
399
-
400
- ### What changed
401
-
402
- - **New entry: [src/browser-entry.ts](./src/browser-entry.ts).** The IIFE that attaches `window.GameHubSDK`, sends `READY` to the host, and runs `autoInit()` on `DOMContentLoaded` is now in its own file. This is the entry the script-tag UMD bundle is built from.
403
- - **[src/main.ts](./src/main.ts) is now pure.** Importing the module entry only declares exports — no `window`, `document`, or boot logic runs at evaluation time. Verified by `require()`-ing the compiled output under Node with no globals stubbed.
404
- - **`isBrowser()` helper** added to [src/utils.ts](./src/utils.ts). Used to gate every DOM-touching code path.
405
- - **`Sdk` methods are now SSR-callable.** `isInIframe()` returns `false` when there's no `window`; `notifyComplete` / `requestClose` / `logEvent` silently no-op; `ready()` resolves to `false`; every multiplayer / bootstrap / state getter returns sensible defaults (`null`, `false`, `[]`).
406
- - **`bridge.ts`** (`sendToParent`, `requestBootstrapFromParent`, `getAuthTokenFromParent`), **`init.ts`** (`detectEnvironment`, `installHostMessageListener`, `autoInit`, `ensureInitialized`) all bail early when not in a browser.
407
- - **`detectEnvironment` and `installHostMessageListener` are now idempotent** and called lazily from `autoInit()`. This preserves module-consumer parity — calling `createSdk()` then `await sdk.ready()` from an Angular service now resolves the API base URL and registers the host listener correctly, without those needing to be wired up by the now-defunct top-level IIFE.
408
-
409
- ### Breaking change for module consumers
410
-
411
- If anything in your code relied on `import '@ksaa-nlp/gamehub-sdk'` attaching `window.GameHubSDK` as a side effect, that no longer happens. Use `createSdk()` to get an instance, or load the script-tag bundle. See [MIGRATION.md](./MIGRATION.md) for code examples.
412
-
413
- ### Unchanged
414
-
415
- - Wire protocol with the host (postMessage names, payload shapes, WebSocket frame format).
416
- - `<script>`-tag end-user URLs and behaviour. Once the build pipeline points the UMD output at `browser-entry.ts` (next release), `<script src="gamehub-sdk.js">` continues to work identically.
417
- - Every method's runtime behaviour in a browser context.
418
- - `BootstrapData` / `Sdk` / type shapes from v0.2.0.
419
-
420
- ---
421
-
422
- ## 0.2.0 — 2026-04-28
423
-
424
- Internal restructure: every source file moved from TypeScript `namespace GameHub.X { ... }` (script-mode) to standard ES modules with named exports. No runtime behaviour change for `<script>`-tag consumers; meaningful change for anyone consuming via `import` / `require()` or extending the source. See [MIGRATION.md](./MIGRATION.md) for before/after snippets.
425
-
426
- ### Why
427
-
428
- The namespace-and-IIFE layout dated from when the SDK was a single bundled file dropped into a host page. As we set up to support Node.js and Angular consumers (Angular SSR specifically — modules are evaluated under Node), namespaces stopped paying off:
429
-
430
- - TypeScript treats namespace-mode files as scripts; their emitted `.d.ts` isn't a real module, so consumers needed a hand-written shim ([scripts/emit-module-entry.mjs](./scripts/emit-module-entry.mjs)) just to get `import` working.
431
- - Bundlers can't tree-shake namespace members, and `sideEffects: false` is unsafe for an IIFE entry.
432
- - Cross-file references via `GameHub.X.foo` only work if every file is bundled into a single output — incompatible with per-file ESM emit.
433
-
434
- This release is the prerequisite for the upcoming dual ESM+CJS package, SSR-safe import, and explicit `createSdk()` lifecycle.
435
-
436
- ### What changed
437
-
438
- - All `namespace GameHub.X { ... }` blocks are now top-level `export`s in their respective files. Cross-file references use ordinary `import`s.
439
- - `GameHub.State` (previously a namespace of mutable `export let`s) is now a single mutable object exported as `state` from [src/state.ts](./src/state.ts). ES modules don't allow consumers to reassign imported `let` bindings, so the per-`let` pattern was untranslatable.
440
- - The public surface is now exposed as a `createSdk()` factory plus an `Sdk` type, exported from [src/main.ts](./src/main.ts). The legacy IIFE that attaches `window.GameHubSDK` and runs `autoInit()` is preserved at the bottom of `main.ts` so the `<script>`-tag bootstrapping path is unchanged.
441
- - All public types (`BootstrapData`, `MatchContext`, `Sdk`, `RoomInfo`, `SubmitScoreResult`, ...) are now re-exported from the main entry as named ESM types.
442
- - `tsconfig.json`: `module: ESNext`, `moduleResolution: Bundler`, `outDir: ./dist`, plus `declarationMap`/`sourceMap`. The hand-curated `include` list is replaced with `["src/**/*", "types/**/*"]`.
443
- - The previous `scripts/emit-module-entry.mjs` shim and its hand-written `dist/index.mjs` / `dist/index.d.ts` will be retired in a follow-up release that wires up proper `package.json` `exports` for ESM and CJS — until then, the default-import singleton pattern (`import sdk from '@ksaa-nlp/gamehub-sdk'`) is no longer the recommended consumption shape.
444
-
445
- ### Unchanged
446
-
447
- - Wire protocol with the host (postMessage names, payload shapes, WebSocket frame format).
448
- - `<script>`-tag consumption: `window.GameHubSDK` is still attached on load and auto-init still runs.
449
- - Every method on the `Sdk` interface keeps the same name, signature, and behaviour.
450
- - `BootstrapData` shape (the v0.1 reshape from the previous release).
451
- - Multiplayer host gating, `asViewer` semantics, monotonic-seq dedup.
452
-
453
- ---
454
-
455
- ## 0.1 — 2026-04-16
456
-
457
- Reshapes the `getBootstrap()` payload so games get a predictable, non-stale snapshot. No runtime breakage for games that only call `ready()`, `startSession()`, `submitScore()`, or the `multiplayer.*` helpers — this release only affects code that reads from `getBootstrap()` directly.
458
-
459
- ### Why
460
-
461
- v0.1's `BootstrapData` included `players`, `currentPlayer`, `peersCount`, and `status`. These were sourced from an HTTP snapshot taken while the host page was still transitioning from the lobby, so host and guest could see divergent values (most visibly: host reads `peersCount: 0, players: []` while guest reads `peersCount: 1, players: [host]`). They were also tempting to use as the single source of truth for peer state, which they were never reliable enough to be.
462
-
463
- ### Breaking changes to `getBootstrap()`
464
-
465
- **Removed fields:**
466
-
467
- | Removed | Use instead |
468
- | --------------------------- | --------------------------------------------------------------------- |
469
- | `bootstrap.players` | `sdk.multiplayer.getPeers()` |
470
- | `bootstrap.currentPlayer` | `sdk.multiplayer.selfId()` + `getPeers().find(p => p.peerId === …)` |
471
- | `bootstrap.room.peersCount` | `sdk.multiplayer.getPeers().length` |
472
- | `bootstrap.room.status` | `sdk.multiplayer.getRoom()` and listen to `peer_joined` / `peer_left` |
473
-
474
- **Reshaped fields:** the three room fields previously sprinkled at both the top level and under `room` are now collapsed into a single nested `room` object:
475
-
476
- ```ts
477
- // v0.0.1
478
- bootstrap.roomCode;
479
- bootstrap.shareId;
480
- bootstrap.maxPlayers;
481
- bootstrap.room.roomCode; // duplicate
482
- bootstrap.room.shareId; // duplicate
483
- // ...
484
-
485
- // v0.1.0
486
- bootstrap.room.roomCode;
487
- bootstrap.room.shareId;
488
- bootstrap.room.maxPlayers;
489
- // bootstrap.room is `null` for single-player / non-multiplayer sessions.
490
- ```
491
-
492
- ### Types
493
-
494
- - Added exported `BootstrapRoom` interface (`{ roomCode, shareId, maxPlayers }`, all nullable).
495
- - Removed `BootstrapPlayer` and `PeerAvatar` — they were only ever used by the removed fields.
496
- - `BootstrapConfig.room` is now `Partial<BootstrapRoom> | null` (host-side shape, unchanged behaviour — still allowed to be absent, null, or partial).
497
- - `BootstrapData.room` is `BootstrapRoom | null`.
498
-
499
- ### Migration
500
-
501
- If your game reads room metadata from bootstrap:
502
-
503
- ```ts
504
- // Before
505
- const { roomCode, shareId, maxPlayers } = sdk.getBootstrap();
506
-
507
- // After
508
- const { room } = sdk.getBootstrap();
509
- if (room) {
510
- const { roomCode, shareId, maxPlayers } = room;
511
- }
512
- ```
513
-
514
- If your game was reading peer state from bootstrap:
515
-
516
- ```ts
517
- // Before — stale on host
518
- const players = sdk.getBootstrap().players;
519
- const me = sdk.getBootstrap().currentPlayer;
520
-
521
- // After — live, authoritative
522
- await sdk.ready();
523
- const players = sdk.multiplayer.getPeers();
524
- const me = players.find((p) => p.peerId === sdk.multiplayer.selfId());
525
-
526
- // Stay in sync as peers come and go
527
- sdk.multiplayer.on("peer_joined", ({ peer }) => {
528
- /* … */
529
- });
530
- sdk.multiplayer.on("peer_left", ({ peer }) => {
531
- /* … */
532
- });
533
- ```
534
-
535
- ### Unchanged
536
-
537
- Everything else in the v0.1 contract still applies:
538
-
539
- - `sdk.multiplayer.*` API surface (host authority, `broadcast()`, `send()`, `on()`, `selfId()`, `isHost()`, `isViewer()`, `getRole()`).
540
- - `submitScore()` / `submitMatchResult()` host gating (non-host peers return `{ success: true, skipped: true }`).
541
- - Monotonic seq guard against duplicate `game_event` frames.
542
- - `JoinOptions.asViewer` for read-only spectators.
543
- - `bootstrap.peerId` (the server-assigned id — still present).
544
-
545
- ---