@ksaa-nlp/gamehub-sdk 0.9.0 → 3.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 (74) hide show
  1. package/README.md +154 -374
  2. package/SPEC.md +865 -0
  3. package/dist/gamehub-sdk.js +164 -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 +27 -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 +23 -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/README.md CHANGED
@@ -1,485 +1,265 @@
1
- # GameHub SDK v0.4.0 — Official Developer Guide
1
+ # GameHub SDK
2
2
 
3
- GameHub SDK is an ESM SDK used by GameHub-hosted games to communicate with the platform for authentication, sessions, score submission, league matches, questions, and multiplayer rooms.
3
+ The client library GameHub-hosted games use to talk to the platform: auth, sessions, score submission, questions, league matches, and the bootstrap pipeline that hands games a multiplayer reconnection token.
4
4
 
5
- It runs in any modern JavaScript environment — browser, Node, Angular Universal / SSR, Vite, webpack, esbuild, Bun. It also ships a self-contained IIFE bundle for plain `<script>`-tag use.
5
+ Transport-agnostic — no `@colyseus/sdk` dependency. Games that need realtime open their own socket.
6
6
 
7
- ## Install
7
+ For exhaustive contract details see [SPEC.md](./SPEC.md). The README below is a hands-on tour.
8
8
 
9
- ### Package-based games (Angular, React, Vue, Phaser, Vite, webpack, ...)
9
+ ## Install
10
10
 
11
11
  ```bash
12
12
  npm install @ksaa-nlp/gamehub-sdk
13
13
  ```
14
14
 
15
- ```ts
16
- import { createSdk, type Sdk } from '@ksaa-nlp/gamehub-sdk';
17
-
18
- const sdk: Sdk = createSdk();
15
+ Or drop the script in directly (auto-attaches `window.GameHubSDK`):
19
16
 
20
- await sdk.ready();
21
- await sdk.submitScore(1500);
17
+ ```html
18
+ <script src="/sdk/gamehub-sdk.js"></script>
22
19
  ```
23
20
 
24
- Importing the package has **no side effects** — `createSdk()` builds an SDK instance you control. Calling any method that needs platform state (e.g. `ready()`, `submitScore()`) lazily triggers the bootstrap handshake the first time it's needed.
25
-
26
- The package is **ESM-only**. Modern Node (≥18), Angular CLI, Vite, webpack 5+, esbuild, Bun, and Rollup all consume ESM natively. Tooling that requires CJS `require()` needs a transpile step or a dynamic `import()`.
27
-
28
- ### Server-side rendering (Angular Universal, Next-style SSR, Node services)
29
-
30
- The package is **safe to import on the server** — no `window` / `document` access happens at evaluation time. Methods called server-side return sensible defaults instead of throwing:
21
+ ## 60-second tutorial
31
22
 
32
23
  ```ts
33
- const sdk = createSdk();
34
-
35
- // Safe on the server — no ReferenceError, no exception.
36
- sdk.isInIframe(); // false
37
- sdk.getBootstrap().isBootstrapped; // false
38
- sdk.notifyComplete({ score: 0 }); // silently no-ops
39
- await sdk.ready(); // resolves to false
40
- ```
41
-
42
- You don't need `isPlatformBrowser` / `typeof window` gates around the import or around `createSdk()`.
43
-
44
- ### GameHub ZIP uploads
45
-
46
- When you upload a ZIP game, GameHub injects the SDK into the entry HTML automatically:
47
-
48
- ```html
49
- <script src="/sdk/gamehub-sdk.js" data-game-slug="your-game-slug"></script>
50
- ```
24
+ import { createSdk } from '@ksaa-nlp/gamehub-sdk';
51
25
 
52
- This loads the IIFE bundle, attaches `window.GameHubSDK`, and runs the auto-init handshake on `DOMContentLoaded`. Do not add your own wrapper layer around the SDK. Use the public methods directly and wait for `ready()`.
26
+ const sdk = createSdk();
27
+ await sdk.ready(); // resolves once the host bootstrap arrives
53
28
 
54
- ### Local standalone testing
29
+ console.log('Playing:', sdk.getGameSlug());
30
+ console.log('User auth:', sdk.isAuthenticated());
55
31
 
56
- If you run the game outside GameHub and are not bundling the npm package, add this script tag only for local testing:
32
+ // ... run the game ...
57
33
 
58
- ```html
59
- <script src="https://gamesbeta.ksaa.gov.sa/sdk/gamehub-sdk.js"></script>
34
+ await sdk.submitScore(1234, { level: 3, duration: 42 });
35
+ sdk.notifyComplete({ score: 1234 });
60
36
  ```
61
37
 
62
- Remove the tag before uploading if your build already imports the package or if GameHub will inject it.
38
+ That's the whole minimum game: `createSdk` → `ready` → `submitScore`. Everything else is opt-in.
63
39
 
64
- ## Required boot pattern
40
+ ## Boot lifecycle
65
41
 
66
- There is no separate `init()` call. The SDK auto-detects game context from the script tag (or your import), URL, and host `postMessage` bootstrap payload — `await sdk.ready()` runs the handshake and resolves when it's done.
42
+ The SDK auto-initialises against the host page on first await. You can drive it manually too:
67
43
 
68
44
  ```ts
