@ksaa-nlp/gamehub-sdk 0.1.0 → 0.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 (88) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/MIGRATION.md +322 -0
  3. package/README.md +121 -182
  4. package/dist/gamehub-sdk.js +1202 -1670
  5. package/dist/gamehub-sdk.js.map +7 -0
  6. package/dist/src/api-client.d.ts +11 -0
  7. package/dist/src/api-client.d.ts.map +1 -0
  8. package/dist/src/api-client.js +27 -0
  9. package/dist/src/api-client.js.map +1 -0
  10. package/dist/src/bridge.d.ts +35 -0
  11. package/dist/src/bridge.d.ts.map +1 -0
  12. package/dist/src/bridge.js +280 -0
  13. package/dist/src/bridge.js.map +1 -0
  14. package/dist/src/browser-entry.d.ts +19 -0
  15. package/dist/src/browser-entry.d.ts.map +1 -0
  16. package/dist/src/browser-entry.js +49 -0
  17. package/dist/src/browser-entry.js.map +1 -0
  18. package/dist/src/constants.d.ts +18 -0
  19. package/dist/src/constants.d.ts.map +1 -0
  20. package/dist/src/constants.js +18 -0
  21. package/dist/src/constants.js.map +1 -0
  22. package/dist/src/init.d.ts +36 -0
  23. package/dist/src/init.d.ts.map +1 -0
  24. package/dist/src/init.js +317 -0
  25. package/dist/src/init.js.map +1 -0
  26. package/dist/src/main.d.ts +101 -0
  27. package/dist/src/main.d.ts.map +1 -0
  28. package/dist/src/main.js +126 -0
  29. package/dist/src/main.js.map +1 -0
  30. package/dist/src/match-context.d.ts +11 -0
  31. package/dist/src/match-context.d.ts.map +1 -0
  32. package/dist/src/match-context.js +51 -0
  33. package/dist/src/match-context.js.map +1 -0
  34. package/dist/src/multiplayer.d.ts +82 -0
  35. package/dist/src/multiplayer.d.ts.map +1 -0
  36. package/dist/src/multiplayer.js +461 -0
  37. package/dist/src/multiplayer.js.map +1 -0
  38. package/dist/src/session.d.ts +35 -0
  39. package/dist/src/session.d.ts.map +1 -0
  40. package/dist/src/session.js +206 -0
  41. package/dist/src/session.js.map +1 -0
  42. package/dist/src/state.d.ts +71 -0
  43. package/dist/src/state.d.ts.map +1 -0
  44. package/dist/src/state.js +55 -0
  45. package/dist/src/state.js.map +1 -0
  46. package/dist/src/utils.d.ts +36 -0
  47. package/dist/src/utils.d.ts.map +1 -0
  48. package/dist/src/utils.js +73 -0
  49. package/dist/src/utils.js.map +1 -0
  50. package/dist/types/api.d.ts +21 -0
  51. package/dist/types/api.d.ts.map +1 -0
  52. package/dist/types/api.js +2 -0
  53. package/dist/types/api.js.map +1 -0
  54. package/{types/bootstrap.ts → dist/types/bootstrap.d.ts} +26 -29
  55. package/dist/types/bootstrap.d.ts.map +1 -0
  56. package/dist/types/bootstrap.js +2 -0
  57. package/dist/types/bootstrap.js.map +1 -0
  58. package/dist/types/match.d.ts +37 -0
  59. package/dist/types/match.d.ts.map +1 -0
  60. package/dist/types/match.js +2 -0
  61. package/dist/types/match.js.map +1 -0
  62. package/dist/types/multiplayer.d.ts +138 -0
  63. package/dist/types/multiplayer.d.ts.map +1 -0
  64. package/dist/types/multiplayer.js +2 -0
  65. package/dist/types/multiplayer.js.map +1 -0
  66. package/{types/session.ts → dist/types/session.d.ts} +24 -30
  67. package/dist/types/session.d.ts.map +1 -0
  68. package/dist/types/session.js +2 -0
  69. package/dist/types/session.js.map +1 -0
  70. package/package.json +34 -18
  71. package/dist/gamehub-sdk.d.ts +0 -694
  72. package/dist/index.d.ts +0 -56
  73. package/dist/index.mjs +0 -6
  74. package/scripts/emit-module-entry.mjs +0 -96
  75. package/src/api-client.ts +0 -33
  76. package/src/bridge.ts +0 -312
  77. package/src/constants.ts +0 -24
  78. package/src/init.ts +0 -335
  79. package/src/main.ts +0 -287
  80. package/src/match-context.ts +0 -52
  81. package/src/multiplayer.ts +0 -525
  82. package/src/session.ts +0 -240
  83. package/src/state.ts +0 -78
  84. package/src/utils.ts +0 -68
  85. package/tsconfig.json +0 -33
  86. package/types/api.ts +0 -21
  87. package/types/match.ts +0 -41
  88. package/types/multiplayer.ts +0 -118
