@ksaa-nlp/gamehub-sdk 3.7.0 → 3.11.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 (40) hide show
  1. package/README.md +105 -11
  2. package/SPEC.md +201 -84
  3. package/dist/gamehub-sdk.js +174 -83
  4. package/dist/gamehub-sdk.js.map +3 -3
  5. package/dist/src/api-client.d.ts +6 -5
  6. package/dist/src/api-client.d.ts.map +1 -1
  7. package/dist/src/api-client.js +9 -8
  8. package/dist/src/api-client.js.map +1 -1
  9. package/dist/src/bridge.d.ts +10 -6
  10. package/dist/src/bridge.d.ts.map +1 -1
  11. package/dist/src/bridge.js +90 -59
  12. package/dist/src/bridge.js.map +1 -1
  13. package/dist/src/browser-entry.d.ts.map +1 -1
  14. package/dist/src/browser-entry.js +6 -5
  15. package/dist/src/browser-entry.js.map +1 -1
  16. package/dist/src/constants.d.ts +1 -1
  17. package/dist/src/constants.d.ts.map +1 -1
  18. package/dist/src/constants.js +1 -1
  19. package/dist/src/constants.js.map +1 -1
  20. package/dist/src/init.d.ts.map +1 -1
  21. package/dist/src/init.js +21 -9
  22. package/dist/src/init.js.map +1 -1
  23. package/dist/src/main.d.ts +1 -1
  24. package/dist/src/main.d.ts.map +1 -1
  25. package/dist/src/main.js +1 -0
  26. package/dist/src/main.js.map +1 -1
  27. package/dist/src/session.d.ts.map +1 -1
  28. package/dist/src/session.js +8 -3
  29. package/dist/src/session.js.map +1 -1
  30. package/dist/src/state.d.ts +2 -1
  31. package/dist/src/state.d.ts.map +1 -1
  32. package/dist/src/state.js +1 -0
  33. package/dist/src/state.js.map +1 -1
  34. package/dist/src/transport.d.ts +52 -0
  35. package/dist/src/transport.d.ts.map +1 -0
  36. package/dist/src/transport.js +130 -0
  37. package/dist/src/transport.js.map +1 -0
  38. package/dist/types/bootstrap.d.ts +9 -0
  39. package/dist/types/bootstrap.d.ts.map +1 -1
  40. package/package.json +2 -1
package/README.md CHANGED
@@ -1,8 +1,15 @@
1
1
  # GameHub SDK
2
2
 
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.
3
+ The client library GameHub-hosted games use to talk to the platform: auth, sessions, score submission, questions, the words bank, league matches, and the bootstrap pipeline that hands games their multiplayer seat reservation.
4
4
 