69
- import { createSdk } from '@ksaa-nlp/gamehub-sdk';
70
-
71
45
  const sdk = createSdk();
72
- await sdk.ready();
73
-
74
- const bootstrap = sdk.getBootstrap();
75
- console.log({
76
- version: sdk.version,
77
- gameSlug: bootstrap.gameSlug,
78
- leagueId: bootstrap.leagueId,
79
- matchId: bootstrap.matchId,
80
- peerId: bootstrap.peerId,
81
- room: bootstrap.room,
82
- });
83
- ```
84
-
85
- For `<script>`-tag games:
86
46
 
87
- ```js
88
- await window.GameHubSDK.ready();
89
- const bootstrap = window.GameHubSDK.getBootstrap();
47
+ sdk.isInitialized(); // false — bootstrap hasn't arrived yet
48
+ await sdk.ready(); // does the postMessage handshake with the host
49
+ sdk.isInitialized(); // true
50
+ sdk.hasActiveSession(); // true if auth or league-match context is present
90
51
  ```
91
52
 
92
- ## Bootstrap data
53
+ `ready()` is idempotent; you can call it from multiple places without worrying about races.
93
54
 
94
- `sdk.getBootstrap()` returns the current runtime state:
55
+ ## Bootstrap snapshot
56
+
57
+ `getBootstrap()` returns everything the host told us about this game launch:
95
58
 
96
59
  ```ts
97
- {
98
- gameSlug: string | null;
99
- authToken: string | null;
100
- leagueId: string | null;
101
- gameId: string | null;
102
- matchId: string | null;
103
- match: MatchContext | null;
104
- participant1Id: string | null;
105
- participant2Id: string | null;
106
- participant1MemberIds: string[];
107
- participant2MemberIds: string[];
108
- playerName: string | null;
109
- peerId: string | null;
110
- room: BootstrapRoom | null; // null for non-multiplayer sessions
111
- isBootstrapped: boolean;
112
- }
60
+ const bs = sdk.getBootstrap();
61
+
62
+ bs.gameSlug; // 'my-quiz' — required, populated by host or URL
63
+ bs.authToken; // Bearer token; null for guests
64
+ bs.leagueId; // string | null — set inside a league context
65
+ bs.gameId; // string | null — set inside a league context
66
+ bs.matchId; // string | null — set inside a league match
67
+ bs.mode; // 'two_players_online' | 'two_players_local' | …
68
+ bs.playerName; // free-form display name
69
+ bs.playerCount; // free-form, e.g. '4'
70
+ bs.teamOneName; // free-form
71
+ bs.teamTwoName; // free-form
72
+ bs.multiplayer; // { roomCode, reconnectionToken, wsEndpoint } | null
73
+ bs.isBootstrapped; // true after the host has replied at least once
113
74
  ```
114
75
 
115
- For live peer/room state, use `sdk.multiplayer.getRoom()`, `sdk.multiplayer.getPeers()`, and the `peer_joined` / `peer_left` events — bootstrap intentionally doesn't expose live counts because they'd be stale by the time you read them.
76
+ All fields default to `null`. Don't assume `gameSlug` exists before `ready()` resolves.
116
77
 
117
- ## Score submission
78
+ ## Submitting scores
118
79
 
119
- Call `submitScore` when a standalone game round ends:
80
+ ### Standalone (single-player)
120
81
 
121
82
  ```ts