package/CHANGELOG.md ADDED
@@ -0,0 +1,294 @@
1
+ # Changelog
2
+
3
+ ## 0.5.0 — 2026-04-30
4
+
5
+ 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.
6
+
7
+ ### Why
8
+
9
+ 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.
10
+
11
+ 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.
12
+
13
+ ### What changed
14
+
15
+ - **`SendOptions { retain?: boolean; retainKey?: string }`** is a new optional third argument on `multiplayer.send` and `multiplayer.broadcast`. Defaults preserve the old behaviour exactly.
16
+ - **`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.
17
+ - **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.
18
+ - **`SendOptions` is re-exported** from the package entry alongside the other multiplayer types.
19
+
20
+ ### Wire format
21
+
22
+ Outbound (sender → server):
23
+
24
+ ```jsonc
25
+ {
26
+ "eventName": "link:match_start",
27
+ "payload": { ... },
28
+ "retain": true, // host-only on the server side
29
+ "retainKey": "match_start" // optional; defaults to eventName
30
+ }
31
+ ```
32
+
33
+ Inbound (server → all peers, replay or live):
34
+
35
+ ```jsonc
36
+ {
37
+ "type": "game_event",
38
+ "roomCode": "...",
39
+ "fromPeerId": "...",
40
+ "eventName": "...",
41
+ "payload": { ... },
42
+ "seq": 7,
43
+ "sentAt": 1714378900000,
44
+ "retained": true // present on replays only
45
+ }
46
+ ```
47
+
48
+ ### Server requirements
49
+
50
+ This release pairs with realtime-server changes that:
51
+
52
+ - Store retained frames per room (memory + MongoDB), capped at 64 keys per room with FIFO eviction at the cap.
53
+ - Replay them to every new socket immediately after `room_joined` and before any live frame can reach that socket.
54
+ - Drop the `retain` flag silently from non-host senders so a guest can't forge long-lived state for late joiners.
55
+ - TTL retained docs in MongoDB at 24 hours (orphan cleanup for rooms closed via the HTTP API rather than via host disconnect).
56
+
57
+ 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.
58
+
59
+ ### How games use it
60
+
61
+ ```ts
62
+ // Host-authoritative match start — replays for every reconnecting peer
63
+ sdk.multiplayer.broadcast('link:match_start', payload, {
64
+ retain: true,
65
+ retainKey: 'match_start',
66
+ });
67
+
68
+ // Per-cell board state, replayed cell-by-cell on reconnect
69
+ sdk.multiplayer.broadcast('link:answer_resolved', payload, {
70
+ retain: true,
71
+ retainKey: `cell:${payload.cellId}`,
72
+ });
73
+ ```
74
+
75
+ 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.
76
+
77
+ ### Unchanged
78
+
79
+ - Public `Sdk` interface beyond the new `SendOptions` parameter.
80
+ - `BootstrapData` shape.
81
+ - `MpMessage` for live frames (the `retained` flag is opt-in and absent on every existing path).
82
+ - All other multiplayer methods (`createRoom`, `joinRoom`, `leaveRoom`, `getRoom`, `getPeers`, …).
83
+
84
+ ---
85
+
86
+ ## 0.4.0 — 2026-04-28
87
+
88
+ 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.
89
+
90
+ ### Why
91
+
92
+ 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.
93
+
94
+ ### What changed
95
+
96
+ - **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.
97
+ - **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.
98
+ - **`tsconfig.json`** switched to `module: NodeNext` / `moduleResolution: NodeNext` (was `Bundler`). Stricter — catches missing extensions at type-check time.
99
+ - **New `package.json` `exports` map** with three subpaths:
100
+ - `.` → `./dist/src/main.js` (the npm/Angular/Node ESM entry; no side effects on import).
101
+ - `./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).
102
+ - `./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).
103
+ - **`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.
104
+ - **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).
105
+ - **Retired `scripts/emit-module-entry.mjs`** and its hand-written `dist/index.mjs` / `dist/index.d.ts`. The whole `scripts/` directory is gone.
106
+ - **Trimmed `files`** to ship only `dist/**/*`, `README.md`, `CHANGELOG.md`, `MIGRATION.md`. No more leaking source `.ts`, `tsconfig.json`, or build scripts to consumers.
107
+ - **`SDK_VERSION` constant** is now in sync with `package.json`.
108
+
109
+ ### Breaking change for module consumers
110
+
111
+ `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:
112
+
113
+ ```ts
114
+ import { createSdk } from '@ksaa-nlp/gamehub-sdk';
115
+ const sdk = createSdk();
116
+ await sdk.ready();
117
+ ```
118
+
119
+ 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()`.
120
+
121
+ ### What's verified
122
+
123
+ - `npm pack --dry-run` ships a 41 KB tarball with a single `dist/` tree, no source leakage. `npm audit` clean.
124
+ - 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.
125
+ - `dist/gamehub-sdk.js` IIFE attaches `window.GameHubSDK`, picks up the slug from the script-tag path, reports `version: 0.4.0`.
126
+
127
+ ### Unchanged
128
+
129
+ - Wire protocol with the host.
130
+ - `<script>`-tag end-user URLs and behaviour.
131
+ - Public `Sdk` interface and every method's signature/semantics.
132
+ - `BootstrapData` shape from v0.1.
133
+
134
+ ---
135
+
136
+ ## 0.3.0 — 2026-04-28
137
+
138
+ 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.
139
+
140
+ ### Why
141
+
142
+ 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:
143
+
144
+ - A top-of-module IIFE that read `window.location`, scanned `document.getElementsByTagName('script')`, and registered a `window.addEventListener('message', ...)` handler.
145
+ - A few `Sdk` methods (`isInIframe()`, `notifyComplete()`, `requestClose()`, `logEvent()`) that touched `window` directly with no guard.
146
+
147
+ Either was enough to crash an Angular Universal / Node module load with `ReferenceError: window is not defined`. This release closes that gap.
148
+
149
+ ### What changed
150
+
151
+ - **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.
152
+ - **[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.
153
+ - **`isBrowser()` helper** added to [src/utils.ts](./src/utils.ts). Used to gate every DOM-touching code path.
154
+ - **`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`, `[]`).
155
+ - **`bridge.ts`** (`sendToParent`, `requestBootstrapFromParent`, `getAuthTokenFromParent`), **`init.ts`** (`detectEnvironment`, `installHostMessageListener`, `autoInit`, `ensureInitialized`) all bail early when not in a browser.
156
+ - **`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.
157
+
158
+ ### Breaking change for module consumers
159
+
160
+ 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.
161
+
162
+ ### Unchanged
163
+
164
+ - Wire protocol with the host (postMessage names, payload shapes, WebSocket frame format).
165
+ - `<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.
166
+ - Every method's runtime behaviour in a browser context.
167
+ - `BootstrapData` / `Sdk` / type shapes from v0.2.0.
168
+
169
+ ---
170
+
171
+ ## 0.2.0 — 2026-04-28
172
+
173
+ 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.
174
+
175
+ ### Why
176
+
177
+ 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:
178
+
179
+ - 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.
180
+ - Bundlers can't tree-shake namespace members, and `sideEffects: false` is unsafe for an IIFE entry.
181
+ - Cross-file references via `GameHub.X.foo` only work if every file is bundled into a single output — incompatible with per-file ESM emit.
182
+
183
+ This release is the prerequisite for the upcoming dual ESM+CJS package, SSR-safe import, and explicit `createSdk()` lifecycle.
184
+
185
+ ### What changed
186
+
187
+ - All `namespace GameHub.X { ... }` blocks are now top-level `export`s in their respective files. Cross-file references use ordinary `import`s.
188
+ - `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.
189
+ - 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.
190
+ - All public types (`BootstrapData`, `MatchContext`, `Sdk`, `RoomInfo`, `SubmitScoreResult`, ...) are now re-exported from the main entry as named ESM types.
191
+ - `tsconfig.json`: `module: ESNext`, `moduleResolution: Bundler`, `outDir: ./dist`, plus `declarationMap`/`sourceMap`. The hand-curated `include` list is replaced with `["src/**/*", "types/**/*"]`.
192
+ - 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.
193
+
194
+ ### Unchanged
195
+
196
+ - Wire protocol with the host (postMessage names, payload shapes, WebSocket frame format).
197
+ - `<script>`-tag consumption: `window.GameHubSDK` is still attached on load and auto-init still runs.
198
+ - Every method on the `Sdk` interface keeps the same name, signature, and behaviour.
199
+ - `BootstrapData` shape (the v0.1 reshape from the previous release).
200
+ - Multiplayer host gating, `asViewer` semantics, monotonic-seq dedup.
201
+
202
+ ---
203
+
204
+ ## 0.1 — 2026-04-16
205
+
206
+ 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.
207
+
208
+ ### Why
209
+
210
+ 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.
211
+
212
+ ### Breaking changes to `getBootstrap()`
213
+
214
+ **Removed fields:**
215
+
216
+ | Removed | Use instead |
217
+ | --------------------------- | --------------------------------------------------------------------- |
218
+ | `bootstrap.players` | `sdk.multiplayer.getPeers()` |
219
+ | `bootstrap.currentPlayer` | `sdk.multiplayer.selfId()` + `getPeers().find(p => p.peerId === …)` |
220
+ | `bootstrap.room.peersCount` | `sdk.multiplayer.getPeers().length` |
221
+ | `bootstrap.room.status` | `sdk.multiplayer.getRoom()` and listen to `peer_joined` / `peer_left` |
222
+
223
+ **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:
224
+
225
+ ```ts
226
+ // v0.0.1
227
+ bootstrap.roomCode;
228
+ bootstrap.shareId;
229
+ bootstrap.maxPlayers;
230
+ bootstrap.room.roomCode; // duplicate
231
+ bootstrap.room.shareId; // duplicate
232
+ // ...
233
+
234
+ // v0.1.0
235
+ bootstrap.room.roomCode;
236
+ bootstrap.room.shareId;
237
+ bootstrap.room.maxPlayers;
238
+ // bootstrap.room is `null` for single-player / non-multiplayer sessions.
239
+ ```
240
+
241
+ ### Types
242
+
243
+ - Added exported `BootstrapRoom` interface (`{ roomCode, shareId, maxPlayers }`, all nullable).
244
+ - Removed `BootstrapPlayer` and `PeerAvatar` — they were only ever used by the removed fields.
245
+ - `BootstrapConfig.room` is now `Partial<BootstrapRoom> | null` (host-side shape, unchanged behaviour — still allowed to be absent, null, or partial).
246
+ - `BootstrapData.room` is `BootstrapRoom | null`.
247
+
248
+ ### Migration
249
+
250
+ If your game reads room metadata from bootstrap:
251
+
252
+ ```ts
253
+ // Before
254
+ const { roomCode, shareId, maxPlayers } = sdk.getBootstrap();
255
+
256
+ // After
257
+ const { room } = sdk.getBootstrap();
258
+ if (room) {
259
+ const { roomCode, shareId, maxPlayers } = room;
260
+ }
261
+ ```
262
+
263
+ If your game was reading peer state from bootstrap:
264
+
265
+ ```ts
266
+ // Before — stale on host
267
+ const players = sdk.getBootstrap().players;
268
+ const me = sdk.getBootstrap().currentPlayer;
269
+
270
+ // After — live, authoritative
271
+ await sdk.ready();
272
+ const players = sdk.multiplayer.getPeers();
273
+ const me = players.find((p) => p.peerId === sdk.multiplayer.selfId());
274
+
275
+ // Stay in sync as peers come and go
276
+ sdk.multiplayer.on("peer_joined", ({ peer }) => {
277
+ /* … */
278
+ });
279
+ sdk.multiplayer.on("peer_left", ({ peer }) => {
280
+ /* … */
281
+ });
282
+ ```
283
+
284
+ ### Unchanged
285
+
286
+ Everything else in the v0.1 contract still applies:
287
+
288
+ - `sdk.multiplayer.*` API surface (host authority, `broadcast()`, `send()`, `on()`, `selfId()`, `isHost()`, `isViewer()`, `getRole()`).
289
+ - `submitScore()` / `submitMatchResult()` host gating (non-host peers return `{ success: true, skipped: true }`).
290
+ - Monotonic seq guard against duplicate `game_event` frames.
291
+ - `JoinOptions.asViewer` for read-only spectators.
292
+ - `bootstrap.peerId` (the server-assigned id — still present).
293
+
294
+ ---
package/MIGRATION.md ADDED
@@ -0,0 +1,322 @@
1
+ # Migration guide
2
+
3
+ Each section below covers one consumption pattern. Pick whichever describes how your project used the previous version of `@ksaa-nlp/gamehub-sdk` and follow only that section.
4
+
5
+ This guide covers the cumulative migration from **v0.1 → v0.4.0**. The intermediate v0.2.0 and v0.3.0 releases are referenced where they changed something you can still observe; if you're upgrading directly from v0.1, you don't need to apply intermediate changes separately — they're all rolled in.
6
+
7
+ ## TL;DR by consumer type
8
+
9
+ | You consume the SDK via... | Action required |
10
+ | --- | --- |
11
+ | A `<script>` tag in a host page | None. `window.GameHubSDK` and auto-init are unchanged. |
12
+ | `import sdk from '@ksaa-nlp/gamehub-sdk'` (default-import singleton) | Switch to `import { createSdk } from '@ksaa-nlp/gamehub-sdk'` and call `createSdk()`. Nothing happens on import — call `await sdk.ready()` to boot. |
13
+ | Angular / SSR / Node | Same as above. **New in v0.3.0:** importing the package no longer touches `window` or `document`, so SSR builds no longer crash on import. |
14
+ | `import type { ... } from '@ksaa-nlp/gamehub-sdk'` | Type names are unchanged; they're now real ESM named exports rather than members of a `gamehubSdk` namespace import. Most code keeps working as-is. |
15
+ | Source-level access to `GameHub.X.*` (forking, patching, vendoring) | Replace each `GameHub.Foo.bar` reference with a named `import` from the matching module file. |
16
+
17
+ ## 1. `<script>`-tag consumers
18
+
19
+ No migration required. The compiled UMD bundle still:
20
+
21
+ - Attaches `sdk` to `window.GameHubSDK` on load.
22
+ - Runs `autoInit()` once the DOM is ready (or immediately if it already is).
23
+ - Sends `READY` to the host via postMessage.
24
+ - Auto-joins any pending multiplayer room signalled by URL params or bootstrap.
25
+
26
+ Existing host pages and existing games using `window.GameHubSDK.submitScore(...)` need no changes.
27
+
28
+ > **What's different under the hood:** in v0.3.0 the IIFE that does this work moved from [src/main.ts](./src/main.ts) into a dedicated [src/browser-entry.ts](./src/browser-entry.ts). This split is invisible to script-tag end users — the published `gamehub-sdk.js` continues to do exactly the same thing — but it matters if you build the SDK from source (see [Build pipeline](#build-pipeline) below).
29
+
30
+ ## 2. Default-import singleton consumers
31
+
32
+ ### Before (v0.1)
33
+
34
+ The package shipped a hand-written shim ([scripts/emit-module-entry.mjs](./scripts/emit-module-entry.mjs)) that imported the IIFE for its side effect and re-exported `window.GameHubSDK` as the default export:
35
+
36
+ ```ts
37
+ // v0.1
38
+ import sdk from '@ksaa-nlp/gamehub-sdk';
39
+
40
+ await sdk.ready();
41
+ sdk.submitScore(100);
42
+ ```
43
+
44
+ ```js
45
+ // CommonJS variant
46
+ const sdk = require('@ksaa-nlp/gamehub-sdk');
47
+ sdk.notifyComplete({ score: 100 });
48
+ ```
49
+
50
+ Both forms returned the same singleton that the IIFE had attached to the window.
51
+
52
+ ### After (v0.3.0)
53
+
54
+ The default-import singleton shape is gone. The SDK now exposes a named `createSdk` factory:
55
+
56
+ ```ts
57
+ // v0.3.0
58
+ import { createSdk, type Sdk } from '@ksaa-nlp/gamehub-sdk';
59
+
60
+ const sdk: Sdk = createSdk();
61
+ await sdk.ready();
62
+ sdk.submitScore(100);
63
+ ```
64
+
65
+ ```js
66
+ // CommonJS variant (once the dual build lands — see "Build pipeline" below)
67
+ const { createSdk } = require('@ksaa-nlp/gamehub-sdk');
68
+ const sdk = createSdk();
69
+ sdk.notifyComplete({ score: 100 });
70
+ ```
71
+
72
+ The `Sdk` interface, every result type (`StartSessionResult`, `SubmitScoreResult`, ...), and every payload type (`BootstrapData`, `MatchContext`, `RoomInfo`, ...) are exported as named ESM types from the package root.
73
+
74
+ ### Lifecycle: nothing happens until you call something
75
+
76
+ In v0.1, importing the package immediately ran environment detection, registered a `window.addEventListener('message', ...)` handler, and started the bootstrap handshake. In v0.3.0 none of that runs at import time. Concretely:
77
+
78
+ - `import { createSdk } from '@ksaa-nlp/gamehub-sdk'` — no side effects.
79
+ - `createSdk()` — builds and returns a plain SDK object. No DOM access.
80
+ - `await sdk.ready()` — **this** is the point where `detectEnvironment()` runs (resolving the API base URL), the host message listener installs, and the bootstrap / auth handshake fires. Both `detectEnvironment` and the listener installation are idempotent, so calling `ready()` multiple times is safe.
81
+
82
+ If you previously relied on the act of importing the package being enough to populate `window.GameHubSDK` — for example, an HTML host page that does `import('@ksaa-nlp/gamehub-sdk')` and then expects `window.GameHubSDK.submitScore(...)` to work — that no longer happens. Use `createSdk()` and keep your own reference, or load the script-tag bundle.
83
+
84
+ ### Why we dropped the singleton default
85
+
86
+ The v0.1 default-import returned a shared mutable instance attached to `window`. That made it impossible to use the SDK in environments without a `window` (Node, Angular SSR), and it tied your module's state to whichever script tag had loaded the IIFE. With `createSdk()`, callers control lifecycle explicitly.
87
+
88
+ ### Angular SSR / Node module consumers (new in v0.3.0)
89
+
90
+ In v0.1 and v0.2.0, `import '@ksaa-nlp/gamehub-sdk'` would crash an SSR build with `ReferenceError: window is not defined` — the IIFE ran at module evaluation time. **In v0.3.0 the import is pure**, and every method on the returned `Sdk` is callable in a non-browser environment without throwing:
91
+
92
+ - Read-only methods (`isInitialized`, `isAuthenticated`, `hasActiveSession`, `isInIframe`, `getGameSlug`, `getBootstrap`, `multiplayer.getRoom`, `multiplayer.getPeers`, `multiplayer.isConnected`, `multiplayer.getRole`, `multiplayer.isHost`, `multiplayer.isViewer`, `multiplayer.selfId`) return sensible defaults (`null`, `false`, `[]`).
93
+ - Side-effect methods (`notifyComplete`, `requestClose`, `logEvent`) silently no-op.
94
+ - `await sdk.ready()` resolves to `false` instead of throwing.
95
+
96
+ This means an Angular service can be straightforward:
97
+
98
+ ```ts
99
+ import { Injectable } from '@angular/core';
100
+ import { createSdk, type Sdk } from '@ksaa-nlp/gamehub-sdk';
101
+
102
+ @Injectable({ providedIn: 'root' })
103
+ export class GameHubService {
104
+ // Safe to construct on either platform — no window access happens here.
105
+ private readonly sdk: Sdk = createSdk();
106
+
107
+ // Boot lazily. On the server this resolves to `false` and skips the
108
+ // bootstrap handshake; in the browser it runs the full auto-init flow.
109
+ ready() {
110
+ return this.sdk.ready();
111
+ }
112
+
113
+ submitScore(score: number) {
114
+ return this.sdk.submitScore(score);
115
+ }
116
+ }
117
+ ```
118
+
119
+ You don't need `isPlatformBrowser` gates around the import or the `createSdk()` call. You only need to gate calls whose semantics genuinely require a browser (multiplayer / WebSocket-backed methods will still throw if the WebSocket constructor isn't present).
120
+
121
+ > **Stable in v0.4.0:** the `package.json` `exports` map, the dual build pipeline, and the dropped CJS path are all in place. Importing the package via `import { createSdk } from '@ksaa-nlp/gamehub-sdk'` works under Node's native ESM loader without a bundler, under Angular CLI, Vite, webpack, esbuild, Bun, and Rollup. The `scripts/emit-module-entry.mjs` shim is gone.
122
+
123
+ ## 3. Type-only consumers
124
+
125
+ ### Before
126
+
127
+ The previous `dist/index.d.ts` exposed types as members of a single namespace import:
128
+
129
+ ```ts
130
+ import type sdkTypes = require('@ksaa-nlp/gamehub-sdk');
131
+ type Bootstrap = sdkTypes.BootstrapData;
132
+ type Score = sdkTypes.SubmitScoreResult;
133
+ ```
134
+
135
+ Or, depending on `esModuleInterop`:
136
+
137
+ ```ts
138
+ import type gamehubSdk from '@ksaa-nlp/gamehub-sdk';
139
+ type Bootstrap = gamehubSdk.BootstrapData; // worked through `declare namespace gamehubSdk`
140
+ ```
141
+
142
+ ### After
143
+
144
+ Every public type is now a real top-level named export:
145
+
146
+ ```ts
147
+ import type {
148
+ Sdk,
149
+ BootstrapData,
150
+ MatchContext,
151
+ RoomInfo,
152
+ SubmitScoreResult,
153
+ StartSessionResult,
154
+ CreateRoomResult,
155
+ JoinOptions,
156
+ JoinRoomResult,
157
+ ScoreMetadata,
158
+ Question,
159
+ QuestionOptions,
160
+ } from '@ksaa-nlp/gamehub-sdk';
161
+ ```
162
+
163
+ Type names are unchanged from v0.1, so a project-wide find-and-replace from `gamehubSdk.<TypeName>` to `<TypeName>` plus the named `import type` is usually all that's needed. v0.3.0 adds no new type changes on top of the v0.2.0 conversion.
164
+
165
+ ## 4. Source-level / vendored consumers
166
+
167
+ If your project forks or vendors the SDK source (e.g. a monorepo path import, or `link:` install), every cross-file reference needs to switch from namespace lookup to a named import.
168
+
169
+ ### State access
170
+
171
+ The single biggest change: `GameHub.State` is no longer a namespace of mutable `export let`s. It's a single object exported from `src/state.ts`.
172
+
173
+ ```ts
174
+ // Before
175
+ GameHub.State.gameSlug = 'my-game';
176
+ const token = GameHub.State.authToken;
177
+
178
+ // After
179
+ import { state } from './state';
180
+ state.gameSlug = 'my-game';
181
+ const token = state.authToken;
182
+ ```
183
+
184
+ Every field name on `state` matches the previous `GameHub.State.*` field exactly.
185
+
186
+ ### Function references
187
+
188
+ ```ts
189
+ // Before
190
+ GameHub.Session.startSession();
191
+ GameHub.Multiplayer.joinRoom(code);
192
+ GameHub.Bridge.sendToParent('LOG_EVENT', payload);
193
+ GameHub.Utils.warn('something');
194
+ GameHub.Api.apiRequest('/sessions/start', { method: 'POST' });
195
+
196
+ // After
197
+ import * as Session from './session';
198
+ import * as Multiplayer from './multiplayer';
199
+ import { sendToParent } from './bridge';
200
+ import { warn } from './utils';
201
+ import { apiRequest } from './api-client';
202
+
203
+ Session.startSession();
204
+ Multiplayer.joinRoom(code);
205
+ sendToParent('LOG_EVENT', payload);
206
+ warn('something');
207
+ apiRequest('/sessions/start', { method: 'POST' });
208
+ ```
209
+
210
+ Either style works — namespace import (`import * as Session from './session'`) reads similarly to the old `GameHub.Session.*`; named imports tree-shake better.
211
+
212
+ ### Constants
213
+
214
+ ```ts
215
+ // Before
216
+ GameHub.SDK_VERSION;
217
+ GameHub.MESSAGE_PREFIX;
218
+ GameHub.MP_MAX_RECONNECT_ATTEMPTS;
219
+
220
+ // After
221
+ import {
222
+ SDK_VERSION,
223
+ MESSAGE_PREFIX,
224
+ MP_MAX_RECONNECT_ATTEMPTS,
225
+ } from './constants';
226
+ ```
227
+
228
+ ### Types
229
+
230
+ ```ts
231
+ // Before — types lived in the same `namespace GameHub` block as constants/state
232
+ const ctx: GameHub.MatchContext = ...;
233
+ const opts: GameHub.JoinOptions = ...;
234
+
235
+ // After — types live in `types/*.ts` and import like any other module
236
+ import type { MatchContext } from '../types/match';
237
+ import type { JoinOptions } from '../types/multiplayer';
238
+ ```
239
+
240
+ ### Public surface
241
+
242
+ ```ts
243
+ // Before
244
+ GameHub.Public.create();
245
+ type Sdk = GameHub.Public.Sdk;
246
+
247
+ // After
248
+ import { createSdk, type Sdk } from './main';
249
+ ```
250
+
251
+ ### Module map
252
+
253
+ | Old namespace | New module path |
254
+ | --- | --- |
255
+ | `GameHub` (constants) | [`src/constants.ts`](./src/constants.ts) |
256
+ | `GameHub.State` | `state` object exported from [`src/state.ts`](./src/state.ts) |
257
+ | `GameHub.Utils` | [`src/utils.ts`](./src/utils.ts) (now also exports `isBrowser()` for SSR guards) |
258
+ | `GameHub.Api` | [`src/api-client.ts`](./src/api-client.ts) (function `apiRequest`) |
259
+ | `GameHub.Bridge` | [`src/bridge.ts`](./src/bridge.ts) |
260
+ | `GameHub.MatchCtx` | [`src/match-context.ts`](./src/match-context.ts) |
261
+ | `GameHub.Session` | [`src/session.ts`](./src/session.ts) |
262
+ | `GameHub.Multiplayer` | [`src/multiplayer.ts`](./src/multiplayer.ts) |
263
+ | `GameHub.Init` | [`src/init.ts`](./src/init.ts) |
264
+ | `GameHub.Public.create` / `GameHub.Public.Sdk` | `createSdk` / `Sdk` from [`src/main.ts`](./src/main.ts) |
265
+ | Bootstrap IIFE (v0.1: bottom of `main.ts` script bundle) | [`src/browser-entry.ts`](./src/browser-entry.ts) — new in v0.3.0 |
266
+ | Type definitions (`MatchContext`, `BootstrapData`, ...) | [`types/*.ts`](./types) |
267
+
268
+ ## Build pipeline
269
+
270
+ The SDK has **two entry points** built by **two tools**, both wired up in [package.json](./package.json) under `npm run build`:
271
+
272
+ | Entry | Built by | Output | Purpose |
273
+ | --- | --- | --- | --- |
274
+ | [src/main.ts](./src/main.ts) | `tsc` (per-file ESM emit) | `dist/src/main.js` + `.d.ts` | npm / Angular / Node ESM consumers. No side effects on import. |
275
+ | [src/browser-entry.ts](./src/browser-entry.ts) | `esbuild` (single IIFE bundle) | `dist/gamehub-sdk.js` | `<script>`-tag distribution. Self-contained 40 KB IIFE that attaches `window.GameHubSDK`. |
276
+
277
+ ```jsonc
278
+ // package.json scripts
279
+ "build:tsc": "tsc -p ./tsconfig.json",
280
+ "build:bundle": "esbuild src/browser-entry.ts --bundle --format=iife --platform=browser --target=es2020 --outfile=dist/gamehub-sdk.js --sourcemap",
281
+ "build": "npm run build:tsc && npm run build:bundle",
282
+ "prepack": "npm run build"
283
+ ```
284
+
285
+ `tsc` alone can't bundle (it does per-file emit only), so the script-tag artifact needs `esbuild`. `prepack` ensures `npm pack` / `npm publish` always rebuild from source — no stale `dist/` ships.
286
+
287
+ ### Resulting dist layout
288
+
289
+ ```
290
+ dist/
291
+ ├── gamehub-sdk.js ← 40 KB IIFE for <script src="...">
292
+ ├── gamehub-sdk.js.map
293
+ └── src/
294
+ ├── main.js ← exports map "." entry (npm/Angular/Node)
295
+ ├── main.d.ts
296
+ ├── browser-entry.js ← exports map "./browser" entry
297
+ └── *.js + *.d.ts + *.map ← per-file ESM
298
+ └── types/
299
+ └── *.d.ts ← shared type declarations
300
+ ```
301
+
302
+ ### `package.json` exports map
303
+
304
+ ```jsonc
305
+ "type": "module",
306
+ "exports": {
307
+ ".": { "types": "./dist/src/main.d.ts", "import": "./dist/src/main.js" },
308
+ "./browser": { "types": "./dist/src/browser-entry.d.ts", "import": "./dist/src/browser-entry.js" },
309
+ "./gamehub-sdk.js": "./dist/gamehub-sdk.js",
310
+ "./package.json": "./package.json"
311
+ }
312
+ ```
313
+
314
+ ### Source-level invariants
315
+
316
+ - **Every relative import in [src/](./src) and [types/](./types) ends in `.js`** — even when importing a `.ts` file. TypeScript with `moduleResolution: NodeNext` resolves `./foo.js` to `./foo.ts` at compile time and preserves the `.js` extension in the emitted output. This is the standard Node-ESM pattern; without it the dist won't load under Node's native ESM loader.
317
+ - **`src/main.ts` has no side effects.** All side-effecting boot code lives in [src/browser-entry.ts](./src/browser-entry.ts). Don't add IIFE / top-level DOM access to `main.ts` or any of its transitive imports.
318
+ - **Use `isBrowser()` from [src/utils.ts](./src/utils.ts)** for any new code that touches `window` / `document` / `WebSocket`. Top-level type references to those globals are fine (TS-only); top-level value reads will break SSR.
319
+
320
+ ## Questions / problems?
321
+
322
+ If something in your migration isn't covered here, please open an issue with a code snippet of the previous usage and we'll add it to this guide.