@ksaa-nlp/gamehub-sdk 0.7.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.
- package/README.md +154 -374
- package/SPEC.md +865 -0
- package/dist/gamehub-sdk.js +164 -1163
- package/dist/gamehub-sdk.js.map +3 -3
- package/dist/src/api-client.d.ts +15 -5
- package/dist/src/api-client.d.ts.map +1 -1
- package/dist/src/api-client.js +21 -5
- package/dist/src/api-client.js.map +1 -1
- package/dist/src/bridge.d.ts +31 -14
- package/dist/src/bridge.d.ts.map +1 -1
- package/dist/src/bridge.js +148 -159
- package/dist/src/bridge.js.map +1 -1
- package/dist/src/constants.d.ts +8 -6
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/constants.js +8 -6
- package/dist/src/constants.js.map +1 -1
- package/dist/src/init.d.ts +18 -12
- package/dist/src/init.d.ts.map +1 -1
- package/dist/src/init.js +23 -156
- package/dist/src/init.js.map +1 -1
- package/dist/src/main.d.ts +45 -85
- package/dist/src/main.d.ts.map +1 -1
- package/dist/src/main.js +27 -52
- package/dist/src/main.js.map +1 -1
- package/dist/src/match-context.d.ts.map +1 -1
- package/dist/src/match-context.js +0 -14
- package/dist/src/match-context.js.map +1 -1
- package/dist/src/server-dev-harness.d.ts +85 -0
- package/dist/src/server-dev-harness.d.ts.map +1 -0
- package/dist/src/server-dev-harness.js +233 -0
- package/dist/src/server-dev-harness.js.map +1 -0
- package/dist/src/server-entry.d.ts +127 -0
- package/dist/src/server-entry.d.ts.map +1 -0
- package/dist/src/server-entry.js +26 -0
- package/dist/src/server-entry.js.map +1 -0
- package/dist/src/session.d.ts +16 -9
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/session.js +38 -27
- package/dist/src/session.js.map +1 -1
- package/dist/src/state.d.ts +17 -55
- package/dist/src/state.d.ts.map +1 -1
- package/dist/src/state.js +13 -32
- package/dist/src/state.js.map +1 -1
- package/dist/src/utils.d.ts +3 -14
- package/dist/src/utils.d.ts.map +1 -1
- package/dist/src/utils.js +3 -31
- package/dist/src/utils.js.map +1 -1
- package/dist/types/bootstrap.d.ts +56 -36
- package/dist/types/bootstrap.d.ts.map +1 -1
- package/dist/types/question.d.ts +36 -0
- package/dist/types/question.d.ts.map +1 -0
- package/dist/types/question.js +21 -0
- package/dist/types/question.js.map +1 -0
- package/dist/types/session.d.ts +23 -20
- package/dist/types/session.d.ts.map +1 -1
- package/package.json +14 -4
- package/CHANGELOG.md +0 -467
- package/MIGRATION.md +0 -322
- package/dist/src/multiplayer-match.d.ts +0 -42
- package/dist/src/multiplayer-match.d.ts.map +0 -1
- package/dist/src/multiplayer-match.js +0 -551
- package/dist/src/multiplayer-match.js.map +0 -1
- package/dist/src/multiplayer.d.ts +0 -96
- package/dist/src/multiplayer.d.ts.map +0 -1
- package/dist/src/multiplayer.js +0 -495
- package/dist/src/multiplayer.js.map +0 -1
- package/dist/types/multiplayer-match.d.ts +0 -204
- package/dist/types/multiplayer-match.d.ts.map +0 -1
- package/dist/types/multiplayer-match.js +0 -15
- package/dist/types/multiplayer-match.js.map +0 -1
- package/dist/types/multiplayer.d.ts +0 -157
- package/dist/types/multiplayer.d.ts.map +0 -1
- package/dist/types/multiplayer.js +0 -2
- package/dist/types/multiplayer.js.map +0 -1
package/SPEC.md
ADDED
|
@@ -0,0 +1,865 @@
|
|
|
1
|
+
# GameHub SDK — Specification
|
|
2
|
+
|
|
3
|
+
Version: 3.1.0
|
|
4
|
+
Status: Authoritative. Supersedes README/MIGRATION/CHANGELOG where they conflict.
|
|
5
|
+
|
|
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
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## 1. Purpose
|
|
11
|
+
|
|
12
|
+
The GameHub SDK is the client library that GameHub-hosted games use to talk to the GameHub platform. It is a thin, transport-agnostic adapter providing four capabilities:
|
|
13
|
+
|
|
14
|
+
1. **Bootstrap pipeline.** A cross-origin `postMessage` handshake with the host page to discover the active game, the user's auth context, and (when applicable) a multiplayer reconnection token.
|
|
15
|
+
2. **Sessions and scoring.** HTTP wrappers that open a session token and submit scores, with auto-init of the session when a submit is the first call.
|
|
16
|
+
3. **Questions.** HTTP wrapper for the questions endpoint, used by quiz-style games.
|
|
17
|
+
4. **League-match HTTP.** Wrappers for the league-match context fetch and the match-result submit endpoint.
|
|
18
|
+
|
|
19
|
+
The SDK is not coupled to any realtime transport. When the host attaches a multiplayer room, the SDK exposes the connection parameters verbatim and the game opens its own socket.
|
|
20
|
+
|
|
21
|
+
## 2. Scope and non-goals
|
|
22
|
+
|
|
23
|
+
### In scope
|
|
24
|
+
|
|
25
|
+
- Discover the API base URL, the active game slug, and the league/match context from the iframe environment.
|
|
26
|
+
- Exchange a small set of `postMessage` envelopes with the host page (bootstrap, auth, ready, init, command).
|
|
27
|
+
- Hold a single in-memory session token and supply it to the GameHub REST API when submitting scores.
|
|
28
|
+
- Submit scores (`submitScore`, `submitMatchScore`) and league-match results (`submitMatchResult`).
|
|
29
|
+
- Fetch questions (`getQuestions`).
|
|
30
|
+
- Surface a bootstrap snapshot (`getBootstrap()`) including the opaque `multiplayer` block.
|
|
31
|
+
- Forward player-visible host commands (`pause`, `resume`) to optional `window.onGameHubPause` / `onGameHubResume` callbacks.
|
|
32
|
+
- Type definitions for authoring UGC server bundles (`./server` subpath, types-only at runtime).
|
|
33
|
+
- Node-only dev harness (`./server/dev` subpath) for unit-testing a guest bundle against a simulated `ctx`.
|
|
34
|
+
|
|
35
|
+
### Out of scope
|
|
36
|
+
|
|
37
|
+
- Opening or managing WebSocket / WebRTC / SSE connections.
|
|
38
|
+
- Maintaining live realtime room state, peer rosters, message routing, or reconnection.
|
|
39
|
+
- Server-side authority for **browser-side** game logic. The `./server` subpath is types-only; authoritative server logic for UGC games runs inside the colyseus UGC sandbox (`packages/colyseus/src/rooms/ugc/`).
|
|
40
|
+
- Persistent storage. The SDK keeps everything in memory; refresh resets it.
|
|
41
|
+
- UI. The SDK never renders or injects DOM.
|
|
42
|
+
- Analytics. `logEvent` forwards a payload to the host via postMessage; the SDK does not POST to any analytics endpoint itself.
|
|
43
|
+
- Realtime time-sync. Server-clock helpers ship in `@ksaa-nlp/colyseus-schemas/clock`, not here.
|
|
44
|
+
- Multi-tenant or multi-game state. The SDK assumes one game slug per page load.
|
|
45
|
+
|
|
46
|
+
## 3. Architecture
|
|
47
|
+
|
|
48
|
+
### 3.1 Module layout
|
|
49
|
+
|
|
50
|
+
The package is laid out flat under `src/` and `types/`. No subdirectories.
|
|
51
|
+
|
|
52
|
+
| File | Responsibility |
|
|
53
|
+
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
54
|
+
| `src/main.ts` | Public entry. Defines the `Sdk` interface and `createSdk()` factory. Pure on import. |
|
|
55
|
+
| `src/browser-entry.ts` | The only file with side effects on import. Used by the IIFE bundle to attach `window.GameHubSDK`. |
|
|
56
|
+
| `src/init.ts` | `detectEnvironment`, `autoInit`, `ensureInitialized`, `installHostMessageListener`. |
|
|
57
|
+
| `src/bridge.ts` | postMessage protocol: bootstrap parsing, request/response handlers, send helper. |
|
|
58
|
+
| `src/session.ts` | `startSession`, `submitScore`, `submitMatchScore`, `submitMatchResult`, `getQuestions`. |
|
|
59
|
+
| `src/match-context.ts` | `fetchMatchContext` (HTTP `/leagues/<id>/matches/<id>`). |
|
|
60
|
+
| `src/api-client.ts` | `apiRequest`: thin `fetch` wrapper that prefixes the API base and attaches the Bearer token. |
|
|
61
|
+
| `src/state.ts` | `SdkState` interface + the singleton `state` object. All mutable state lives here. |
|
|
62
|
+
| `src/constants.ts` | `SDK_VERSION`, `MESSAGE_PREFIX`, `PARENT_REQUEST_TIMEOUT_MS`, `QUESTIONS_LIMIT_CAP`. |
|
|
63
|
+
| `src/utils.ts` | `isBrowser`, `warn`, `error`, `unwrapResult`, `readQueryParam`. |
|
|
64
|
+
| `types/api.ts` | `ApiResponse`, `ApiRequestOptions`. |
|
|
65
|
+
| `types/bootstrap.ts` | `BootstrapMultiplayer`, `BootstrapConfig`, `BootstrapData`. |
|
|
66
|
+
| `types/session.ts` | `Question`, `QuestionOptions`, `ScoreMetadata`, `EventData`, `GameCompleteData`, `StartSessionResult`, `SubmitScoreResult`. |
|
|
67
|
+
| `types/match.ts` | `MatchParticipantMember`, `MatchParticipant`, `MatchContext`, `MatchResultPayload`. |
|
|
68
|
+
| `src/server-entry.ts` | `./server` subpath. Types-only at runtime: `GuestModule`, `Ctx`, `PeerInfo`, `BroadcastOptions`, `EndMatchPayload`, `CreateOptions`. No imports from the browser SDK; safe for tooling that compiles the bundle on Node. |
|
|
69
|
+
| `src/server-dev-harness.ts` | `./server/dev` subpath. `runLocal(guest, opts)` returns a `LocalRoom` that simulates the colyseus host (`join`, `send`, `leave`, `advance`, etc.) and records every bridge call to `outbox`. Pure Node — does not import `isolated-vm` or anything browser. |
|
|
70
|
+
|
|
71
|
+
### 3.2 Singleton model
|
|
72
|
+
|
|
73
|
+
The SDK is a process-wide singleton. `createSdk()` returns an interface object whose methods all close over the shared `state` from `src/state.ts`. Calling `createSdk()` twice yields two distinct interface objects backed by the same state — there is no isolation.
|
|
74
|
+
|
|
75
|
+
### 3.3 Side-effect rules
|
|
76
|
+
|
|
77
|
+
- Importing `@ksaa-nlp/gamehub-sdk` (the `main.ts` ESM entry) must be free of side effects. It must not touch `window`, `document`, network, or storage.
|
|
78
|
+
- Importing the IIFE bundle (`gamehub-sdk.js` or the `./browser` subpath) executes `bootstrapSdk()` once at load:
|
|
79
|
+
1. `detectEnvironment()` reads URL + `<script>` tag.
|
|
80
|
+
2. `installHostMessageListener()` adds a `message` listener to `window`.
|
|
81
|
+
3. `createSdk()` runs and the result is assigned to `window.GameHubSDK`.
|
|
82
|
+
4. If `window.parent !== window`, a `READY` postMessage is fired up.
|
|
83
|
+
5. If a boot signal is present (resolved slug or inside-iframe), `autoInit()` is kicked off after `DOMContentLoaded`.
|
|
84
|
+
|
|
85
|
+
This is the only place in the package that does work on import. Module / npm consumers do not get this and must call `createSdk()` (and, implicitly, `ready()` or any other method that calls `ensureInitialized()`).
|
|
86
|
+
|
|
87
|
+
## 4. Distribution
|
|
88
|
+
|
|
89
|
+
### 4.1 Build outputs
|
|
90
|
+
|
|
91
|
+
`npm run build` produces:
|
|
92
|
+
|
|
93
|
+
| Artifact | Purpose |
|
|
94
|
+
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
95
|
+
| `dist/src/main.js` | ESM entry. Pure on import. |
|
|
96
|
+
| `dist/src/main.d.ts` | Public type surface. |
|
|
97
|
+
| `dist/src/browser-entry.js` | ESM entry that performs the same side effects as the IIFE bundle. Used by frameworks that want a tree-shakeable side-effectful import. |
|
|
98
|
+
| `dist/gamehub-sdk.js` | IIFE bundle for `<script>` tag use, target ES2020, no external deps. Includes `browser-entry.ts`. Marked `sideEffects: true`. |
|
|
99
|
+
|
|
100
|
+
`build:tsc` emits ESM with `.js` extensions in imports (NodeNext) and full `.d.ts` files. `build:bundle` runs esbuild over `src/browser-entry.ts` to produce the IIFE.
|
|
101
|
+
|
|
102
|
+
### 4.2 Package metadata
|
|
103
|
+
|
|
104
|
+
- `"type": "module"` — ESM only.
|
|
105
|
+
- `main` and `module` both point at `./dist/src/main.js`.
|
|
106
|
+
- `exports`:
|
|
107
|
+
- `"."` → `./dist/src/main.js` (pure entry).
|
|
108
|
+
- `"./browser"` → `./dist/src/browser-entry.js` (side-effectful entry).
|
|
109
|
+
- `"./gamehub-sdk.js"` → `./dist/gamehub-sdk.js` (raw IIFE).
|
|
110
|
+
- `"./package.json"` → `./package.json`.
|
|
111
|
+
- `sideEffects`: `["./dist/src/browser-entry.js", "./dist/gamehub-sdk.js"]` — everything else is tree-shakeable.
|
|
112
|
+
- `files`: only `dist/**/*`, `README.md`, `CHANGELOG.md`, `MIGRATION.md` are published.
|
|
113
|
+
- `dependencies`: none.
|
|
114
|
+
- `peerDependencies`: none.
|
|
115
|
+
- `devDependencies`: `esbuild`, `typescript`.
|
|
116
|
+
|
|
117
|
+
The SDK has zero runtime dependencies. Adding one requires a deliberate decision and a major-version bump.
|
|
118
|
+
|
|
119
|
+
### 4.3 Target environments
|
|
120
|
+
|
|
121
|
+
- Modern browsers (ES2020 baseline).
|
|
122
|
+
- Node ≥ 18 (for SSR / build-time imports of the pure entry).
|
|
123
|
+
- Bundlers: Vite, webpack, esbuild, Rollup, Parcel, Bun.
|
|
124
|
+
- Angular Universal / Next.js SSR — the pure entry is import-safe; `isBrowser()` short-circuits all DOM-touching helpers.
|
|
125
|
+
|
|
126
|
+
## 5. Environment detection
|
|
127
|
+
|
|
128
|
+
`detectEnvironment()` runs at most once. It is idempotent and a no-op outside a browser. On first call it populates:
|
|
129
|
+
|
|
130
|
+
| `state` field | Source |
|
|
131
|
+
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
132
|
+
| `sdkOrigin` | The origin of the `<script src="…/sdk/gamehub-sdk.js">` tag, if found; otherwise `window.location.origin`. |
|
|
133
|
+
| `sdkPathPrefix` | Path prefix preceding `/sdk/gamehub-sdk.js` in the script src (e.g. `/app`). Used so the SDK works when GameHub is mounted under a non-root path. |
|
|
134
|
+
| `runtimeBasePath` | Path prefix preceding `/games/<slug>/` or `/uploaded-games/<slug>/` in `window.location.pathname`. Fallback when the script tag isn't matched. |
|
|
135
|
+
| `apiBase` | `sdkOrigin + (sdkPathPrefix \|\| runtimeBasePath) + '/api'`. |
|
|
136
|
+
| `gameSlug` | First match of: `<script data-game-slug="…">` attribute → path component under `/games/` or `/uploaded-games/` → null. |
|
|
137
|
+
| `leagueId`, `gameId`, `matchId` | From `?leagueId=`, `?gameId=`, `?matchId=` query parameters. |
|
|
138
|
+
|
|
139
|
+
The detection logic is intentionally tolerant: if any signal is missing, the SDK still works for whichever code paths don't need it. A missing `gameSlug` is the only fatal condition for `autoInit()`.
|
|
140
|
+
|
|
141
|
+
### 5.1 Recognised URL patterns
|
|
142
|
+
|
|
143
|
+
```
|
|
144
|
+
/games/<slug>/... → slug = <slug>, runtimeBasePath = ""
|
|
145
|
+
/uploaded-games/<slug>/... → slug = <slug>, runtimeBasePath = ""
|
|
146
|
+
/<prefix>/games/<slug>/... → slug = <slug>, runtimeBasePath = "/<prefix>"
|
|
147
|
+
/<prefix>/uploaded-games/<slug>/... → slug = <slug>, runtimeBasePath = "/<prefix>"
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Slug must match `[a-z0-9-]+` (case-insensitive).
|
|
151
|
+
|
|
152
|
+
## 6. Bootstrap protocol
|
|
153
|
+
|
|
154
|
+
The SDK communicates with the host page through namespaced `postMessage` envelopes. All envelope types are `MESSAGE_PREFIX + '_' + name`, where `MESSAGE_PREFIX = 'GAMEHUB_SDK'`. The full taxonomy follows.
|
|
155
|
+
|
|
156
|
+
### 6.1 Message-type taxonomy
|
|
157
|
+
|
|
158
|
+
| Direction | Type (after prefix) | Purpose |
|
|
159
|
+
| ---------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
160
|
+
| SDK → host | `READY` | Fired once on script load when inside an iframe. Carries `{ version }`. |
|
|
161
|
+
| SDK → host | `BOOTSTRAP_REQUEST` | Asks the host for bootstrap config. Carries `{ messageId }`. |
|
|
162
|
+
| host → SDK | `BOOTSTRAP` | Bootstrap config response. Carries `{ payload: BootstrapConfig, messageId? }`. Host may also push an unsolicited one any time. |
|
|
163
|
+
| SDK → host | `AUTH_REQUEST` | Asks the host for an auth token. Carries `{ messageId }`. |
|
|
164
|
+
| host → SDK | `AUTH_RESPONSE` | Auth response. Carries `{ token: string \| null, leagueId?, gameId?, matchId?, messageId }`. |
|
|
165
|
+
| host → SDK | `SET_AUTH` | Unsolicited auth update. Carries `{ token }`. Triggers session start if not already running. |
|
|
166
|
+
| host → SDK | `COMMAND` | Player-visible host command. Carries `{ command: 'pause' \| 'resume' }`. Routed to optional `window.onGameHubPause/Resume`. |
|
|
167
|
+
| SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`. |
|
|
168
|
+
| SDK → host | `SESSION_STARTED` | Fired when a session token is obtained. Carries `{ token }`. |
|
|
169
|
+
| SDK → host | `SCORE_SUBMITTED` | Fired when a score is accepted. Carries `{ score, accepted, timeTaken }`. |
|
|
170
|
+
| SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
|
|
171
|
+
| SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
|
|
172
|
+
| SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
|
|
173
|
+
| SDK → host | `QUESTION_REPORT` | Fired by `sdk.reportQuestion(data)`. Carries `{ questionId, prompt?, message? }`. The host opens its report dialog. |
|
|
174
|
+
| SDK → host | `API_REQUEST` | Asks the host to proxy a backend HTTP call. Carries `{ messageId, endpoint, method, body }`. See §6.6. |
|
|
175
|
+
| host → SDK | `API_RESPONSE` | Result of a proxied call. Carries `{ messageId, ok: boolean, result?: ApiResponse, error?: string }`. See §6.6. |
|
|
176
|
+
|
|
177
|
+
Every SDK → host envelope also includes the resolved `gameSlug` as a top-level field (except `API_REQUEST`, whose payload is the proxied request).
|
|
178
|
+
|
|
179
|
+
### 6.2 Origin handling
|
|
180
|
+
|
|
181
|
+
The SDK fires the initial `BOOTSTRAP_REQUEST` with target origin `'*'` because it has not yet learned the parent's origin. The very first `BOOTSTRAP` reply records `event.origin` into `state.parentOrigin`. All subsequent SDK → host messages target that recorded origin. Calls before any inbound message fall back to `'*'`.
|
|
182
|
+
|
|
183
|
+
If `event.origin` changes mid-session (e.g. the host navigates between origins), `state.parentOrigin` is overwritten by the next inbound message. There is no origin allowlist; the SDK trusts whatever the parent reports. This is acceptable because the iframe contents are themselves served by GameHub.
|
|
184
|
+
|
|
185
|
+
### 6.3 Request/response correlation
|
|
186
|
+
|
|
187
|
+
- Each SDK-initiated request includes a `messageId: string` (currently `Date.now().toString()`).
|
|
188
|
+
- The host's response must echo the same `messageId`. The SDK's `requestBootstrapFromParent` and `getAuthTokenFromParent` ignore messages with a mismatched `messageId`.
|
|
189
|
+
- The host may push an unsolicited `BOOTSTRAP` with no `messageId`; the SDK still merges it.
|
|
190
|
+
- Each request has a `PARENT_REQUEST_TIMEOUT_MS` (2000 ms) timeout. On timeout the promise resolves to `null` (bootstrap) or `null` (auth); the SDK does not retry.
|
|
191
|
+
|
|
192
|
+
### 6.4 Bootstrap merge semantics
|
|
193
|
+
|
|
194
|
+
`mergeBootstrapConfig(config)` folds a partial `BootstrapConfig` into `state` with these rules:
|
|
195
|
+
|
|
196
|
+
- String fields (`gameSlug`, `authToken`, `leagueId`, `gameId`, `matchId`, `mode`, `playerName`, `playerCount`, `teamOneName`, `teamTwoName`, `profileId`) are trimmed.
|
|
197
|
+
- Empty string after trim → `null`.
|
|
198
|
+
- Explicit `null` in the payload → `null`.
|
|
199
|
+
- Non-string and non-null → ignored (field left as-is).
|
|
200
|
+
- `multiplayer`:
|
|
201
|
+
- Explicit `null` → `null`.
|
|
202
|
+
- Object with `roomCode`, `reconnectionToken`, `wsEndpoint` all strings → trimmed and stored.
|
|
203
|
+
- Any other shape → ignored (field left as-is).
|
|
204
|
+
|
|
205
|
+
This lets the host clear fields explicitly (via `null`) without overwriting unset fields.
|
|
206
|
+
|
|
207
|
+
### 6.5 Bootstrap lifecycle
|
|
208
|
+
|
|
209
|
+
1. **Idle.** `state.bootstrapReceived = false`.
|
|
210
|
+
2. **Request.** First call to `requestBootstrapFromParent()` posts `BOOTSTRAP_REQUEST` and starts the timeout.
|
|
211
|
+
3. **Response.** Host replies with `BOOTSTRAP`. `state.bootstrapReceived = true`. `parentOrigin` recorded.
|
|
212
|
+
4. **Cache.** Subsequent calls return `snapshotBootstrap()` synchronously (wrapped in a resolved promise).
|
|
213
|
+
5. **Update.** Any later unsolicited `BOOTSTRAP` from the host triggers `mergeBootstrapConfig` without affecting `bootstrapReceived`. Existing callers do not get re-notified.
|
|
214
|
+
|
|
215
|
+
A standalone (non-iframe) game has no parent; `requestBootstrapFromParent()` resolves `null` immediately, and `state.bootstrapReceived` stays `false`. `autoInit()` still runs the slug-only path.
|
|
216
|
+
|
|
217
|
+
### 6.6 Host-proxied API transport
|
|
218
|
+
|
|
219
|
+
The SDK never issues a cross-origin request to the GameHub backend. When a game is served from a different domain than GameHub, a direct `fetch` from the iframe would fail CORS. Instead, **every backend call made while embedded is proxied through the host** over the same `postMessage` bridge.
|
|
220
|
+
|
|
221
|
+
`apiRequest(endpoint, options)` (`src/api-client.ts`) chooses its transport by context:
|
|
222
|
+
|
|
223
|
+
- **Embedded** (`window.parent !== window`): delegates to `requestApiFromParent(endpoint, options)` (`src/bridge.ts`). This posts `API_REQUEST` `{ messageId, endpoint, method, body }` to the parent and awaits the matching `API_RESPONSE`.
|
|
224
|
+
- **Standalone** (dev harness, or a game served from the GameHub origin): the legacy direct `fetch` path against `state.apiBase`, attaching `Authorization: Bearer <token>` (§7.2). This path is same-origin by construction, so CORS does not apply.
|
|
225
|
+
|
|
226
|
+
Protocol details:
|
|
227
|
+
|
|
228
|
+
- `endpoint` is the path **after** `/api` (e.g. `/sessions/start`), exactly as passed to `apiRequest`. The host prepends its own same-origin API base. The host **must reject** any `endpoint` that is not a relative path (does not start with `/`, or starts with `//`) so the iframe cannot use the host as an open proxy.
|
|
229
|
+
- `body` is the unserialised request body (or `null`); the host serialises it.
|
|
230
|
+
- The host attaches authentication from **its own** auth context (it holds the same token it bootstrapped to the SDK). The SDK does not send the bearer token in `API_REQUEST`.
|
|
231
|
+
- `API_RESPONSE.ok === true` carries the parsed JSON envelope in `result`; the promise resolves with it. `ok === false` carries an `error` string; the promise rejects. The per-call `try/catch` blocks in `session.ts` / `match-context.ts` turn either outcome into the usual degraded result — public methods still never throw (§17).
|
|
232
|
+
- Timeout is `HOST_API_TIMEOUT_MS` (15 000 ms), larger than the 2 s bootstrap/auth timeout because the round-trip includes the host's real network call. On timeout the promise rejects and the call degrades.
|
|
233
|
+
- `messageId` is `'api_' + Date.now() + '_' + <seq>`, where `<seq>` is a monotonic counter so concurrent proxied calls (e.g. session start + questions) never collide.
|
|
234
|
+
|
|
235
|
+
## 7. Authentication
|
|
236
|
+
|
|
237
|
+
### 7.1 Token sources
|
|
238
|
+
|
|
239
|
+
`state.authToken` is set from, in order:
|
|
240
|
+
|
|
241
|
+
1. `BootstrapConfig.authToken` (via `BOOTSTRAP`).
|
|
242
|
+
2. `AUTH_RESPONSE.token` (the SDK's explicit auth request).
|
|
243
|
+
3. `SET_AUTH.token` (unsolicited host update).
|
|
244
|
+
|
|
245
|
+
The SDK never reads the token from storage and never writes it. Each page load starts with `authToken = null` and the bootstrap pipeline reseeds it.
|
|
246
|
+
|
|
247
|
+
### 7.2 Sending the token
|
|
248
|
+
|
|
249
|
+
On the **standalone** transport, when `state.authToken` is non-null, `apiRequest` attaches `Authorization: Bearer <token>` to every outbound HTTP request. On the **host-proxied** transport (§6.6, the embedded default) the host attaches the bearer header from its own auth context instead. Either way the SDK does not parse the token, refresh it, or check its expiry. A 401 from the server is a normal failed response; the SDK surfaces the error and does not retry.
|
|
250
|
+
|
|
251
|
+
### 7.3 Token rotation
|
|
252
|
+
|
|
253
|
+
If the host posts `SET_AUTH` mid-session, the new token is used for subsequent requests. The session token (separate concept; see §8) is not invalidated by an auth-token rotation — the GameHub server enforces session continuity.
|
|
254
|
+
|
|
255
|
+
## 8. Sessions
|
|
256
|
+
|
|
257
|
+
### 8.1 Session selection
|
|
258
|
+
|
|
259
|
+
`startSession()` picks one of three endpoints from the active context:
|
|
260
|
+
|
|
261
|
+
| Condition | Endpoint | Body |
|
|
262
|
+
| ----------------------------------- | ---------------------------------------------------- | -------------- |
|
|
263
|
+
| `leagueId && gameId && matchId` | `POST /leagues/<leagueId>/matches/<matchId>/session` | `{ gameId }` |
|
|
264
|
+
| `leagueId && gameId` (no `matchId`) | `POST /leagues/<leagueId>/sessions` | `{ gameId }` |
|
|
265
|
+
| otherwise | `POST /sessions/start` | `{ gameSlug }` |
|
|
266
|
+
|
|
267
|
+
### 8.2 Preconditions
|
|
268
|
+
|
|
269
|
+
- `gameSlug` must be non-null. If null, `startSession` returns `{ success: false, error: 'Game slug not set' }` synchronously.
|
|
270
|
+
- Auth is required unless this is a league-match session (`leagueId && gameId && matchId`), which allows guest play.
|
|
271
|
+
|
|
272
|
+
### 8.3 Idempotency
|
|
273
|
+
|
|
274
|
+
Once `state.sessionToken` is non-null, subsequent `startSession()` calls short-circuit to `{ success: true, token }`. Concurrent callers share `state.sessionStartPromise`. The SDK never starts a second session.
|
|
275
|
+
|
|
276
|
+
### 8.4 Session start triggers
|
|
277
|
+
|
|
278
|
+
A session is opened by any of:
|
|
279
|
+
|
|
280
|
+
- `autoInit()` (when auth or league-match context is present).
|
|
281
|
+
- The host posting `SET_AUTH` (when the slug is known and no session is already running).
|
|
282
|
+
- Any score-submitting call that finds no session.
|
|
283
|
+
- An explicit `sdk.startSession()` call.
|
|
284
|
+
|
|
285
|
+
### 8.5 Side effect
|
|
286
|
+
|
|
287
|
+
On success, the SDK posts `SESSION_STARTED { token }` to the host.
|
|
288
|
+
|
|
289
|
+
## 9. Scores
|
|
290
|
+
|
|
291
|
+
### 9.1 `submitScore(score, meta?)`
|
|
292
|
+
|
|
293
|
+
- Awaits `ensureInitialized()`.
|
|
294
|
+
- If no session, opens one (or awaits the in-flight start).
|
|
295
|
+
- Validates: `score` must be a non-negative number; coerced to `Math.floor(score)` before submit.
|
|
296
|
+
- POSTs to `/sessions/submit` with `{ token, score, meta }`.
|
|
297
|
+
- On success or `data.accepted`, posts `SCORE_SUBMITTED { score, accepted, timeTaken }` to the host and resolves `{ success: true, accepted, timeTaken }`.
|
|
298
|
+
- On failure, resolves `{ success: false, error }`. Never throws.
|
|
299
|
+
|
|
300
|
+
### 9.2 `submitMatchScore(score, meta?)`
|
|
301
|
+
|
|
302
|
+
- Requires `state.matchId`. Returns `{ success: false, error: 'No matchId found for this game session' }` otherwise.
|
|
303
|
+
- Calls `submitScore` with `meta` augmented by `{ matchId, leagueId, gameId }` from state.
|
|
304
|
+
|
|
305
|
+
### 9.3 `submitMatchResult(result?)`
|
|
306
|
+
|
|
307
|
+
- Wraps a `MatchResultPayload` (winner, scores, reason, details) and submits with a zero placeholder score: `submitMatchScore(0, { matchResult: result })`.
|
|
308
|
+
- The server derives the actual leaderboard entries from `meta.matchResult`.
|
|
309
|
+
- Rejects non-object payloads with `{ success: false, error: 'match result payload is required' }`.
|
|
310
|
+
|
|
311
|
+
### 9.4 Host gating
|
|
312
|
+
|
|
313
|
+
The SDK does not gate score submission by realtime role. Games that want only one peer to call this make the decision themselves (e.g. `if (room.state.hostPeerId === room.sessionId) sdk.submitScore(...)`).
|
|
314
|
+
|
|
315
|
+
## 10. League-match context
|
|
316
|
+
|
|
317
|
+
### 10.1 `getMatchContext()`
|
|
318
|
+
|
|
319
|
+
- Awaits `ensureInitialized()`, then delegates to `fetchMatchContext()`.
|
|
320
|
+
- Requires `state.leagueId && state.matchId`. Returns `null` otherwise.
|
|
321
|
+
- GETs `/leagues/<leagueId>/matches/<matchId>`.
|
|
322
|
+
- Result is memoised on `state.matchContext` after the first success.
|
|
323
|
+
- Concurrent callers share `state.matchContextPromise`.
|
|
324
|
+
- On HTTP error, transport error, or unwrapped failure, resolves `null`. Never throws.
|
|
325
|
+
|
|
326
|
+
### 10.2 Payload
|
|
327
|
+
|
|
328
|
+
`MatchContext` shape:
|
|
329
|
+
|
|
330
|
+
```ts
|
|
331
|
+
interface MatchContext {
|
|
332
|
+
id: string;
|
|
333
|
+
leagueId: string;
|
|
334
|
+
gameId: string;
|
|
335
|
+
participant1: MatchParticipant;
|
|
336
|
+
participant2: MatchParticipant;
|
|
337
|
+
status: string;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
interface MatchParticipant {
|
|
341
|
+
participantId: string;
|
|
342
|
+
name?: string;
|
|
343
|
+
members?: MatchParticipantMember[];
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
interface MatchParticipantMember {
|
|
347
|
+
leaguePlayerId: string;
|
|
348
|
+
fullname?: string;
|
|
349
|
+
avatar?: string;
|
|
350
|
+
}
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
The SDK stores the response as-is; no further parsing or validation.
|
|
354
|
+
|
|
355
|
+
### 10.3 Stability
|
|
356
|
+
|
|
357
|
+
The HTTP league-match surface (`getMatchContext`, `submitMatchResult`) is independent of any realtime transport. It must continue to work even if the multiplayer block is absent from the bootstrap.
|
|
358
|
+
|
|
359
|
+
## 11. Questions
|
|
360
|
+
|
|
361
|
+
### 11.1 `getQuestions(options?)`
|
|
362
|
+
|
|
363
|
+
- Awaits `ensureInitialized()`.
|
|
364
|
+
- Identifier is `state.gameId || state.gameSlug`. Returns `[]` if both are null.
|
|
365
|
+
- Validates `options.difficulty` against `'easy' | 'medium' | 'hard'`. Returns `[]` on mismatch.
|
|
366
|
+
- Validates `options.limit` is a positive number. Returns `[]` on mismatch.
|
|
367
|
+
- GETs `/games/<identifier>/questions?limit=<n>&random=true[&gameId=…][&difficulty=…][&category=…][&profileId=…]`.
|
|
368
|
+
- `options.profileId` selects a game **profile** on the gamehub side (the resolver returns the union of that profile's private/bank/fixed parts). When omitted, the bootstrap-supplied `profileId` (`getBootstrap().profileId`, set from the player's pre-start picker) is used; an unknown/omitted value falls back to the game's `isDefault` profile — identical to prior behaviour.
|
|
369
|
+
- `limit` is clamped to `QUESTIONS_LIMIT_CAP` (100) and defaults to 100.
|
|
370
|
+
- Response shapes accepted:
|
|
371
|
+
- `Question[]` directly.
|
|
372
|
+
- `{ questions: Question[] }`.
|
|
373
|
+
- Anything else → `[]`.
|
|
374
|
+
- Never throws. All failure modes (bad input, network error, malformed response) resolve `[]`.
|
|
375
|
+
|
|
376
|
+
### 11.2 `Question` shape
|
|
377
|
+
|
|
378
|
+
```ts
|
|
379
|
+
interface Question {
|
|
380
|
+
id: string;
|
|
381
|
+
difficulty?: 'easy' | 'medium' | 'hard' | string;
|
|
382
|
+
category?: string;
|
|
383
|
+
prompt: string;
|
|
384
|
+
choices: string[];
|
|
385
|
+
answer: string | number;
|
|
386
|
+
explanation?: string;
|
|
387
|
+
points: number;
|
|
388
|
+
}
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
## 12. Host command channel
|
|
392
|
+
|
|
393
|
+
`COMMAND` messages from the host dispatch to optional global handlers:
|
|
394
|
+
|
|
395
|
+
| Command | Handler |
|
|
396
|
+
| -------- | -------------------------- |
|
|
397
|
+
| `pause` | `window.onGameHubPause()` |
|
|
398
|
+
| `resume` | `window.onGameHubResume()` |
|
|
399
|
+
|
|
400
|
+
Handlers are checked for `typeof === 'function'` before calling; missing handlers are silent. The SDK itself does not pause the game — it just delivers the signal.
|
|
401
|
+
|
|
402
|
+
## 13. State model
|
|
403
|
+
|
|
404
|
+
All mutable state lives on a single object exported from `src/state.ts`. The full shape:
|
|
405
|
+
|
|
406
|
+
```ts
|
|
407
|
+
interface SdkState {
|
|
408
|
+
// Endpoint resolution
|
|
409
|
+
sdkOrigin: string;
|
|
410
|
+
sdkPathPrefix: string;
|
|
411
|
+
runtimeBasePath: string;
|
|
412
|
+
apiBase: string;
|
|
413
|
+
|
|
414
|
+
// Game / league context
|
|
415
|
+
gameSlug: string | null;
|
|
416
|
+
sessionToken: string | null;
|
|
417
|
+
authToken: string | null;
|
|
418
|
+
leagueId: string | null;
|
|
419
|
+
gameId: string | null;
|
|
420
|
+
matchId: string | null;
|
|
421
|
+
|
|
422
|
+
// Free-form bootstrap fields
|
|
423
|
+
bootstrapMode: string | null;
|
|
424
|
+
bootstrapPlayerName: string | null;
|
|
425
|
+
bootstrapPlayerCount: string | null;
|
|
426
|
+
bootstrapTeamOneName: string | null;
|
|
427
|
+
bootstrapTeamTwoName: string | null;
|
|
428
|
+
|
|
429
|
+
// Multiplayer block (opaque to the SDK)
|
|
430
|
+
bootstrapMultiplayer: BootstrapMultiplayer | null;
|
|
431
|
+
bootstrapReceived: boolean;
|
|
432
|
+
|
|
433
|
+
// Init lifecycle
|
|
434
|
+
isInitialized: boolean;
|
|
435
|
+
isAutoInitializing: boolean;
|
|
436
|
+
autoInitPromise: Promise<boolean> | null;
|
|
437
|
+
bootstrapRequestPromise: Promise<BootstrapConfig | null> | null;
|
|
438
|
+
parentOrigin: string | null;
|
|
439
|
+
sessionStartPromise: Promise<StartSessionResult> | null;
|
|
440
|
+
|
|
441
|
+
// League match (HTTP)
|
|
442
|
+
matchContext: MatchContext | null;
|
|
443
|
+
matchContextPromise: Promise<MatchContext | null> | null;
|
|
444
|
+
}
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
### 13.1 Invariants
|
|
448
|
+
|
|
449
|
+
- `apiBase` is set exactly once, by `detectEnvironment()`, before any HTTP request. It is never mutated afterwards.
|
|
450
|
+
- `gameSlug` may be updated by the bootstrap merge but should be considered stable after `isInitialized = true`. Changing the slug mid-session is undefined behaviour.
|
|
451
|
+
- `sessionToken` is set at most once per page load. The SDK never invalidates or rotates it.
|
|
452
|
+
- `matchContext` is set at most once. Stale match context across renavigations is the host's problem (refresh resets the SDK).
|
|
453
|
+
- All `*Promise` fields are cleared when their underlying operation settles (success or failure).
|
|
454
|
+
|
|
455
|
+
### 13.2 Mutation rules
|
|
456
|
+
|
|
457
|
+
- Any mutation must go through the file that owns the field (`init.ts` for environment, `bridge.ts` for bootstrap, `session.ts` for session/score, `match-context.ts` for `matchContext*`).
|
|
458
|
+
- No file outside `state.ts` may add fields. Add to `SdkState` first, then mutate.
|
|
459
|
+
- New fields must default to `null` / `false` / `""` consistent with the surrounding section.
|
|
460
|
+
|
|
461
|
+
## 14. Public API
|
|
462
|
+
|
|
463
|
+
`createSdk()` returns an object satisfying the `Sdk` interface. Every method below is on that object unless marked otherwise.
|
|
464
|
+
|
|
465
|
+
### 14.1 Static
|
|
466
|
+
|
|
467
|
+
| Member | Type | Notes |
|
|
468
|
+
| --------- | -------- | ------------------------------------------------------------------ |
|
|
469
|
+
| `version` | `string` | Reads `SDK_VERSION`. Matches `package.json` version at build time. |
|
|
470
|
+
|
|
471
|
+
### 14.2 Lifecycle
|
|
472
|
+
|
|
473
|
+
| Method | Returns | Notes |
|
|
474
|
+
| -------------------- | ----------------------------- | ------------------------------------------------------------------------------------------- |
|
|
475
|
+
| `isInitialized()` | `boolean` | True iff `autoInit()` has resolved successfully. |
|
|
476
|
+
| `isAuthenticated()` | `boolean` | True iff `state.authToken` is set. |
|
|
477
|
+
| `hasActiveSession()` | `boolean` | True iff `state.sessionToken` is set. |
|
|
478
|
+
| `ready()` | `Promise<boolean>` | Idempotent. Resolves `true` if init succeeds, `false` outside a browser or on init failure. |
|
|
479
|
+
| `startSession()` | `Promise<StartSessionResult>` | Idempotent. Re-uses an in-flight start. Awaits `ensureInitialized()` first. |
|
|
480
|
+
|
|
481
|
+
### 14.3 Scores
|
|
482
|
+
|
|
483
|
+
| Method | Returns | Notes |
|
|
484
|
+
| -------------------------------- | ---------------------------- | ------------------------------------------------------------------------------- |
|
|
485
|
+
| `submitScore(score, meta?)` | `Promise<SubmitScoreResult>` | Auto-opens a session if needed. Never throws. |
|
|
486
|
+
| `submitMatchScore(score, meta?)` | `Promise<SubmitScoreResult>` | Requires `matchId`. Augments `meta` with `matchId/leagueId/gameId`. |
|
|
487
|
+
| `submitMatchResult(result?)` | `Promise<SubmitScoreResult>` | Zero-score wrapper over `submitMatchScore`; payload goes to `meta.matchResult`. |
|
|
488
|
+
|
|
489
|
+
### 14.4 League match
|
|
490
|
+
|
|
491
|
+
| Method | Returns | Notes |
|
|
492
|
+
| ------------------- | ------------------------------- | ------------------------------------------------------------------------ |
|
|
493
|
+
| `getMatchContext()` | `Promise<MatchContext \| null>` | Requires `leagueId && matchId`. Memoised. Returns `null` on any failure. |
|
|
494
|
+
|
|
495
|
+
### 14.5 Questions
|
|
496
|
+
|
|
497
|
+
| Method | Returns | Notes |
|
|
498
|
+
| ------------------------ | --------------------- | --------------------------------------------- |
|
|
499
|
+
| `getQuestions(options?)` | `Promise<Question[]>` | Returns `[]` on any failure or invalid input. |
|
|
500
|
+
|
|
501
|
+
### 14.6 Host signalling
|
|
502
|
+
|
|
503
|
+
| Method | Returns | Postmessage emitted (after prefix) |
|
|
504
|
+
| --------------------------------- | ------- | ------------------------------------------------- |
|
|
505
|
+
| `notifyComplete(data?)` | `void` | `GAME_COMPLETE` |
|
|
506
|
+
| `requestClose()` | `void` | `REQUEST_CLOSE` |
|
|
507
|
+
| `logEvent(eventName, eventData?)` | `void` | `LOG_EVENT { event: eventName, data: eventData }` |
|
|
508
|
+
| `reportQuestion(data)` | `void` | `QUESTION_REPORT { questionId, prompt?, message? }` |
|
|
509
|
+
|
|
510
|
+
`reportQuestion(data: ReportQuestionData)` asks the host to open its "report this question" dialog for `data.questionId`. The host owns the dialog (the SDK renders no DOM — see §19.3) and submits the report, collecting the reason, an optional message, and — for guests — name/email. Like the other host signals it no-ops outside an iframe.
|
|
511
|
+
|
|
512
|
+
### 14.7 Read-only context
|
|
513
|
+
|
|
514
|
+
| Method | Returns | Notes |
|
|
515
|
+
| ---------------- | ---------------- | -------------------------------------------------------------------- |
|
|
516
|
+
| `getGameSlug()` | `string \| null` | The resolved slug, may be null until bootstrap arrives. |
|
|
517
|
+
| `isInIframe()` | `boolean` | True iff browser AND `window.parent !== window`. |
|
|
518
|
+
| `getBootstrap()` | `BootstrapData` | Snapshot of bootstrap-sourced state. Includes `isBootstrapped` flag. |
|
|
519
|
+
|
|
520
|
+
## 15. Type reference
|
|
521
|
+
|
|
522
|
+
All types listed below are re-exported from the package root and form the public type contract. Adding a field is a minor bump; removing or renaming a field is a major bump.
|
|
523
|
+
|
|
524
|
+
### 15.1 Bootstrap
|
|
525
|
+
|
|
526
|
+
```ts
|
|
527
|
+
interface BootstrapMultiplayer {
|
|
528
|
+
roomCode: string;
|
|
529
|
+
reconnectionToken: string;
|
|
530
|
+
wsEndpoint: string;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
interface BootstrapConfig {
|
|
534
|
+
gameSlug?: string | null;
|
|
535
|
+
authToken?: string | null;
|
|
536
|
+
leagueId?: string | null;
|
|
537
|
+
gameId?: string | null;
|
|
538
|
+
matchId?: string | null;
|
|
539
|
+
mode?: string | null;
|
|
540
|
+
playerName?: string | null;
|
|
541
|
+
playerCount?: string | null;
|
|
542
|
+
teamOneName?: string | null;
|
|
543
|
+
teamTwoName?: string | null;
|
|
544
|
+
profileId?: string | null;
|
|
545
|
+
multiplayer?: BootstrapMultiplayer | null;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
interface BootstrapData {
|
|
549
|
+
gameSlug: string | null;
|
|
550
|
+
authToken: string | null;
|
|
551
|
+
leagueId: string | null;
|
|
552
|
+
gameId: string | null;
|
|
553
|
+
matchId: string | null;
|
|
554
|
+
mode: string | null;
|
|
555
|
+
playerName: string | null;
|
|
556
|
+
playerCount: string | null;
|
|
557
|
+
teamOneName: string | null;
|
|
558
|
+
teamTwoName: string | null;
|
|
559
|
+
profileId: string | null;
|
|
560
|
+
multiplayer: BootstrapMultiplayer | null;
|
|
561
|
+
isBootstrapped: boolean;
|
|
562
|
+
}
|
|
563
|
+
```
|
|
564
|
+
|
|
565
|
+
### 15.2 Session / scoring
|
|
566
|
+
|
|
567
|
+
```ts
|
|
568
|
+
interface ScoreMetadata {
|
|
569
|
+
level?: number;
|
|
570
|
+
duration?: number;
|
|
571
|
+
custom?: Record<string, any>;
|
|
572
|
+
[key: string]: any;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
interface StartSessionResult {
|
|
576
|
+
success: boolean;
|
|
577
|
+
token?: string | null;
|
|
578
|
+
error?: string;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
interface SubmitScoreResult {
|
|
582
|
+
success: boolean;
|
|
583
|
+
accepted?: boolean;
|
|
584
|
+
timeTaken?: number;
|
|
585
|
+
error?: string;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
interface GameCompleteData {
|
|
589
|
+
score?: number;
|
|
590
|
+
status?: string;
|
|
591
|
+
meta?: Record<string, any>;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
interface EventData {
|
|
595
|
+
category?: string;
|
|
596
|
+
label?: string;
|
|
597
|
+
value?: number;
|
|
598
|
+
properties?: Record<string, any>;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
interface QuestionOptions {
|
|
602
|
+
difficulty?: 'easy' | 'medium' | 'hard' | string;
|
|
603
|
+
category?: string | number;
|
|
604
|
+
limit?: number;
|
|
605
|
+
profileId?: string; // selects a game profile; falls back to bootstrap profileId, then isDefault
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
interface Question {
|
|
609
|
+
id: string;
|
|
610
|
+
difficulty?: 'easy' | 'medium' | 'hard' | string;
|
|
611
|
+
category?: string;
|
|
612
|
+
prompt: string;
|
|
613
|
+
choices: string[];
|
|
614
|
+
answer: string | number;
|
|
615
|
+
explanation?: string;
|
|
616
|
+
points: number;
|
|
617
|
+
}
|
|
618
|
+
```
|
|
619
|
+
|
|
620
|
+
### 15.3 League match
|
|
621
|
+
|
|
622
|
+
```ts
|
|
623
|
+
interface MatchParticipantMember {
|
|
624
|
+
leaguePlayerId: string;
|
|
625
|
+
fullname?: string;
|
|
626
|
+
avatar?: string;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
interface MatchParticipant {
|
|
630
|
+
participantId: string;
|
|
631
|
+
name?: string;
|
|
632
|
+
members?: MatchParticipantMember[];
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
interface MatchContext {
|
|
636
|
+
id: string;
|
|
637
|
+
leagueId: string;
|
|
638
|
+
gameId: string;
|
|
639
|
+
participant1: MatchParticipant;
|
|
640
|
+
participant2: MatchParticipant;
|
|
641
|
+
status: string;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
interface MatchResultPayload {
|
|
645
|
+
winnerId?: string;
|
|
646
|
+
reason?: string;
|
|
647
|
+
scores?: Record<string, number>;
|
|
648
|
+
details?: Record<string, any>;
|
|
649
|
+
}
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
### 15.4 HTTP
|
|
653
|
+
|
|
654
|
+
```ts
|
|
655
|
+
interface ApiResponse {
|
|
656
|
+
success: boolean;
|
|
657
|
+
data?: any;
|
|
658
|
+
token?: string;
|
|
659
|
+
error?: { message?: string };
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
interface ApiRequestOptions {
|
|
663
|
+
method?: string;
|
|
664
|
+
headers?: Record<string, string>;
|
|
665
|
+
body?: any;
|
|
666
|
+
credentials?: RequestCredentials;
|
|
667
|
+
}
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
## 16. REST API contract
|
|
671
|
+
|
|
672
|
+
The SDK assumes the GameHub server exposes the following endpoints. When embedded these are reached via the host proxy (§6.6); standalone they are reached directly under `state.apiBase`. Either way the SDK calls `apiRequest` with the same `endpoint` path. Any change to these contracts must be coordinated server-side and is a major-version event for the SDK.
|
|
673
|
+
|
|
674
|
+
| Method | Path | Auth | Request body | Successful response shape |
|
|
675
|
+
| ------ | ----------------------------------------------- | -------- | ------------------------ | ------------------------------------------------------------------ |
|
|
676
|
+
| POST | `/sessions/start` | Bearer | `{ gameSlug }` | `{ success: true, data: { token } }` or `{ success: true, token }` |
|
|
677
|
+
| POST | `/leagues/<leagueId>/sessions` | Bearer | `{ gameId }` | as above |
|
|
678
|
+
| POST | `/leagues/<leagueId>/matches/<matchId>/session` | optional | `{ gameId }` | as above (guest sessions allowed) |
|
|
679
|
+
| POST | `/sessions/submit` | optional | `{ token, score, meta }` | `{ success: true, data: { accepted, timeTaken } }` |
|
|
680
|
+
| GET | `/games/<id-or-slug>/questions?…` | optional | n/a | `Question[]` or `{ questions: Question[] }` |
|
|
681
|
+
| GET | `/leagues/<leagueId>/matches/<matchId>` | optional | n/a | `{ success: true, data: MatchContext }` |
|
|
682
|
+
|
|
683
|
+
### 16.1 Response envelope
|
|
684
|
+
|
|
685
|
+
The SDK expects (but tolerates absence of) a `{ success, data, token?, error? }` envelope. `unwrapResult` flattens it to the inner `data` payload when present; otherwise it returns the raw response. Both shapes are accepted on every endpoint.
|
|
686
|
+
|
|
687
|
+
### 16.2 Failure surface
|
|
688
|
+
|
|
689
|
+
- Non-2xx HTTP responses are parsed as JSON and surfaced via the returned `SubmitScoreResult.error` / `null` / `[]` (depending on the call).
|
|
690
|
+
- `fetch` exceptions (network failure, malformed JSON) are caught by every public method and surfaced as the same failure shape. The SDK never throws past its public surface.
|
|
691
|
+
- When embedded, a host-proxy rejection (host-reported error, or `HOST_API_TIMEOUT_MS` timeout — see §6.6) surfaces identically: the call degrades to its failure shape. CORS is no longer a failure mode for embedded games, since the host (same-origin with the backend) makes the actual request.
|
|
692
|
+
|
|
693
|
+
## 17. Error handling philosophy
|
|
694
|
+
|
|
695
|
+
- **Never throw to consumers.** Every public method returns either a typed success/failure result, or the degraded value (`null` / `[]`).
|
|
696
|
+
- **No retries.** A single attempt per call. Consumers retry if they want to.
|
|
697
|
+
- **No global error reporting.** Errors are logged with the `[GameHubSDK]` prefix via `console.warn` / `console.error`. The SDK does not POST to any error endpoint.
|
|
698
|
+
- **No timeouts on direct HTTP.** The standalone `fetch` path inherits `fetch`'s default behaviour. The postMessage handshakes have timeouts (2 s for bootstrap/auth), and the host-proxied API transport has its own `HOST_API_TIMEOUT_MS` (15 s) cap (§6.6).
|
|
699
|
+
- **Silent degradation on partial bootstrap.** Missing fields are tolerated where possible (`getQuestions` works without `gameId`, falling back to slug; `submitScore` requires auth or a league-match session but no realtime context).
|
|
700
|
+
|
|
701
|
+
## 18. Versioning and stability
|
|
702
|
+
|
|
703
|
+
- Semantic versioning. The package version is the source of truth; `SDK_VERSION` mirrors it and is reported on `READY` and as `sdk.version`.
|
|
704
|
+
- **Breaking** (major bump): removing or renaming a method on `Sdk`, removing or narrowing a public type, changing a postMessage type name, changing the merge semantics of a bootstrap field, adding a required runtime dependency.
|
|
705
|
+
- **Feature** (minor bump): adding a method, widening a public type with optional fields, adding a postMessage type, accepting new optional bootstrap fields.
|
|
706
|
+
- **Patch**: bug fixes that don't change observable behaviour for valid inputs.
|
|
707
|
+
|
|
708
|
+
## 19. Boundary rules
|
|
709
|
+
|
|
710
|
+
These rules exist because of a real prior regression where transport-related cleanup deleted unrelated HTTP plumbing. They are tight on purpose.
|
|
711
|
+
|
|
712
|
+
### 19.1 No realtime in the SDK
|
|
713
|
+
|
|
714
|
+
- The SDK must not import any realtime client (`@colyseus/sdk`, `ws`, `socket.io-client`, …).
|
|
715
|
+
- The SDK must not open a `WebSocket`, `EventSource`, or `RTCPeerConnection`.
|
|
716
|
+
- The `bootstrapMultiplayer` field is opaque. The SDK validates only its shape (three strings); it does not parse or interpret the values.
|
|
717
|
+
- The server-clock helper (`attachServerClock`) belongs in `@ksaa-nlp/colyseus-schemas/clock`, not here.
|
|
718
|
+
|
|
719
|
+
### 19.2 HTTP plumbing is transport-agnostic
|
|
720
|
+
|
|
721
|
+
- `submitMatchResult`, `getMatchContext`, `MatchContext`, and `MatchResultPayload` are **not** part of any realtime stack.
|
|
722
|
+
- A future cleanup that removes realtime support **must not** delete league-match HTTP code as collateral.
|
|
723
|
+
- The match-context endpoint is plain HTTP and continues to work even with `bootstrap.multiplayer === null`.
|
|
724
|
+
|
|
725
|
+
### 19.3 No DOM injection
|
|
726
|
+
|
|
727
|
+
- The SDK must not create, modify, or query DOM elements outside reading `window.location` and the `<script>` tag list during environment detection.
|
|
728
|
+
- The SDK must not register global event listeners outside the single `message` listener installed by `installHostMessageListener()`.
|
|
729
|
+
|
|
730
|
+
### 19.4 No storage
|
|
731
|
+
|
|
732
|
+
- The SDK must not call `localStorage`, `sessionStorage`, `IndexedDB`, or cookies.
|
|
733
|
+
- Tokens (auth and session) live in memory only; refresh resets them. Persistent identity is the host page's responsibility.
|
|
734
|
+
|
|
735
|
+
### 19.5 Singleton
|
|
736
|
+
|
|
737
|
+
- The SDK keeps a single `state` object. Multi-instance / multi-game isolation is out of scope.
|
|
738
|
+
|
|
739
|
+
## 20. Build and dependencies
|
|
740
|
+
|
|
741
|
+
### 20.1 Toolchain
|
|
742
|
+
|
|
743
|
+
- TypeScript ≥ 6 with `module: NodeNext`, `target: ES2020`, `strict: true`, `lib: ["DOM", "DOM.Iterable", "ES2020"]`.
|
|
744
|
+
- esbuild for the IIFE bundle. ES2020 target.
|
|
745
|
+
|
|
746
|
+
### 20.2 Imports
|
|
747
|
+
|
|
748
|
+
- All TypeScript imports use the `.js` extension (`from './state.js'`) to satisfy `NodeNext` resolution.
|
|
749
|
+
- No CommonJS. No top-level `require()`.
|
|
750
|
+
|
|
751
|
+
### 20.3 Bundle budget
|
|
752
|
+
|
|
753
|
+
The IIFE bundle (`dist/gamehub-sdk.js`) is expected to remain under **25 KB raw / 10 KB gzip** in the absence of new feature areas. Crossing that threshold should be a deliberate decision tied to a release note. Current size: ~20 KB raw.
|
|
754
|
+
|
|
755
|
+
### 20.4 No runtime dependencies
|
|
756
|
+
|
|
757
|
+
`package.json` `dependencies` and `peerDependencies` must remain empty. Adding either is a major-version event and requires updating §2 (non-goals) and §19 (boundary rules).
|
|
758
|
+
|
|
759
|
+
## 21. Testing acceptance criteria
|
|
760
|
+
|
|
761
|
+
The SDK does not currently ship a test suite, but every change should be verifiable against this checklist:
|
|
762
|
+
|
|
763
|
+
### 21.1 Pure-import safety
|
|
764
|
+
|
|
765
|
+
- `import { createSdk } from '@ksaa-nlp/gamehub-sdk'` in a Node REPL must succeed without errors and without touching `window` or `document`.
|
|
766
|
+
- `createSdk()` called outside a browser must not throw. The returned object's read-only methods (`getGameSlug`, `isInIframe`, `getBootstrap`, etc.) must return safe defaults.
|
|
767
|
+
|
|
768
|
+
### 21.2 Standalone (non-iframe) browser
|
|
769
|
+
|
|
770
|
+
- `autoInit()` resolves `false` and logs the slug-not-found warning when the page is not under `/games/<slug>/`.
|
|
771
|
+
- Score-submit calls in this state return `{ success: false, error }` and never throw.
|
|
772
|
+
|
|
773
|
+
### 21.3 Iframe boot
|
|
774
|
+
|
|
775
|
+
- The iframe receives a `BOOTSTRAP_REQUEST` from the SDK within ~100 ms of script load.
|
|
776
|
+
- Replying with `BOOTSTRAP { payload: { gameSlug } }` causes `getBootstrap().isBootstrapped` to flip to `true` and `getGameSlug()` to return the value.
|
|
777
|
+
- Replying with `AUTH_RESPONSE { token }` makes `isAuthenticated()` true.
|
|
778
|
+
- Posting `SET_AUTH { token }` after init opens a session and fires `SESSION_STARTED`.
|
|
779
|
+
|
|
780
|
+
### 21.4 Score submission
|
|
781
|
+
|
|
782
|
+
- `submitScore(42, { level: 3 })` causes a POST to `/api/sessions/submit` with `{ token, score: 42, meta: { level: 3 } }` and Bearer auth. When embedded (the default), this travels as an `API_REQUEST` `{ endpoint: '/sessions/submit', method: 'POST', body: { … } }` and the **host** performs the POST with its own bearer auth (§6.6); standalone, the SDK POSTs directly.
|
|
783
|
+
- Returns `{ success: true, accepted: true, timeTaken: <n> }` on a `{ success: true, data: { accepted: true, timeTaken: 1234 } }` server response.
|
|
784
|
+
- Fires `SCORE_SUBMITTED { score: 42, accepted: true, timeTaken: 1234 }` to the host.
|
|
785
|
+
|
|
786
|
+
### 21.4b Host-proxied transport (embedded)
|
|
787
|
+
|
|
788
|
+
- Inside an iframe, no public method issues a direct cross-origin `fetch`; each `apiRequest` posts an `API_REQUEST` and resolves on the matching `API_RESPONSE`.
|
|
789
|
+
- A host that never replies leaves the call pending until `HOST_API_TIMEOUT_MS` (15 s), after which it degrades to the usual failure shape.
|
|
790
|
+
- An `API_RESPONSE { ok: false, error }` degrades identically. The host must reject endpoints that aren't relative API paths.
|
|
791
|
+
|
|
792
|
+
### 21.5 League-match path
|
|
793
|
+
|
|
794
|
+
- With `leagueId`, `gameId`, `matchId` set, `startSession()` hits the match-session endpoint and a guest user (no auth token) is allowed through.
|
|
795
|
+
- `getMatchContext()` GETs the match endpoint and caches the result.
|
|
796
|
+
- `submitMatchResult({ winnerId: 'X', scores: { player1Score: 5, player2Score: 3 } })` POSTs to `/sessions/submit` with `{ score: 0, meta: { matchId, leagueId, gameId, matchResult: { … } } }`.
|
|
797
|
+
|
|
798
|
+
### 21.6 Boundary
|
|
799
|
+
|
|
800
|
+
- `grep -rn "@colyseus" src/ types/` returns only comment references (no import statements).
|
|
801
|
+
- `npm pack --dry-run` produces a tarball whose `peerDependencies` and `dependencies` are both empty/absent.
|
|
802
|
+
|
|
803
|
+
## 21bis. UGC server bundle subpath
|
|
804
|
+
|
|
805
|
+
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.
|
|
806
|
+
|
|
807
|
+
### 21bis.1 `./server` — types
|
|
808
|
+
|
|
809
|
+
`@ksaa-nlp/gamehub-sdk/server` exports types only at runtime; the `.js` artifact contains no runtime symbols. Authors use the types from TypeScript:
|
|
810
|
+
|
|
811
|
+
```ts
|
|
812
|
+
import type { GuestModule, Ctx, PeerInfo } from '@ksaa-nlp/gamehub-sdk/server';
|
|
813
|
+
|
|
814
|
+
const guest: GuestModule = {
|
|
815
|
+
onCreate(ctx, opts) { ctx.state.round = 0; },
|
|
816
|
+
onJoin(ctx, peer) { ctx.broadcast('peer:joined', { peerId: peer.peerId }); },
|
|
817
|
+
onMessage(ctx, peer, type, payload) {
|
|
818
|
+
if (type === 'answer') ctx.send(peer.peerId, 'ack', { ok: true });
|
|
819
|
+
},
|
|
820
|
+
};
|
|
821
|
+
|
|
822
|
+
module.exports = guest;
|
|
823
|
+
```
|
|
824
|
+
|
|
825
|
+
The actual `ctx` is injected by the colyseus UgcRoom sandbox at runtime; the import does not need to be in the published bundle.
|
|
826
|
+
|
|
827
|
+
### 21bis.2 `./server/dev` — `runLocal`
|
|
828
|
+
|
|
829
|
+
`@ksaa-nlp/gamehub-sdk/server/dev` exports `runLocal(guest, opts)` for unit-testing a guest in plain Node (no `isolated-vm` needed):
|
|
830
|
+
|
|
831
|
+
```ts
|
|
832
|
+
import { runLocal } from '@ksaa-nlp/gamehub-sdk/server/dev';
|
|
833
|
+
import guest from './index';
|
|
834
|
+
|
|
835
|
+
const room = runLocal(guest, {
|
|
836
|
+
seed: 42,
|
|
837
|
+
clock: 'manual',
|
|
838
|
+
initialOptions: { gameSlug: 'trivia', maxPlayers: 2 },
|
|
839
|
+
});
|
|
840
|
+
|
|
841
|
+
room.join('A');
|
|
842
|
+
room.join('B');
|
|
843
|
+
room.start();
|
|
844
|
+
room.send('A', 'answer', { value: 42 });
|
|
845
|
+
|
|
846
|
+
expect(room.state.scores).toEqual({ A: 10 });
|
|
847
|
+
expect(room.outbox).toContainEqual({
|
|
848
|
+
kind: 'broadcast',
|
|
849
|
+
type: 'score:awarded',
|
|
850
|
+
payload: { peerId: 'A', delta: 10 },
|
|
851
|
+
opts: null,
|
|
852
|
+
});
|
|
853
|
+
```
|
|
854
|
+
|
|
855
|
+
`LocalRoom` methods: `join`, `leave`, `send`, `start`, `advance`, `dispose`, `clearOutbox`. Live `state` and `outbox` are readable. The harness mirrors the production sandbox's PRNG (Mulberry32, seedable) and manual clock for deterministic tests. It does **not** simulate memory caps, per-call timeouts, or JSON serialization round-trips — production sandbox catches violations that the harness lets through.
|
|
856
|
+
|
|
857
|
+
## 22. Glossary
|
|
858
|
+
|
|
859
|
+
- **Bootstrap.** The set of context the host gives the iframe at load: slug, IDs, auth, multiplayer block, display strings.
|
|
860
|
+
- **Session.** A server-issued token representing a single playthrough. Used to authenticate `submitScore`.
|
|
861
|
+
- **League match.** A scheduled game between two participants tracked by GameHub's league system. Has its own session endpoint that allows guest submitters.
|
|
862
|
+
- **Multiplayer block.** The opaque `{ roomCode, reconnectionToken, wsEndpoint }` triple the host provides for the game to open its own realtime connection.
|
|
863
|
+
- **Host.** The GameHub-served page that frames the game in an iframe. Owns auth, matchmaking, and the bootstrap pipeline.
|
|
864
|
+
- **Game.** The iframe-hosted application that consumes this SDK.
|
|
865
|
+
- **Standalone.** A game loaded outside an iframe. `isInIframe()` returns false; the bootstrap pipeline is skipped.
|