@ksaa-nlp/gamehub-sdk 0.1.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/MIGRATION.md +322 -0
  3. package/README.md +121 -182
  4. package/dist/gamehub-sdk.js +1202 -1670
  5. package/dist/gamehub-sdk.js.map +7 -0
  6. package/dist/src/api-client.d.ts +11 -0
  7. package/dist/src/api-client.d.ts.map +1 -0
  8. package/dist/src/api-client.js +27 -0
  9. package/dist/src/api-client.js.map +1 -0
  10. package/dist/src/bridge.d.ts +35 -0
  11. package/dist/src/bridge.d.ts.map +1 -0
  12. package/dist/src/bridge.js +280 -0
  13. package/dist/src/bridge.js.map +1 -0
  14. package/dist/src/browser-entry.d.ts +19 -0
  15. package/dist/src/browser-entry.d.ts.map +1 -0
  16. package/dist/src/browser-entry.js +49 -0
  17. package/dist/src/browser-entry.js.map +1 -0
  18. package/dist/src/constants.d.ts +18 -0
  19. package/dist/src/constants.d.ts.map +1 -0
  20. package/dist/src/constants.js +18 -0
  21. package/dist/src/constants.js.map +1 -0
  22. package/dist/src/init.d.ts +36 -0
  23. package/dist/src/init.d.ts.map +1 -0
  24. package/dist/src/init.js +317 -0
  25. package/dist/src/init.js.map +1 -0
  26. package/dist/src/main.d.ts +101 -0
  27. package/dist/src/main.d.ts.map +1 -0
  28. package/dist/src/main.js +126 -0
  29. package/dist/src/main.js.map +1 -0
  30. package/dist/src/match-context.d.ts +11 -0
  31. package/dist/src/match-context.d.ts.map +1 -0
  32. package/dist/src/match-context.js +51 -0
  33. package/dist/src/match-context.js.map +1 -0
  34. package/dist/src/multiplayer.d.ts +82 -0
  35. package/dist/src/multiplayer.d.ts.map +1 -0
  36. package/dist/src/multiplayer.js +461 -0
  37. package/dist/src/multiplayer.js.map +1 -0
  38. package/dist/src/session.d.ts +35 -0
  39. package/dist/src/session.d.ts.map +1 -0
  40. package/dist/src/session.js +206 -0
  41. package/dist/src/session.js.map +1 -0
  42. package/dist/src/state.d.ts +71 -0
  43. package/dist/src/state.d.ts.map +1 -0
  44. package/dist/src/state.js +55 -0
  45. package/dist/src/state.js.map +1 -0
  46. package/dist/src/utils.d.ts +36 -0
  47. package/dist/src/utils.d.ts.map +1 -0
  48. package/dist/src/utils.js +73 -0
  49. package/dist/src/utils.js.map +1 -0
  50. package/dist/types/api.d.ts +21 -0
  51. package/dist/types/api.d.ts.map +1 -0
  52. package/dist/types/api.js +2 -0
  53. package/dist/types/api.js.map +1 -0
  54. package/{types/bootstrap.ts → dist/types/bootstrap.d.ts} +26 -29
  55. package/dist/types/bootstrap.d.ts.map +1 -0
  56. package/dist/types/bootstrap.js +2 -0
  57. package/dist/types/bootstrap.js.map +1 -0
  58. package/dist/types/match.d.ts +37 -0
  59. package/dist/types/match.d.ts.map +1 -0
  60. package/dist/types/match.js +2 -0
  61. package/dist/types/match.js.map +1 -0
  62. package/dist/types/multiplayer.d.ts +138 -0
  63. package/dist/types/multiplayer.d.ts.map +1 -0
  64. package/dist/types/multiplayer.js +2 -0
  65. package/dist/types/multiplayer.js.map +1 -0
  66. package/{types/session.ts → dist/types/session.d.ts} +24 -30
  67. package/dist/types/session.d.ts.map +1 -0
  68. package/dist/types/session.js +2 -0
  69. package/dist/types/session.js.map +1 -0
  70. package/package.json +34 -18
  71. package/dist/gamehub-sdk.d.ts +0 -694
  72. package/dist/index.d.ts +0 -56
  73. package/dist/index.mjs +0 -6
  74. package/scripts/emit-module-entry.mjs +0 -96
  75. package/src/api-client.ts +0 -33
  76. package/src/bridge.ts +0 -312
  77. package/src/constants.ts +0 -24
  78. package/src/init.ts +0 -335
  79. package/src/main.ts +0 -287
  80. package/src/match-context.ts +0 -52
  81. package/src/multiplayer.ts +0 -525
  82. package/src/session.ts +0 -240
  83. package/src/state.ts +0 -78
  84. package/src/utils.ts +0 -68
  85. package/tsconfig.json +0 -33
  86. package/types/api.ts +0 -21
  87. package/types/match.ts +0 -41
  88. package/types/multiplayer.ts +0 -118
@@ -1,1693 +1,1225 @@
1
1
  "use strict";