122
83
  const result = await sdk.submitScore(score, {
123
- mode: 'single',
124
- correctAnswers: 8,
125
- totalQuestions: 10,
126
- durationMs: 92000,
127
84
  level: 3,
85
+ duration: 42,
86
+ custom: { combo: 7 },
128
87
  });
129
88
 
130
- if (result.skipped) {
131
- // In an online room, this peer is not the host. The host will submit.
132
- } else if (!result.success) {
89
+ if (result.success) {
90
+ console.log('accepted:', result.accepted, 'timeTaken:', result.timeTaken);
91
+ } else {
133
92
  console.error(result.error);
134
93
  }
135
94
  ```
136
95
 
137
- `submitScore` returns a `SubmitScoreResult`:
138
-
139
- ```ts
140
- {
141
- success: boolean;
142
- accepted?: boolean;
143
- timeTaken?: number;
144
- error?: string;
145
- skipped?: boolean;
146
- }
147
- ```
148
-
149
- Inside a multiplayer room, only the host can write scores. Guests and viewers receive `{ success: true, skipped: true }` without a network write.
96
+ `submitScore` opens a session automatically on first call. If the user isn't authenticated and there's no league-match context, it returns `{ success: false, error: '...' }` — it never throws.
150
97
 
151
- ## League match integration
152
-
153
- When a game is opened from a league match, the host supplies `leagueId`, `gameId`, and `matchId`. The SDK uses these values to start a scoped match session.
154
-
155
- Fetch participant names and team members:
98
+ ### League match (one-score scoring)
156
99
 
157
100
  ```ts
158
- await sdk.ready();
159
-
160
- const match = await sdk.getMatchContext();
161
- if (match) {
162
- renderSideA(match.participant1.name, match.participant1.members);
163
- renderSideB(match.participant2.name, match.participant2.members);
164
- }
101
+ await sdk.submitMatchScore(score, { level: 3 });
165
102
  ```
166
103
 
167
- `MatchContext`:
104
+ Same shape as `submitScore`, but tags the submission with the current `matchId`/`leagueId`/`gameId` from bootstrap. Fails fast if `matchId` is missing.
168
105
 
169
- ```ts
170
- {
171
- id: string;
172
- leagueId: string;
173
- gameId: string;
174
- participant1: {
175
- participantId: string;
176
- name?: string;
177
- members?: Array<{ leaguePlayerId: string; fullname?: string; avatar?: string }>;
178
- };
179
- participant2: {
180
- participantId: string;
181
- name?: string;
182
- members?: Array<{ leaguePlayerId: string; fullname?: string; avatar?: string }>;
183
- };
184
- status: string;
185
- }
186
- ```
106
+ ### League match (winner + per-participant scoring)
187
107
 
188
- Submit the match winner and scores:
108
+ For matches whose leaderboard is derived from a result object (winner, side scores, reason):
189
109
 
190
110
  ```ts
111
+ const ctx = await sdk.getMatchContext();
112
+ if (!ctx) return; // not in a league match
113
+
191
114
  await sdk.submitMatchResult({
192
- winnerId: match.participant1.participantId,
115
+ winnerId: ctx.participant1.participantId,
193
116
  scores: {
194
- [match.participant1.participantId]: 12,
195
- [match.participant2.participantId]: 8,
196
- },
197
- reason: 'normal_finish',
198
- details: {
199
- durationMs: 94000,
117
+ player1Score: 5,
118
+ player2Score: 3,
200
119
  },
120
+ reason: 'connection',
201
121
  });
202
122
  ```
203
123
 
204
- For a match-specific score without a full bracket result:
205
-
206
- ```ts
207
- await sdk.submitMatchScore(1200, {
208
- correctAnswers: 10,
209
- totalQuestions: 12,
210
- });
211
- ```
212
-
213
- In multiplayer league matches, the host should submit the match result. If shared game code calls `submitMatchResult` from a guest or viewer, the SDK returns `skipped`.
124
+ `submitMatchResult` posts a zero placeholder score with the payload in `meta.matchResult`; the server derives leaderboard entries from it.
214
125
 
215
126
  ## Questions
216
127
 
217
- Fetch published questions for the active game:
128
+ For quiz-style games:
218
129
 
219
130
  ```ts
220
131
  const questions = await sdk.getQuestions({
221
132
  difficulty: 'medium',
222
- category: 'science',
223
- limit: 20,
133
+ category: 'capitals',
134
+ limit: 25,
224
135
  });
225
- ```
226
-
227
- The SDK uses `gameId` when provided by the host. Otherwise it falls back to the game slug.
228
-
229
- Question shape:
230
136
 
231
- ```ts
232
- {
233
- id: string;
234
- difficulty?: 'easy' | 'medium' | 'hard' | string;
235
- category?: string;
236
- prompt: string;
237
- choices: string[];
238
- answer: string | number;
239
- explanation?: string;
240
- points: number;
241
- }
137
+ questions.forEach((q) => {
138
+ console.log(q.prompt, q.choices, '→', q.answer);
139
+ });
242
140
  ```
243
141
 
244
- Invalid options or API failures return an empty array.
245
-
246
- ## Multiplayer model
142
+ `limit` is clamped to 100. Any failure (bad inputs, network error, malformed response) resolves to `[]` — there's no `error` field to check.
247
143
 
248
- GameHub multiplayer is host-authoritative:
144
+ ## Host signalling
249
145
 
250
- | Concern | Owner |
251
- | -------------------------------- | --------------------------------------------- |
252
- | Random grids, seeds, decks | Host |
253
- | Turn order and round advancement | Host |
254
- | Click/move validation | Host |
255
- | Player input | Local player sends intent |
256
- | Final score and match result | Host only |
257
- | Timer | Host broadcasts or sends an absolute deadline |
258
-
259
- Guests send intent with `send`. The host validates and publishes resolved state with `broadcast`.
260
-
261
- ### Create and join
146
+ Tell the host page things:
262
147
 
263
148
  ```ts
264
- const room = await sdk.multiplayer.createRoom({
265
- maxPlayers: 2,
266
- passcode: '1234',
267
- });
149
+ sdk.notifyComplete({ score: 1234, status: 'win' }); // game finished
150
+ sdk.requestClose(); // return to lobby
151
+ sdk.logEvent('used_powerup', { kind: 'extra_time' }); // analytics breadcrumb
268
152
 
269
- console.log(room.roomCode, room.shareUrl);
153
+ // Let the player flag the current question — the host opens a report dialog
154
+ sdk.reportQuestion({ questionId: q.id, prompt: q.prompt });
270
155
  ```
271
156
 
272
- ```ts
273
- await sdk.multiplayer.joinRoom('AB12CD', {
274
- passcode: '1234',
275
- displayName: 'Player 2',
276
- });
157
+ All of these are fire-and-forget — they just `postMessage` to the parent window. `reportQuestion` asks the host to open its report dialog (the host collects the reason + optional message, plus name/email for guests, and submits it).
277
158
 
278
- await sdk.multiplayer.joinRoomByLink(window.location.href);
279
-
280
- // Read-only guest:
281
- await sdk.multiplayer.joinRoom('AB12CD', { asViewer: true });
282
- ```
159
+ ## Pause/resume from the host
283
160
 
284
- ### Auto-join on boot
161
+ The host can pause/resume the iframe by posting a command. Define globals to receive them:
285
162
 
286
- The SDK auto-joins when it can detect a pending room — you don't need to wire any of this yourself:
287
-
288
- | Signal | Where it comes from |
289
- | ------------------------------------------------------------ | ---------------------------------------------------------------------- |
290
- | `?mp=<shareId>` on the page URL | QR scan or shared link — SDK auto-calls `joinRoomByLink`. |
291
- | `?roomCode=<CODE>&playerName=<name>` | Host UI forwarded this after `join-token` — SDK auto-calls `joinRoom`. |
292
- | `GAMEHUB_SDK_BOOTSTRAP` postMessage (`shareId` / `roomCode`) | Host page pushed them into the iframe. |
163
+ ```ts
164
+ window.onGameHubPause = () => pauseGameLoop();
165
+ window.onGameHubResume = () => resumeGameLoop();
166
+ ```
293
167
 
294
- By the time `await sdk.ready()` resolves, your `getBootstrap()` already contains `peerId` and `room`, and the socket is connecting. **The bootstrap does not contain the peer list or live room state** — those would be stale by the time you read them. Use `multiplayer.getRoom()`, `multiplayer.getPeers()`, and listen to `connected` / `room_joined` / `peer_joined` / `peer_left` for live data.
168
+ Both are optional. The SDK doesn't pause anything itself; it just delivers the signal.
295
169
 
296
- ### Send and receive game events
170
+ ## Multiplayer
297
171
 
298
- Guests send intent with `send()`. The host validates and publishes resolved state with `broadcast()` — host-only; returns `false` for guests and viewers.
172
+ The SDK does not open a WebSocket. The host has already created a Colyseus room before the iframe boots and passes the reconnection token in the bootstrap. Open it yourself:
299
173
 
300
174
  ```ts
301
- const mp = sdk.multiplayer;
302
-
303
- function onCellClick(cellId: string) {
304
- mp.send('cell_click', { cellId });
175
+ import { Client } from '@colyseus/sdk';
176
+ import { UgcState } from '@ksaa-nlp/colyseus-schemas/ugc';
177
+ import { attachServerClock } from '@ksaa-nlp/colyseus-schemas/clock';
178
+
179
+ const { multiplayer } = sdk.getBootstrap();
180
+ if (!multiplayer) {
181
+ startSoloMode();
182
+ return;
305
183
  }
306
184
 
307
- mp.on('cell_click', ({ fromPeerId, payload }) => {
308
- if (!mp.isHost()) return;
309
- const result = resolveMove(fromPeerId, payload.cellId);
310
- mp.broadcast('cell_resolved', result);
311
- });
185
+ const client = new Client(multiplayer.wsEndpoint);
186
+ const room = await client.reconnect<UgcState>(multiplayer.reconnectionToken);
312
187
 
313
- mp.on('cell_resolved', ({ payload }) => {
314
- applyResolvedMove(payload);
315
- });
316
- ```
188
+ const serverNow = attachServerClock(room);
317
189
 
318
- ### Role helpers
319
-
320
- ```ts
321
- sdk.multiplayer.getRole(); // 'host' | 'player' | 'viewer' | null
322
- sdk.multiplayer.isHost();
323
- sdk.multiplayer.isViewer();
324
- sdk.multiplayer.selfId();
325
- sdk.multiplayer.getRoom();
326
- sdk.multiplayer.getPeers();
327
- sdk.multiplayer.isConnected();
328
- sdk.multiplayer.leaveRoom();
190
+ room.onStateChange((state) => render(state));
191
+ room.onMessage('fx:answer', (msg) => playSound(msg));
192
+ room.send('answer:submit', { answer: 'B' });
329
193
  ```
330
194
 
331
- ### Events
332
-
333
- Subscribe with `sdk.multiplayer.on(eventName, handler)`. Use `'*'` to observe all events.
195
+ The returned `room` is a stock `@colyseus/sdk` `Room` — see <https://docs.colyseus.io/client/room/> for its full API. Install `@colyseus/sdk`, `@colyseus/schema`, and `@ksaa-nlp/colyseus-schemas` in your game; the SDK doesn't pull them in.
334
196
 
335
- | Event | Payload | Meaning |
336
- | -------------- | ------------------------------------------------- | --------------------------- |
337
- | `connected` | `{ roomCode, peerId }` | WebSocket opened |
338
- | `disconnected` | `{ roomCode }` | WebSocket closed |
339
- | `reconnecting` | `{ attempts, delayMs }` | SDK is reconnecting |
340
- | `room_joined` | `{ peerId, role, peers }` | Local peer joined |
341
- | `peer_joined` | `{ peerId, role, ... }` | Another peer joined |
342
- | `peer_left` | `{ peerId }` | A peer left |
343
- | `room_closed` | `{ reason }` | Host/server closed the room |
344
- | `room_left` | `{ reason }` | Local peer left |
345
- | `error` | `{ code }` | Server rejected a frame |
346
- | `message` | `{ eventName, payload, fromPeerId, seq, sentAt }` | Any custom game event |
347
-
348
- Custom game events are also emitted by their own name:
197
+ ## API summary
349
198
 
350
199
  ```ts
351
- mp.on('round_resolved', ({ payload, fromPeerId, seq }) => {
352
- applyRound(payload);
353
- });
200
+ const sdk = createSdk();
201
+
202
+ // Lifecycle
203
+ sdk.version; // '3.1.0'
204
+ sdk.ready(); // Promise<boolean>
205
+ sdk.isInitialized(); // boolean
206
+ sdk.isAuthenticated(); // boolean
207
+ sdk.hasActiveSession(); // boolean
208
+ sdk.startSession(); // Promise<StartSessionResult>
209
+
210
+ // Scores
211
+ sdk.submitScore(score, meta?); // Promise<SubmitScoreResult>
212
+ sdk.submitMatchScore(score, meta?); // Promise<SubmitScoreResult>
213
+ sdk.submitMatchResult({ winnerId, scores }); // Promise<SubmitScoreResult>
214
+
215
+ // League match
216
+ sdk.getMatchContext(); // Promise<MatchContext | null>
217
+
218
+ // Questions
219
+ sdk.getQuestions({ difficulty, category, limit }); // Promise<Question[]>
220
+
221
+ // Host signalling
222
+ sdk.notifyComplete(data?); // void
223
+ sdk.requestClose(); // void
224
+ sdk.logEvent(name, data?); // void
225
+ sdk.reportQuestion({ questionId, prompt?, message? }); // void
226
+
227
+ // Context
228
+ sdk.getGameSlug(); // string | null
229
+ sdk.isInIframe(); // boolean
230
+ sdk.getBootstrap(); // BootstrapData
354
231
  ```
355
232
 
356
- The SDK drops late or duplicate game-event frames using the server-provided `seq` per sending peer.
357
-
358
- ## Public API reference
359
-
360
- Core:
361
-
362
- - `version: string`
363
- - `ready(): Promise<boolean>`
364
- - `isInitialized(): boolean`
365
- - `isAuthenticated(): boolean`
366
- - `hasActiveSession(): boolean`
367
- - `startSession(): Promise<StartSessionResult>`
368
- - `submitScore(score, meta?): Promise<SubmitScoreResult>`
369
- - `submitMatchScore(score, meta?): Promise<SubmitScoreResult>`
370
- - `submitMatchResult(result?): Promise<SubmitScoreResult>`
371
- - `playAgain(): Promise<{ success: boolean; token: string | null }>`
372
- - `notifyComplete(data?): void`
373
- - `requestClose(): void`
374
- - `logEvent(eventName, eventData?): void`
375
- - `getGameSlug(): string | null`
376
- - `isInIframe(): boolean`
377
- - `getBootstrap(): BootstrapData`
378
- - `getMatchContext(): Promise<MatchContext | null>`
379
- - `getQuestions(options?): Promise<Question[]>`
380
-
381
- Multiplayer:
382
-
383
- - `multiplayer.createRoom(options?)`
384
- - `multiplayer.joinRoom(roomCode, options?)`
385
- - `multiplayer.joinRoomByLink(link, options?)`
386
- - `multiplayer.leaveRoom(reason?)`
387
- - `multiplayer.send(eventName, payload?)`
388
- - `multiplayer.broadcast(eventName, payload?)`
389
- - `multiplayer.on(eventName, handler)`
390
- - `multiplayer.getRoom()`
391
- - `multiplayer.getPeers()`
392
- - `multiplayer.isConnected()`
393
- - `multiplayer.getRole()`
394
- - `multiplayer.isHost()`
395
- - `multiplayer.isViewer()`
396
- - `multiplayer.selfId()`
397
-
398
- ### Type imports
399
-
400
- Every public type is exported as a named ESM type from the package root. Import what you need:
233
+ ## TypeScript types
234
+
235
+ Every public type is re-exported from the package root:
401
236
 
402
237
  ```ts
403
238
  import type {
404
239
  Sdk,
405
240
  BootstrapData,
406
- BootstrapRoom,
407
- MatchContext,
408
- MatchParticipant,
409
- MatchResultPayload,
410
- RoomInfo,
411
- Peer,
412
- RoomOptions,
413
- JoinOptions,
414
- CreateRoomResult,
415
- JoinRoomResult,
241
+ BootstrapConfig,
242
+ BootstrapMultiplayer,
416
243
  ScoreMetadata,
244
+ SubmitScoreResult,
245
+ StartSessionResult,
417
246
  Question,
418
247
  QuestionOptions,
419
- StartSessionResult,
420
- SubmitScoreResult,
421
- MpMessage,
422
- MpEventHandler,
248
+ GameCompleteData,
249
+ EventData,
250
+ MatchContext,
251
+ MatchParticipant,
252
+ MatchParticipantMember,
253
+ MatchResultPayload,
254
+ ApiResponse,
255
+ ApiRequestOptions,
423
256
  } from '@ksaa-nlp/gamehub-sdk';
424
257
  ```
425
258
 
426
- ## Pause and resume
427
-
428
- If the host pauses/resumes the iframe, define these optional handlers:
429
-
430
- ```js
431
- window.onGameHubPause = function () {
432
- pauseGame();
433
- };
434
-
435
- window.onGameHubResume = function () {
436
- resumeGame();
437
- };
438
- ```
439
-
440
- ## Common issues
441
-
442
- ### `window.GameHubSDK` is undefined
443
-
444
- You're on the `<script>`-tag path but the bundle didn't load. Either:
445
-
446
- - The script tag is missing from your HTML — re-add `<script src="/sdk/gamehub-sdk.js">` (or the local-testing CDN URL).
447
- - You're inside a bundled app and never imported the SDK — import `@ksaa-nlp/gamehub-sdk` and call `createSdk()` instead. The npm path doesn't attach `window.GameHubSDK`; that's only for the script-tag flow.
448
-
449
- ### `import sdk from '@ksaa-nlp/gamehub-sdk'` fails or returns `undefined`
450
-
451
- The default-import singleton was removed in v0.2.0. Use the named factory:
452
-
453
- ```ts
454
- import { createSdk } from '@ksaa-nlp/gamehub-sdk';
455
- const sdk = createSdk();
456
- ```
457
-
458
- ### `ReferenceError: window is not defined` at import time
459
-
460
- You're on a version older than v0.3.0. Upgrade to v0.4.0 or later — importing the package no longer touches `window` / `document`. If you still see this on a current version, something is importing the script-tag entry (`@ksaa-nlp/gamehub-sdk/browser` or `dist/gamehub-sdk.js`) on the server. Use the default `.` entry instead.
461
-
462
- ### `Cannot use import statement outside a module` / CJS `require()` fails
463
-
464
- The package is ESM-only. Set `"type": "module"` in your `package.json`, or use a dynamic `import()` from CJS code.
465
-
466
- ### Score returns `skipped`
467
-
468
- The current peer is not the multiplayer host, or it joined as a viewer. This is expected and prevents duplicate writes.
469
-
470
- ### Match context is `null`
471
-
472
- The game was not launched with `leagueId` and `matchId`, or the match endpoint could not resolve the match. Fall back to normal game UI.
473
-
474
- ### Questions return `[]`
475
-
476
- No published questions matched the filters, options were invalid, or the API request failed. Treat this as the empty/degraded state.
477
-
478
- ### Guest state differs from host
259
+ ## Specification
479
260
 
480
- Move all random generation and final state transitions to the host. Guests should send intent only and wait for `broadcast`ed resolved events.
261
+ [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.
481
262
 
482
- ## Versions
263
+ ## License
483
264
 
484
- - [CHANGELOG.md](./CHANGELOG.md) — release notes for every version.
485
- - [MIGRATION.md](./MIGRATION.md) — upgrading from v0.1 / v0.2.x / v0.3.x.
265
+ ISC.