@ksaa-nlp/gamehub-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +546 -0
- package/dist/gamehub-sdk.d.ts +694 -0
- package/dist/gamehub-sdk.js +1693 -0
- package/dist/index.d.ts +56 -0
- package/dist/index.mjs +6 -0
- package/package.json +31 -0
- package/scripts/emit-module-entry.mjs +96 -0
- package/src/api-client.ts +33 -0
- package/src/bridge.ts +312 -0
- package/src/constants.ts +24 -0
- package/src/init.ts +335 -0
- package/src/main.ts +287 -0
- package/src/match-context.ts +52 -0
- package/src/multiplayer.ts +525 -0
- package/src/session.ts +240 -0
- package/src/state.ts +78 -0
- package/src/utils.ts +68 -0
- package/tsconfig.json +33 -0
- package/types/api.ts +21 -0
- package/types/bootstrap.ts +65 -0
- package/types/match.ts +41 -0
- package/types/multiplayer.ts +118 -0
- package/types/session.ts +67 -0
|
@@ -0,0 +1,1693 @@
|
|
|
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());
|
|
1214
|
+
}
|
|
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);
|
|
1220
|
+
}
|
|
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;
|
|
1298
|
+
}
|
|
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');
|
|
1308
|
+
}
|
|
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;
|
|
1315
|
+
}
|
|
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;
|
|
1321
|
+
}
|
|
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;
|
|
1327
|
+
}
|
|
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;
|
|
1333
|
+
}
|
|
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;
|
|
1340
|
+
}
|
|
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();
|
|
1353
|
+
}
|
|
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;
|
|
1385
|
+
}
|
|
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
|
+
}
|
|
1402
|
+
}
|
|
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
|
+
}
|
|
1422
|
+
}
|
|
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;
|
|
1470
|
+
}
|
|
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();
|
|
1483
|
+
}
|
|
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
|
+
});
|
|
1526
|
+
}
|
|
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
|
+
};
|
|
1651
|
+
}
|
|
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();
|
|
1665
|
+
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
|
+
if (window.parent !== window) {
|
|
1676
|
+
GameHub.Bridge.sendToParent('READY', { version: GameHub.SDK_VERSION });
|
|
1677
|
+
}
|
|
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
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
})();
|