@ksaa-nlp/gamehub-sdk 5.0.0 → 5.5.1

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 (45) hide show
  1. package/README.md +53 -3
  2. package/SPEC.md +138 -3
  3. package/dist/gamehub-sdk.js +1 -1442
  4. package/dist/gamehub-sdk.js.map +4 -4
  5. package/dist/src/answers.d.ts +22 -0
  6. package/dist/src/answers.d.ts.map +1 -0
  7. package/dist/src/answers.js +139 -0
  8. package/dist/src/answers.js.map +1 -0
  9. package/dist/src/bridge.d.ts.map +1 -1
  10. package/dist/src/bridge.js +2 -0
  11. package/dist/src/bridge.js.map +1 -1
  12. package/dist/src/constants.d.ts +1 -1
  13. package/dist/src/constants.js +1 -1
  14. package/dist/src/loading.d.ts +5 -0
  15. package/dist/src/loading.d.ts.map +1 -0
  16. package/dist/src/loading.js +54 -0
  17. package/dist/src/loading.js.map +1 -0
  18. package/dist/src/main.d.ts +13 -2
  19. package/dist/src/main.d.ts.map +1 -1
  20. package/dist/src/main.js +9 -0
  21. package/dist/src/main.js.map +1 -1
  22. package/dist/src/multiplayer-client.d.ts +2 -0
  23. package/dist/src/multiplayer-client.d.ts.map +1 -1
  24. package/dist/src/multiplayer-client.js +18 -0
  25. package/dist/src/multiplayer-client.js.map +1 -1
  26. package/dist/src/session.d.ts.map +1 -1
  27. package/dist/src/session.js +25 -5
  28. package/dist/src/session.js.map +1 -1
  29. package/dist/types/bootstrap.d.ts +2 -0
  30. package/dist/types/bootstrap.d.ts.map +1 -1
  31. package/dist/types/loading.d.ts +6 -0
  32. package/dist/types/loading.d.ts.map +1 -0
  33. package/dist/types/loading.js +2 -0
  34. package/dist/types/loading.js.map +1 -0
  35. package/dist/types/question.d.ts +0 -1
  36. package/dist/types/question.d.ts.map +1 -1
  37. package/dist/types/question.js +0 -1
  38. package/dist/types/question.js.map +1 -1
  39. package/dist/types/session.d.ts +16 -0
  40. package/dist/types/session.d.ts.map +1 -1
  41. package/dist/vendor/colyseus-schemas/common.d.ts +18 -0
  42. package/dist/vendor/colyseus-schemas/common.js +4 -1
  43. package/dist/vendor/gamehub-multiplayer-contracts/index.d.ts +25 -1
  44. package/dist/vendor/gamehub-multiplayer-contracts/index.js +3 -1
  45. package/package.json +2 -2