5
- Transport-agnostic — no `@colyseus/sdk` dependency. Games that need realtime open their own socket.
5
+ Works in two host environments out of the box:
6
+
7
+ - **iframe** — the classic embedding; the SDK talks to its parent window over `postMessage`.
8
+ - **native WebView** — e.g. a Flutter app; the SDK talks to an injected `window.GameHubNativeHost` bridge.
9
+
10
+ It also runs **standalone** (served from the GameHub origin or in the dev harness). Detection is automatic — your game code is identical across all three. See [Host transports](#host-transports).
11
+
12
+ Transport-agnostic for realtime — no `@colyseus/sdk` dependency. Games that need multiplayer open their own socket.
6
13
 
7
14
  For exhaustive contract details see [SPEC.md](./SPEC.md). The README below is a hands-on tour.
8
15
 
@@ -52,6 +59,20 @@ sdk.hasActiveSession(); // true if auth or league-match context is present
52
59
 
53
60
  `ready()` is idempotent; you can call it from multiple places without worrying about races.
54
61
 
62
+ ## Host transports
63
+
64
+ The SDK auto-detects how to reach its host. You never choose the transport — the same game code runs everywhere.
65
+
66
+ | Transport | When | Wire |
67
+ | ------------- | ------------------------------------------------------------ | ----------------------------------------------- |
68
+ | `postmessage` | Game runs in an `<iframe>` (`window.parent !== window`) | `window.postMessage` to the parent |
69
+ | `native` | Game is the top document in a native WebView (Flutter, etc.) | injected `window.GameHubNativeHost` bridge |
70
+ | none | Standalone — dev harness or served from the GameHub origin | direct `fetch`; host round-trips resolve `null` |
71
+
72
+ The native bridge wins over the iframe check, so a WebView host always takes precedence. The native app must inject `window.GameHubNativeHost` **before** the SDK script loads. See [SPEC.md §6.7](./SPEC.md#67-native-bridge-transport) for the bridge contract a native host must implement.
73
+
74
+ **Host-proxied HTTP.** When embedded (iframe or native), the SDK does **not** issue cross-origin requests to the GameHub backend itself — it asks the host to proxy them. The host (same-origin with the backend, and holder of the bearer token) makes the real call and returns the result. This sidesteps CORS and keeps the auth token out of the game entirely. It's transparent: `submitScore`, `getQuestions`, etc. behave identically; only the wire underneath differs. Standalone, the SDK calls the backend directly. See [SPEC.md §6.6](./SPEC.md#66-host-proxied-api-transport).
75
+
55
76
  ## Bootstrap snapshot
56
77
 
57
78
  `getBootstrap()` returns everything the host told us about this game launch:
@@ -64,12 +85,14 @@ bs.authToken; // Bearer token; null for guests
64
85
  bs.leagueId; // string | null — set inside a league context
65
86
  bs.gameId; // string | null — set inside a league context
66
87
  bs.matchId; // string | null — set inside a league match
88
+ bs.sessionMode; // 'authenticated' | 'embed-guest' | 'league-guest' | null
67
89
  bs.mode; // 'two_players_online' | 'two_players_local' | …
68
90
  bs.playerName; // free-form display name
69
91
  bs.playerCount; // free-form, e.g. '4'
70
92
  bs.teamOneName; // free-form
71
93
  bs.teamTwoName; // free-form
72
- bs.multiplayer; // { roomCode, reconnectionToken, wsEndpoint } | null
94
+ bs.profileId; // string | null — game profile chosen in the pre-start picker
95
+ bs.multiplayer; // reservation + wsEndpoint, with optional roomCode/role/connectionScope
73
96
  bs.isBootstrapped; // true after the host has replied at least once
74
97
  ```
75
98
 
@@ -77,7 +100,7 @@ All fields default to `null`. Don't assume `gameSlug` exists before `ready()` re
77
100
 
78
101
  ## Submitting scores
79
102
 
80
- ### Standalone (single-player)
103
+ ### Standalone or public embed (single-player)
81
104
 
82
105
  ```ts
83
106
  const result = await sdk.submitScore(score, {
@@ -93,7 +116,9 @@ if (result.success) {
93
116
  }
94
117
  ```
95
118
 
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.
119
+ `submitScore` opens a session automatically on first call. In a public GameHub embed, the trusted host supplies either `sessionMode: 'embed-guest'` or `sessionMode: 'authenticated'` and transparently exchanges the same `/sessions/start` and `/sessions/submit` SDK calls for the correct host-owned flow. Games never create guest IDs or receive login codes, user JWTs, or opaque embed credentials. Outside a trusted embed mode, an unauthenticated standalone game with no league-match context returns `{ success: false, error: '...' }` — it never throws.
120
+
121
+ Embed guest results are administrative play records. Authenticated embed results are normal account-attributed scores and enter the standard leaderboards.
97
122
 
98
123
  ### League match (one-score scoring)
99
124
 
@@ -141,6 +166,33 @@ questions.forEach((q) => {
141
166
 
142
167
  `limit` is clamped to 100. Any failure (bad inputs, network error, malformed response) resolves to `[]` — there's no `error` field to check.
143
168
 
169
+ Pass `profileId` to draw from a specific game **profile**. When omitted, the SDK uses the bootstrap-supplied `profileId` (set by the player's pre-start picker), and otherwise falls back to the game's default profile:
170
+
171
+ ```ts
172
+ const questions = await sdk.getQuestions({ profileId: 'beginner-pack' });
173
+ ```
174
+
175
+ ## Words (Words Bank)
176
+
177
+ For vocabulary games, `getWords` mirrors `getQuestions` but returns full nested `Word` entries (lemma, senses, word forms, relations):
178
+
179
+ ```ts
180
+ const words = await sdk.getWords({
181
+ difficulty: 'medium',
182
+ tags: ['animals', 'nature'],
183
+ limit: 20,
184
+ });
185
+
186
+ words.forEach((w) => {
187
+ console.log(w.lemma, '→', w.senses?.[0]?.definition);
188
+ });
189
+ ```
190
+
191
+ - `tags` (a `string[]`) is ANDed on top of the profile selection.
192
+ - `profileId` selects a game profile (the same profile carries both questions and words); falls back to the bootstrap `profileId`, then the default profile.
193
+ - `limit` is clamped to **50** (lower than questions' 100 because a full `Word` is heavier) and defaults to 50.
194
+ - Like `getQuestions`, any failure resolves to `[]`.
195
+
144
196
  ## Host signalling
145
197
 
146
198
  Tell the host page things:
@@ -157,9 +209,15 @@ sdk.reportQuestion({ questionId: q.id, prompt: q.prompt });
157
209
  sdk.reportQuestion({
158
210
  questions: quiz.map((q) => ({ questionId: q.id, prompt: q.prompt })),
159
211
  });
212
+
213
+ // Words Bank: report a word — same single/dropdown semantics, relabeled to lemma
214
+ sdk.reportWord({ wordId: w.id, lemma: w.lemma });
215
+ sdk.reportWord({
216
+ words: bank.map((w) => ({ wordId: w.id, lemma: w.lemma })),
217
+ });
160
218
  ```
161
219
 
162
- 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). Pass `questions` instead of a single `questionId` to have the host render a dropdown so the player chooses which question to report.
220
+ All of these are fire-and-forget — they just signal the host (over whichever transport is active). `reportQuestion` / `reportWord` ask the host to open its report dialog (the host collects the reason + optional message, plus name/email for guests, and submits it). Pass `questions` / `words` instead of a single id to have the host render a dropdown so the player chooses which item to report.
163
221
 
164
222
  ## Pause/resume from the host
165
223
 
@@ -174,7 +232,7 @@ Both are optional. The SDK doesn't pause anything itself; it just delivers the s
174
232
 
175
233
  ## Multiplayer
176
234
 
177
- 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:
235
+ The SDK does not open a WebSocket. The host has already created a Colyseus room before the game boots and passes a **seat reservation** in the bootstrap. Consume it yourself:
178
236
 
179
237
  ```ts
180
238
  import { Client } from '@colyseus/sdk';
@@ -188,7 +246,9 @@ if (!multiplayer) {
188
246
  }
189
247
 
190
248
  const client = new Client(multiplayer.wsEndpoint);
191
- const room = await client.reconnect<UgcState>(multiplayer.reconnectionToken);
249
+ const room = await client.consumeSeatReservation<UgcState>(
250
+ multiplayer.reservation
251
+ );
192
252
 
193
253
  const serverNow = attachServerClock(room);
194
254
 
@@ -197,7 +257,15 @@ room.onMessage('fx:answer', (msg) => playSound(msg));
197
257
  room.send('answer:submit', { answer: 'B' });
198
258
  ```
199
259
 
200
- 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.
260
+ `multiplayer.reservation` is a Colyseus `SeatReservation` (the `{ room, sessionId }` envelope) — feed it straight to `consumeSeatReservation`, which performs the clean first join. No reconnection-token handoff crosses the host→game boundary; after joining, the server mints `room.reconnectionToken` for the game to keep if it wants to reconnect later.
261
+
262
+ External embeds also provide `roomCode`, `role`, and `connectionScope` when
263
+ available. If the game persists its server-issued reconnection token, include
264
+ `connectionScope` in that storage key so two publisher tabs cannot reuse each
265
+ other's reconnect state. These fields are opaque launch context; the SDK never
266
+ opens a socket or writes reconnection data.
267
+
268
+ 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. This works the same inside a native WebView host — the game opens its own socket from inside the WebView; the SDK never proxies realtime traffic over the native bridge.
201
269
 
202
270
  ## API summary
203
271
 
@@ -205,7 +273,7 @@ The returned `room` is a stock `@colyseus/sdk` `Room` — see <https://docs.coly
205
273
  const sdk = createSdk();
206
274
 
207
275
  // Lifecycle
208
- sdk.version; // '3.1.0'
276
+ sdk.version; // '3.8.0'
209
277
  sdk.ready(); // Promise<boolean>
210
278
  sdk.isInitialized(); // boolean
211
279
  sdk.isAuthenticated(); // boolean
@@ -221,13 +289,17 @@ sdk.submitMatchResult({ winnerId, scores }); // Promise<SubmitScoreResult>
221
289
  sdk.getMatchContext(); // Promise<MatchContext | null>
222
290
 
223
291
  // Questions
224
- sdk.getQuestions({ difficulty, category, limit }); // Promise<Question[]>
292
+ sdk.getQuestions({ difficulty, category, limit, profileId }); // Promise<Question[]>
293
+
294
+ // Words (Words Bank)
295
+ sdk.getWords({ difficulty, category, tags, limit, profileId }); // Promise<Word[]>
225
296
 
226
297
  // Host signalling
227
298
  sdk.notifyComplete(data?); // void
228
299
  sdk.requestClose(); // void
229
300
  sdk.logEvent(name, data?); // void
230
301
  sdk.reportQuestion({ questionId?, prompt?, message?, questions? }); // void
302
+ sdk.reportWord({ wordId?, lemma?, message?, words? }); // void
231
303
 
232
304
  // Context
233
305
  sdk.getGameSlug(); // string | null
@@ -249,7 +321,10 @@ import type {
249
321
  SubmitScoreResult,
250
322
  StartSessionResult,
251
323
  Question,
324
+ QuestionDifficulty,
252
325
  QuestionOptions,
326
+ ReportQuestionData,
327
+ ReportableQuestion,
253
328
  GameCompleteData,
254
329
  EventData,
255
330
  MatchContext,
@@ -258,9 +333,28 @@ import type {
258
333
  MatchResultPayload,
259
334
  ApiResponse,
260
335
  ApiRequestOptions,
336
+ // Words Bank
337
+ Word,
338
+ WordDifficulty,
339
+ WordOptions,
340
+ ReportWordData,
341
+ ReportableWord,
342
+ WordSense,
343
+ WordForm,
261
344
  } from '@ksaa-nlp/gamehub-sdk';
262
345
  ```
263
346
 
347
+ The full nested `Word` shape and its sub-interfaces (`WordSense`, `WordForm`, `Lookup`, `Synset`, `DynamicProperty`, …) are all re-exported from the package root — see [`types/word.ts`](./types/word.ts).
348
+
349
+ ## Authoring server bundles (UGC)
350
+
351
+ For games with authoritative server logic running in the Colyseus UGC sandbox, the SDK ships two extra subpaths, separate from the browser runtime:
352
+
353
+ - `@ksaa-nlp/gamehub-sdk/server` — **types only** (`GuestModule`, `Ctx`, `PeerInfo`, …) for writing the guest module.
354
+ - `@ksaa-nlp/gamehub-sdk/server/dev` — `runLocal(guest, opts)`, a pure-Node harness to unit-test a guest bundle against a simulated room without `isolated-vm`.
355
+
356
+ See [SPEC.md §21bis](./SPEC.md#21bis-ugc-server-bundle-subpath) for the full contract.
357
+
264
358
  ## Specification
265
359
 
266
360
  [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.