2
- var GameHub;
3
- (function (GameHub) {
4
- /**
5
- * Bundle version reported by the SDK. Bumped at release time.
6
- */
7
- GameHub.SDK_VERSION = '0.1.0';
8
- /**
9
- * Prefix applied to every cross-origin postMessage the SDK emits and accepts.
10
- * Keeps our messages isolated from unrelated frames on the same page.
11
- */
12
- GameHub.MESSAGE_PREFIX = 'GAMEHUB_SDK';
13
- /** How long to wait for the host to reply to bootstrap/auth requests. */
14
- GameHub.PARENT_REQUEST_TIMEOUT_MS = 2000;
15
- /** Maximum number of WebSocket reconnect attempts before giving up. */
16
- GameHub.MP_MAX_RECONNECT_ATTEMPTS = 5;
17
- /** Hard cap on reconnect backoff. */
18
- GameHub.MP_MAX_RECONNECT_DELAY_MS = 10000;
19
- /** Upper bound used when the caller doesn't pass an explicit limit. */
20
- GameHub.QUESTIONS_LIMIT_CAP = 100;
21
- })(GameHub || (GameHub = {}));
22
- /**
23
- * Centralised mutable state for the SDK singleton.
24
- *
25
- * Everything here is module-global by design — the SDK is a singleton per
26
- * window and this is the single source of truth. Keeping it in one file makes
27
- * lifetime and invalidation rules easier to audit than spreading `let`s across
28
- * every feature module.
29
- */
30
- var GameHub;
31
- (function (GameHub) {
32
- var State;
33
- (function (State) {
34
- // --- API endpoint resolution ---------------------------------------------
35
- State.sdkOrigin = '';
36
- State.sdkPathPrefix = '';
37
- State.runtimeBasePath = '';
38
- State.apiBase = '';
39
- // --- Game / league context ------------------------------------------------
40
- State.gameSlug = null;
41
- State.sessionToken = null;
42
- State.authToken = null;
43
- State.leagueId = null;
44
- State.gameId = null;
45
- State.matchId = null;
46
- State.participant1Id = null;
47
- State.participant2Id = null;
48
- State.participant1MemberIds = [];
49
- State.participant2MemberIds = [];
50
- // --- Match metadata (fetched lazily from the API) ------------------------
51
- State.matchContext = null;
52
- State.matchContextPromise = null;
53
- // --- Bootstrap payload from host -----------------------------------------
54
- State.bootstrapShareId = null;
55
- State.bootstrapRoomCode = null;
56
- State.bootstrapRoomRole = null;
57
- State.bootstrapRoomToken = null;
58
- State.bootstrapWsUrl = null;
59
- State.bootstrapPlayerName = null;
60
- State.bootstrapPeerId = null;
61
- State.bootstrapMaxPlayers = null;
62
- State.bootstrapReceived = false;
63
- // --- Initialisation lifecycle --------------------------------------------
64
- State.isInitialized = false;
65
- State.isAutoInitializing = false;
66
- State.autoInitPromise = null;
67
- State.bootstrapRequestPromise = null;
68
- State.parentOrigin = null;
69
- State.sessionStartPromise = null;
70
- State.lastAutoJoinShareId = null;
71
- State.lastAutoJoinRoomCode = null;
72
- // --- Multiplayer runtime --------------------------------------------------
73
- State.mpSocket = null;
74
- State.mpReconnectTimer = null;
75
- State.mpReconnectAttempts = 0;
76
- State.mpExpectedClose = false;
77
- State.mpRoom = null;
78
- State.mpLastJoinRequest = null;
79
- State.mpPeers = new Map();
80
- State.mpHandlers = new Map();
81
- /**
82
- * Highest `seq` we've already delivered to game code, per sending peer.
83
- * Used to drop late/duplicate `game_event` frames so a reconnect or a
84
- * buffered message can't double-advance game state.
85
- */
86
- State.mpLastSeqByPeer = new Map();
87
- /**
88
- * Local override for view-only guests. The server doesn't know about
89
- * viewers — this is a client-side flag the SDK flips when the game joins
90
- * with `{ asViewer: true }`. It gates outbound `send`/`broadcast` and
91
- * score submission.
92
- */
93
- State.mpViewerOverride = false;
94
- })(State = GameHub.State || (GameHub.State = {}));
95
- })(GameHub || (GameHub = {}));
96
- var GameHub;
97
- (function (GameHub) {
98
- var Utils;
99
- (function (Utils) {
100
- /**
101
- * Logs with a consistent `[GameHubSDK]` prefix so host-page developers can
102
- * easily filter SDK messages in their console.
103
- */
104
- function warn(message, ...rest) {
105
- console.warn('[GameHubSDK] ' + message, ...rest);
106
- }
107
- Utils.warn = warn;
108
- function error(message, ...rest) {
109
- console.error('[GameHubSDK] ' + message, ...rest);
110
- }
111
- Utils.error = error;
112
- /**
113
- * Flattens the standard `{ success, data }` envelope returned by our REST API
114
- * down to the inner `data` payload, or returns the raw response if it isn't
115
- * shaped that way.
116
- */
117
- function unwrapResult(result) {
118
- if (!result)
119
- return null;
120
- if (result.success && result.data)
121
- return result.data;
122
- return result;
123
- }
124
- Utils.unwrapResult = unwrapResult;
125
- /**
126
- * Extracts a share ID from either:
127
- * - a full multiplayer URL (`/join?mp=<shareId>`), or
128
- * - a short path where the last segment is the share ID itself.
129
- * Returns null if the link can't be parsed.
130
- */
131
- function extractShareIdFromLink(link) {
132
- try {
133
- const parsed = new URL(link, window.location.origin);
134
- const mp = parsed.searchParams.get('mp');
135
- if (mp)
136
- return mp;
137
- return parsed.pathname.split('/').pop() || null;
138
- }
139
- catch {
140
- return null;
141
- }
142
- }
143
- Utils.extractShareIdFromLink = extractShareIdFromLink;
144
- /**
145
- * Safely read a query-string parameter, falling back to a regex scan when
146
- * URLSearchParams is unavailable (very old browsers / odd runtimes).
147
- */
148
- function readQueryParam(name) {
149
- try {
150
- const params = new URLSearchParams(window.location.search);
151
- return params.get(name);
152
- }
153
- catch {
154
- const match = window.location.search.match(new RegExp('[?&]' + name + '=([^&]+)'));
155
- return match ? decodeURIComponent(match[1]) : null;
156
- }
157
- }
158
- Utils.readQueryParam = readQueryParam;
159
- /**
160
- * Reads a CSV query parameter and returns the trimmed, non-empty values.
161
- */
162
- function readCsvQueryParam(name) {
163
- const raw = readQueryParam(name) || '';
164
- return raw
165
- .split(',')
166
- .map((value) => value.trim())
167
- .filter(Boolean);
168
- }
169
- Utils.readCsvQueryParam = readCsvQueryParam;
170
- })(Utils = GameHub.Utils || (GameHub.Utils = {}));
171
- })(GameHub || (GameHub = {}));
172
- var GameHub;
173
- (function (GameHub) {
174
- var Api;
175
- (function (Api) {
176
- /**
177
- * Performs a request against the GameHub REST API, prefixing the configured
178
- * API base, attaching the Bearer auth token when available, and parsing the
179
- * JSON response.
180
- *
181
- * Throws whatever `fetch`/`JSON.parse` throw — callers decide whether to
182
- * retry, fall back, or surface the error to the host.
183
- */
184
- async function apiRequest(endpoint, options = {}) {
185
- const url = GameHub.State.apiBase + endpoint;
186
- const headers = {
187
- 'Content-Type': 'application/json',
188
- ...(options.headers || {}),
189
- };
190
- if (GameHub.State.authToken) {
191
- headers.Authorization = 'Bearer ' + GameHub.State.authToken;
192
- }
193
- const response = await fetch(url, {
194
- ...options,
195
- credentials: options.credentials || 'same-origin',
196
- headers,
197
- body: options.body ? JSON.stringify(options.body) : undefined,
198
- });
199
- return response.json();
200
- }
201
- Api.apiRequest = apiRequest;
202
- })(Api = GameHub.Api || (GameHub.Api = {}));
203
- })(GameHub || (GameHub = {}));
204
- /**
205
- * Cross-origin communication layer between the game iframe and its host page.
206
- *
207
- * Messages are namespaced with {@link GameHub.MESSAGE_PREFIX} so we don't pick
208
- * up unrelated postMessage traffic. The host is expected to implement a small
209
- * protocol (BOOTSTRAP_REQUEST / BOOTSTRAP, AUTH_REQUEST / AUTH_RESPONSE, etc.).
210
- */
211
- var GameHub;
212
- (function (GameHub) {
213
- var Bridge;
214
- (function (Bridge) {
215
- /**
216
- * Fold a {@link BootstrapConfig} from the host into internal state. Accepts
217
- * partial configs: only the fields that are explicitly set (including
218
- * explicit `null`s used to clear a value) are applied.
219
- */
220
- function mergeBootstrapConfig(config = {}) {
221
- if (!config || typeof config !== 'object')
222
- return;
223
- const S = GameHub.State;
224
- if (typeof config.gameSlug === 'string' && config.gameSlug.trim()) {
225
- S.gameSlug = config.gameSlug.trim();
226
- }
227
- if (typeof config.authToken === 'string') {
228
- S.authToken = config.authToken;
229
- }
230
- else if (config.authToken === null) {
231
- S.authToken = null;
232
- }
233
- if (typeof config.leagueId === 'string' && config.leagueId.trim()) {
234
- S.leagueId = config.leagueId.trim();
235
- }
236
- else if (config.leagueId === null) {
237
- S.leagueId = null;
238
- }
239
- if (typeof config.gameId === 'string' && config.gameId.trim()) {
240
- S.gameId = config.gameId.trim();
241
- }
242
- else if (config.gameId === null) {
243
- S.gameId = null;
244
- }
245
- if (typeof config.matchId === 'string' && config.matchId.trim()) {
246
- S.matchId = config.matchId.trim();
247
- }
248
- else if (config.matchId === null) {
249
- S.matchId = null;
250
- }
251
- if (typeof config.participant1Id === 'string' &&
252
- config.participant1Id.trim()) {
253
- S.participant1Id = config.participant1Id.trim();
254
- }
255
- else if (config.participant1Id === null) {
256
- S.participant1Id = null;
257
- }
258
- if (typeof config.participant2Id === 'string' &&
259
- config.participant2Id.trim()) {
260
- S.participant2Id = config.participant2Id.trim();
261
- }
262
- else if (config.participant2Id === null) {
263
- S.participant2Id = null;
264
- }
265
- if (Array.isArray(config.participant1MemberIds)) {
266
- S.participant1MemberIds = config.participant1MemberIds.filter(Boolean);
267
- }
268
- if (Array.isArray(config.participant2MemberIds)) {
269
- S.participant2MemberIds = config.participant2MemberIds.filter(Boolean);
270
- }
271
- if (typeof config.playerName === 'string' && config.playerName.trim()) {
272
- S.bootstrapPlayerName = config.playerName.trim();
273
- }
274
- else if (config.playerName === null) {
275
- S.bootstrapPlayerName = null;
276
- }
277
- if (typeof config.peerId === 'string' && config.peerId.trim()) {
278
- S.bootstrapPeerId = config.peerId.trim();
279
- }
280
- else if (config.peerId === null) {
281
- S.bootstrapPeerId = null;
282
- }
283
- // `room` is an object on the wire so roomCode/shareId/maxPlayers and
284
- // optional live join credentials stay
285
- // grouped — but SDK state keeps them flat to avoid allocating a fresh
286
- // object on every merge and to keep URL-seeded values (e.g. from
287
- // `?roomCode=`) in the same place.
288
- if (config.room && typeof config.room === 'object') {
289
- const room = config.room;
290
- if (typeof room.roomCode === 'string' && room.roomCode.trim()) {
291
- S.bootstrapRoomCode = room.roomCode.trim().toUpperCase();
292
- }
293
- else if (room.roomCode === null) {
294
- S.bootstrapRoomCode = null;
295
- }
296
- if (typeof room.shareId === 'string' && room.shareId.trim()) {
297
- S.bootstrapShareId = room.shareId.trim();
298
- }
299
- else if (room.shareId === null) {
300
- S.bootstrapShareId = null;
301
- }
302
- if (typeof room.maxPlayers === 'number' &&
303
- Number.isFinite(room.maxPlayers)) {
304
- S.bootstrapMaxPlayers = room.maxPlayers;
305
- }
306
- else if (room.maxPlayers === null) {
307
- S.bootstrapMaxPlayers = null;
308
- }
309
- if (typeof room.role === 'string' && room.role.trim()) {
310
- S.bootstrapRoomRole = room.role.trim();
311
- }
312
- else if (room.role === null) {
313
- S.bootstrapRoomRole = null;
314
- }
315
- if (typeof room.roomToken === 'string' && room.roomToken.trim()) {
316
- S.bootstrapRoomToken = room.roomToken.trim();
317
- }
318
- else if (room.roomToken === null) {
319
- S.bootstrapRoomToken = null;
320
- }
321
- if (typeof room.wsUrl === 'string' && room.wsUrl.trim()) {
322
- S.bootstrapWsUrl = room.wsUrl.trim();
323
- }
324
- else if (room.wsUrl === null) {
325
- S.bootstrapWsUrl = null;
326
- }
327
- }
328
- else if (config.room === null) {
329
- S.bootstrapRoomCode = null;
330
- S.bootstrapShareId = null;
331
- S.bootstrapMaxPlayers = null;
332
- S.bootstrapRoomRole = null;
333
- S.bootstrapRoomToken = null;
334
- S.bootstrapWsUrl = null;
335
- }
336
- }
337
- Bridge.mergeBootstrapConfig = mergeBootstrapConfig;
338
- /**
339
- * Ask the host for its bootstrap payload. Resolves `null` if the game is
340
- * standalone (no parent), if the host doesn't reply within the timeout, or
341
- * if we're not in an iframe.
342
- *
343
- * Subsequent calls after a successful bootstrap short-circuit to the cached
344
- * state snapshot.
345
- */
346
- function requestBootstrapFromParent() {
347
- const S = GameHub.State;
348
- if (window.parent === window) {
349
- return Promise.resolve(null);
350
- }
351
- if (S.bootstrapReceived) {
352
- return Promise.resolve({
353
- gameSlug: S.gameSlug,
354
- authToken: S.authToken,
355
- leagueId: S.leagueId,
356
- gameId: S.gameId,
357
- matchId: S.matchId,
358
- participant1Id: S.participant1Id,
359
- participant2Id: S.participant2Id,
360
- participant1MemberIds: S.participant1MemberIds,
361
- participant2MemberIds: S.participant2MemberIds,
362
- playerName: S.bootstrapPlayerName,
363
- peerId: S.bootstrapPeerId,
364
- room: S.bootstrapRoomCode
365
- ? {
366
- roomCode: S.bootstrapRoomCode,
367
- shareId: S.bootstrapShareId,
368
- maxPlayers: S.bootstrapMaxPlayers,
369
- role: S.bootstrapRoomRole,
370
- roomToken: S.bootstrapRoomToken,
371
- wsUrl: S.bootstrapWsUrl,
372
- }
373
- : null,
374
- });
375
- }
376
- if (S.bootstrapRequestPromise) {
377
- return S.bootstrapRequestPromise;
378
- }
379
- S.bootstrapRequestPromise = new Promise((resolve) => {
380
- const messageId = Date.now().toString();
381
- let settled = false;
382
- let timeoutId = null;
383
- const handler = (event) => {
384
- if (event.data &&
385
- event.data.type === GameHub.MESSAGE_PREFIX + '_BOOTSTRAP' &&
386
- event.data.payload) {
387
- if (event.data.messageId && event.data.messageId !== messageId) {
388
- return;
389
- }
390
- if (settled)
391
- return;
392
- settled = true;
393
- window.removeEventListener('message', handler);
394
- if (timeoutId)
395
- clearTimeout(timeoutId);
396
- S.parentOrigin = event.origin;
397
- S.bootstrapReceived = true;
398
- mergeBootstrapConfig(event.data.payload);
399
- resolve(event.data.payload);
400
- }
401
- };
402
- window.addEventListener('message', handler);
403
- window.parent.postMessage({
404
- type: GameHub.MESSAGE_PREFIX + '_BOOTSTRAP_REQUEST',
405
- messageId,
406
- }, '*');
407
- timeoutId = setTimeout(() => {
408
- if (settled)
409
- return;
410
- settled = true;
411
- window.removeEventListener('message', handler);
412
- resolve(null);
413
- }, GameHub.PARENT_REQUEST_TIMEOUT_MS);
414
- }).finally(() => {
415
- S.bootstrapRequestPromise = null;
416
- });
417
- return S.bootstrapRequestPromise;
418
- }
419
- Bridge.requestBootstrapFromParent = requestBootstrapFromParent;
420
- /**
421
- * Ask the host for a fresh auth token. The host may also use the response to
422
- * override league/match context — when it does, we prefer its values over
423
- * whatever was on the URL.
424
- */
425
- function getAuthTokenFromParent() {
426
- return new Promise((resolve) => {
427
- if (window.parent === window) {
428
- resolve(null);
429
- return;
430
- }
431
- const S = GameHub.State;
432
- const messageId = Date.now().toString();
433
- let settled = false;
434
- let timeoutId = null;
435
- const handler = (event) => {
436
- if (event.data &&
437
- event.data.type === GameHub.MESSAGE_PREFIX + '_AUTH_RESPONSE' &&
438
- event.data.messageId === messageId) {
439
- if (settled)
440
- return;
441
- settled = true;
442
- window.removeEventListener('message', handler);
443
- if (timeoutId)
444
- clearTimeout(timeoutId);
445
- S.parentOrigin = event.origin;
446
- // Host-supplied context wins over URL params.
447
- if (event.data.leagueId)
448
- S.leagueId = event.data.leagueId;
449
- if (event.data.gameId)
450
- S.gameId = event.data.gameId;
451
- if (event.data.matchId)
452
- S.matchId = event.data.matchId;
453
- if (event.data.participant1Id)
454
- S.participant1Id = event.data.participant1Id;
455
- if (event.data.participant2Id)
456
- S.participant2Id = event.data.participant2Id;
457
- if (Array.isArray(event.data.participant1MemberIds))
458
- S.participant1MemberIds =
459
- event.data.participant1MemberIds.filter(Boolean);
460
- if (Array.isArray(event.data.participant2MemberIds))
461
- S.participant2MemberIds =
462
- event.data.participant2MemberIds.filter(Boolean);
463
- resolve(event.data.token || null);
464
- }
465
- };
466
- window.addEventListener('message', handler);
467
- window.parent.postMessage({ type: GameHub.MESSAGE_PREFIX + '_AUTH_REQUEST', messageId }, '*');
468
- timeoutId = setTimeout(() => {
469
- if (settled)
470
- return;
471
- settled = true;
472
- window.removeEventListener('message', handler);
473
- resolve(null);
474
- }, GameHub.PARENT_REQUEST_TIMEOUT_MS);
475
- });
476
- }
477
- Bridge.getAuthTokenFromParent = getAuthTokenFromParent;
478
- /**
479
- * Fire a namespaced message up to the host window. Silently no-ops when we
480
- * aren't inside an iframe.
481
- */
482
- function sendToParent(type, data) {
483
- if (window.parent !== window) {
484
- window.parent.postMessage({
485
- type: GameHub.MESSAGE_PREFIX + '_' + type,
486
- gameSlug: GameHub.State.gameSlug,
487
- ...data,
488
- }, GameHub.State.parentOrigin || '*');
489
- }
490
- }
491
- Bridge.sendToParent = sendToParent;
492
- })(Bridge = GameHub.Bridge || (GameHub.Bridge = {}));
493
- })(GameHub || (GameHub = {}));
494
- var GameHub;
495
- (function (GameHub) {
496
- var MatchCtx;
497
- (function (MatchCtx) {
498
- /**
499
- * Lazily load the match context for a league game. Results are cached on
500
- * {@link GameHub.State.matchContext}; concurrent callers share a single
501
- * in-flight request via {@link GameHub.State.matchContextPromise}.
502
- *
503
- * Resolves `null` when required context (league or match id) is missing, or
504
- * when the server returns an error — callers decide how to degrade.
505
- */
506
- async function fetchMatchContext() {
507
- const S = GameHub.State;
508
- if (!S.leagueId || !S.matchId)
509
- return null;
510
- if (S.matchContext)
511
- return S.matchContext;
512
- if (S.matchContextPromise)
513
- return await S.matchContextPromise;
514
- S.matchContextPromise = GameHub.Api.apiRequest('/leagues/' +
515
- encodeURIComponent(S.leagueId) +
516
- '/matches/' +
517
- encodeURIComponent(S.matchId), { method: 'GET' })
518
- .then((result) => {
519
- const data = GameHub.Utils.unwrapResult(result);
520
- if (result?.success && data) {
521
- S.matchContext = data;
522
- S.participant1Id =
523
- data.participant1?.participantId || S.participant1Id;
524
- S.participant2Id =
525
- data.participant2?.participantId || S.participant2Id;
526
- S.participant1MemberIds = Array.isArray(data.participant1?.members)
527
- ? data.participant1.members
528
- .map((member) => member?.leaguePlayerId)
529
- .filter(Boolean)
530
- : S.participant1MemberIds;
531
- S.participant2MemberIds = Array.isArray(data.participant2?.members)
532
- ? data.participant2.members
533
- .map((member) => member?.leaguePlayerId)
534
- .filter(Boolean)
535
- : S.participant2MemberIds;
536
- return S.matchContext;
537
- }
538
- return null;
539
- })
540
- .catch(() => null)
541
- .finally(() => {
542
- S.matchContextPromise = null;
543
- });
544
- return await S.matchContextPromise;
545
- }
546
- MatchCtx.fetchMatchContext = fetchMatchContext;
547
- })(MatchCtx = GameHub.MatchCtx || (GameHub.MatchCtx = {}));
548
- })(GameHub || (GameHub = {}));
549
- var GameHub;
550
- (function (GameHub) {
551
- var Session;
552
- (function (Session) {
553
- /**
554
- * Starts a new game session and caches the returned session token. Safe to
555
- * call multiple times — the cached token short-circuits subsequent calls.
556
- *
557
- * Endpoint is selected from the active context:
558
- * - league + game + match → scoped match session
559
- * - league + game → scoped league session
560
- * - otherwise → standalone session (requires auth)
561
- */
562
- async function startSession() {
563
- const S = GameHub.State;
564
- if (!S.gameSlug)
565
- return { success: false, error: 'Game slug not set' };
566
- const isLeagueMatchSession = Boolean(S.leagueId && S.gameId && S.matchId);
567
- if (!S.authToken && !isLeagueMatchSession) {
568
- return { success: false, error: 'User not authenticated' };
569
- }
570
- if (S.sessionToken)
571
- return { success: true, token: S.sessionToken };
572
- try {
573
- let endpoint = '/sessions/start';
574
- let body = { gameSlug: S.gameSlug };
575
- if (S.leagueId && S.gameId && S.matchId) {
576
- endpoint =
577
- '/leagues/' + S.leagueId + '/matches/' + S.matchId + '/session';
578
- body = { gameId: S.gameId };
579
- }
580
- else if (S.leagueId && S.gameId) {
581
- endpoint = '/leagues/' + S.leagueId + '/sessions';
582
- body = { gameId: S.gameId };
583
- }
584
- const result = await GameHub.Api.apiRequest(endpoint, {
585
- method: 'POST',
586
- body,
587
- });
588
- const data = GameHub.Utils.unwrapResult(result);
589
- if (result.success || data?.token) {
590
- S.sessionToken = data?.token || result?.token || null;
591
- GameHub.Bridge.sendToParent('SESSION_STARTED', {
592
- token: S.sessionToken,
593
- });
594
- return { success: true, token: S.sessionToken };
595
- }
596
- return {
597
- success: false,
598
- error: result.error?.message || 'Failed to start session',
599
- };
600
- }
601
- catch (err) {
602
- return { success: false, error: err.message };
603
- }
604
- }
605
- Session.startSession = startSession;
606
- /**
607
- * Submit a score to the current session. If no session exists yet we try to
608
- * open one (re-using any in-flight start attempt).
609
- */
610
- async function submitScore(score, meta = {}) {
611
- const S = GameHub.State;
612
- await GameHub.Init.ensureInitialized();
613
- if (!S.isInitialized) {
614
- return {
615
- success: false,
616
- error: 'SDK could not initialize. Is game slug set?',
617
- };
618
- }
619
- // Online-mode gate: when the SDK is joined to a multiplayer room, only the
620
- // host is allowed to submit. Guests and viewers short-circuit with
621
- // `{ skipped: true }` so games can call `submitScore` from shared code
622
- // without double-counting the match.
623
- if (S.mpRoom && S.mpRoom.role !== 'host') {
624
- GameHub.Utils.warn('submitScore skipped: only the multiplayer host may submit scores');
625
- return { success: true, skipped: true };
626
- }
627
- if (!S.sessionToken) {
628
- if (S.sessionStartPromise) {
629
- await S.sessionStartPromise;
630
- }
631
- else {
632
- const sessionResult = await startSession();
633
- if (!sessionResult.success) {
634
- return {
635
- success: false,
636
- error: sessionResult.error || 'Could not start session',
637
- };
638
- }
639
- }
640
- }
641
- if (!S.sessionToken) {
642
- return {
643
- success: false,
644
- error: 'No active session. User may not be authenticated.',
645
- };
646
- }
647
- if (typeof score !== 'number' || score < 0) {
648
- return { success: false, error: 'Score must be a non-negative number' };
649
- }
650
- try {
651
- const result = await GameHub.Api.apiRequest('/sessions/submit', {
652
- method: 'POST',
653
- body: {
654
- token: S.sessionToken,
655
- score: Math.floor(score),
656
- meta,
657
- },
658
- });
659
- const data = GameHub.Utils.unwrapResult(result);
660
- if (result.success || data?.accepted) {
661
- GameHub.Bridge.sendToParent('SCORE_SUBMITTED', {
662
- score,
663
- accepted: data?.accepted,
664
- timeTaken: data?.timeTaken,
665
- });
666
- return {
667
- success: true,
668
- accepted: data?.accepted,
669
- timeTaken: data?.timeTaken,
670
- };
671
- }
672
- return {
673
- success: false,
674
- error: result.error?.message || 'Score rejected',
675
- };
676
- }
677
- catch (err) {
678
- return { success: false, error: err.message };
679
- }
680
- }
681
- Session.submitScore = submitScore;
682
- /**
683
- * Convenience wrapper that tags a score with the current league match
684
- * context. Fails early if there's no matchId — a plain {@link submitScore}
685
- * is the right call in that case.
686
- */
687
- async function submitMatchScore(score, meta = {}) {
688
- const S = GameHub.State;
689
- if (!S.matchId) {
690
- return {
691
- success: false,
692
- error: 'No matchId found for this game session',
693
- };
694
- }
695
- return await submitScore(score, {
696
- ...(meta || {}),
697
- matchId: S.matchId,
698
- leagueId: S.leagueId || meta.leagueId,
699
- gameId: S.gameId || meta.gameId,
700
- });
701
- }
702
- Session.submitMatchScore = submitMatchScore;
703
- /**
704
- * Submit a match result (winner, scores, etc.) with a zero placeholder
705
- * score — the server derives the real leaderboard entries from the result
706
- * payload.
707
- */
708
- async function submitMatchResult(result = {}) {
709
- if (!result || typeof result !== 'object') {
710
- return { success: false, error: 'match result payload is required' };
711
- }
712
- return await submitMatchScore(0, { matchResult: result });
713
- }
714
- Session.submitMatchResult = submitMatchResult;
715
- /**
716
- * Fetch questions for this game. Returns an empty array on any failure or
717
- * invalid input — callers can treat "no questions" as the degraded state.
718
- */
719
- async function getQuestions(options = {}) {
720
- const S = GameHub.State;
721
- await GameHub.Init.ensureInitialized();
722
- const gameIdentifier = S.gameId || S.gameSlug;
723
- if (!gameIdentifier)
724
- return [];
725
- const { difficulty, category, limit } = options;
726
- if (difficulty && !['easy', 'medium', 'hard'].includes(difficulty)) {
727
- return [];
728
- }
729
- if (limit !== undefined && (typeof limit !== 'number' || limit < 1)) {
730
- return [];
731
- }
732
- try {
733
- const params = new URLSearchParams({
734
- limit: String(Math.min(limit || GameHub.QUESTIONS_LIMIT_CAP, GameHub.QUESTIONS_LIMIT_CAP)),
735
- random: 'true',
736
- });
737
- if (S.gameId)
738
- params.set('gameId', S.gameId);
739
- if (difficulty)
740
- params.set('difficulty', difficulty);
741
- if (category)
742
- params.set('category', String(category));
743
- const result = await GameHub.Api.apiRequest('/games/' +
744
- encodeURIComponent(gameIdentifier) +
745
- '/questions?' +
746
- params.toString(), { method: 'GET' });
747
- const data = GameHub.Utils.unwrapResult(result);
748
- if (Array.isArray(data))
749
- return data;
750
- if (!data || !Array.isArray(data.questions))
751
- return [];
752
- return data.questions;
753
- }
754
- catch {
755
- return [];
756
- }
757
- }
758
- Session.getQuestions = getQuestions;
759
- })(Session = GameHub.Session || (GameHub.Session = {}));
760
- })(GameHub || (GameHub = {}));
761
- /**
762
- * Multiplayer layer: room creation/join, WebSocket connection management,
763
- * reconnection, and an event emitter for game code to listen on.
764
- */
765
- var GameHub;
766
- (function (GameHub) {
767
- var Multiplayer;
768
- (function (Multiplayer) {
769
- // --- Event emitter -------------------------------------------------------
770
- /**
771
- * Dispatch an event to per-name listeners and the wildcard (`'*'`) listeners.
772
- * Handler errors are caught and logged so a buggy listener can't break the
773
- * socket loop.
774
- */
775
- function emit(eventName, payload) {
776
- const handlers = GameHub.State.mpHandlers.get(eventName);
777
- if (handlers) {
778
- handlers.forEach((handler) => {
779
- try {
780
- handler(payload);
781
- }
782
- catch (err) {
783
- GameHub.Utils.error('Multiplayer handler error:', err);
784
- }
785
- });
786
- }
787
- const allHandlers = GameHub.State.mpHandlers.get('*');
788
- if (allHandlers) {
789
- allHandlers.forEach((handler) => {
790
- try {
791
- handler({ eventName, payload });
792
- }
793
- catch (err) {
794
- GameHub.Utils.error('Multiplayer * handler error:', err);
795
- }
796
- });
797
- }
798
- }
799
- Multiplayer.emit = emit;
800
- // --- Connection lifecycle ------------------------------------------------
801
- /**
802
- * Detach listeners from the current socket and close it. Idempotent.
803
- * The caller is responsible for clearing {@link GameHub.State.mpRoom} and
804
- * related state — this function only touches the transport.
805
- */
806
- function clearSocket() {
807
- const S = GameHub.State;
808
- if (S.mpReconnectTimer) {
809
- clearTimeout(S.mpReconnectTimer);
810
- S.mpReconnectTimer = null;
811
- }
812
- if (S.mpSocket) {
813
- try {
814
- S.mpSocket.onopen = null;
815
- S.mpSocket.onclose = null;
816
- S.mpSocket.onmessage = null;
817
- S.mpSocket.onerror = null;
818
- S.mpSocket.close();
819
- }
820
- catch {
821
- // ignore
822
- }
823
- }
824
- S.mpSocket = null;
825
- }
826
- Multiplayer.clearSocket = clearSocket;
827
- /**
828
- * Open a WebSocket for the given join info and wire up the message/close
829
- * handlers. Automatically reconnects with exponential backoff up to
830
- * {@link GameHub.MP_MAX_RECONNECT_ATTEMPTS} attempts.
831
- */
832
- function connect(joinInfo) {
833
- const S = GameHub.State;
834
- clearSocket();
835
- const wsBase = joinInfo.wsUrl.replace(/\/+$/, '');
836
- const wsUrl = wsBase +
837
- '?roomToken=' +
838
- encodeURIComponent(joinInfo.roomToken) +
839
- '&gameSlug=' +
840
- encodeURIComponent(joinInfo.gameSlug) +
841
- '&sdk=2.x';
842
- S.mpExpectedClose = false;
843
- S.mpSocket = new WebSocket(wsUrl);
844
- S.mpSocket.onopen = () => {
845
- S.mpReconnectAttempts = 0;
846
- emit('connected', {
847
- roomCode: joinInfo.roomCode,
848
- peerId: joinInfo.peerId,
849
- });
850
- };
851
- S.mpSocket.onmessage = (event) => {
852
- let message = null;
853
- try {
854
- message = JSON.parse(event.data);
855
- }
856
- catch {
857
- return;
858
- }
859
- if (!message || !message.type)
860
- return;
861
- if (message.type === 'system') {
862
- if (message.eventName === 'room_joined') {
863
- S.mpPeers.clear();
864
- const peers = message.payload?.peers || [];
865
- peers.forEach((peer) => {
866
- if (peer && peer.peerId)
867
- S.mpPeers.set(peer.peerId, peer);
868
- });
869
- }
870
- if (message.eventName === 'peer_joined' && message.payload?.peerId) {
871
- S.mpPeers.set(message.payload.peerId, message.payload);
872
- }
873
- if (message.eventName === 'peer_left' && message.payload?.peerId) {
874
- S.mpPeers.delete(message.payload.peerId);
875
- }
876
- if (message.eventName === 'room_closed') {
877
- emit('room_left', { reason: 'room_closed' });
878
- clearSocket();
879
- }
880
- emit(message.eventName, message.payload || {});
881
- return;
882
- }
883
- if (message.type === 'game_event') {
884
- // Reentrancy guard: drop late / duplicate frames from the same peer so
885
- // a reconnect-replay or an out-of-order delivery can't double-advance
886
- // game state. The server stamps a strictly-monotonic `seq` per sender.
887
- if (typeof message.seq === 'number' &&
888
- typeof message.fromPeerId === 'string') {
889
- const last = S.mpLastSeqByPeer.get(message.fromPeerId) || 0;
890
- if (message.seq <= last)
891
- return;
892
- S.mpLastSeqByPeer.set(message.fromPeerId, message.seq);
893
- }
894
- emit('message', {
895
- roomCode: message.roomCode,
896
- fromPeerId: message.fromPeerId,
897
- eventName: message.eventName,
898
- payload: message.payload,
899
- seq: message.seq,
900
- sentAt: message.sentAt,
901
- });
902
- // Also fan out to per-eventName subscribers so game code can do
903
- // `multiplayer.on('player_move', handler)` directly instead of
904
- // filtering inside a single `message` listener.
905
- emit(message.eventName, {
906
- roomCode: message.roomCode,
907
- fromPeerId: message.fromPeerId,
908
- payload: message.payload,
909
- seq: message.seq,
910
- sentAt: message.sentAt,
911
- });
912
- }
913
- };
914
- S.mpSocket.onclose = () => {
915
- emit('disconnected', { roomCode: joinInfo.roomCode });
916
- if (S.mpExpectedClose || !S.mpLastJoinRequest)
917
- return;
918
- if (S.mpReconnectAttempts >= GameHub.MP_MAX_RECONNECT_ATTEMPTS)
919
- return;
920
- S.mpReconnectAttempts += 1;
921
- const delay = Math.min(1000 * Math.pow(2, S.mpReconnectAttempts - 1), GameHub.MP_MAX_RECONNECT_DELAY_MS);
922
- emit('reconnecting', {
923
- attempts: S.mpReconnectAttempts,
924
- delayMs: delay,
925
- });
926
- S.mpReconnectTimer = setTimeout(() => {
927
- if (!S.mpLastJoinRequest)
928
- return;
929
- connect(S.mpLastJoinRequest);
930
- }, delay);
931
- };
932
- S.mpSocket.onerror = () => {
933
- // The `onclose` handler owns reconnect logic; we only avoid
934
- // double-triggering it here.
935
- };
936
- }
937
- Multiplayer.connect = connect;
938
- // --- High-level room actions --------------------------------------------
939
- /**
940
- * Create a room for the current game and connect as the host.
941
- */
942
- async function createRoom(options = {}) {
943
- const S = GameHub.State;
944
- await GameHub.Init.ensureInitialized();
945
- if (!S.gameSlug) {
946
- return { success: false, error: 'Game slug is required' };
947
- }
948
- const result = await GameHub.Api.apiRequest('/multiplayer/rooms/create', {
949
- method: 'POST',
950
- body: {
951
- gameSlug: S.gameSlug,
952
- maxPlayers: options.maxPlayers,
953
- passcode: options.passcode,
954
- },
955
- });
956
- const data = GameHub.Utils.unwrapResult(result);
957
- if (!result.success || !data?.roomToken) {
958
- return {
959
- success: false,
960
- error: result.error?.message || 'Failed to create room',
961
- };
962
- }
963
- S.mpRoom = {
964
- roomCode: data.roomCode,
965
- shareId: data.shareId,
966
- shareUrl: data.shareUrl,
967
- peerId: data.peerId,
968
- role: data.role,
969
- gameSlug: data.gameSlug,
970
- roomToken: data.roomToken,
971
- wsUrl: data.wsUrl,
972
- };
973
- S.mpLastJoinRequest = {
974
- roomCode: data.roomCode,
975
- roomToken: data.roomToken,
976
- wsUrl: data.wsUrl,
977
- gameSlug: data.gameSlug,
978
- peerId: data.peerId,
979
- };
980
- connect(S.mpLastJoinRequest);
981
- return {
982
- success: true,
983
- roomCode: data.roomCode,
984
- shareId: data.shareId,
985
- shareUrl: data.shareUrl,
986
- peerId: data.peerId,
987
- roomToken: data.roomToken,
988
- };
989
- }
990
- Multiplayer.createRoom = createRoom;
991
- /**
992
- * Join an existing room by its short alphanumeric code.
993
- */
994
- async function joinRoom(roomCode, options = {}) {
995
- const S = GameHub.State;
996
- await GameHub.Init.ensureInitialized();
997
- if (!S.gameSlug) {
998
- return { success: false, error: 'Game slug is required' };
999
- }
1000
- const result = await GameHub.Api.apiRequest('/multiplayer/rooms/join-token', {
1001
- method: 'POST',
1002
- body: {
1003
- gameSlug: S.gameSlug,
1004
- roomCode,
1005
- passcode: options.passcode,
1006
- displayName: options.displayName,
1007
- },
1008
- });
1009
- const data = GameHub.Utils.unwrapResult(result);
1010
- if (!result.success || !data?.roomToken) {
1011
- return {
1012
- success: false,
1013
- error: result.error?.message || 'Failed to join room',
1014
- };
1015
- }
1016
- const resolvedRole = options.asViewer && data.role !== 'host' ? 'viewer' : data.role;
1017
- S.mpViewerOverride = resolvedRole === 'viewer';
1018
- S.mpRoom = {
1019
- roomCode: data.roomCode,
1020
- shareId: data.shareId,
1021
- peerId: data.peerId,
1022
- role: resolvedRole,
1023
- gameSlug: data.gameSlug,
1024
- roomToken: data.roomToken,
1025
- wsUrl: data.wsUrl,
1026
- };
1027
- S.mpLastJoinRequest = {
1028
- roomCode: data.roomCode,
1029
- roomToken: data.roomToken,
1030
- wsUrl: data.wsUrl,
1031
- gameSlug: data.gameSlug,
1032
- peerId: data.peerId,
1033
- };
1034
- connect(S.mpLastJoinRequest);
1035
- return {
1036
- success: true,
1037
- roomCode: data.roomCode,
1038
- shareId: data.shareId,
1039
- peerId: data.peerId,
1040
- roomToken: data.roomToken,
1041
- };
1042
- }
1043
- Multiplayer.joinRoom = joinRoom;
1044
- /**
1045
- * Join an existing room by its share ID or full share URL.
1046
- */
1047
- async function joinRoomByLink(link, options = {}) {
1048
- const S = GameHub.State;
1049
- await GameHub.Init.ensureInitialized();
1050
- if (!S.gameSlug) {
1051
- return { success: false, error: 'Game slug is required' };
1052
- }
1053
- const shareId = GameHub.Utils.extractShareIdFromLink(link);
1054
- if (!shareId) {
1055
- return { success: false, error: 'Invalid multiplayer link' };
1056
- }
1057
- const result = await GameHub.Api.apiRequest('/multiplayer/rooms/join-token', {
1058
- method: 'POST',
1059
- body: {
1060
- gameSlug: S.gameSlug,
1061
- shareId,
1062
- passcode: options.passcode,
1063
- displayName: options.displayName,
1064
- },
1065
- });
1066
- const data = GameHub.Utils.unwrapResult(result);
1067
- if (!result.success || !data?.roomToken) {
1068
- return {
1069
- success: false,
1070
- error: result.error?.message || 'Failed to join room by link',
1071
- };
1072
- }
1073
- const resolvedRole = options.asViewer && data.role !== 'host' ? 'viewer' : data.role;
1074
- S.mpViewerOverride = resolvedRole === 'viewer';
1075
- S.mpRoom = {
1076
- roomCode: data.roomCode,
1077
- shareId: data.shareId,
1078
- peerId: data.peerId,
1079
- role: resolvedRole,
1080
- gameSlug: data.gameSlug,
1081
- roomToken: data.roomToken,
1082
- wsUrl: data.wsUrl,
1083
- };
1084
- S.mpLastJoinRequest = {
1085
- roomCode: data.roomCode,
1086
- roomToken: data.roomToken,
1087
- wsUrl: data.wsUrl,
1088
- gameSlug: data.gameSlug,
1089
- peerId: data.peerId,
1090
- };
1091
- connect(S.mpLastJoinRequest);
1092
- return {
1093
- success: true,
1094
- roomCode: data.roomCode,
1095
- shareId: data.shareId,
1096
- peerId: data.peerId,
1097
- roomToken: data.roomToken,
1098
- };
1099
- }
1100
- Multiplayer.joinRoomByLink = joinRoomByLink;
1101
- /**
1102
- * Disconnect from the current room. If we're the host, also ask the server
1103
- * to close the room so stragglers get booted cleanly.
1104
- */
1105
- async function leaveRoom(reason = 'left') {
1106
- const S = GameHub.State;
1107
- if (S.mpRoom && S.mpRoom.role === 'host' && S.mpRoom.roomToken) {
1108
- try {
1109
- await GameHub.Api.apiRequest('/multiplayer/rooms/' +
1110
- encodeURIComponent(S.mpRoom.roomCode) +
1111
- '/close', {
1112
- method: 'POST',
1113
- body: { roomToken: S.mpRoom.roomToken },
1114
- });
1115
- }
1116
- catch {
1117
- // ignore
1118
- }
1119
- }
1120
- S.mpExpectedClose = true;
1121
- clearSocket();
1122
- S.mpRoom = null;
1123
- S.mpLastJoinRequest = null;
1124
- S.mpPeers.clear();
1125
- S.mpLastSeqByPeer.clear();
1126
- S.mpViewerOverride = false;
1127
- emit('room_left', { reason });
1128
- }
1129
- Multiplayer.leaveRoom = leaveRoom;
1130
- /**
1131
- * Send a custom game event to every other peer in the room. Returns false
1132
- * when the socket isn't open or the current peer is a view-only guest.
1133
- */
1134
- function send(eventName, payload = {}) {
1135
- const S = GameHub.State;
1136
- if (S.mpViewerOverride) {
1137
- GameHub.Utils.warn('multiplayer.send ignored: peer is a viewer');
1138
- return false;
1139
- }
1140
- const socket = S.mpSocket;
1141
- if (!socket || socket.readyState !== WebSocket.OPEN) {
1142
- return false;
1143
- }
1144
- socket.send(JSON.stringify({ eventName, payload }));
1145
- return true;
1146
- }
1147
- Multiplayer.send = send;
1148
- /**
1149
- * Host-only variant of {@link send}. Silently no-ops (and logs a warning) if
1150
- * the current peer isn't the host. Use this for authoritative state updates
1151
- * — grid shuffles, turn advances, round resolution — so a guest that
1152
- * accidentally calls it can't corrupt the match.
1153
- */
1154
- function broadcast(eventName, payload = {}) {
1155
- if (!isHost()) {
1156
- GameHub.Utils.warn('multiplayer.broadcast ignored: peer is not the host');
1157
- return false;
1158
- }
1159
- return send(eventName, payload);
1160
- }
1161
- Multiplayer.broadcast = broadcast;
1162
- /** @returns the current peer's role (`host`, `player`, `viewer`, ...) or null. */
1163
- function getRole() {
1164
- return GameHub.State.mpRoom ? GameHub.State.mpRoom.role : null;
1165
- }
1166
- Multiplayer.getRole = getRole;
1167
- /** @returns true when the current peer is the room's authoritative host. */
1168
- function isHost() {
1169
- return GameHub.State.mpRoom?.role === 'host';
1170
- }
1171
- Multiplayer.isHost = isHost;
1172
- /** @returns true when the current peer joined with `{ asViewer: true }`. */
1173
- function isViewer() {
1174
- return GameHub.State.mpViewerOverride === true;
1175
- }
1176
- Multiplayer.isViewer = isViewer;
1177
- /**
1178
- * Returns the peerId of the current player (self), or null if not joined.
1179
- * Convenience for filtering self-originated echoes inside a `message`
1180
- * listener: `if (msg.fromPeerId === selfId()) return;`.
1181
- */
1182
- function selfId() {
1183
- return GameHub.State.mpRoom ? GameHub.State.mpRoom.peerId : null;
1184
- }
1185
- Multiplayer.selfId = selfId;
1186
- /**
1187
- * Subscribe to a multiplayer event. Use `'*'` to receive every event.
1188
- * Returns an unsubscribe function.
1189
- */
1190
- function on(eventName, handler) {
1191
- const handlers = GameHub.State.mpHandlers;
1192
- if (!handlers.has(eventName)) {
1193
- handlers.set(eventName, new Set());
1194
- }
1195
- handlers.get(eventName).add(handler);
1196
- return () => {
1197
- const set = handlers.get(eventName);
1198
- if (!set)
1199
- return;
1200
- set.delete(handler);
1201
- if (set.size === 0)
1202
- handlers.delete(eventName);
1203
- };
1204
- }
1205
- Multiplayer.on = on;
1206
- /** @returns a copy of the current room descriptor, or null if not in one. */
1207
- function getRoom() {
1208
- return GameHub.State.mpRoom ? { ...GameHub.State.mpRoom } : null;
1209
- }
1210
- Multiplayer.getRoom = getRoom;
1211
- /** @returns every peer currently in the room (self included). */
1212
- function getPeers() {
1213
- return Array.from(GameHub.State.mpPeers.values());
2
+ (() => {
3
+ // src/constants.ts
4
+ var SDK_VERSION = "0.5.0";
5
+ var MESSAGE_PREFIX = "GAMEHUB_SDK";
6
+ var PARENT_REQUEST_TIMEOUT_MS = 2e3;
7
+ var MP_MAX_RECONNECT_ATTEMPTS = 5;
8
+ var MP_MAX_RECONNECT_DELAY_MS = 1e4;
9
+ var QUESTIONS_LIMIT_CAP = 100;
10
+
11
+ // src/state.ts
12
+ var state = {
13
+ sdkOrigin: "",
14
+ sdkPathPrefix: "",
15
+ runtimeBasePath: "",
16
+ apiBase: "",
17
+ gameSlug: null,
18
+ sessionToken: null,
19
+ authToken: null,
20
+ leagueId: null,
21
+ gameId: null,
22
+ matchId: null,
23
+ participant1Id: null,
24
+ participant2Id: null,
25
+ participant1MemberIds: [],
26
+ participant2MemberIds: [],
27
+ matchContext: null,
28
+ matchContextPromise: null,
29
+ bootstrapShareId: null,
30
+ bootstrapRoomCode: null,
31
+ bootstrapRoomRole: null,
32
+ bootstrapRoomToken: null,
33
+ bootstrapWsUrl: null,
34
+ bootstrapPlayerName: null,
35
+ bootstrapPeerId: null,
36
+ bootstrapMaxPlayers: null,
37
+ bootstrapReceived: false,
38
+ isInitialized: false,
39
+ isAutoInitializing: false,
40
+ autoInitPromise: null,
41
+ bootstrapRequestPromise: null,
42
+ parentOrigin: null,
43
+ sessionStartPromise: null,
44
+ lastAutoJoinShareId: null,
45
+ lastAutoJoinRoomCode: null,
46
+ mpSocket: null,
47
+ mpReconnectTimer: null,
48
+ mpReconnectAttempts: 0,
49
+ mpExpectedClose: false,
50
+ mpRoom: null,
51
+ mpLastJoinRequest: null,
52
+ mpPeers: /* @__PURE__ */ new Map(),
53
+ mpHandlers: /* @__PURE__ */ new Map(),
54
+ mpLastSeqByPeer: /* @__PURE__ */ new Map(),
55
+ mpViewerOverride: false
56
+ };
57
+
58
+ // src/utils.ts
59
+ function isBrowser() {
60
+ return typeof window !== "undefined" && typeof document !== "undefined";
61
+ }
62
+ function warn(message, ...rest) {
63
+ console.warn("[GameHubSDK] " + message, ...rest);
64
+ }
65
+ function error(message, ...rest) {
66
+ console.error("[GameHubSDK] " + message, ...rest);
67
+ }
68
+ function unwrapResult(result) {
69
+ if (!result) return null;
70
+ if (result.success && result.data) return result.data;
71
+ return result;
72
+ }
73
+ function extractShareIdFromLink(link) {
74
+ try {
75
+ const parsed = new URL(link, window.location.origin);
76
+ const mp = parsed.searchParams.get("mp");
77
+ if (mp) return mp;
78
+ return parsed.pathname.split("/").pop() || null;
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ function readQueryParam(name) {
84
+ try {
85
+ const params = new URLSearchParams(window.location.search);
86
+ return params.get(name);
87
+ } catch {
88
+ const match = window.location.search.match(
89
+ new RegExp("[?&]" + name + "=([^&]+)")
90
+ );
91
+ return match ? decodeURIComponent(match[1]) : null;
92
+ }
93
+ }
94
+ function readCsvQueryParam(name) {
95
+ const raw = readQueryParam(name) || "";
96
+ return raw.split(",").map((value) => value.trim()).filter(Boolean);
97
+ }
98
+
99
+ // src/bridge.ts
100
+ function mergeBootstrapConfig(config = {}) {
101
+ if (!config || typeof config !== "object") return;
102
+ if (typeof config.gameSlug === "string" && config.gameSlug.trim()) {
103
+ state.gameSlug = config.gameSlug.trim();
104
+ }
105
+ if (typeof config.authToken === "string") {
106
+ state.authToken = config.authToken;
107
+ } else if (config.authToken === null) {
108
+ state.authToken = null;
109
+ }
110
+ if (typeof config.leagueId === "string" && config.leagueId.trim()) {
111
+ state.leagueId = config.leagueId.trim();
112
+ } else if (config.leagueId === null) {
113
+ state.leagueId = null;
114
+ }
115
+ if (typeof config.gameId === "string" && config.gameId.trim()) {
116
+ state.gameId = config.gameId.trim();
117
+ } else if (config.gameId === null) {
118
+ state.gameId = null;
119
+ }
120
+ if (typeof config.matchId === "string" && config.matchId.trim()) {
121
+ state.matchId = config.matchId.trim();
122
+ } else if (config.matchId === null) {
123
+ state.matchId = null;
124
+ }
125
+ if (typeof config.participant1Id === "string" && config.participant1Id.trim()) {
126
+ state.participant1Id = config.participant1Id.trim();
127
+ } else if (config.participant1Id === null) {
128
+ state.participant1Id = null;
129
+ }
130
+ if (typeof config.participant2Id === "string" && config.participant2Id.trim()) {
131
+ state.participant2Id = config.participant2Id.trim();
132
+ } else if (config.participant2Id === null) {
133
+ state.participant2Id = null;
134
+ }
135
+ if (Array.isArray(config.participant1MemberIds)) {
136
+ state.participant1MemberIds = config.participant1MemberIds.filter(Boolean);
137
+ }
138
+ if (Array.isArray(config.participant2MemberIds)) {
139
+ state.participant2MemberIds = config.participant2MemberIds.filter(Boolean);
140
+ }
141
+ if (typeof config.playerName === "string" && config.playerName.trim()) {
142
+ state.bootstrapPlayerName = config.playerName.trim();
143
+ } else if (config.playerName === null) {
144
+ state.bootstrapPlayerName = null;
145
+ }
146
+ if (typeof config.peerId === "string" && config.peerId.trim()) {
147
+ state.bootstrapPeerId = config.peerId.trim();
148
+ } else if (config.peerId === null) {
149
+ state.bootstrapPeerId = null;
150
+ }
151
+ if (config.room && typeof config.room === "object") {
152
+ const room = config.room;
153
+ if (typeof room.roomCode === "string" && room.roomCode.trim()) {
154
+ state.bootstrapRoomCode = room.roomCode.trim().toUpperCase();
155
+ } else if (room.roomCode === null) {
156
+ state.bootstrapRoomCode = null;
157
+ }
158
+ if (typeof room.shareId === "string" && room.shareId.trim()) {
159
+ state.bootstrapShareId = room.shareId.trim();
160
+ } else if (room.shareId === null) {
161
+ state.bootstrapShareId = null;
162
+ }
163
+ if (typeof room.maxPlayers === "number" && Number.isFinite(room.maxPlayers)) {
164
+ state.bootstrapMaxPlayers = room.maxPlayers;
165
+ } else if (room.maxPlayers === null) {
166
+ state.bootstrapMaxPlayers = null;
167
+ }
168
+ if (typeof room.role === "string" && room.role.trim()) {
169
+ state.bootstrapRoomRole = room.role.trim();
170
+ } else if (room.role === null) {
171
+ state.bootstrapRoomRole = null;
172
+ }
173
+ if (typeof room.roomToken === "string" && room.roomToken.trim()) {
174
+ state.bootstrapRoomToken = room.roomToken.trim();
175
+ } else if (room.roomToken === null) {
176
+ state.bootstrapRoomToken = null;
177
+ }
178
+ if (typeof room.wsUrl === "string" && room.wsUrl.trim()) {
179
+ state.bootstrapWsUrl = room.wsUrl.trim();
180
+ } else if (room.wsUrl === null) {
181
+ state.bootstrapWsUrl = null;
182
+ }
183
+ } else if (config.room === null) {
184
+ state.bootstrapRoomCode = null;
185
+ state.bootstrapShareId = null;
186
+ state.bootstrapMaxPlayers = null;
187
+ state.bootstrapRoomRole = null;
188
+ state.bootstrapRoomToken = null;
189
+ state.bootstrapWsUrl = null;
190
+ }
191
+ }
192
+ function requestBootstrapFromParent() {
193
+ if (!isBrowser() || window.parent === window) {
194
+ return Promise.resolve(null);
195
+ }
196
+ if (state.bootstrapReceived) {
197
+ return Promise.resolve({
198
+ gameSlug: state.gameSlug,
199
+ authToken: state.authToken,
200
+ leagueId: state.leagueId,
201
+ gameId: state.gameId,
202
+ matchId: state.matchId,
203
+ participant1Id: state.participant1Id,
204
+ participant2Id: state.participant2Id,
205
+ participant1MemberIds: state.participant1MemberIds,
206
+ participant2MemberIds: state.participant2MemberIds,
207
+ playerName: state.bootstrapPlayerName,
208
+ peerId: state.bootstrapPeerId,
209
+ room: state.bootstrapRoomCode ? {
210
+ roomCode: state.bootstrapRoomCode,
211
+ shareId: state.bootstrapShareId,
212
+ maxPlayers: state.bootstrapMaxPlayers,
213
+ role: state.bootstrapRoomRole,
214
+ roomToken: state.bootstrapRoomToken,
215
+ wsUrl: state.bootstrapWsUrl
216
+ } : null
217
+ });
218
+ }
219
+ if (state.bootstrapRequestPromise) {
220
+ return state.bootstrapRequestPromise;
221
+ }
222
+ state.bootstrapRequestPromise = new Promise(
223
+ (resolve) => {
224
+ const messageId = Date.now().toString();
225
+ let settled = false;
226
+ let timeoutId = null;
227
+ const handler = (event) => {
228
+ if (event.data && event.data.type === MESSAGE_PREFIX + "_BOOTSTRAP" && event.data.payload) {
229
+ if (event.data.messageId && event.data.messageId !== messageId) {
230
+ return;
231
+ }
232
+ if (settled) return;
233
+ settled = true;
234
+ window.removeEventListener("message", handler);
235
+ if (timeoutId) clearTimeout(timeoutId);
236
+ state.parentOrigin = event.origin;
237
+ state.bootstrapReceived = true;
238
+ mergeBootstrapConfig(event.data.payload);
239
+ resolve(event.data.payload);
240
+ }
241
+ };
242
+ window.addEventListener("message", handler);
243
+ window.parent.postMessage(
244
+ {
245
+ type: MESSAGE_PREFIX + "_BOOTSTRAP_REQUEST",
246
+ messageId
247
+ },
248
+ "*"
249
+ );
250
+ timeoutId = setTimeout(() => {
251
+ if (settled) return;
252
+ settled = true;
253
+ window.removeEventListener("message", handler);
254
+ resolve(null);
255
+ }, PARENT_REQUEST_TIMEOUT_MS);
256
+ }
257
+ ).finally(() => {
258
+ state.bootstrapRequestPromise = null;
259
+ });
260
+ return state.bootstrapRequestPromise;
261
+ }
262
+ function getAuthTokenFromParent() {
263
+ return new Promise((resolve) => {
264
+ if (!isBrowser() || window.parent === window) {
265
+ resolve(null);
266
+ return;
267
+ }
268
+ const messageId = Date.now().toString();
269
+ let settled = false;
270
+ let timeoutId = null;
271
+ const handler = (event) => {
272
+ if (event.data && event.data.type === MESSAGE_PREFIX + "_AUTH_RESPONSE" && event.data.messageId === messageId) {
273
+ if (settled) return;
274
+ settled = true;
275
+ window.removeEventListener("message", handler);
276
+ if (timeoutId) clearTimeout(timeoutId);
277
+ state.parentOrigin = event.origin;
278
+ if (event.data.leagueId) state.leagueId = event.data.leagueId;
279
+ if (event.data.gameId) state.gameId = event.data.gameId;
280
+ if (event.data.matchId) state.matchId = event.data.matchId;
281
+ if (event.data.participant1Id)
282
+ state.participant1Id = event.data.participant1Id;
283
+ if (event.data.participant2Id)
284
+ state.participant2Id = event.data.participant2Id;
285
+ if (Array.isArray(event.data.participant1MemberIds))
286
+ state.participant1MemberIds = event.data.participant1MemberIds.filter(Boolean);
287
+ if (Array.isArray(event.data.participant2MemberIds))
288
+ state.participant2MemberIds = event.data.participant2MemberIds.filter(Boolean);
289
+ resolve(event.data.token || null);
1214
290
  }
1215
- Multiplayer.getPeers = getPeers;
1216
- /** @returns whether the WebSocket is currently open. */
1217
- function isConnected() {
1218
- const s = GameHub.State.mpSocket;
1219
- return Boolean(s && s.readyState === WebSocket.OPEN);
291
+ };
292
+ window.addEventListener("message", handler);
293
+ window.parent.postMessage(
294
+ { type: MESSAGE_PREFIX + "_AUTH_REQUEST", messageId },
295
+ "*"
296
+ );
297
+ timeoutId = setTimeout(() => {
298
+ if (settled) return;
299
+ settled = true;
300
+ window.removeEventListener("message", handler);
301
+ resolve(null);
302
+ }, PARENT_REQUEST_TIMEOUT_MS);
303
+ });
304
+ }
305
+ function sendToParent(type, data) {
306
+ if (!isBrowser() || window.parent === window) return;
307
+ window.parent.postMessage(
308
+ {
309
+ type: MESSAGE_PREFIX + "_" + type,
310
+ gameSlug: state.gameSlug,
311
+ ...data
312
+ },
313
+ state.parentOrigin || "*"
314
+ );
315
+ }
316
+
317
+ // src/api-client.ts
318
+ async function apiRequest(endpoint, options = {}) {
319
+ const url = state.apiBase + endpoint;
320
+ const headers = {
321
+ "Content-Type": "application/json",
322
+ ...options.headers || {}
323
+ };
324
+ if (state.authToken) {
325
+ headers.Authorization = "Bearer " + state.authToken;
326
+ }
327
+ const response = await fetch(url, {
328
+ ...options,
329
+ credentials: options.credentials || "same-origin",
330
+ headers,
331
+ body: options.body ? JSON.stringify(options.body) : void 0
332
+ });
333
+ return response.json();
334
+ }
335
+
336
+ // src/multiplayer.ts
337
+ function emit(eventName, payload) {
338
+ const handlers = state.mpHandlers.get(eventName);
339
+ if (handlers) {
340
+ handlers.forEach((handler) => {
341
+ try {
342
+ handler(payload);
343
+ } catch (err) {
344
+ error("Multiplayer handler error:", err);
1220
345
  }
1221
- Multiplayer.isConnected = isConnected;
1222
- })(Multiplayer = GameHub.Multiplayer || (GameHub.Multiplayer = {}));
1223
- })(GameHub || (GameHub = {}));
1224
- /**
1225
- * SDK discovery + auto-initialisation.
1226
- *
1227
- * Detects the API base URL (from the `<script>` tag or the page location),
1228
- * the active game slug, and the league/match context from the URL. Then
1229
- * exchanges a few postMessages with the host to pick up an auth token and the
1230
- * full bootstrap payload before opening a session and auto-joining any
1231
- * pending multiplayer room.
1232
- */
1233
- var GameHub;
1234
- (function (GameHub) {
1235
- var Init;
1236
- (function (Init) {
1237
- /**
1238
- * One-off environment detection. Should be called exactly once at SDK boot
1239
- * time, before any other Init function.
1240
- */
1241
- function detectEnvironment() {
1242
- const S = GameHub.State;
1243
- S.sdkOrigin = window.location.origin;
1244
- // Detect when the game is being served under /games/<slug>/ or
1245
- // /uploaded-games/<slug>/ — this lets us infer both the slug and the
1246
- // mount point (which we use to build the API base URL).
1247
- const runtimePathMatch = window.location.pathname.match(/^(.*)\/(?:uploaded-games|games)\/([a-z0-9-]+)(?:\/|$)/i);
1248
- let detectedSlug = null;
1249
- if (runtimePathMatch) {
1250
- S.runtimeBasePath = runtimePathMatch[1] || '';
1251
- detectedSlug = runtimePathMatch[2] || null;
1252
- }
1253
- // Pull league/match context off the URL if present. The host may still
1254
- // override these later via postMessage.
1255
- S.leagueId = GameHub.Utils.readQueryParam('leagueId');
1256
- S.gameId = GameHub.Utils.readQueryParam('gameId');
1257
- S.matchId = GameHub.Utils.readQueryParam('matchId');
1258
- S.participant1Id = GameHub.Utils.readQueryParam('participant1Id');
1259
- S.participant2Id = GameHub.Utils.readQueryParam('participant2Id');
1260
- S.participant1MemberIds = GameHub.Utils.readCsvQueryParam('participant1MemberIds');
1261
- S.participant2MemberIds = GameHub.Utils.readCsvQueryParam('participant2MemberIds');
1262
- // Locate our own <script> tag so we can honour `data-game-slug` and
1263
- // resolve the path prefix (needed when served from a subpath like /app).
1264
- const scripts = document.getElementsByTagName('script');
1265
- for (let i = 0; i < scripts.length; i++) {
1266
- const src = scripts[i].src;
1267
- if (!src.includes('gamehub-sdk.js'))
1268
- continue;
1269
- try {
1270
- const parsedSrc = new URL(src, window.location.origin);
1271
- S.sdkOrigin = parsedSrc.origin;
1272
- const match = parsedSrc.pathname.match(/(.*)\/sdk\/gamehub-sdk\.js$/);
1273
- S.sdkPathPrefix = match ? match[1] || '' : '';
1274
- }
1275
- catch {
1276
- const match = src.match(/(.*)\/sdk\/gamehub-sdk\.js/);
1277
- if (match) {
1278
- const fallbackUrl = new URL(match[1], window.location.origin);
1279
- S.sdkOrigin = fallbackUrl.origin;
1280
- S.sdkPathPrefix = fallbackUrl.pathname || '';
1281
- }
1282
- }
1283
- const slugAttr = scripts[i].getAttribute('data-game-slug');
1284
- if (slugAttr)
1285
- detectedSlug = slugAttr;
1286
- break;
1287
- }
1288
- // Final fallback: look for a games slug in the path even if we didn't
1289
- // match the full pattern earlier.
1290
- if (!detectedSlug) {
1291
- const pathMatch = window.location.pathname.match(/\/(?:uploaded-games|games)\/([a-z0-9-]+)\//i);
1292
- if (pathMatch)
1293
- detectedSlug = pathMatch[1];
1294
- }
1295
- const effectiveBasePath = S.sdkPathPrefix || S.runtimeBasePath || '';
1296
- S.apiBase = S.sdkOrigin + effectiveBasePath + '/api';
1297
- S.gameSlug = detectedSlug;
346
+ });
347
+ }
348
+ const allHandlers = state.mpHandlers.get("*");
349
+ if (allHandlers) {
350
+ allHandlers.forEach((handler) => {
351
+ try {
352
+ handler({ eventName, payload });
353
+ } catch (err) {
354
+ error("Multiplayer * handler error:", err);
1298
355
  }
1299
- Init.detectEnvironment = detectEnvironment;
1300
- /**
1301
- * Returns the share ID we should auto-join on boot, if any. Bootstrap takes
1302
- * priority over URL params so hosts can override a stale link.
1303
- */
1304
- function getPendingShareId() {
1305
- if (GameHub.State.bootstrapShareId)
1306
- return GameHub.State.bootstrapShareId;
1307
- return GameHub.Utils.readQueryParam('mp');
356
+ });
357
+ }
358
+ }
359
+ function clearSocket() {
360
+ if (state.mpReconnectTimer) {
361
+ clearTimeout(state.mpReconnectTimer);
362
+ state.mpReconnectTimer = null;
363
+ }
364
+ if (state.mpSocket) {
365
+ try {
366
+ state.mpSocket.onopen = null;
367
+ state.mpSocket.onclose = null;
368
+ state.mpSocket.onmessage = null;
369
+ state.mpSocket.onerror = null;
370
+ state.mpSocket.close();
371
+ } catch {
372
+ }
373
+ }
374
+ state.mpSocket = null;
375
+ }
376
+ function connect(joinInfo) {
377
+ clearSocket();
378
+ const wsBase = joinInfo.wsUrl.replace(/\/+$/, "");
379
+ const wsUrl = wsBase + "?roomToken=" + encodeURIComponent(joinInfo.roomToken) + "&gameSlug=" + encodeURIComponent(joinInfo.gameSlug) + "&sdk=2.x";
380
+ state.mpExpectedClose = false;
381
+ state.mpSocket = new WebSocket(wsUrl);
382
+ state.mpSocket.onopen = () => {
383
+ state.mpReconnectAttempts = 0;
384
+ emit("connected", {
385
+ roomCode: joinInfo.roomCode,
386
+ peerId: joinInfo.peerId
387
+ });
388
+ };
389
+ state.mpSocket.onmessage = (event) => {
390
+ let message = null;
391
+ try {
392
+ message = JSON.parse(event.data);
393
+ } catch {
394
+ return;
395
+ }
396
+ if (!message || !message.type) return;
397
+ if (message.type === "system") {
398
+ if (message.eventName === "room_joined") {
399
+ state.mpPeers.clear();
400
+ const peers = message.payload?.peers || [];
401
+ peers.forEach((peer) => {
402
+ if (peer && peer.peerId) state.mpPeers.set(peer.peerId, peer);
403
+ });
1308
404
  }
1309
- /** Same as {@link getPendingShareId} but for room codes. */
1310
- function getPendingRoomCode() {
1311
- if (GameHub.State.bootstrapRoomCode)
1312
- return GameHub.State.bootstrapRoomCode;
1313
- const roomCode = GameHub.Utils.readQueryParam('roomCode');
1314
- return roomCode ? roomCode.trim().toUpperCase() : null;
405
+ if (message.eventName === "peer_joined" && message.payload?.peerId) {
406
+ state.mpPeers.set(message.payload.peerId, message.payload);
1315
407
  }
1316
- function getPendingRoomRole() {
1317
- if (GameHub.State.bootstrapRoomRole)
1318
- return GameHub.State.bootstrapRoomRole;
1319
- const role = GameHub.Utils.readQueryParam('roomRole');
1320
- return role ? role.trim() : null;
408
+ if (message.eventName === "peer_left" && message.payload?.peerId) {
409
+ state.mpPeers.delete(message.payload.peerId);
1321
410
  }
1322
- function getPendingRoomToken() {
1323
- if (GameHub.State.bootstrapRoomToken)
1324
- return GameHub.State.bootstrapRoomToken;
1325
- const roomToken = GameHub.Utils.readQueryParam('roomToken');
1326
- return roomToken ? roomToken.trim() : null;
411
+ if (message.eventName === "room_closed") {
412
+ emit("room_left", { reason: "room_closed" });
413
+ clearSocket();
1327
414
  }
1328
- function getPendingWsUrl() {
1329
- if (GameHub.State.bootstrapWsUrl)
1330
- return GameHub.State.bootstrapWsUrl;
1331
- const wsUrl = GameHub.Utils.readQueryParam('wsUrl');
1332
- return wsUrl ? wsUrl.trim() : null;
415
+ emit(message.eventName, message.payload || {});
416
+ return;
417
+ }
418
+ if (message.type === "game_event") {
419
+ const isRetained = message.retained === true;
420
+ if (!isRetained && typeof message.seq === "number" && typeof message.fromPeerId === "string") {
421
+ const last = state.mpLastSeqByPeer.get(message.fromPeerId) || 0;
422
+ if (message.seq <= last) return;
423
+ state.mpLastSeqByPeer.set(message.fromPeerId, message.seq);
1333
424
  }
1334
- /** Same as {@link getPendingShareId} but for the host-preferred display name. */
1335
- function getPendingPlayerName() {
1336
- if (GameHub.State.bootstrapPlayerName)
1337
- return GameHub.State.bootstrapPlayerName;
1338
- const playerName = GameHub.Utils.readQueryParam('playerName');
1339
- return playerName ? playerName.trim() : undefined;
425
+ emit("message", {
426
+ roomCode: message.roomCode,
427
+ fromPeerId: message.fromPeerId,
428
+ eventName: message.eventName,
429
+ payload: message.payload,
430
+ seq: message.seq,
431
+ sentAt: message.sentAt,
432
+ retained: isRetained
433
+ });
434
+ emit(message.eventName, {
435
+ roomCode: message.roomCode,
436
+ fromPeerId: message.fromPeerId,
437
+ payload: message.payload,
438
+ seq: message.seq,
439
+ sentAt: message.sentAt,
440
+ retained: isRetained
441
+ });
442
+ }
443
+ };
444
+ state.mpSocket.onclose = () => {
445
+ emit("disconnected", { roomCode: joinInfo.roomCode });
446
+ if (state.mpExpectedClose || !state.mpLastJoinRequest) return;
447
+ if (state.mpReconnectAttempts >= MP_MAX_RECONNECT_ATTEMPTS) return;
448
+ state.mpReconnectAttempts += 1;
449
+ const delay = Math.min(
450
+ 1e3 * Math.pow(2, state.mpReconnectAttempts - 1),
451
+ MP_MAX_RECONNECT_DELAY_MS
452
+ );
453
+ emit("reconnecting", {
454
+ attempts: state.mpReconnectAttempts,
455
+ delayMs: delay
456
+ });
457
+ state.mpReconnectTimer = setTimeout(() => {
458
+ if (!state.mpLastJoinRequest) return;
459
+ connect(state.mpLastJoinRequest);
460
+ }, delay);
461
+ };
462
+ state.mpSocket.onerror = () => {
463
+ };
464
+ }
465
+ async function createRoom(options = {}) {
466
+ await ensureInitialized();
467
+ if (!state.gameSlug) {
468
+ return { success: false, error: "Game slug is required" };
469
+ }
470
+ const result = await apiRequest("/multiplayer/rooms/create", {
471
+ method: "POST",
472
+ body: {
473
+ gameSlug: state.gameSlug,
474
+ maxPlayers: options.maxPlayers,
475
+ passcode: options.passcode
476
+ }
477
+ });
478
+ const data = unwrapResult(result);
479
+ if (!result.success || !data?.roomToken) {
480
+ return {
481
+ success: false,
482
+ error: result.error?.message || "Failed to create room"
483
+ };
484
+ }
485
+ state.mpRoom = {
486
+ roomCode: data.roomCode,
487
+ shareId: data.shareId,
488
+ shareUrl: data.shareUrl,
489
+ peerId: data.peerId,
490
+ role: data.role,
491
+ gameSlug: data.gameSlug,
492
+ roomToken: data.roomToken,
493
+ wsUrl: data.wsUrl
494
+ };
495
+ state.mpLastJoinRequest = {
496
+ roomCode: data.roomCode,
497
+ roomToken: data.roomToken,
498
+ wsUrl: data.wsUrl,
499
+ gameSlug: data.gameSlug,
500
+ peerId: data.peerId
501
+ };
502
+ connect(state.mpLastJoinRequest);
503
+ return {
504
+ success: true,
505
+ roomCode: data.roomCode,
506
+ shareId: data.shareId,
507
+ shareUrl: data.shareUrl,
508
+ peerId: data.peerId,
509
+ roomToken: data.roomToken
510
+ };
511
+ }
512
+ async function joinRoom(roomCode, options = {}) {
513
+ await ensureInitialized();
514
+ if (!state.gameSlug) {
515
+ return { success: false, error: "Game slug is required" };
516
+ }
517
+ const result = await apiRequest("/multiplayer/rooms/join-token", {
518
+ method: "POST",
519
+ body: {
520
+ gameSlug: state.gameSlug,
521
+ roomCode,
522
+ passcode: options.passcode,
523
+ displayName: options.displayName
524
+ }
525
+ });
526
+ const data = unwrapResult(result);
527
+ if (!result.success || !data?.roomToken) {
528
+ return {
529
+ success: false,
530
+ error: result.error?.message || "Failed to join room"
531
+ };
532
+ }
533
+ const resolvedRole = options.asViewer && data.role !== "host" ? "viewer" : data.role;
534
+ state.mpViewerOverride = resolvedRole === "viewer";
535
+ state.mpRoom = {
536
+ roomCode: data.roomCode,
537
+ shareId: data.shareId,
538
+ peerId: data.peerId,
539
+ role: resolvedRole,
540
+ gameSlug: data.gameSlug,
541
+ roomToken: data.roomToken,
542
+ wsUrl: data.wsUrl
543
+ };
544
+ state.mpLastJoinRequest = {
545
+ roomCode: data.roomCode,
546
+ roomToken: data.roomToken,
547
+ wsUrl: data.wsUrl,
548
+ gameSlug: data.gameSlug,
549
+ peerId: data.peerId
550
+ };
551
+ connect(state.mpLastJoinRequest);
552
+ return {
553
+ success: true,
554
+ roomCode: data.roomCode,
555
+ shareId: data.shareId,
556
+ peerId: data.peerId,
557
+ roomToken: data.roomToken
558
+ };
559
+ }
560
+ async function joinRoomByLink(link, options = {}) {
561
+ await ensureInitialized();
562
+ if (!state.gameSlug) {
563
+ return { success: false, error: "Game slug is required" };
564
+ }
565
+ const shareId = extractShareIdFromLink(link);
566
+ if (!shareId) {
567
+ return { success: false, error: "Invalid multiplayer link" };
568
+ }
569
+ const result = await apiRequest("/multiplayer/rooms/join-token", {
570
+ method: "POST",
571
+ body: {
572
+ gameSlug: state.gameSlug,
573
+ shareId,
574
+ passcode: options.passcode,
575
+ displayName: options.displayName
576
+ }
577
+ });
578
+ const data = unwrapResult(result);
579
+ if (!result.success || !data?.roomToken) {
580
+ return {
581
+ success: false,
582
+ error: result.error?.message || "Failed to join room by link"
583
+ };
584
+ }
585
+ const resolvedRole = options.asViewer && data.role !== "host" ? "viewer" : data.role;
586
+ state.mpViewerOverride = resolvedRole === "viewer";
587
+ state.mpRoom = {
588
+ roomCode: data.roomCode,
589
+ shareId: data.shareId,
590
+ peerId: data.peerId,
591
+ role: resolvedRole,
592
+ gameSlug: data.gameSlug,
593
+ roomToken: data.roomToken,
594
+ wsUrl: data.wsUrl
595
+ };
596
+ state.mpLastJoinRequest = {
597
+ roomCode: data.roomCode,
598
+ roomToken: data.roomToken,
599
+ wsUrl: data.wsUrl,
600
+ gameSlug: data.gameSlug,
601
+ peerId: data.peerId
602
+ };
603
+ connect(state.mpLastJoinRequest);
604
+ return {
605
+ success: true,
606
+ roomCode: data.roomCode,
607
+ shareId: data.shareId,
608
+ peerId: data.peerId,
609
+ roomToken: data.roomToken
610
+ };
611
+ }
612
+ async function leaveRoom(reason = "left") {
613
+ if (state.mpRoom && state.mpRoom.role === "host" && state.mpRoom.roomToken) {
614
+ try {
615
+ await apiRequest(
616
+ "/multiplayer/rooms/" + encodeURIComponent(state.mpRoom.roomCode) + "/close",
617
+ {
618
+ method: "POST",
619
+ body: { roomToken: state.mpRoom.roomToken }
620
+ }
621
+ );
622
+ } catch {
623
+ }
624
+ }
625
+ state.mpExpectedClose = true;
626
+ clearSocket();
627
+ state.mpRoom = null;
628
+ state.mpLastJoinRequest = null;
629
+ state.mpPeers.clear();
630
+ state.mpLastSeqByPeer.clear();
631
+ state.mpViewerOverride = false;
632
+ emit("room_left", { reason });
633
+ }
634
+ function send(eventName, payload = {}, options = {}) {
635
+ if (state.mpViewerOverride) {
636
+ warn("multiplayer.send ignored: peer is a viewer");
637
+ return false;
638
+ }
639
+ const socket = state.mpSocket;
640
+ if (!socket || socket.readyState !== WebSocket.OPEN) {
641
+ return false;
642
+ }
643
+ const frame = { eventName, payload };
644
+ if (options.retain) {
645
+ frame.retain = true;
646
+ if (options.retainKey) frame.retainKey = options.retainKey;
647
+ }
648
+ socket.send(JSON.stringify(frame));
649
+ return true;
650
+ }
651
+ function broadcast(eventName, payload = {}, options = {}) {
652
+ if (!isHost()) {
653
+ warn("multiplayer.broadcast ignored: peer is not the host");
654
+ return false;
655
+ }
656
+ return send(eventName, payload, options);
657
+ }
658
+ function getRole() {
659
+ return state.mpRoom ? state.mpRoom.role : null;
660
+ }
661
+ function isHost() {
662
+ return state.mpRoom?.role === "host";
663
+ }
664
+ function isViewer() {
665
+ return state.mpViewerOverride === true;
666
+ }
667
+ function selfId() {
668
+ return state.mpRoom ? state.mpRoom.peerId : null;
669
+ }
670
+ function on(eventName, handler) {
671
+ const handlers = state.mpHandlers;
672
+ if (!handlers.has(eventName)) {
673
+ handlers.set(eventName, /* @__PURE__ */ new Set());
674
+ }
675
+ handlers.get(eventName).add(handler);
676
+ return () => {
677
+ const set = handlers.get(eventName);
678
+ if (!set) return;
679
+ set.delete(handler);
680
+ if (set.size === 0) handlers.delete(eventName);
681
+ };
682
+ }
683
+ function getRoom() {
684
+ return state.mpRoom ? { ...state.mpRoom } : null;
685
+ }
686
+ function getPeers() {
687
+ return Array.from(state.mpPeers.values());
688
+ }
689
+ function isConnected() {
690
+ const s = state.mpSocket;
691
+ return Boolean(s && s.readyState === WebSocket.OPEN);
692
+ }
693
+
694
+ // src/match-context.ts
695
+ async function fetchMatchContext() {
696
+ if (!state.leagueId || !state.matchId) return null;
697
+ if (state.matchContext) return state.matchContext;
698
+ if (state.matchContextPromise) return await state.matchContextPromise;
699
+ state.matchContextPromise = apiRequest(
700
+ "/leagues/" + encodeURIComponent(state.leagueId) + "/matches/" + encodeURIComponent(state.matchId),
701
+ { method: "GET" }
702
+ ).then((result) => {
703
+ const data = unwrapResult(result);
704
+ if (result?.success && data) {
705
+ state.matchContext = data;
706
+ state.participant1Id = data.participant1?.participantId || state.participant1Id;
707
+ state.participant2Id = data.participant2?.participantId || state.participant2Id;
708
+ state.participant1MemberIds = Array.isArray(data.participant1?.members) ? data.participant1.members.map((member) => member?.leaguePlayerId).filter(Boolean) : state.participant1MemberIds;
709
+ state.participant2MemberIds = Array.isArray(data.participant2?.members) ? data.participant2.members.map((member) => member?.leaguePlayerId).filter(Boolean) : state.participant2MemberIds;
710
+ return state.matchContext;
711
+ }
712
+ return null;
713
+ }).catch(() => null).finally(() => {
714
+ state.matchContextPromise = null;
715
+ });
716
+ return await state.matchContextPromise;
717
+ }
718
+
719
+ // src/session.ts
720
+ async function startSession() {
721
+ if (!state.gameSlug) return { success: false, error: "Game slug not set" };
722
+ const isLeagueMatchSession = Boolean(
723
+ state.leagueId && state.gameId && state.matchId
724
+ );
725
+ if (!state.authToken && !isLeagueMatchSession) {
726
+ return { success: false, error: "User not authenticated" };
727
+ }
728
+ if (state.sessionToken) return { success: true, token: state.sessionToken };
729
+ try {
730
+ let endpoint = "/sessions/start";
731
+ let body = { gameSlug: state.gameSlug };
732
+ if (state.leagueId && state.gameId && state.matchId) {
733
+ endpoint = "/leagues/" + state.leagueId + "/matches/" + state.matchId + "/session";
734
+ body = { gameId: state.gameId };
735
+ } else if (state.leagueId && state.gameId) {
736
+ endpoint = "/leagues/" + state.leagueId + "/sessions";
737
+ body = { gameId: state.gameId };
738
+ }
739
+ const result = await apiRequest(endpoint, {
740
+ method: "POST",
741
+ body
742
+ });
743
+ const data = unwrapResult(result);
744
+ if (result.success || data?.token) {
745
+ state.sessionToken = data?.token || result?.token || null;
746
+ sendToParent("SESSION_STARTED", { token: state.sessionToken });
747
+ return { success: true, token: state.sessionToken };
748
+ }
749
+ return {
750
+ success: false,
751
+ error: result.error?.message || "Failed to start session"
752
+ };
753
+ } catch (err) {
754
+ return { success: false, error: err.message };
755
+ }
756
+ }
757
+ async function submitScore(score, meta = {}) {
758
+ await ensureInitialized();
759
+ if (!state.isInitialized) {
760
+ return {
761
+ success: false,
762
+ error: "SDK could not initialize. Is game slug set?"
763
+ };
764
+ }
765
+ if (state.mpRoom && state.mpRoom.role !== "host") {
766
+ warn("submitScore skipped: only the multiplayer host may submit scores");
767
+ return { success: true, skipped: true };
768
+ }
769
+ if (!state.sessionToken) {
770
+ if (state.sessionStartPromise) {
771
+ await state.sessionStartPromise;
772
+ } else {
773
+ const sessionResult = await startSession();
774
+ if (!sessionResult.success) {
775
+ return {
776
+ success: false,
777
+ error: sessionResult.error || "Could not start session"
778
+ };
1340
779
  }
1341
- /**
1342
- * Resolve the peerId for "this player" — bootstrap wins over the URL so the
1343
- * host can correct a stale link. Populated opportunistically so games know
1344
- * their assigned peerId before the multiplayer WS has joined.
1345
- */
1346
- function seedPeerIdFromUrl() {
1347
- const S = GameHub.State;
1348
- if (S.bootstrapPeerId)
1349
- return;
1350
- const fromUrl = GameHub.Utils.readQueryParam('peerId');
1351
- if (fromUrl)
1352
- S.bootstrapPeerId = fromUrl.trim();
780
+ }
781
+ }
782
+ if (!state.sessionToken) {
783
+ return {
784
+ success: false,
785
+ error: "No active session. User may not be authenticated."
786
+ };
787
+ }
788
+ if (typeof score !== "number" || score < 0) {
789
+ return { success: false, error: "Score must be a non-negative number" };
790
+ }
791
+ try {
792
+ const result = await apiRequest("/sessions/submit", {
793
+ method: "POST",
794
+ body: {
795
+ token: state.sessionToken,
796
+ score: Math.floor(score),
797
+ meta
1353
798
  }
1354
- function resumePendingRoomFromBootstrap() {
1355
- const S = GameHub.State;
1356
- const roomCode = getPendingRoomCode();
1357
- const roomToken = getPendingRoomToken();
1358
- const wsUrl = getPendingWsUrl();
1359
- const peerId = S.bootstrapPeerId ||
1360
- GameHub.Utils.readQueryParam('peerId')?.trim() ||
1361
- null;
1362
- if (!S.gameSlug || !roomCode || !roomToken || !wsUrl || !peerId) {
1363
- return false;
1364
- }
1365
- const role = getPendingRoomRole() || 'player';
1366
- S.mpViewerOverride = role === 'viewer';
1367
- S.mpRoom = {
1368
- roomCode,
1369
- shareId: S.bootstrapShareId || '',
1370
- peerId,
1371
- role,
1372
- gameSlug: S.gameSlug,
1373
- roomToken,
1374
- wsUrl,
1375
- };
1376
- S.mpLastJoinRequest = {
1377
- roomCode,
1378
- roomToken,
1379
- wsUrl,
1380
- gameSlug: S.gameSlug,
1381
- peerId,
1382
- };
1383
- GameHub.Multiplayer.connect(S.mpLastJoinRequest);
1384
- return true;
799
+ });
800
+ const data = unwrapResult(result);
801
+ if (result.success || data?.accepted) {
802
+ sendToParent("SCORE_SUBMITTED", {
803
+ score,
804
+ accepted: data?.accepted,
805
+ timeTaken: data?.timeTaken
806
+ });
807
+ return {
808
+ success: true,
809
+ accepted: data?.accepted,
810
+ timeTaken: data?.timeTaken
811
+ };
812
+ }
813
+ return {
814
+ success: false,
815
+ error: result.error?.message || "Score rejected"
816
+ };
817
+ } catch (err) {
818
+ return { success: false, error: err.message };
819
+ }
820
+ }
821
+ async function submitMatchScore(score, meta = {}) {
822
+ if (!state.matchId) {
823
+ return {
824
+ success: false,
825
+ error: "No matchId found for this game session"
826
+ };
827
+ }
828
+ return await submitScore(score, {
829
+ ...meta || {},
830
+ matchId: state.matchId,
831
+ leagueId: state.leagueId || meta.leagueId,
832
+ gameId: state.gameId || meta.gameId
833
+ });
834
+ }
835
+ async function submitMatchResult(result = {}) {
836
+ if (!result || typeof result !== "object") {
837
+ return { success: false, error: "match result payload is required" };
838
+ }
839
+ return await submitMatchScore(0, { matchResult: result });
840
+ }
841
+ async function getQuestions(options = {}) {
842
+ await ensureInitialized();
843
+ const gameIdentifier = state.gameId || state.gameSlug;
844
+ if (!gameIdentifier) return [];
845
+ const { difficulty, category, limit } = options;
846
+ if (difficulty && !["easy", "medium", "hard"].includes(difficulty)) {
847
+ return [];
848
+ }
849
+ if (limit !== void 0 && (typeof limit !== "number" || limit < 1)) {
850
+ return [];
851
+ }
852
+ try {
853
+ const params = new URLSearchParams({
854
+ limit: String(Math.min(limit || QUESTIONS_LIMIT_CAP, QUESTIONS_LIMIT_CAP)),
855
+ random: "true"
856
+ });
857
+ if (state.gameId) params.set("gameId", state.gameId);
858
+ if (difficulty) params.set("difficulty", difficulty);
859
+ if (category) params.set("category", String(category));
860
+ const result = await apiRequest(
861
+ "/games/" + encodeURIComponent(gameIdentifier) + "/questions?" + params.toString(),
862
+ { method: "GET" }
863
+ );
864
+ const data = unwrapResult(result);
865
+ if (Array.isArray(data)) return data;
866
+ if (!data || !Array.isArray(data.questions)) return [];
867
+ return data.questions;
868
+ } catch {
869
+ return [];
870
+ }
871
+ }
872
+
873
+ // src/init.ts
874
+ var environmentDetected = false;
875
+ var hostListenerInstalled = false;
876
+ function detectEnvironment() {
877
+ if (!isBrowser() || environmentDetected) return;
878
+ environmentDetected = true;
879
+ state.sdkOrigin = window.location.origin;
880
+ const runtimePathMatch = window.location.pathname.match(
881
+ /^(.*)\/(?:uploaded-games|games)\/([a-z0-9-]+)(?:\/|$)/i
882
+ );
883
+ let detectedSlug = null;
884
+ if (runtimePathMatch) {
885
+ state.runtimeBasePath = runtimePathMatch[1] || "";
886
+ detectedSlug = runtimePathMatch[2] || null;
887
+ }
888
+ state.leagueId = readQueryParam("leagueId");
889
+ state.gameId = readQueryParam("gameId");
890
+ state.matchId = readQueryParam("matchId");
891
+ state.participant1Id = readQueryParam("participant1Id");
892
+ state.participant2Id = readQueryParam("participant2Id");
893
+ state.participant1MemberIds = readCsvQueryParam("participant1MemberIds");
894
+ state.participant2MemberIds = readCsvQueryParam("participant2MemberIds");
895
+ const scripts = document.getElementsByTagName("script");
896
+ for (let i = 0; i < scripts.length; i++) {
897
+ const src = scripts[i].src;
898
+ if (!src.includes("gamehub-sdk.js")) continue;
899
+ try {
900
+ const parsedSrc = new URL(src, window.location.origin);
901
+ state.sdkOrigin = parsedSrc.origin;
902
+ const match = parsedSrc.pathname.match(/(.*)\/sdk\/gamehub-sdk\.js$/);
903
+ state.sdkPathPrefix = match ? match[1] || "" : "";
904
+ } catch {
905
+ const match = src.match(/(.*)\/sdk\/gamehub-sdk\.js/);
906
+ if (match) {
907
+ const fallbackUrl = new URL(match[1], window.location.origin);
908
+ state.sdkOrigin = fallbackUrl.origin;
909
+ state.sdkPathPrefix = fallbackUrl.pathname || "";
1385
910
  }
1386
- async function autoJoinPendingShare() {
1387
- const shareId = getPendingShareId();
1388
- if (!shareId)
1389
- return;
1390
- if (GameHub.State.lastAutoJoinShareId === shareId)
1391
- return;
1392
- try {
1393
- GameHub.State.lastAutoJoinShareId = shareId;
1394
- await GameHub.Multiplayer.joinRoomByLink(shareId, {
1395
- displayName: getPendingPlayerName(),
1396
- });
1397
- }
1398
- catch (err) {
1399
- GameHub.State.lastAutoJoinShareId = null;
1400
- GameHub.Utils.warn('Auto join by link failed: ' + (err?.message || err));
1401
- }
911
+ }
912
+ const slugAttr = scripts[i].getAttribute("data-game-slug");
913
+ if (slugAttr) detectedSlug = slugAttr;
914
+ break;
915
+ }
916
+ if (!detectedSlug) {
917
+ const pathMatch = window.location.pathname.match(
918
+ /\/(?:uploaded-games|games)\/([a-z0-9-]+)\//i
919
+ );
920
+ if (pathMatch) detectedSlug = pathMatch[1];
921
+ }
922
+ const effectiveBasePath = state.sdkPathPrefix || state.runtimeBasePath || "";
923
+ state.apiBase = state.sdkOrigin + effectiveBasePath + "/api";
924
+ state.gameSlug = detectedSlug;
925
+ }
926
+ function getPendingShareId() {
927
+ if (state.bootstrapShareId) return state.bootstrapShareId;
928
+ return readQueryParam("mp");
929
+ }
930
+ function getPendingRoomCode() {
931
+ if (state.bootstrapRoomCode) return state.bootstrapRoomCode;
932
+ const roomCode = readQueryParam("roomCode");
933
+ return roomCode ? roomCode.trim().toUpperCase() : null;
934
+ }
935
+ function getPendingRoomRole() {
936
+ if (state.bootstrapRoomRole) return state.bootstrapRoomRole;
937
+ const role = readQueryParam("roomRole");
938
+ return role ? role.trim() : null;
939
+ }
940
+ function getPendingRoomToken() {
941
+ if (state.bootstrapRoomToken) return state.bootstrapRoomToken;
942
+ const roomToken = readQueryParam("roomToken");
943
+ return roomToken ? roomToken.trim() : null;
944
+ }
945
+ function getPendingWsUrl() {
946
+ if (state.bootstrapWsUrl) return state.bootstrapWsUrl;
947
+ const wsUrl = readQueryParam("wsUrl");
948
+ return wsUrl ? wsUrl.trim() : null;
949
+ }
950
+ function getPendingPlayerName() {
951
+ if (state.bootstrapPlayerName) return state.bootstrapPlayerName;
952
+ const playerName = readQueryParam("playerName");
953
+ return playerName ? playerName.trim() : void 0;
954
+ }
955
+ function seedPeerIdFromUrl() {
956
+ if (state.bootstrapPeerId) return;
957
+ const fromUrl = readQueryParam("peerId");
958
+ if (fromUrl) state.bootstrapPeerId = fromUrl.trim();
959
+ }
960
+ function resumePendingRoomFromBootstrap() {
961
+ const roomCode = getPendingRoomCode();
962
+ const roomToken = getPendingRoomToken();
963
+ const wsUrl = getPendingWsUrl();
964
+ const peerId = state.bootstrapPeerId || readQueryParam("peerId")?.trim() || null;
965
+ if (!state.gameSlug || !roomCode || !roomToken || !wsUrl || !peerId) {
966
+ return false;
967
+ }
968
+ const role = getPendingRoomRole() || "player";
969
+ state.mpViewerOverride = role === "viewer";
970
+ state.mpRoom = {
971
+ roomCode,
972
+ shareId: state.bootstrapShareId || "",
973
+ peerId,
974
+ role,
975
+ gameSlug: state.gameSlug,
976
+ roomToken,
977
+ wsUrl
978
+ };
979
+ state.mpLastJoinRequest = {
980
+ roomCode,
981
+ roomToken,
982
+ wsUrl,
983
+ gameSlug: state.gameSlug,
984
+ peerId
985
+ };
986
+ connect(state.mpLastJoinRequest);
987
+ return true;
988
+ }
989
+ async function autoJoinPendingShare() {
990
+ const shareId = getPendingShareId();
991
+ if (!shareId) return;
992
+ if (state.lastAutoJoinShareId === shareId) return;
993
+ try {
994
+ state.lastAutoJoinShareId = shareId;
995
+ await joinRoomByLink(shareId, {
996
+ displayName: getPendingPlayerName()
997
+ });
998
+ } catch (err) {
999
+ state.lastAutoJoinShareId = null;
1000
+ warn("Auto join by link failed: " + (err?.message || err));
1001
+ }
1002
+ }
1003
+ async function autoJoinPendingRoomCode() {
1004
+ const roomCode = getPendingRoomCode();
1005
+ if (!roomCode) return;
1006
+ if (state.lastAutoJoinRoomCode === roomCode) return;
1007
+ try {
1008
+ state.lastAutoJoinRoomCode = roomCode;
1009
+ if (resumePendingRoomFromBootstrap()) {
1010
+ return;
1011
+ }
1012
+ await joinRoom(roomCode, {
1013
+ displayName: getPendingPlayerName()
1014
+ });
1015
+ } catch (err) {
1016
+ state.lastAutoJoinRoomCode = null;
1017
+ warn("Auto join by room code failed: " + (err?.message || err));
1018
+ }
1019
+ }
1020
+ async function autoInit() {
1021
+ if (!isBrowser()) return false;
1022
+ if (state.isInitialized || state.isAutoInitializing)
1023
+ return state.autoInitPromise;
1024
+ detectEnvironment();
1025
+ installHostMessageListener();
1026
+ state.isAutoInitializing = true;
1027
+ state.autoInitPromise = (async () => {
1028
+ try {
1029
+ await requestBootstrapFromParent();
1030
+ seedPeerIdFromUrl();
1031
+ if (!state.gameSlug) {
1032
+ warn(
1033
+ "Could not resolve game slug. Ensure the host page sends bootstrap config or serves the game under /games/{slug}."
1034
+ );
1035
+ state.isAutoInitializing = false;
1036
+ return false;
1402
1037
  }
1403
- async function autoJoinPendingRoomCode() {
1404
- const roomCode = getPendingRoomCode();
1405
- if (!roomCode)
1406
- return;
1407
- if (GameHub.State.lastAutoJoinRoomCode === roomCode)
1408
- return;
1409
- try {
1410
- GameHub.State.lastAutoJoinRoomCode = roomCode;
1411
- if (resumePendingRoomFromBootstrap()) {
1412
- return;
1413
- }
1414
- await GameHub.Multiplayer.joinRoom(roomCode, {
1415
- displayName: getPendingPlayerName(),
1416
- });
1417
- }
1418
- catch (err) {
1419
- GameHub.State.lastAutoJoinRoomCode = null;
1420
- GameHub.Utils.warn('Auto join by room code failed: ' + (err?.message || err));
1421
- }
1038
+ if (!state.authToken) {
1039
+ state.authToken = await getAuthTokenFromParent();
1422
1040
  }
1423
- /**
1424
- * Orchestrates the full SDK boot sequence:
1425
- * 1. Request bootstrap config from the host (seeds slug + context).
1426
- * 2. Exchange for an auth token if we don't already have one.
1427
- * 3. Notify the host that we've booted, then fetch match context.
1428
- * 4. Open a session if we can, and auto-join any pending multiplayer room.
1429
- *
1430
- * Safe to call multiple times — concurrent callers share a single promise.
1431
- */
1432
- async function autoInit() {
1433
- const S = GameHub.State;
1434
- if (S.isInitialized || S.isAutoInitializing)
1435
- return S.autoInitPromise;
1436
- S.isAutoInitializing = true;
1437
- S.autoInitPromise = (async () => {
1438
- try {
1439
- await GameHub.Bridge.requestBootstrapFromParent();
1440
- seedPeerIdFromUrl();
1441
- if (!S.gameSlug) {
1442
- GameHub.Utils.warn('Could not resolve game slug. Ensure the host page sends bootstrap config or serves the game under /games/{slug}.');
1443
- S.isAutoInitializing = false;
1444
- return false;
1445
- }
1446
- if (!S.authToken) {
1447
- S.authToken = await GameHub.Bridge.getAuthTokenFromParent();
1448
- }
1449
- S.isInitialized = true;
1450
- S.isAutoInitializing = false;
1451
- GameHub.Bridge.sendToParent('INIT', {
1452
- slug: S.gameSlug,
1453
- auto: true,
1454
- });
1455
- await GameHub.MatchCtx.fetchMatchContext();
1456
- if (S.authToken || (S.leagueId && S.gameId && S.matchId)) {
1457
- S.sessionStartPromise = GameHub.Session.startSession();
1458
- }
1459
- await autoJoinPendingShare();
1460
- await autoJoinPendingRoomCode();
1461
- return true;
1462
- }
1463
- catch (err) {
1464
- GameHub.Utils.error('Auto-init failed:', err);
1465
- S.isAutoInitializing = false;
1466
- return false;
1467
- }
1468
- })();
1469
- return S.autoInitPromise;
1041
+ state.isInitialized = true;
1042
+ state.isAutoInitializing = false;
1043
+ sendToParent("INIT", {
1044
+ slug: state.gameSlug,
1045
+ auto: true
1046
+ });
1047
+ await fetchMatchContext();
1048
+ if (state.authToken || state.leagueId && state.gameId && state.matchId) {
1049
+ state.sessionStartPromise = startSession();
1470
1050
  }
1471
- Init.autoInit = autoInit;
1472
- /**
1473
- * Ensures init has at least started; callers `await` this before touching
1474
- * any state that depends on bootstrap / auth having resolved.
1475
- */
1476
- async function ensureInitialized() {
1477
- const S = GameHub.State;
1478
- if (S.isInitialized)
1479
- return true;
1480
- if (S.autoInitPromise)
1481
- return await S.autoInitPromise;
1482
- return await autoInit();
1051
+ await autoJoinPendingShare();
1052
+ await autoJoinPendingRoomCode();
1053
+ return true;
1054
+ } catch (err) {
1055
+ error("Auto-init failed:", err);
1056
+ state.isAutoInitializing = false;
1057
+ return false;
1058
+ }
1059
+ })();
1060
+ return state.autoInitPromise;
1061
+ }
1062
+ async function ensureInitialized() {
1063
+ if (state.isInitialized) return true;
1064
+ if (!isBrowser()) return false;
1065
+ if (state.autoInitPromise) return await state.autoInitPromise;
1066
+ return await autoInit();
1067
+ }
1068
+ function installHostMessageListener() {
1069
+ if (!isBrowser() || hostListenerInstalled) return;
1070
+ hostListenerInstalled = true;
1071
+ window.addEventListener("message", (event) => {
1072
+ if (!event.data || !event.data.type) return;
1073
+ const type = event.data.type;
1074
+ if (type === MESSAGE_PREFIX + "_BOOTSTRAP" && event.data.payload) {
1075
+ state.parentOrigin = event.origin;
1076
+ state.bootstrapReceived = true;
1077
+ mergeBootstrapConfig(event.data.payload);
1078
+ if (state.isInitialized && state.bootstrapShareId && !state.mpRoom) {
1079
+ autoJoinPendingShare();
1483
1080
  }
1484
- Init.ensureInitialized = ensureInitialized;
1485
- /**
1486
- * Wires up the ambient message listener the host uses to push updates into
1487
- * the running SDK (fresh bootstrap, rotated auth, pause/resume commands).
1488
- */
1489
- function installHostMessageListener() {
1490
- window.addEventListener('message', (event) => {
1491
- if (!event.data || !event.data.type)
1492
- return;
1493
- const type = event.data.type;
1494
- const S = GameHub.State;
1495
- if (type === GameHub.MESSAGE_PREFIX + '_BOOTSTRAP' &&
1496
- event.data.payload) {
1497
- S.parentOrigin = event.origin;
1498
- S.bootstrapReceived = true;
1499
- GameHub.Bridge.mergeBootstrapConfig(event.data.payload);
1500
- if (S.isInitialized && S.bootstrapShareId && !S.mpRoom) {
1501
- autoJoinPendingShare();
1502
- }
1503
- }
1504
- if (type === GameHub.MESSAGE_PREFIX + '_SET_AUTH') {
1505
- S.authToken = event.data.token;
1506
- S.parentOrigin = event.origin;
1507
- if (S.gameSlug &&
1508
- !S.sessionToken &&
1509
- !S.sessionStartPromise &&
1510
- (S.authToken || (S.leagueId && S.gameId && S.matchId))) {
1511
- S.sessionStartPromise = GameHub.Session.startSession();
1512
- }
1513
- }
1514
- if (type === GameHub.MESSAGE_PREFIX + '_COMMAND') {
1515
- const command = event.data.command;
1516
- const w = window;
1517
- if (command === 'pause' && typeof w.onGameHubPause === 'function') {
1518
- w.onGameHubPause();
1519
- }
1520
- else if (command === 'resume' &&
1521
- typeof w.onGameHubResume === 'function') {
1522
- w.onGameHubResume();
1523
- }
1524
- }
1525
- });
1081
+ }
1082
+ if (type === MESSAGE_PREFIX + "_SET_AUTH") {
1083
+ state.authToken = event.data.token;
1084
+ state.parentOrigin = event.origin;
1085
+ if (state.gameSlug && !state.sessionToken && !state.sessionStartPromise && (state.authToken || state.leagueId && state.gameId && state.matchId)) {
1086
+ state.sessionStartPromise = startSession();
1526
1087
  }
1527
- Init.installHostMessageListener = installHostMessageListener;
1528
- })(Init = GameHub.Init || (GameHub.Init = {}));
1529
- })(GameHub || (GameHub = {}));
1530
- /**
1531
- * Public SDK surface — the one and only object that game code interacts with.
1532
- *
1533
- * Games load this as a plain `<script>` tag, so we expose ourselves via
1534
- * `window.GameHubSDK`. We also emit a `module.exports` assignment for the
1535
- * rare case of CommonJS-style consumption in a build tool, but CommonJS is
1536
- * not the primary distribution channel.
1537
- */
1538
- var GameHub;
1539
- (function (GameHub) {
1540
- var Public;
1541
- (function (Public) {
1542
- /**
1543
- * Assemble the public API object. Methods are thin adapters that route to
1544
- * the internal `GameHub.*` namespaces — keeping the surface area small and
1545
- * the internals freely refactorable.
1546
- */
1547
- function create() {
1548
- return {
1549
- version: GameHub.SDK_VERSION,
1550
- isInitialized() {
1551
- return GameHub.State.isInitialized;
1552
- },
1553
- isAuthenticated() {
1554
- return !!GameHub.State.authToken;
1555
- },
1556
- hasActiveSession() {
1557
- return !!GameHub.State.sessionToken;
1558
- },
1559
- async startSession() {
1560
- await GameHub.Init.ensureInitialized();
1561
- if (GameHub.State.sessionStartPromise)
1562
- return await GameHub.State.sessionStartPromise;
1563
- return await GameHub.Session.startSession();
1564
- },
1565
- submitScore(score, meta = {}) {
1566
- return GameHub.Session.submitScore(score, meta);
1567
- },
1568
- submitMatchScore(score, meta = {}) {
1569
- return GameHub.Session.submitMatchScore(score, meta);
1570
- },
1571
- submitMatchResult(result = {}) {
1572
- return GameHub.Session.submitMatchResult(result);
1573
- },
1574
- async playAgain() {
1575
- // Same session — each play is appended as a new record in plays[].
1576
- return { success: true, token: GameHub.State.sessionToken };
1577
- },
1578
- notifyComplete(data = {}) {
1579
- GameHub.Bridge.sendToParent('GAME_COMPLETE', data);
1580
- },
1581
- requestClose() {
1582
- GameHub.Bridge.sendToParent('REQUEST_CLOSE', {});
1583
- },
1584
- logEvent(eventName, eventData = {}) {
1585
- GameHub.Bridge.sendToParent('LOG_EVENT', {
1586
- event: eventName,
1587
- data: eventData,
1588
- });
1589
- },
1590
- getGameSlug() {
1591
- return GameHub.State.gameSlug;
1592
- },
1593
- isInIframe() {
1594
- return window.parent !== window;
1595
- },
1596
- async ready() {
1597
- return await GameHub.Init.ensureInitialized();
1598
- },
1599
- getBootstrap() {
1600
- const S = GameHub.State;
1601
- return {
1602
- gameSlug: S.gameSlug,
1603
- authToken: S.authToken,
1604
- leagueId: S.leagueId,
1605
- gameId: S.gameId,
1606
- matchId: S.matchId,
1607
- match: S.matchContext,
1608
- participant1Id: S.participant1Id,
1609
- participant2Id: S.participant2Id,
1610
- participant1MemberIds: S.participant1MemberIds,
1611
- participant2MemberIds: S.participant2MemberIds,
1612
- playerName: S.bootstrapPlayerName,
1613
- peerId: S.bootstrapPeerId,
1614
- room: S.bootstrapRoomCode
1615
- ? {
1616
- roomCode: S.bootstrapRoomCode,
1617
- shareId: S.bootstrapShareId,
1618
- maxPlayers: S.bootstrapMaxPlayers,
1619
- role: S.bootstrapRoomRole,
1620
- roomToken: S.bootstrapRoomToken,
1621
- wsUrl: S.bootstrapWsUrl,
1622
- }
1623
- : null,
1624
- isBootstrapped: S.bootstrapReceived,
1625
- };
1626
- },
1627
- async getMatchContext() {
1628
- await GameHub.Init.ensureInitialized();
1629
- return await GameHub.MatchCtx.fetchMatchContext();
1630
- },
1631
- getQuestions(options = {}) {
1632
- return GameHub.Session.getQuestions(options);
1633
- },
1634
- multiplayer: {
1635
- createRoom: GameHub.Multiplayer.createRoom,
1636
- joinRoom: GameHub.Multiplayer.joinRoom,
1637
- joinRoomByLink: GameHub.Multiplayer.joinRoomByLink,
1638
- leaveRoom: GameHub.Multiplayer.leaveRoom,
1639
- send: GameHub.Multiplayer.send,
1640
- broadcast: GameHub.Multiplayer.broadcast,
1641
- on: GameHub.Multiplayer.on,
1642
- getRoom: GameHub.Multiplayer.getRoom,
1643
- getPeers: GameHub.Multiplayer.getPeers,
1644
- isConnected: GameHub.Multiplayer.isConnected,
1645
- getRole: GameHub.Multiplayer.getRole,
1646
- isHost: GameHub.Multiplayer.isHost,
1647
- isViewer: GameHub.Multiplayer.isViewer,
1648
- selfId: GameHub.Multiplayer.selfId,
1649
- },
1650
- };
1088
+ }
1089
+ if (type === MESSAGE_PREFIX + "_COMMAND") {
1090
+ const command = event.data.command;
1091
+ const w = window;
1092
+ if (command === "pause" && typeof w.onGameHubPause === "function") {
1093
+ w.onGameHubPause();
1094
+ } else if (command === "resume" && typeof w.onGameHubResume === "function") {
1095
+ w.onGameHubResume();
1651
1096
  }
1652
- Public.create = create;
1653
- })(Public = GameHub.Public || (GameHub.Public = {}));
1654
- })(GameHub || (GameHub = {}));
1655
- /**
1656
- * Boot sequence. Runs unconditionally as the script is loaded — everything
1657
- * before this point has only declared helpers/state. Wrapping in an IIFE
1658
- * keeps the few locals we create here out of the global scope.
1659
- */
1660
- (function bootstrapSdk() {
1661
- 'use strict';
1662
- GameHub.Init.detectEnvironment();
1663
- GameHub.Init.installHostMessageListener();
1664
- const sdk = GameHub.Public.create();
1097
+ }
1098
+ });
1099
+ }
1100
+
1101
+ // src/main.ts
1102
+ function createSdk() {
1103
+ return {
1104
+ version: SDK_VERSION,
1105
+ isInitialized() {
1106
+ return state.isInitialized;
1107
+ },
1108
+ isAuthenticated() {
1109
+ return !!state.authToken;
1110
+ },
1111
+ hasActiveSession() {
1112
+ return !!state.sessionToken;
1113
+ },
1114
+ async startSession() {
1115
+ await ensureInitialized();
1116
+ if (state.sessionStartPromise) return await state.sessionStartPromise;
1117
+ return await startSession();
1118
+ },
1119
+ submitScore(score, meta = {}) {
1120
+ return submitScore(score, meta);
1121
+ },
1122
+ submitMatchScore(score, meta = {}) {
1123
+ return submitMatchScore(score, meta);
1124
+ },
1125
+ submitMatchResult(result = {}) {
1126
+ return submitMatchResult(result);
1127
+ },
1128
+ async playAgain() {
1129
+ return { success: true, token: state.sessionToken };
1130
+ },
1131
+ notifyComplete(data = {}) {
1132
+ sendToParent("GAME_COMPLETE", data);
1133
+ },
1134
+ requestClose() {
1135
+ sendToParent("REQUEST_CLOSE", {});
1136
+ },
1137
+ logEvent(eventName, eventData = {}) {
1138
+ sendToParent("LOG_EVENT", {
1139
+ event: eventName,
1140
+ data: eventData
1141
+ });
1142
+ },
1143
+ getGameSlug() {
1144
+ return state.gameSlug;
1145
+ },
1146
+ isInIframe() {
1147
+ return isBrowser() && window.parent !== window;
1148
+ },
1149
+ async ready() {
1150
+ return await ensureInitialized();
1151
+ },
1152
+ getBootstrap() {
1153
+ return {
1154
+ gameSlug: state.gameSlug,
1155
+ authToken: state.authToken,
1156
+ leagueId: state.leagueId,
1157
+ gameId: state.gameId,
1158
+ matchId: state.matchId,
1159
+ match: state.matchContext,
1160
+ participant1Id: state.participant1Id,
1161
+ participant2Id: state.participant2Id,
1162
+ participant1MemberIds: state.participant1MemberIds,
1163
+ participant2MemberIds: state.participant2MemberIds,
1164
+ playerName: state.bootstrapPlayerName,
1165
+ peerId: state.bootstrapPeerId,
1166
+ room: state.bootstrapRoomCode ? {
1167
+ roomCode: state.bootstrapRoomCode,
1168
+ shareId: state.bootstrapShareId,
1169
+ maxPlayers: state.bootstrapMaxPlayers,
1170
+ role: state.bootstrapRoomRole,
1171
+ roomToken: state.bootstrapRoomToken,
1172
+ wsUrl: state.bootstrapWsUrl
1173
+ } : null,
1174
+ isBootstrapped: state.bootstrapReceived
1175
+ };
1176
+ },
1177
+ async getMatchContext() {
1178
+ await ensureInitialized();
1179
+ return await fetchMatchContext();
1180
+ },
1181
+ getQuestions(options = {}) {
1182
+ return getQuestions(options);
1183
+ },
1184
+ multiplayer: {
1185
+ createRoom,
1186
+ joinRoom,
1187
+ joinRoomByLink,
1188
+ leaveRoom,
1189
+ send,
1190
+ broadcast,
1191
+ on,
1192
+ getRoom,
1193
+ getPeers,
1194
+ isConnected,
1195
+ getRole,
1196
+ isHost,
1197
+ isViewer,
1198
+ selfId
1199
+ }
1200
+ };
1201
+ }
1202
+
1203
+ // src/browser-entry.ts
1204
+ (function bootstrapSdk() {
1205
+ "use strict";
1206
+ if (!isBrowser()) return;
1207
+ detectEnvironment();
1208
+ installHostMessageListener();
1209
+ const sdk = createSdk();
1665
1210
  window.GameHubSDK = sdk;
1666
- // CommonJS interop for consumers that `require()` this file through a
1667
- // bundler. Guarded so the global-first pattern still works in the browser.
1668
- const anyModule = typeof globalThis.module !== 'undefined'
1669
- ? globalThis.module
1670
- : undefined;
1671
- if (anyModule && anyModule.exports) {
1672
- anyModule.exports = sdk;
1673
- }
1674
- // Announce presence to the host as soon as the script runs.
1675
1211
  if (window.parent !== window) {
1676
- GameHub.Bridge.sendToParent('READY', { version: GameHub.SDK_VERSION });
1212
+ sendToParent("READY", { version: SDK_VERSION });
1677
1213
  }
1678
- // Kick off auto-init if we have any signal we're embedded in GameHub: either
1679
- // we detected a slug locally, or we're inside an iframe that might feed us
1680
- // one. Waits for DOMContentLoaded so script tags declared after us are
1681
- // available for the slug-detection scan.
1682
- const hasBootSignal = !!GameHub.State.gameSlug || window.parent !== window;
1683
- if (hasBootSignal) {
1684
- if (document.readyState === 'loading') {
1685
- document.addEventListener('DOMContentLoaded', () => {
1686
- GameHub.Init.autoInit();
1687
- });
1688
- }
1689
- else {
1690
- GameHub.Init.autoInit();
1691
- }
1214
+ const hasBootSignal = !!state.gameSlug || window.parent !== window;
1215
+ if (!hasBootSignal) return;
1216
+ if (document.readyState === "loading") {
1217
+ document.addEventListener("DOMContentLoaded", () => {
1218
+ autoInit();
1219
+ });
1220
+ } else {
1221
+ autoInit();
1692
1222
  }
1223
+ })();
1693
1224
  })();
1225
+ //# sourceMappingURL=gamehub-sdk.js.map