package/README.md CHANGED
@@ -239,6 +239,27 @@ sdk.reportWord({
239
239
 
240
240
  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 for logged-in users and submits it; guests see a login prompt). Pass `questions` / `words` instead of a single id to have the host render a dropdown so the player chooses which item to report.
241
241
 
242
+ ## Recording answers
243
+
244
+ Report each answered question so the platform can show which questions are
245
+ hardest, which wrong option players pick most, and how long answers take:
246
+
247
+ ```ts
248
+ const shownAt = performance.now();
249
+ // …the player picks an option…
250
+ sdk.recordAnswer({
251
+ questionId: q.id, // the question-bank id, or your own stable id
252
+ correct: picked === q.answer,
253
+ choice: picked, // the option's text or its index — never typed text
254
+ timeMs: performance.now() - shownAt,
255
+ level: currentLevel,
256
+ });
257
+ ```
258
+
259
+ It is fire-and-forget: answers are batched and sent before `submitScore`. Only
260
+ signed-in players' sessions send them, and the platform keeps them anonymously,
261
+ without the player. Invalid answers are dropped silently.
262
+
242
263
  ## Pause/resume from the host
243
264
 
244
265
  The host can pause/resume the iframe by posting a command. Define globals to receive them:
@@ -290,6 +311,7 @@ sdk.getWords({ difficulty, category, tags, limit, profileId }); // Promise<Word[
290
311
  sdk.notifyComplete(data?); // void
291
312
  sdk.requestClose(); // void
292
313
  sdk.logEvent(name, data?); // void
314
+ sdk.recordAnswer({ questionId, correct, choice?, timeMs?, level? }); // void
293
315
  sdk.reportQuestion({ questionId?, prompt?, message?, questions? }); // void
294
316
  sdk.reportWord({ wordId?, lemma?, message?, words? }); // void
295
317
 
@@ -455,9 +477,11 @@ contract are in the [multiplayer reference](../../specs/multiplayer.md#3-package
455
477
 
456
478
  ## Create and join inside your game (SDK 4.3)
457
479
 
458
- Declare `lobbyUi: "game"` in `gamehub.multiplayer.json`, then disable the game's
459
- platform-lobby setting. Wait for bootstrap and implement the menu using typed
460
- host controls. Hosts retain authentication and session ownership.
480
+ The admin platform waiting-room setting enables normal multiplayer; TV support
481
+ independently enables AirConsole. Do not add `lobbyUi` to the manifest: it is retired.
482
+ The typed menu controls below remain available to existing game-owned session
483
+ hosts. Disabling the waiting-room setting disables new normal multiplayer entry;
484
+ it no longer selects a game-owned menu. Hosts retain authentication and session ownership.
461
485
 
462
486
  ```ts
463
487
  await sdk.ready();
@@ -485,3 +509,29 @@ session retirement. Start transitions to a newly mounted pinned game document;
485
509
  read `multiplayerLaunch` there and connect `MultiplayerClient`. Lobby menus
486
510
  cannot start/submit ordinary client scores. See the starter for ready/start,
487
511
  bots, leave and rematch controls.
512
+
513
+ ### Shared platform loading screens
514
+
515
+ With SDK 5.2, games report loading state; GameHub renders the same loading UI
516
+ for solo, embedded, standard multiplayer and AirConsole gameplay:
517
+
518
+ ```ts
519
+ const sdk = createSdk();
520
+ sdk.setLoading('loading'); // Queued until the trusted host bootstraps.
521
+ await sdk.ready();
522
+ try {
523
+ await loadGameAssets();
524
+ sdk.setLoading(null); // Reveal interactive instructions or gameplay.
525
+ } catch {
526
+ sdk.setLoading('failed'); // Platform retry UI.
527
+ }
528
+ ```
529
+
530
+ For a game-specific wait, use `sdk.setLoading('waiting-for-players')`, then
531
+ `null` when it ends. Pass the SDK itself to `new MultiplayerClient(sdk, launch)`;
532
+ the updated adapter automatically reports connection, arrival, recovery and
533
+ finishing states through its independent channel. Do not draw a second loading
534
+ screen inside the game when hosted by GameHub. Clearing a custom loading state
535
+ does not clear an active connection wait. SDK `ready()` is not asset readiness.
536
+ Existing bundled adapters require rebuilding and republishing the game package;
537
+ the platform cannot infer every internal state from an older bundle.
package/SPEC.md CHANGED
@@ -1,10 +1,97 @@
1
1
  # GameHub SDK — Specification
2
2
 
3
- Version: 5.0.0
3
+ Version: 5.5.1
4
4
  Status: Authoritative. Supersedes README/MIGRATION/CHANGELOG where they conflict.
5
5
 
6
6
  This document is the single source of truth for the GameHub SDK. Code, tests, and consumer docs follow this spec; if a behaviour is observed in code but not described here, treat it as undocumented and revisit before relying on it.
7
7
 
8
+ ## Minified script-tag bundle (5.5.1)
9
+
10
+ The IIFE bundle (`dist/gamehub-sdk.js`, served at `/sdk/gamehub-sdk.js`) is now
11
+ built with esbuild `--minify`: about 28 KB raw and 9 KB gzip instead of 54 KB
12
+ and 12.4 KB. The public API, message types, the `window.GameHubSDK` global and
13
+ its method names are unchanged (object property names are not mangled); the
14
+ source map still maps the served file back to the sources. ESM entries are
15
+ unaffected. §20.3 lowers the budget to match.
16
+
17
+ ## Answer recording (5.5.0)
18
+
19
+ `sdk.recordAnswer({ questionId, correct, choice?, timeMs?, level? })` reports
20
+ one answered question for the platform's play analytics. It is fire-and-forget
21
+ (`void`, never throws, never blocks play):
22
+
23
+ - **Validation.** `questionId` is 1–64 characters of `A-Z a-z 0-9 _ : . -` (a
24
+ question-bank id from `getQuestions`, or the game's own stable id, never prompt
25
+ text); `correct` is a boolean; `choice` is the picked option's text (≤ 100
26
+ characters) or an integer index; `timeMs` is 0–600 000 (rounded); `level` is
27
+ an integer 0–1000. An invalid answer is dropped.
28
+ - **Scope.** Answers are kept only for a signed-in player's standalone account
29
+ session: a 24-hex session token, no league context and not an embed guest.
30
+ Otherwise the call does nothing. It does not start a session.
31
+ - **Delivery.** Each answer gets the next `seq` (0–499) of its session; later
32
+ answers are dropped. The SDK sends `POST /sessions/answers`
33
+ `{ token, answers: [...] }` (§16) when ten answers are queued, three seconds
34
+ after the last answer, and always before `submitScore` sends the score.
35
+ Batches hold at most 50 answers. A failed batch is dropped, not retried: it
36
+ loses analytics only, and the platform stores each `seq` once.
37
+ - **Anonymous storage.** The platform keeps answers without the player or the
38
+ session: the session token only authorizes the batch. The endpoint answers
39
+ `{ recorded }`, the number of new answers stored.
40
+
41
+ `RecordAnswerData` is exported with the other session types. The React Native
42
+ SDK 1.3.0 implements the same method and rules. Usage report: feature
43
+ `recordAnswer`, scanner 8, observed on the server endpoint (§21.7).
44
+
45
+ ## Platform loading presentation (5.4.0)
46
+
47
+ `sdk.setLoading(state, launch?)` requests the platform's common loading screen.
48
+ `GameLoadingState` is `loading | waiting-for-players | reconnecting | failed | null`.
49
+ `null` clears that channel. Call it before asset/content work and clear it before
50
+ interactive tutorials or gameplay; errors use `failed`. It does not mark players
51
+ ready, pause a room, fetch data or change game rules. `ready()` and wire `READY`
52
+ refer to SDK initialization, not game asset readiness.
53
+
54
+ The optional `GameLoadingLaunch` contains only `multiplayerSessionId`, `roundId`,
55
+ `attemptId`, `seatId`, `hostInstanceId`; it selects the separate multiplayer
56
+ channel. `MultiplayerClient` calls the optional `LaunchHost.setLoading` with this
57
+ identity automatically: connecting/finishing → loading, connected/loading →
58
+ waiting-for-players, reconnecting → reconnecting, failed → failed, playing/
59
+ completed/disposed → null. Status changes alone trigger reports; optional host
60
+ exceptions cannot break connection recovery. Native/custom launch hosts that
61
+ omit the optional method retain existing behavior, with no browser dependencies.
62
+
63
+ The maintained React Native SDK implements the same signal in version 1.2.0,
64
+ using a per-client loading owner, snapshot/subscription API and optional React
65
+ hook instead of a DOM bridge. Its loading types are copied from this package's
66
+ authoritative contract at build time. The mobile WebView host also accepts this
67
+ browser signal and renders loading outside the game; see the native SDK and
68
+ mobile app specifications for their lifecycle and document fencing contracts.
69
+
70
+ Supported iframe hosts supply an opaque `BootstrapConfig.loadingContext` on
71
+ bootstrap and rotate it on document load/replacement/retry. The transport emits
72
+ `GAMEHUB_SDK_LOADING` with `{loadingContext,state,launch?}` only after a valid
73
+ context arrives through the existing trusted bootstrap. Calls made before then
74
+ retain the latest value per channel; a new context replays both channels.
75
+ Invalid state/identity/context values are ignored. Only the five bounded identity
76
+ fields are copied, never reservations or credentials. Unsupported hosts and
77
+ standalone games receive no loading signal and retain their own fallback UI.
78
+ Hosts validate current iframe source, origin, context and all launch identity
79
+ fields; loading has no authority over results, scoring or session operations.
80
+
81
+ Solo, embed, standard multiplayer and AirConsole gameplay share the same host
82
+ component. The game stays mounted and continues work while its iframe is inert.
83
+ A continuous 45-second wait offers retry without cancelling the running game;
84
+ recovery can still clear the screen. Legacy bundles use document loading and
85
+ host-observed round progress after a launch request. They must adopt this SDK
86
+ and `setLoading` for otherwise invisible asset waits and local reconnection.
87
+ Immutable game packages are not rewritten by a platform deployment.
88
+
89
+ SDK Usage scanner 7 adds `setLoading` with the standard call-site detection,
90
+ Arabic labels, filtering and CSV. A valid current-document host signal records
91
+ runtime evidence once per mounted source; untrusted/stale signals do not count.
92
+ The package, SDK_VERSION and served JS/map are 5.4.0; the existing 52 KiB raw /
93
+ 12 KiB gzip distribution gate remains unchanged.
94
+
8
95
  ---
9
96
 
10
97
  ## 1. Purpose
@@ -189,6 +276,7 @@ The full taxonomy follows. It applies to **both** transports identically.
189
276
  | SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`. |
190
277
  | SDK → host | `SESSION_STARTED` | Fired when a session token is obtained. Carries `{ token }`. |
191
278
  | SDK → host | `SCORE_SUBMITTED` | Fired only when a score is accepted. Carries `{ score, sessionId, status: 'accepted', terminal: true, serverDurationMs, timeTaken, replayed? }`; score metadata is never included. |
279
+ | SDK → host | `GUEST_SCORE` | Fired by `submitScore` when no session can open for an unauthenticated player (§8.2), before it resolves `SESSION_START_FAILED`. Carries `{ score }`, the floored valid score; nothing is recorded. Unverified: hosts use it for display only (§9.1). |
192
280
  | SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
193
281
  | SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
194
282
  | SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
@@ -396,6 +484,7 @@ On success, the SDK posts `SESSION_STARTED { token }` to the host.
396
484
  - A structured terminal error resolves `{ success: false, status: 'rejected', terminal: true, code, error, sessionStatus? }`. Accepted and rejected terminal outcomes clear the token/start/submission/pending state after accepted host notification.
397
485
  - `RATE_LIMITED` and `SUBMISSION_IN_PROGRESS` resolve the retriable variant. Server/transport failures resolve the failed variant. All non-terminal outcomes retain the active token and exact first body; an explicit same-payload call retries it and can consume `replayed: true`.
398
486
  - Posts `SCORE_SUBMITTED` only for accepted outcomes. The telemetry contains lifecycle fields, never arbitrary `meta`.
487
+ - With no session and an unauthenticated player (no token, no league match, no trusted `embed-guest`/`authenticated` mode), posts `GUEST_SCORE { score: floor(score) }` when `score` is valid, then resolves `SESSION_START_FAILED` as before. Never with `meta`. The score is the game's own claim: a host may show or share it but must not record or reward it.
399
488
  - Every public score method resolves a result and never throws.
400
489
 
401
490
  ### 9.2 `submitMatchScore(score, meta?)`
@@ -630,7 +719,8 @@ bootstrap merge; subscriptions hold callbacks only in memory.
630
719
 
631
720
  | Method | Returns | Notes |
632
721
  | -------------------------------- | ---------------------------- | ------------------------------------------------------------------------------- |
633
- | `submitScore(score, meta?)` | `Promise<SubmitScoreResult>` | Auto-opens a session if needed. Never throws. |
722
+ | `submitScore(score, meta?)` | `Promise<SubmitScoreResult>` | Auto-opens a session if needed. Sends queued answers first. Never throws. |
723
+ | `recordAnswer(answer)` | `void` | Queues one answered question for the signed-in session; see 5.5.0 above. |
634
724
  | `submitMatchScore(score, meta?)` | `Promise<SubmitScoreResult>` | Requires `matchId`. Augments `meta` with `matchId/leagueId/gameId`. |
635
725
  | `submitMatchResult(result?)` | `Promise<SubmitScoreResult>` | Zero-score wrapper over `submitMatchScore`; payload goes to `meta.matchResult`. |
636
726
 
@@ -885,6 +975,7 @@ The SDK assumes the GameHub server exposes the following endpoints. When embedde
885
975
  | POST | `/sessions/start` | Bearer or trusted embed-guest host | `{ gameSlug }` | `{ success: true, data: { token } }` or `{ success: true, token }` |
886
976
  | POST | `/leagues/<leagueId>/sessions` | Bearer | `{ gameId }` | as above |
887
977
  | POST | `/leagues/<leagueId>/matches/<matchId>/session` | optional | `{ gameId }` | as above (guest sessions allowed) |
978
+ | POST | `/sessions/answers` | Bearer (account session) | `{ token, answers }` | `{ success: true, data: { recorded } }`; the SDK ignores the response |
888
979
  | POST | `/sessions/submit` | optional | `{ token, score, meta }` | Account target: `{ success: true, data: { status: 'accepted', terminal: true, sessionId, serverDurationMs, timeTaken, replayed? } }`; guest/league accepted responses are normalized by the SDK |
889
980
  | GET | `/games/<id-or-slug>/questions?…` | optional | n/a | `Question[]` or `{ questions: Question[] }` |
890
981
  | GET | `/leagues/<leagueId>/matches/<matchId>` | optional | n/a | `{ success: true, data: MatchContext }` |
@@ -961,7 +1052,7 @@ These rules exist because of a real prior regression where transport-related cle
961
1052
 
962
1053
  ### 20.3 Bundle budget
963
1054
 
964
- The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **52 KiB raw** and **12 KiB gzip**. SDK 4.3 deliberately raises the previous 44/10 KiB limits to include bounded lobby-state validation, typed host controls and independent subscriptions. Runtime dependencies remain empty; the distribution test checks the built and served bytes and both budgets.
1055
+ The IIFE bundle (`dist/gamehub-sdk.js`) is minified and must remain under **36 KiB raw** and **11 KiB gzip**. SDK 4.3 raised the earlier 44/10 KiB limits of the unminified bundle to 52/12 KiB for bounded lobby-state validation, typed host controls and independent subscriptions; 5.5.0's `recordAnswer` crossed them, and 5.5.1 minifies the bundle (about 28 KB raw / 9 KB gzip) and sets the current limits. Runtime dependencies remain empty; the distribution test checks the built and served bytes and both budgets.
965
1056
 
966
1057
  ### 20.4 Runtime dependencies
967
1058
 
@@ -1060,6 +1151,11 @@ filters/CSV and fixtures are synchronized. Runtime aggregation excludes these
1060
1151
  local APIs. The example in `demos/game-settings/` is a reference game and
1061
1152
  host for manual testing of global/local mute and live preference updates.
1062
1153
 
1154
+ Version 5.5.0 adds `recordAnswer` (scanner version 8, Arabic label
1155
+ «الإجابات»). It is observed at runtime when `POST /api/sessions/answers` (or
1156
+ its authenticated-embed twin) accepts a batch for a valid session, whether or
1157
+ not the platform stores answers; answer values are never part of telemetry.
1158
+
1063
1159
  ## 21bis. UGC server bundle subpath
1064
1160
 
1065
1161
  The `./server` and `./server/dev` subpaths are separate from the browser SDK. Importing them has **no overlap** with the iframe runtime — they target the colyseus UGC sandbox, not the browser host.
@@ -1241,6 +1337,15 @@ remains as the reserved-launch reservation type.
1241
1337
 
1242
1338
  ## 21ter. Multiplayer subpath (5.0.0)
1243
1339
 
1340
+ - **Native build consumer.** The sibling `@ksaa-nlp/gamehub-react-native-sdk`
1341
+ builds an unchanged source copy of `src/multiplayer-client.ts` and
1342
+ `types/{session,question,word,match,multiplayer-session}.ts` through its
1343
+ `scripts/copy-types.mjs`. These files are shared build inputs: changes must
1344
+ pass both this package's tests and `npm run test:sdk:native`. Changes to
1345
+ imports, runtime dependencies or platform assumptions also require
1346
+ `npm run test:sdk:native:metro` for iOS/Android. Keep the realtime core free
1347
+ of browser globals. Generated native `vendor/` and `dist/` copies are never
1348
+ edited; the published native package has no runtime dependency on this SDK.
1244
1349
  - **`@ksaa-nlp/gamehub-sdk/multiplayer`** exports `MultiplayerClient`,
1245
1350
  `ConnectionStatus`, `LaunchHost`, `MultiplayerSnapshot`, `TokenStorage` and
1246
1351
  re-exports every contract. The full API, storage and recovery contract is §10 of
@@ -1279,3 +1384,33 @@ Scanner version 6 detects it through the `"gamehub.mp.v2"` reconnect-token
1279
1384
  namespace literal the class always builds, which survives minification and
1280
1385
  is tree-shaken with the class. A bare `MultiplayerClient` identifier is only `possible`. See
1281
1386
  [the usage report](../../specs/sdk-usage-report.md).
1387
+
1388
+ ## Party contract distribution (5.1.0)
1389
+
1390
+ The 5.1.0 release includes the updated vendored common schema constants
1391
+ (`PLATFORM_MESSAGES`) and `PartyGameResult` contract from the private workspaces.
1392
+ Package version, `SDK_VERSION`, the rebuilt IIFE and its served web copy report
1393
+ 5.1.0 together. No new SDK method or runtime dependency is introduced. Publish
1394
+ this SDK release with the party deployment; a local build is not an npm publish.
1395
+
1396
+ ## Ended lobby membership contract (5.2.0)
1397
+
1398
+ The vendored multiplayer contracts 1.3.0 add `SEAT_LEFT` to the exported error
1399
+ vocabulary, distinguishing ended membership from explicit `SEAT_REMOVED`.
1400
+ Hosts clear stale lobby membership and saved restoration state; a fresh join
1401
+ still follows the current room admission rules. This widens the error type on
1402
+ existing operations and introduces no SDK method, capability or usage-report
1403
+ feature. The existing lobby-control observation strategy remains unchanged.
1404
+ Package version, `SDK_VERSION` and served JS/map report 5.2.0 together.
1405
+
1406
+ ## Guest round score (5.3.0)
1407
+
1408
+ `submitScore` from an unauthenticated player on the standalone play page now
1409
+ posts `GUEST_SCORE { score }` (§6.1, §9.1) before resolving the unchanged
1410
+ `SESSION_START_FAILED`. The GameHub play page uses it to offer «شارك نتيجتك»
1411
+ to guests; nothing is stored. No method, public type or runtime dependency is
1412
+ added, and the usage report needs no new feature: a game still calls the
1413
+ tracked `submitScore`, and the host does not count `GUEST_SCORE` as a runtime
1414
+ observation, since a browser report must not fabricate a score call
1415
+ ([usage report §11.3](../../specs/sdk-usage-report.md)). Package version,
1416
+ `SDK_VERSION` and served JS/map report 5.3.0 together.