@ksaa-nlp/gamehub-sdk 3.7.0 → 3.8.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/SPEC.md +109 -54
- package/dist/gamehub-sdk.js +142 -75
- package/dist/gamehub-sdk.js.map +3 -3
- package/dist/src/api-client.d.ts +6 -5
- package/dist/src/api-client.d.ts.map +1 -1
- package/dist/src/api-client.js +9 -8
- package/dist/src/api-client.js.map +1 -1
- package/dist/src/bridge.d.ts +10 -6
- package/dist/src/bridge.d.ts.map +1 -1
- package/dist/src/bridge.js +70 -56
- package/dist/src/bridge.js.map +1 -1
- package/dist/src/browser-entry.d.ts.map +1 -1
- package/dist/src/browser-entry.js +6 -5
- package/dist/src/browser-entry.js.map +1 -1
- package/dist/src/constants.d.ts +1 -1
- package/dist/src/constants.js +1 -1
- package/dist/src/init.d.ts.map +1 -1
- package/dist/src/init.js +14 -9
- package/dist/src/init.js.map +1 -1
- package/dist/src/transport.d.ts +47 -0
- package/dist/src/transport.d.ts.map +1 -0
- package/dist/src/transport.js +102 -0
- package/dist/src/transport.js.map +1 -0
- package/package.json +1 -1
package/SPEC.md
CHANGED
|
@@ -50,24 +50,25 @@ The SDK is not coupled to any realtime transport. When the host attaches a multi
|
|
|
50
50
|
|
|
51
51
|
The package is laid out flat under `src/` and `types/`. No subdirectories.
|
|
52
52
|
|
|
53
|
-
| File
|
|
54
|
-
|
|
|
55
|
-
| `src/main.ts`
|
|
56
|
-
| `src/browser-entry.ts`
|
|
57
|
-
| `src/init.ts`
|
|
58
|
-
| `src/
|
|
59
|
-
| `src/
|
|
60
|
-
| `src/
|
|
61
|
-
| `src/
|
|
62
|
-
| `src/
|
|
63
|
-
| `src/
|
|
64
|
-
| `src/
|
|
65
|
-
| `
|
|
66
|
-
| `types/
|
|
67
|
-
| `types/
|
|
68
|
-
| `types/
|
|
69
|
-
| `types/
|
|
70
|
-
| `
|
|
53
|
+
| File | Responsibility |
|
|
54
|
+
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
55
|
+
| `src/main.ts` | Public entry. Defines the `Sdk` interface and `createSdk()` factory. Pure on import. |
|
|
56
|
+
| `src/browser-entry.ts` | The only file with side effects on import. Used by the IIFE bundle to attach `window.GameHubSDK`. |
|
|
57
|
+
| `src/init.ts` | `detectEnvironment`, `autoInit`, `ensureInitialized`, `installHostMessageListener`. |
|
|
58
|
+
| `src/transport.ts` | Host transport abstraction: `HostTransport` interface, `PostMessageTransport` (iframe ⇄ parent) and `NativeBridgeTransport` (`window.GameHubNativeHost`), plus `getTransport()` / `hasHost()` detection. See §6.7. |
|
|
59
|
+
| `src/bridge.ts` | Host protocol: builds the `GAMEHUB_SDK_*` envelopes, correlates request/response by `messageId`, send helper. Transport-independent — routes through `getTransport()`. |
|
|
60
|
+
| `src/session.ts` | `startSession`, `submitScore`, `submitMatchScore`, `submitMatchResult`, `getQuestions`, `getWords`. |
|
|
61
|
+
| `src/match-context.ts` | `fetchMatchContext` (HTTP `/leagues/<id>/matches/<id>`). |
|
|
62
|
+
| `src/api-client.ts` | `apiRequest`: thin `fetch` wrapper that prefixes the API base and attaches the Bearer token. |
|
|
63
|
+
| `src/state.ts` | `SdkState` interface + the singleton `state` object. All mutable state lives here. |
|
|
64
|
+
| `src/constants.ts` | `SDK_VERSION`, `MESSAGE_PREFIX`, `PARENT_REQUEST_TIMEOUT_MS`, `QUESTIONS_LIMIT_CAP`, `WORDS_LIMIT_CAP`. |
|
|
65
|
+
| `src/utils.ts` | `isBrowser`, `warn`, `error`, `unwrapResult`, `readQueryParam`. |
|
|
66
|
+
| `types/api.ts` | `ApiResponse`, `ApiRequestOptions`. |
|
|
67
|
+
| `types/bootstrap.ts` | `BootstrapMultiplayer`, `BootstrapConfig`, `BootstrapData`. |
|
|
68
|
+
| `types/session.ts` | `Question`, `QuestionOptions`, `ScoreMetadata`, `EventData`, `GameCompleteData`, `StartSessionResult`, `SubmitScoreResult`, `WordOptions`, `ReportWordData`, `ReportableWord` (re-exports `Word`). |
|
|
69
|
+
| `types/word.ts` | `Word` + sub-interfaces (`WordSense`, `WordForm`, `Lookup`, `Synset`, `FormRepresentation`, `DynamicProp`, …) — Words Bank feature. |
|
|
70
|
+
| `types/match.ts` | `MatchParticipantMember`, `MatchParticipant`, `MatchContext`, `MatchResultPayload`. |
|
|
71
|
+
| `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. |
|
|
71
72
|
| `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. |
|
|
72
73
|
|
|
73
74
|
### 3.2 Singleton model
|
|
@@ -153,38 +154,46 @@ Slug must match `[a-z0-9-]+` (case-insensitive).
|
|
|
153
154
|
|
|
154
155
|
## 6. Bootstrap protocol
|
|
155
156
|
|
|
156
|
-
The SDK communicates with the host
|
|
157
|
+
The SDK communicates with the host through namespaced envelopes. All envelope types are `MESSAGE_PREFIX + '_' + name`, where `MESSAGE_PREFIX = 'GAMEHUB_SDK'`. The envelope shapes and the `messageId` correlation are **transport-independent**; the wire underneath is chosen by `getTransport()` (`src/transport.ts`):
|
|
158
|
+
|
|
159
|
+
- **`postmessage`** — the game runs in an `<iframe>` and exchanges envelopes with its parent window via `window.postMessage` (the classic embedding).
|
|
160
|
+
- **`native`** — the game is the top-level document in a native WebView (e.g. a Flutter app) and exchanges envelopes through an injected `window.GameHubNativeHost` object. See §6.7.
|
|
161
|
+
- **none** — standalone (dev harness, or served from the GameHub origin). `getTransport()` returns `null` and `hasHost()` is `false`; host round-trips resolve `null` and `apiRequest` falls back to a direct `fetch`.
|
|
162
|
+
|
|
163
|
+
The full taxonomy follows. It applies to **both** transports identically.
|
|
157
164
|
|
|
158
165
|
### 6.1 Message-type taxonomy
|
|
159
166
|
|
|
160
|
-
| Direction | Type (after prefix) | Purpose
|
|
161
|
-
| ---------- | ------------------- |
|
|
162
|
-
| SDK → host | `READY` | Fired once on script load when
|
|
163
|
-
| SDK → host | `BOOTSTRAP_REQUEST` | Asks the host for bootstrap config. Carries `{ messageId }`.
|
|
164
|
-
| host → SDK | `BOOTSTRAP` | Bootstrap config response. Carries `{ payload: BootstrapConfig, messageId? }`. Host may also push an unsolicited one any time.
|
|
165
|
-
| SDK → host | `AUTH_REQUEST` | Asks the host for an auth token. Carries `{ messageId }`.
|
|
166
|
-
| host → SDK | `AUTH_RESPONSE` | Auth response. Carries `{ token: string \| null, leagueId?, gameId?, matchId?, messageId }`.
|
|
167
|
-
| host → SDK | `SET_AUTH` | Unsolicited auth update. Carries `{ token }`. Triggers session start if not already running.
|
|
168
|
-
| host → SDK | `COMMAND` | Player-visible host command. Carries `{ command: 'pause' \| 'resume' }`. Routed to optional `window.onGameHubPause/Resume`.
|
|
169
|
-
| SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`.
|
|
170
|
-
| SDK → host | `SESSION_STARTED` | Fired when a session token is obtained. Carries `{ token }`.
|
|
171
|
-
| SDK → host | `SCORE_SUBMITTED` | Fired when a score is accepted. Carries `{ score, accepted, timeTaken }`.
|
|
172
|
-
| SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim.
|
|
173
|
-
| SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload.
|
|
174
|
-
| SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`.
|
|
167
|
+
| Direction | Type (after prefix) | Purpose |
|
|
168
|
+
| ---------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
169
|
+
| SDK → host | `READY` | Fired once on script load when a host transport is present (`hasHost()`). Carries `{ version }`. |
|
|
170
|
+
| SDK → host | `BOOTSTRAP_REQUEST` | Asks the host for bootstrap config. Carries `{ messageId }`. |
|
|
171
|
+
| host → SDK | `BOOTSTRAP` | Bootstrap config response. Carries `{ payload: BootstrapConfig, messageId? }`. Host may also push an unsolicited one any time. |
|
|
172
|
+
| SDK → host | `AUTH_REQUEST` | Asks the host for an auth token. Carries `{ messageId }`. |
|
|
173
|
+
| host → SDK | `AUTH_RESPONSE` | Auth response. Carries `{ token: string \| null, leagueId?, gameId?, matchId?, messageId }`. |
|
|
174
|
+
| host → SDK | `SET_AUTH` | Unsolicited auth update. Carries `{ token }`. Triggers session start if not already running. |
|
|
175
|
+
| host → SDK | `COMMAND` | Player-visible host command. Carries `{ command: 'pause' \| 'resume' }`. Routed to optional `window.onGameHubPause/Resume`. |
|
|
176
|
+
| SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`. |
|
|
177
|
+
| SDK → host | `SESSION_STARTED` | Fired when a session token is obtained. Carries `{ token }`. |
|
|
178
|
+
| SDK → host | `SCORE_SUBMITTED` | Fired when a score is accepted. Carries `{ score, accepted, timeTaken }`. |
|
|
179
|
+
| SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
|
|
180
|
+
| SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
|
|
181
|
+
| SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
|
|
175
182
|
| SDK → host | `QUESTION_REPORT` | Fired by `sdk.reportQuestion(data)`. Carries `{ questionId?, prompt?, message?, questions? }`. With `questions` the host renders a question-picker dropdown; otherwise it reports the single `questionId`. |
|
|
176
|
-
| SDK → host | `WORD_REPORT` | Fired by `sdk.reportWord(data)` (Words Bank feature). Carries `{ wordId?, lemma?, message?, words? }`. Same picker/single semantics as `QUESTION_REPORT`, relabeled to lemma.
|
|
177
|
-
| SDK → host | `API_REQUEST` | Asks the host to proxy a backend HTTP call. Carries `{ messageId, endpoint, method, body }`. See §6.6.
|
|
178
|
-
| host → SDK | `API_RESPONSE` | Result of a proxied call. Carries `{ messageId, ok: boolean, result?: ApiResponse, error?: string }`. See §6.6.
|
|
183
|
+
| SDK → host | `WORD_REPORT` | Fired by `sdk.reportWord(data)` (Words Bank feature). Carries `{ wordId?, lemma?, message?, words? }`. Same picker/single semantics as `QUESTION_REPORT`, relabeled to lemma. |
|
|
184
|
+
| SDK → host | `API_REQUEST` | Asks the host to proxy a backend HTTP call. Carries `{ messageId, endpoint, method, body }`. See §6.6. |
|
|
185
|
+
| host → SDK | `API_RESPONSE` | Result of a proxied call. Carries `{ messageId, ok: boolean, result?: ApiResponse, error?: string }`. See §6.6. |
|
|
179
186
|
|
|
180
187
|
Every SDK → host envelope also includes the resolved `gameSlug` as a top-level field (except `API_REQUEST`, whose payload is the proxied request).
|
|
181
188
|
|
|
182
189
|
### 6.2 Origin handling
|
|
183
190
|
|
|
184
|
-
The SDK fires the initial `BOOTSTRAP_REQUEST` with target origin `'*'` because it has not yet learned the parent's origin. The very first
|
|
191
|
+
Origin handling is a property of the **postMessage** transport only. The SDK fires the initial `BOOTSTRAP_REQUEST` with target origin `'*'` because it has not yet learned the parent's origin. The very first inbound reply records `event.origin` into `state.parentOrigin`. All subsequent SDK → host messages target that recorded origin. Calls before any inbound message fall back to `'*'`.
|
|
185
192
|
|
|
186
193
|
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.
|
|
187
194
|
|
|
195
|
+
On the **native** transport there is no web origin: inbound `HostMessage.origin` is `null`, `state.parentOrigin` stays `null`, and the transport ignores it when sending (it posts through `window.GameHubNativeHost`). The trust boundary is the native app itself, which owns the WebView and injects the bridge.
|
|
196
|
+
|
|
188
197
|
### 6.3 Request/response correlation
|
|
189
198
|
|
|
190
199
|
- Each SDK-initiated request includes a `messageId: string` (currently `Date.now().toString()`).
|
|
@@ -202,7 +211,7 @@ If `event.origin` changes mid-session (e.g. the host navigates between origins),
|
|
|
202
211
|
- Non-string and non-null → ignored (field left as-is).
|
|
203
212
|
- `multiplayer`:
|
|
204
213
|
- Explicit `null` → `null`.
|
|
205
|
-
- Object with `
|
|
214
|
+
- Object with a `reservation` object (string `name`, `sessionId`, `roomId` — the `SdkSeatReservation` shape) and a string `wsEndpoint` → only `wsEndpoint` is trimmed; the `reservation` object is stored as-is.
|
|
206
215
|
- Any other shape → ignored (field left as-is).
|
|
207
216
|
|
|
208
217
|
This lets the host clear fields explicitly (via `null`) without overwriting unset fields.
|
|
@@ -223,8 +232,8 @@ The SDK never issues a cross-origin request to the GameHub backend. When a game
|
|
|
223
232
|
|
|
224
233
|
`apiRequest(endpoint, options)` (`src/api-client.ts`) chooses its transport by context:
|
|
225
234
|
|
|
226
|
-
- **
|
|
227
|
-
- **Standalone** (dev harness, or a game served from the GameHub origin): the
|
|
235
|
+
- **Hosted** (`hasHost()` — iframe parent or native bridge): delegates to `requestApiFromParent(endpoint, options)` (`src/bridge.ts`). This sends `API_REQUEST` `{ messageId, endpoint, method, body }` to the host and awaits the matching `API_RESPONSE`. On the native transport the host is the native app, which performs the real HTTPS call and keeps the bearer token out of the WebView entirely.
|
|
236
|
+
- **Standalone** (dev harness, or a game served from the GameHub origin): the direct `fetch` path against `state.apiBase`, attaching `Authorization: Bearer <token>` (§7.2). This path is same-origin by construction, so CORS does not apply.
|
|
228
237
|
|
|
229
238
|
Protocol details:
|
|
230
239
|
|
|
@@ -235,6 +244,31 @@ Protocol details:
|
|
|
235
244
|
- 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.
|
|
236
245
|
- `messageId` is `'api_' + Date.now() + '_' + <seq>`, where `<seq>` is a monotonic counter so concurrent proxied calls (e.g. session start + questions) never collide.
|
|
237
246
|
|
|
247
|
+
### 6.7 Native bridge transport
|
|
248
|
+
|
|
249
|
+
When a game is rendered in a native WebView rather than an iframe, the native app plays the host role. Because the game is the **top-level document** (`window.parent === window`), the postMessage transport is unavailable; the SDK instead talks to an injected `window.GameHubNativeHost` object.
|
|
250
|
+
|
|
251
|
+
**Detection.** `getTransport()` selects the native transport when `window.GameHubNativeHost.postMessage` is a function. This is checked **before** the iframe check, so a native host always wins. The native app must inject the object **before** the SDK script runs (e.g. a WebView user-script evaluated at document start), otherwise the SDK falls through to standalone.
|
|
252
|
+
|
|
253
|
+
**Contract.** The object is bidirectional:
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
interface GameHubNativeHost {
|
|
257
|
+
// game → host. The SDK calls this with a JSON-stringified envelope.
|
|
258
|
+
postMessage(json: string): void;
|
|
259
|
+
// host → game. The SDK installs this; the native app invokes it (via the
|
|
260
|
+
// WebView's "evaluate JavaScript" channel) with one envelope, either as a
|
|
261
|
+
// JSON string or an already-parsed object.
|
|
262
|
+
receive?(envelope: string | object): void;
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
- The native app implements `postMessage` (typically forwarding to its WebView message channel — e.g. `flutter_inappwebview`'s `callHandler`).
|
|
267
|
+
- The SDK installs `receive` when the transport is constructed. The native app calls `window.GameHubNativeHost.receive(env)` to deliver every host → SDK envelope (`BOOTSTRAP`, `AUTH_RESPONSE`, `API_RESPONSE`, `SET_AUTH`, `COMMAND`).
|
|
268
|
+
- Envelope shapes, `messageId` correlation, and timeouts (§6.3) are identical to the postMessage transport. The native host must therefore echo the `messageId` on `BOOTSTRAP`/`AUTH_RESPONSE`/`API_RESPONSE` exactly as an iframe host does.
|
|
269
|
+
- The native host is responsible for the same protocol an iframe host implements: replying to `BOOTSTRAP_REQUEST`/`AUTH_REQUEST`, proxying `API_REQUEST` (performing the real HTTPS call natively — see §6.6), and reacting to one-way signals (`REQUEST_CLOSE`, `QUESTION_REPORT`, `WORD_REPORT`, `SCORE_SUBMITTED`, `GAME_COMPLETE`, `LOG_EVENT`).
|
|
270
|
+
- Multiplayer is unchanged: the host passes `bootstrap.multiplayer` `{ reservation, wsEndpoint }`, and the game opens its own Colyseus WebSocket from inside the WebView (§19.1). The SDK does not proxy realtime traffic over the bridge.
|
|
271
|
+
|
|
238
272
|
## 7. Authentication
|
|
239
273
|
|
|
240
274
|
### 7.1 Token sources
|
|
@@ -249,7 +283,7 @@ The SDK never reads the token from storage and never writes it. Each page load s
|
|
|
249
283
|
|
|
250
284
|
### 7.2 Sending the token
|
|
251
285
|
|
|
252
|
-
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
|
|
286
|
+
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 hosted default — iframe or native) the host attaches the bearer header from its own auth context instead. A native host can therefore keep the token entirely outside the WebView. 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.
|
|
253
287
|
|
|
254
288
|
### 7.3 Token rotation
|
|
255
289
|
|
|
@@ -540,16 +574,17 @@ interface SdkState {
|
|
|
540
574
|
|
|
541
575
|
### 14.6 Host signalling
|
|
542
576
|
|
|
543
|
-
| Method | Returns | Postmessage emitted (after prefix)
|
|
544
|
-
| --------------------------------- | ------- |
|
|
545
|
-
| `notifyComplete(data?)` | `void` | `GAME_COMPLETE`
|
|
546
|
-
| `requestClose()` | `void` | `REQUEST_CLOSE`
|
|
547
|
-
| `logEvent(eventName, eventData?)` | `void` | `LOG_EVENT { event: eventName, data: eventData }`
|
|
577
|
+
| Method | Returns | Postmessage emitted (after prefix) |
|
|
578
|
+
| --------------------------------- | ------- | ---------------------------------------------------------------- |
|
|
579
|
+
| `notifyComplete(data?)` | `void` | `GAME_COMPLETE` |
|
|
580
|
+
| `requestClose()` | `void` | `REQUEST_CLOSE` |
|
|
581
|
+
| `logEvent(eventName, eventData?)` | `void` | `LOG_EVENT { event: eventName, data: eventData }` |
|
|
548
582
|
| `reportQuestion(data)` | `void` | `QUESTION_REPORT { questionId?, prompt?, message?, questions? }` |
|
|
549
583
|
|
|
550
584
|
`reportQuestion(data: ReportQuestionData)` asks the host to open its "report this question" dialog. 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.
|
|
551
585
|
|
|
552
586
|
Two modes:
|
|
587
|
+
|
|
553
588
|
- **Single question** — pass `questionId` (and optionally `prompt`). The dialog reports that one question.
|
|
554
589
|
- **Pick from a list** — pass `questions: ReportableQuestion[]` (each `{ questionId, prompt? }`). The host renders a dropdown so the player chooses which question to report; `questionId`, when also supplied, pre-selects an entry. The `questions` array is forwarded verbatim (each entry normalised to `{ questionId, prompt }`) on the `QUESTION_REPORT` envelope.
|
|
555
590
|
|
|
@@ -568,9 +603,18 @@ All types listed below are re-exported from the package root and form the public
|
|
|
568
603
|
### 15.1 Bootstrap
|
|
569
604
|
|
|
570
605
|
```ts
|
|
606
|
+
interface SdkSeatReservation {
|
|
607
|
+
name: string;
|
|
608
|
+
sessionId: string;
|
|
609
|
+
roomId: string;
|
|
610
|
+
processId?: string;
|
|
611
|
+
publicAddress?: string;
|
|
612
|
+
reconnectionToken?: string;
|
|
613
|
+
devMode?: boolean;
|
|
614
|
+
}
|
|
615
|
+
|
|
571
616
|
interface BootstrapMultiplayer {
|
|
572
|
-
|
|
573
|
-
reconnectionToken: string;
|
|
617
|
+
reservation: SdkSeatReservation;
|
|
574
618
|
wsEndpoint: string;
|
|
575
619
|
}
|
|
576
620
|
|
|
@@ -769,7 +813,7 @@ These rules exist because of a real prior regression where transport-related cle
|
|
|
769
813
|
### 19.3 No DOM injection
|
|
770
814
|
|
|
771
815
|
- The SDK must not create, modify, or query DOM elements outside reading `window.location` and the `<script>` tag list during environment detection.
|
|
772
|
-
-
|
|
816
|
+
- On the postMessage transport, the SDK must not register global event listeners outside the `message` listeners its transport installs (the ambient one from `installHostMessageListener()` plus the short-lived per-request handlers in `bridge.ts`, each removed on settle/timeout). On the native transport it touches only `window.GameHubNativeHost` (reading `postMessage`, installing `receive`) — no DOM and no `window` event listeners.
|
|
773
817
|
|
|
774
818
|
### 19.4 No storage
|
|
775
819
|
|
|
@@ -794,7 +838,7 @@ These rules exist because of a real prior regression where transport-related cle
|
|
|
794
838
|
|
|
795
839
|
### 20.3 Bundle budget
|
|
796
840
|
|
|
797
|
-
The IIFE bundle (`dist/gamehub-sdk.js`) is expected to remain under **
|
|
841
|
+
The IIFE bundle (`dist/gamehub-sdk.js`) is expected to remain under **10 KB gzip**, the figure that matters on the wire. The raw budget was historically **25 KB**; the native-bridge transport added in 3.8.0 (a deliberate new feature area — §6.7) pushed raw to ~26 KB. Current size: ~26 KB raw / ~5.9 KB gzip. Further growth should be a deliberate decision tied to a release note, and gzip remains the hard ceiling.
|
|
798
842
|
|
|
799
843
|
### 20.4 No runtime dependencies
|
|
800
844
|
|
|
@@ -821,6 +865,13 @@ The SDK does not currently ship a test suite, but every change should be verifia
|
|
|
821
865
|
- Replying with `AUTH_RESPONSE { token }` makes `isAuthenticated()` true.
|
|
822
866
|
- Posting `SET_AUTH { token }` after init opens a session and fires `SESSION_STARTED`.
|
|
823
867
|
|
|
868
|
+
### 21.3b Native bridge boot
|
|
869
|
+
|
|
870
|
+
- With `window.GameHubNativeHost = { postMessage(json) { … } }` injected before the SDK loads (and `window.parent === window`), `getTransport().kind === 'native'` and `hasHost()` is `true`.
|
|
871
|
+
- The SDK calls `GameHubNativeHost.postMessage` with a JSON-stringified `BOOTSTRAP_REQUEST` on boot. Calling `window.GameHubNativeHost.receive(JSON.stringify({ type: 'GAMEHUB_SDK_BOOTSTRAP', messageId, payload: { gameSlug } }))` (echoing the requested `messageId`) flips `getBootstrap().isBootstrapped` to `true`.
|
|
872
|
+
- `receive` accepts both a JSON string and an already-parsed object; malformed strings are ignored without throwing.
|
|
873
|
+
- `apiRequest` travels as an `API_REQUEST` over `postMessage`, and the native host's `API_RESPONSE` (delivered via `receive`) resolves/rejects it identically to the iframe path.
|
|
874
|
+
|
|
824
875
|
### 21.4 Score submission
|
|
825
876
|
|
|
826
877
|
- `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.
|
|
@@ -856,8 +907,12 @@ The `./server` and `./server/dev` subpaths are separate from the browser SDK. Im
|
|
|
856
907
|
import type { GuestModule, Ctx, PeerInfo } from '@ksaa-nlp/gamehub-sdk/server';
|
|
857
908
|
|
|
858
909
|
const guest: GuestModule = {
|
|
859
|
-
onCreate(ctx, opts) {
|
|
860
|
-
|
|
910
|
+
onCreate(ctx, opts) {
|
|
911
|
+
ctx.state.round = 0;
|
|
912
|
+
},
|
|
913
|
+
onJoin(ctx, peer) {
|
|
914
|
+
ctx.broadcast('peer:joined', { peerId: peer.peerId });
|
|
915
|
+
},
|
|
861
916
|
onMessage(ctx, peer, type, payload) {
|
|
862
917
|
if (type === 'answer') ctx.send(peer.peerId, 'ack', { ok: true });
|
|
863
918
|
},
|
|
@@ -903,7 +958,7 @@ expect(room.outbox).toContainEqual({
|
|
|
903
958
|
- **Bootstrap.** The set of context the host gives the iframe at load: slug, IDs, auth, multiplayer block, display strings.
|
|
904
959
|
- **Session.** A server-issued token representing a single playthrough. Used to authenticate `submitScore`.
|
|
905
960
|
- **League match.** A scheduled game between two participants tracked by GameHub's league system. Has its own session endpoint that allows guest submitters.
|
|
906
|
-
- **Multiplayer block.** The opaque `{
|
|
961
|
+
- **Multiplayer block.** The opaque `{ reservation, wsEndpoint }` pair the host provides for the game to open its own realtime connection, where `reservation` is the Colyseus seat-reservation (`SdkSeatReservation`).
|
|
907
962
|
- **Host.** The GameHub-served page that frames the game in an iframe. Owns auth, matchmaking, and the bootstrap pipeline.
|
|
908
963
|
- **Game.** The iframe-hosted application that consumes this SDK.
|
|
909
964
|
- **Standalone.** A game loaded outside an iframe. `isInIframe()` returns false; the bootstrap pipeline is skipped.
|
package/dist/gamehub-sdk.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
(() => {
|
|
3
3
|
// src/constants.ts
|
|
4
|
-
var SDK_VERSION = "3.
|
|
4
|
+
var SDK_VERSION = "3.8.0";
|
|
5
5
|
var MESSAGE_PREFIX = "GAMEHUB_SDK";
|
|
6
6
|
var PARENT_REQUEST_TIMEOUT_MS = 2e3;
|
|
7
7
|
var HOST_API_TIMEOUT_MS = 15e3;
|
|
@@ -65,6 +65,69 @@
|
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
// src/transport.ts
|
|
69
|
+
var PostMessageTransport = class {
|
|
70
|
+
constructor() {
|
|
71
|
+
this.kind = "postmessage";
|
|
72
|
+
}
|
|
73
|
+
send(envelope) {
|
|
74
|
+
window.parent.postMessage(envelope, state.parentOrigin || "*");
|
|
75
|
+
}
|
|
76
|
+
subscribe(handler) {
|
|
77
|
+
const listener = (event) => handler({ data: event.data, origin: event.origin });
|
|
78
|
+
window.addEventListener("message", listener);
|
|
79
|
+
return () => window.removeEventListener("message", listener);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
var NativeBridgeTransport = class {
|
|
83
|
+
constructor(host) {
|
|
84
|
+
this.host = host;
|
|
85
|
+
this.kind = "native";
|
|
86
|
+
this.handlers = /* @__PURE__ */ new Set();
|
|
87
|
+
host.receive = (envelope) => {
|
|
88
|
+
let data = envelope;
|
|
89
|
+
if (typeof envelope === "string") {
|
|
90
|
+
try {
|
|
91
|
+
data = JSON.parse(envelope);
|
|
92
|
+
} catch {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (!data || typeof data !== "object") return;
|
|
97
|
+
this.handlers.forEach((h) => h({ data, origin: null }));
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
send(envelope) {
|
|
101
|
+
this.host.postMessage(JSON.stringify(envelope));
|
|
102
|
+
}
|
|
103
|
+
subscribe(handler) {
|
|
104
|
+
this.handlers.add(handler);
|
|
105
|
+
return () => {
|
|
106
|
+
this.handlers.delete(handler);
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
var active;
|
|
111
|
+
function getTransport() {
|
|
112
|
+
if (active !== void 0) return active;
|
|
113
|
+
if (!isBrowser()) {
|
|
114
|
+
active = null;
|
|
115
|
+
return active;
|
|
116
|
+
}
|
|
117
|
+
const nativeHost = window.GameHubNativeHost;
|
|
118
|
+
if (nativeHost && typeof nativeHost.postMessage === "function") {
|
|
119
|
+
active = new NativeBridgeTransport(nativeHost);
|
|
120
|
+
} else if (window.parent !== window) {
|
|
121
|
+
active = new PostMessageTransport();
|
|
122
|
+
} else {
|
|
123
|
+
active = null;
|
|
124
|
+
}
|
|
125
|
+
return active;
|
|
126
|
+
}
|
|
127
|
+
function hasHost() {
|
|
128
|
+
return getTransport() !== null;
|
|
129
|
+
}
|
|
130
|
+
|
|
68
131
|
// src/bridge.ts
|
|
69
132
|
function trimToNullable(value) {
|
|
70
133
|
if (value === null) return null;
|
|
@@ -129,7 +192,8 @@
|
|
|
129
192
|
};
|
|
130
193
|
}
|
|
131
194
|
function requestBootstrapFromParent() {
|
|
132
|
-
|
|
195
|
+
const transport = getTransport();
|
|
196
|
+
if (!transport) {
|
|
133
197
|
return Promise.resolve(null);
|
|
134
198
|
}
|
|
135
199
|
if (state.bootstrapReceived) {
|
|
@@ -143,33 +207,33 @@
|
|
|
143
207
|
const messageId = Date.now().toString();
|
|
144
208
|
let settled = false;
|
|
145
209
|
let timeoutId = null;
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
210
|
+
let unsubscribe = () => {
|
|
211
|
+
};
|
|
212
|
+
const handler = (msg) => {
|
|
213
|
+
const data = msg.data;
|
|
214
|
+
if (data && data.type === MESSAGE_PREFIX + "_BOOTSTRAP" && data.payload) {
|
|
215
|
+
if (data.messageId && data.messageId !== messageId) {
|
|
149
216
|
return;
|
|
150
217
|
}
|
|
151
218
|
if (settled) return;
|
|
152
219
|
settled = true;
|
|
153
|
-
|
|
220
|
+
unsubscribe();
|
|
154
221
|
if (timeoutId) clearTimeout(timeoutId);
|
|
155
|
-
state.parentOrigin =
|
|
222
|
+
state.parentOrigin = msg.origin;
|
|
156
223
|
state.bootstrapReceived = true;
|
|
157
|
-
mergeBootstrapConfig(
|
|
158
|
-
resolve(
|
|
224
|
+
mergeBootstrapConfig(data.payload);
|
|
225
|
+
resolve(data.payload);
|
|
159
226
|
}
|
|
160
227
|
};
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
},
|
|
167
|
-
"*"
|
|
168
|
-
);
|
|
228
|
+
unsubscribe = transport.subscribe(handler);
|
|
229
|
+
transport.send({
|
|
230
|
+
type: MESSAGE_PREFIX + "_BOOTSTRAP_REQUEST",
|
|
231
|
+
messageId
|
|
232
|
+
});
|
|
169
233
|
timeoutId = setTimeout(() => {
|
|
170
234
|
if (settled) return;
|
|
171
235
|
settled = true;
|
|
172
|
-
|
|
236
|
+
unsubscribe();
|
|
173
237
|
resolve(null);
|
|
174
238
|
}, PARENT_REQUEST_TIMEOUT_MS);
|
|
175
239
|
}
|
|
@@ -180,35 +244,36 @@
|
|
|
180
244
|
}
|
|
181
245
|
function getAuthTokenFromParent() {
|
|
182
246
|
return new Promise((resolve) => {
|
|
183
|
-
|
|
247
|
+
const transport = getTransport();
|
|
248
|
+
if (!transport) {
|
|
184
249
|
resolve(null);
|
|
185
250
|
return;
|
|
186
251
|
}
|
|
187
252
|
const messageId = Date.now().toString();
|
|
188
253
|
let settled = false;
|
|
189
254
|
let timeoutId = null;
|
|
190
|
-
|
|
191
|
-
|
|
255
|
+
let unsubscribe = () => {
|
|
256
|
+
};
|
|
257
|
+
const handler = (msg) => {
|
|
258
|
+
const data = msg.data;
|
|
259
|
+
if (data && data.type === MESSAGE_PREFIX + "_AUTH_RESPONSE" && data.messageId === messageId) {
|
|
192
260
|
if (settled) return;
|
|
193
261
|
settled = true;
|
|
194
|
-
|
|
262
|
+
unsubscribe();
|
|
195
263
|
if (timeoutId) clearTimeout(timeoutId);
|
|
196
|
-
state.parentOrigin =
|
|
197
|
-
if (
|
|
198
|
-
if (
|
|
199
|
-
if (
|
|
200
|
-
resolve(
|
|
264
|
+
state.parentOrigin = msg.origin;
|
|
265
|
+
if (data.leagueId) state.leagueId = data.leagueId;
|
|
266
|
+
if (data.gameId) state.gameId = data.gameId;
|
|
267
|
+
if (data.matchId) state.matchId = data.matchId;
|
|
268
|
+
resolve(data.token || null);
|
|
201
269
|
}
|
|
202
270
|
};
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
{ type: MESSAGE_PREFIX + "_AUTH_REQUEST", messageId },
|
|
206
|
-
"*"
|
|
207
|
-
);
|
|
271
|
+
unsubscribe = transport.subscribe(handler);
|
|
272
|
+
transport.send({ type: MESSAGE_PREFIX + "_AUTH_REQUEST", messageId });
|
|
208
273
|
timeoutId = setTimeout(() => {
|
|
209
274
|
if (settled) return;
|
|
210
275
|
settled = true;
|
|
211
|
-
|
|
276
|
+
unsubscribe();
|
|
212
277
|
resolve(null);
|
|
213
278
|
}, PARENT_REQUEST_TIMEOUT_MS);
|
|
214
279
|
});
|
|
@@ -216,62 +281,61 @@
|
|
|
216
281
|
var apiRequestSeq = 0;
|
|
217
282
|
function requestApiFromParent(endpoint, options = {}) {
|
|
218
283
|
return new Promise((resolve, reject) => {
|
|
219
|
-
|
|
220
|
-
|
|
284
|
+
const transport = getTransport();
|
|
285
|
+
if (!transport) {
|
|
286
|
+
reject(new Error("Host bridge unavailable: no host transport"));
|
|
221
287
|
return;
|
|
222
288
|
}
|
|
223
289
|
const messageId = "api_" + Date.now().toString() + "_" + ++apiRequestSeq;
|
|
224
290
|
let settled = false;
|
|
225
291
|
let timeoutId = null;
|
|
226
|
-
|
|
227
|
-
|
|
292
|
+
let unsubscribe = () => {
|
|
293
|
+
};
|
|
294
|
+
const handler = (msg) => {
|
|
295
|
+
const data = msg.data;
|
|
296
|
+
if (!data || data.type !== MESSAGE_PREFIX + "_API_RESPONSE" || data.messageId !== messageId) {
|
|
228
297
|
return;
|
|
229
298
|
}
|
|
230
299
|
if (settled) return;
|
|
231
300
|
settled = true;
|
|
232
|
-
|
|
301
|
+
unsubscribe();
|
|
233
302
|
if (timeoutId) clearTimeout(timeoutId);
|
|
234
|
-
state.parentOrigin =
|
|
235
|
-
if (
|
|
236
|
-
resolve(
|
|
303
|
+
state.parentOrigin = msg.origin;
|
|
304
|
+
if (data.ok) {
|
|
305
|
+
resolve(data.result ?? {});
|
|
237
306
|
} else {
|
|
238
|
-
reject(new Error(
|
|
307
|
+
reject(new Error(data.error || "Host API request failed"));
|
|
239
308
|
}
|
|
240
309
|
};
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
},
|
|
250
|
-
state.parentOrigin || "*"
|
|
251
|
-
);
|
|
310
|
+
unsubscribe = transport.subscribe(handler);
|
|
311
|
+
transport.send({
|
|
312
|
+
type: MESSAGE_PREFIX + "_API_REQUEST",
|
|
313
|
+
messageId,
|
|
314
|
+
endpoint,
|
|
315
|
+
method: options.method || "GET",
|
|
316
|
+
body: options.body ?? null
|
|
317
|
+
});
|
|
252
318
|
timeoutId = setTimeout(() => {
|
|
253
319
|
if (settled) return;
|
|
254
320
|
settled = true;
|
|
255
|
-
|
|
321
|
+
unsubscribe();
|
|
256
322
|
reject(new Error("Host API request timed out"));
|
|
257
323
|
}, HOST_API_TIMEOUT_MS);
|
|
258
324
|
});
|
|
259
325
|
}
|
|
260
326
|
function sendToParent(type, data) {
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
state.parentOrigin || "*"
|
|
269
|
-
);
|
|
327
|
+
const transport = getTransport();
|
|
328
|
+
if (!transport) return;
|
|
329
|
+
transport.send({
|
|
330
|
+
type: MESSAGE_PREFIX + "_" + type,
|
|
331
|
+
gameSlug: state.gameSlug,
|
|
332
|
+
...data
|
|
333
|
+
});
|
|
270
334
|
}
|
|
271
335
|
|
|
272
336
|
// src/api-client.ts
|
|
273
337
|
async function apiRequest(endpoint, options = {}) {
|
|
274
|
-
if (
|
|
338
|
+
if (hasHost()) {
|
|
275
339
|
return requestApiFromParent(endpoint, options);
|
|
276
340
|
}
|
|
277
341
|
const url = state.apiBase + endpoint;
|
|
@@ -580,24 +644,27 @@
|
|
|
580
644
|
}
|
|
581
645
|
function installHostMessageListener() {
|
|
582
646
|
if (!isBrowser() || hostListenerInstalled) return;
|
|
647
|
+
const transport = getTransport();
|
|
648
|
+
if (!transport) return;
|
|
583
649
|
hostListenerInstalled = true;
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
650
|
+
transport.subscribe((msg) => {
|
|
651
|
+
const data = msg.data;
|
|
652
|
+
if (!data || !data.type) return;
|
|
653
|
+
const type = data.type;
|
|
654
|
+
if (type === MESSAGE_PREFIX + "_BOOTSTRAP" && data.payload) {
|
|
655
|
+
state.parentOrigin = msg.origin;
|
|
589
656
|
state.bootstrapReceived = true;
|
|
590
|
-
mergeBootstrapConfig(
|
|
657
|
+
mergeBootstrapConfig(data.payload);
|
|
591
658
|
}
|
|
592
659
|
if (type === MESSAGE_PREFIX + "_SET_AUTH") {
|
|
593
|
-
state.authToken =
|
|
594
|
-
state.parentOrigin =
|
|
660
|
+
state.authToken = data.token;
|
|
661
|
+
state.parentOrigin = msg.origin;
|
|
595
662
|
if (state.gameSlug && !state.sessionToken && !state.sessionStartPromise && (state.authToken || state.leagueId && state.gameId && state.matchId)) {
|
|
596
663
|
state.sessionStartPromise = startSession();
|
|
597
664
|
}
|
|
598
665
|
}
|
|
599
666
|
if (type === MESSAGE_PREFIX + "_COMMAND") {
|
|
600
|
-
const command =
|
|
667
|
+
const command = data.command;
|
|
601
668
|
const w = window;
|
|
602
669
|
if (command === "pause" && typeof w.onGameHubPause === "function") {
|
|
603
670
|
w.onGameHubPause();
|
|
@@ -737,10 +804,10 @@
|
|
|
737
804
|
installHostMessageListener();
|
|
738
805
|
const sdk = createSdk();
|
|
739
806
|
window.GameHubSDK = sdk;
|
|
740
|
-
if (
|
|
807
|
+
if (hasHost()) {
|
|
741
808
|
sendToParent("READY", { version: SDK_VERSION });
|
|
742
809
|
}
|
|
743
|
-
const hasBootSignal = !!state.gameSlug ||
|
|
810
|
+
const hasBootSignal = !!state.gameSlug || hasHost();
|
|
744
811
|
if (!hasBootSignal) return;
|
|
745
812
|
if (document.readyState === "loading") {
|
|
746
813
|
document.addEventListener("DOMContentLoaded", () => {
|