@ksaa-nlp/gamehub-sdk 5.0.0 → 5.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -3
- package/SPEC.md +138 -3
- package/dist/gamehub-sdk.js +1 -1442
- package/dist/gamehub-sdk.js.map +4 -4
- package/dist/src/answers.d.ts +22 -0
- package/dist/src/answers.d.ts.map +1 -0
- package/dist/src/answers.js +139 -0
- package/dist/src/answers.js.map +1 -0
- package/dist/src/bridge.d.ts.map +1 -1
- package/dist/src/bridge.js +2 -0
- package/dist/src/bridge.js.map +1 -1
- package/dist/src/constants.d.ts +1 -1
- package/dist/src/constants.js +1 -1
- package/dist/src/loading.d.ts +5 -0
- package/dist/src/loading.d.ts.map +1 -0
- package/dist/src/loading.js +54 -0
- package/dist/src/loading.js.map +1 -0
- package/dist/src/main.d.ts +13 -2
- package/dist/src/main.d.ts.map +1 -1
- package/dist/src/main.js +9 -0
- package/dist/src/main.js.map +1 -1
- package/dist/src/multiplayer-client.d.ts +2 -0
- package/dist/src/multiplayer-client.d.ts.map +1 -1
- package/dist/src/multiplayer-client.js +18 -0
- package/dist/src/multiplayer-client.js.map +1 -1
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/session.js +25 -5
- package/dist/src/session.js.map +1 -1
- package/dist/types/bootstrap.d.ts +2 -0
- package/dist/types/bootstrap.d.ts.map +1 -1
- package/dist/types/loading.d.ts +6 -0
- package/dist/types/loading.d.ts.map +1 -0
- package/dist/types/loading.js +2 -0
- package/dist/types/loading.js.map +1 -0
- package/dist/types/question.d.ts +0 -1
- package/dist/types/question.d.ts.map +1 -1
- package/dist/types/question.js +0 -1
- package/dist/types/question.js.map +1 -1
- package/dist/types/session.d.ts +16 -0
- package/dist/types/session.d.ts.map +1 -1
- package/dist/vendor/colyseus-schemas/common.d.ts +18 -0
- package/dist/vendor/colyseus-schemas/common.js +4 -1
- package/dist/vendor/gamehub-multiplayer-contracts/index.d.ts +25 -1
- package/dist/vendor/gamehub-multiplayer-contracts/index.js +3 -1
- package/package.json +2 -2
package/dist/gamehub-sdk.js
CHANGED
|
@@ -1,1443 +1,2 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
(() => {
|
|
3
|
-
// src/constants.ts
|
|
4
|
-
var SDK_VERSION = "5.0.0";
|
|
5
|
-
var MESSAGE_PREFIX = "GAMEHUB_SDK";
|
|
6
|
-
var PARENT_REQUEST_TIMEOUT_MS = 2e3;
|
|
7
|
-
var HOST_API_TIMEOUT_MS = 15e3;
|
|
8
|
-
var QUESTIONS_LIMIT_CAP = 100;
|
|
9
|
-
var WORDS_LIMIT_CAP = 50;
|
|
10
|
-
|
|
11
|
-
// src/state.ts
|
|
12
|
-
var state = {
|
|
13
|
-
multiplayerEntry: null,
|
|
14
|
-
gameSettings: { musicEnabled: false },
|
|
15
|
-
settingsListeners: /* @__PURE__ */ new Set(),
|
|
16
|
-
bootstrapLaunch: null,
|
|
17
|
-
bootstrapCapabilities: [],
|
|
18
|
-
sdkOrigin: "",
|
|
19
|
-
sdkPathPrefix: "",
|
|
20
|
-
runtimeBasePath: "",
|
|
21
|
-
apiBase: "",
|
|
22
|
-
gameSlug: null,
|
|
23
|
-
sessionToken: null,
|
|
24
|
-
authToken: null,
|
|
25
|
-
leagueId: null,
|
|
26
|
-
gameId: null,
|
|
27
|
-
matchId: null,
|
|
28
|
-
bootstrapSessionMode: null,
|
|
29
|
-
bootstrapMode: null,
|
|
30
|
-
bootstrapPlayerName: null,
|
|
31
|
-
bootstrapPlayerCount: null,
|
|
32
|
-
bootstrapTeamOneName: null,
|
|
33
|
-
bootstrapTeamTwoName: null,
|
|
34
|
-
bootstrapProfileId: null,
|
|
35
|
-
bootstrapReceived: false,
|
|
36
|
-
isInitialized: false,
|
|
37
|
-
isAutoInitializing: false,
|
|
38
|
-
autoInitPromise: null,
|
|
39
|
-
bootstrapRequestPromise: null,
|
|
40
|
-
parentOrigin: null,
|
|
41
|
-
sessionStartPromise: null,
|
|
42
|
-
submissionPromise: null,
|
|
43
|
-
pendingSubmission: null,
|
|
44
|
-
matchContext: null,
|
|
45
|
-
matchContextPromise: null
|
|
46
|
-
};
|
|
47
|
-
|
|
48
|
-
// dist/vendor/gamehub-multiplayer-contracts/index.js
|
|
49
|
-
var MULTIPLAYER_CAPABILITY = "multiplayer.launch.v2";
|
|
50
|
-
var MULTIPLAYER_LOBBY_CAPABILITY = "multiplayer.lobby.v2";
|
|
51
|
-
var BOT_LEVELS = ["easy", "medium", "hard"];
|
|
52
|
-
var isBotLevel = (value) => BOT_LEVELS.includes(value);
|
|
53
|
-
|
|
54
|
-
// src/multiplayer-session.ts
|
|
55
|
-
var listeners = /* @__PURE__ */ new Set();
|
|
56
|
-
var empty = {
|
|
57
|
-
session: null,
|
|
58
|
-
busy: false,
|
|
59
|
-
error: null,
|
|
60
|
-
disconnected: false
|
|
61
|
-
};
|
|
62
|
-
var current = empty;
|
|
63
|
-
var id = (value) => typeof value === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(value);
|
|
64
|
-
function parseLobbyState(value) {
|
|
65
|
-
if (!value || typeof value !== "object") return null;
|
|
66
|
-
const v = value;
|
|
67
|
-
if (typeof v.busy !== "boolean" || typeof v.disconnected !== "boolean")
|
|
68
|
-
return null;
|
|
69
|
-
const error2 = v.error;
|
|
70
|
-
if (error2 !== null && (!error2 || !id(error2.code) || typeof error2.message !== "string" || error2.message.length > 1e3 || typeof error2.retryable !== "boolean"))
|
|
71
|
-
return null;
|
|
72
|
-
const s = v.session;
|
|
73
|
-
if (s !== null) {
|
|
74
|
-
if (!s || ![s.multiplayerSessionId, s.hostSeatId, s.ownSeatId].every(id) || typeof s.gameSlug !== "string" || !/^[a-z0-9-]{1,100}$/.test(s.gameSlug) || !/^\d{6}$/.test(s.roomCode) || !["waiting", "in_round", "completed", "closed"].includes(s.phase) || !Number.isSafeInteger(s.revision) || s.revision < 0 || typeof s.rematchAllowed !== "boolean" || !Array.isArray(s.seats) || s.seats.length > 272)
|
|
75
|
-
return null;
|
|
76
|
-
for (const url of [s.invitationUrl, s.spectatorInvitationUrl]) {
|
|
77
|
-
if (url !== void 0 && (typeof url !== "string" || url.length > 2048 || !/^https?:\/\//.test(url)))
|
|
78
|
-
return null;
|
|
79
|
-
}
|
|
80
|
-
const p = s.playerPolicy;
|
|
81
|
-
if (!p || ![
|
|
82
|
-
p.minPlayers,
|
|
83
|
-
p.maxPlayers,
|
|
84
|
-
p.minHumanPlayers,
|
|
85
|
-
p.maxBots,
|
|
86
|
-
p.maxSpectators
|
|
87
|
-
].every((n) => Number.isSafeInteger(n) && n >= 0 && n <= 256) || p.minPlayers < 1 || p.minHumanPlayers < 1 || p.maxPlayers < p.minPlayers || p.minHumanPlayers > p.maxPlayers || p.maxBots > p.maxPlayers - p.minHumanPlayers || p.maxSpectators > 16)
|
|
88
|
-
return null;
|
|
89
|
-
if (!s.seats.every(
|
|
90
|
-
(seat) => seat && id(seat.seatId) && typeof seat.displayName === "string" && seat.displayName.length <= 80 && ["human", "bot"].includes(seat.kind) && (seat.botLevel === void 0 || seat.kind === "bot" && isBotLevel(seat.botLevel)) && ["player", "spectator"].includes(seat.type) && typeof seat.ready === "boolean" && typeof seat.online === "boolean"
|
|
91
|
-
))
|
|
92
|
-
return null;
|
|
93
|
-
if (s.round !== null && (!s.round || !id(s.round.roundId) || ![
|
|
94
|
-
"preparing",
|
|
95
|
-
"loading",
|
|
96
|
-
"playing",
|
|
97
|
-
"finishing",
|
|
98
|
-
"completed",
|
|
99
|
-
"aborted",
|
|
100
|
-
"interrupted"
|
|
101
|
-
].includes(s.round.phase) || s.round.reason !== null && (typeof s.round.reason !== "string" || s.round.reason.length > 1e3)))
|
|
102
|
-
return null;
|
|
103
|
-
}
|
|
104
|
-
return {
|
|
105
|
-
busy: v.busy,
|
|
106
|
-
disconnected: v.disconnected,
|
|
107
|
-
error: error2 ? { code: error2.code, message: error2.message, retryable: error2.retryable } : null,
|
|
108
|
-
session: s ? {
|
|
109
|
-
...s.invitationUrl ? { invitationUrl: s.invitationUrl } : {},
|
|
110
|
-
...s.spectatorInvitationUrl ? { spectatorInvitationUrl: s.spectatorInvitationUrl } : {},
|
|
111
|
-
multiplayerSessionId: s.multiplayerSessionId,
|
|
112
|
-
gameSlug: s.gameSlug,
|
|
113
|
-
roomCode: s.roomCode,
|
|
114
|
-
phase: s.phase,
|
|
115
|
-
revision: s.revision,
|
|
116
|
-
hostSeatId: s.hostSeatId,
|
|
117
|
-
ownSeatId: s.ownSeatId,
|
|
118
|
-
rematchAllowed: s.rematchAllowed,
|
|
119
|
-
playerPolicy: {
|
|
120
|
-
minPlayers: s.playerPolicy.minPlayers,
|
|
121
|
-
maxPlayers: s.playerPolicy.maxPlayers,
|
|
122
|
-
minHumanPlayers: s.playerPolicy.minHumanPlayers,
|
|
123
|
-
maxBots: s.playerPolicy.maxBots,
|
|
124
|
-
maxSpectators: s.playerPolicy.maxSpectators
|
|
125
|
-
},
|
|
126
|
-
seats: s.seats.map((seat) => ({
|
|
127
|
-
seatId: seat.seatId,
|
|
128
|
-
displayName: seat.displayName,
|
|
129
|
-
kind: seat.kind,
|
|
130
|
-
...seat.botLevel ? { botLevel: seat.botLevel } : {},
|
|
131
|
-
type: seat.type,
|
|
132
|
-
ready: seat.ready,
|
|
133
|
-
online: seat.online
|
|
134
|
-
})),
|
|
135
|
-
round: s.round ? {
|
|
136
|
-
roundId: s.round.roundId,
|
|
137
|
-
phase: s.round.phase,
|
|
138
|
-
reason: s.round.reason
|
|
139
|
-
} : null
|
|
140
|
-
} : null
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
function acceptLobbyState(value) {
|
|
144
|
-
const parsed = parseLobbyState(value);
|
|
145
|
-
if (!parsed) return;
|
|
146
|
-
current = parsed;
|
|
147
|
-
for (const listener of listeners) {
|
|
148
|
-
try {
|
|
149
|
-
listener(structuredClone(current));
|
|
150
|
-
} catch {
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
function lobbySnapshot() {
|
|
155
|
-
return structuredClone(current);
|
|
156
|
-
}
|
|
157
|
-
function onMultiplayerSessionChange(listener) {
|
|
158
|
-
const subscription = (value) => listener(value);
|
|
159
|
-
listeners.add(subscription);
|
|
160
|
-
try {
|
|
161
|
-
subscription(lobbySnapshot());
|
|
162
|
-
} catch {
|
|
163
|
-
}
|
|
164
|
-
return () => {
|
|
165
|
-
listeners.delete(subscription);
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
async function requestMultiplayerSession(request) {
|
|
169
|
-
if (!state.bootstrapCapabilities.includes(MULTIPLAYER_LOBBY_CAPABILITY))
|
|
170
|
-
return {
|
|
171
|
-
success: false,
|
|
172
|
-
error: {
|
|
173
|
-
code: "PROTOCOL_UNSUPPORTED",
|
|
174
|
-
message: "This host does not support multiplayer lobby controls",
|
|
175
|
-
retryable: false
|
|
176
|
-
}
|
|
177
|
-
};
|
|
178
|
-
const slug = state.gameSlug;
|
|
179
|
-
const launch = state.bootstrapLaunch;
|
|
180
|
-
try {
|
|
181
|
-
const response = await requestApiFromParent("/multiplayer/session", {
|
|
182
|
-
method: "POST",
|
|
183
|
-
body: request
|
|
184
|
-
});
|
|
185
|
-
if (slug !== state.gameSlug || launch !== state.bootstrapLaunch)
|
|
186
|
-
return {
|
|
187
|
-
success: false,
|
|
188
|
-
error: {
|
|
189
|
-
code: "STALE_ATTEMPT",
|
|
190
|
-
message: "The multiplayer context changed",
|
|
191
|
-
retryable: false
|
|
192
|
-
}
|
|
193
|
-
};
|
|
194
|
-
const parsed = response.success ? parseLobbyState(response.data) : null;
|
|
195
|
-
if (parsed && (!parsed.session || parsed.session.gameSlug === slug)) {
|
|
196
|
-
acceptLobbyState(parsed);
|
|
197
|
-
return { success: true, data: lobbySnapshot() };
|
|
198
|
-
}
|
|
199
|
-
return {
|
|
200
|
-
success: false,
|
|
201
|
-
error: {
|
|
202
|
-
code: response.error?.code ?? "UNAVAILABLE",
|
|
203
|
-
message: response.error?.message ?? "Lobby request failed",
|
|
204
|
-
retryable: response.error?.details?.terminal !== true
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
} catch {
|
|
208
|
-
return {
|
|
209
|
-
success: false,
|
|
210
|
-
error: {
|
|
211
|
-
code: "UNAVAILABLE",
|
|
212
|
-
message: "Lobby request timed out; refresh status before retrying",
|
|
213
|
-
retryable: true
|
|
214
|
-
}
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// src/settings.ts
|
|
220
|
-
function getSettings() {
|
|
221
|
-
return { ...state.gameSettings };
|
|
222
|
-
}
|
|
223
|
-
function notify(listener) {
|
|
224
|
-
try {
|
|
225
|
-
listener(getSettings());
|
|
226
|
-
} catch {
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
function onSettingsChange(listener) {
|
|
230
|
-
if (typeof listener !== "function") return () => {
|
|
231
|
-
};
|
|
232
|
-
const subscription = (settings) => listener(settings);
|
|
233
|
-
state.settingsListeners.add(subscription);
|
|
234
|
-
notify(subscription);
|
|
235
|
-
return () => {
|
|
236
|
-
state.settingsListeners.delete(subscription);
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
function mergeSettings(value) {
|
|
240
|
-
if (value === void 0) return;
|
|
241
|
-
let musicEnabled;
|
|
242
|
-
if (value === null) {
|
|
243
|
-
musicEnabled = false;
|
|
244
|
-
} else if (typeof value === "object" && !Array.isArray(value) && typeof value.musicEnabled === "boolean") {
|
|
245
|
-
musicEnabled = value.musicEnabled;
|
|
246
|
-
} else {
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
if (musicEnabled === state.gameSettings.musicEnabled) return;
|
|
250
|
-
state.gameSettings = { musicEnabled };
|
|
251
|
-
for (const listener of [...state.settingsListeners]) {
|
|
252
|
-
if (state.settingsListeners.has(listener)) notify(listener);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
// src/utils.ts
|
|
257
|
-
function isBrowser() {
|
|
258
|
-
return typeof window !== "undefined" && typeof document !== "undefined";
|
|
259
|
-
}
|
|
260
|
-
function warn(message, ...rest) {
|
|
261
|
-
console.warn("[GameHubSDK] " + message, ...rest);
|
|
262
|
-
}
|
|
263
|
-
function error(message, ...rest) {
|
|
264
|
-
console.error("[GameHubSDK] " + message, ...rest);
|
|
265
|
-
}
|
|
266
|
-
function unwrapResult(result) {
|
|
267
|
-
if (!result) return null;
|
|
268
|
-
if (result.success && result.data) return result.data;
|
|
269
|
-
return result;
|
|
270
|
-
}
|
|
271
|
-
function readQueryParam(name) {
|
|
272
|
-
try {
|
|
273
|
-
const params = new URLSearchParams(window.location.search);
|
|
274
|
-
return params.get(name);
|
|
275
|
-
} catch {
|
|
276
|
-
const match = window.location.search.match(
|
|
277
|
-
new RegExp("[?&]" + name + "=([^&]+)")
|
|
278
|
-
);
|
|
279
|
-
return match ? decodeURIComponent(match[1]) : null;
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
// src/transport.ts
|
|
284
|
-
var PostMessageTransport = class {
|
|
285
|
-
constructor() {
|
|
286
|
-
this.kind = "postmessage";
|
|
287
|
-
}
|
|
288
|
-
send(envelope) {
|
|
289
|
-
window.parent.postMessage(envelope, state.parentOrigin || "*");
|
|
290
|
-
}
|
|
291
|
-
subscribe(handler) {
|
|
292
|
-
const listener = (event) => {
|
|
293
|
-
if (event.source !== window.parent) return;
|
|
294
|
-
if (state.parentOrigin && event.origin !== state.parentOrigin) return;
|
|
295
|
-
handler({ data: event.data, origin: event.origin });
|
|
296
|
-
};
|
|
297
|
-
window.addEventListener("message", listener);
|
|
298
|
-
return () => window.removeEventListener("message", listener);
|
|
299
|
-
}
|
|
300
|
-
};
|
|
301
|
-
function acceptParentOrigin(origin) {
|
|
302
|
-
if (origin === null) return true;
|
|
303
|
-
if (!origin || origin === "null") return false;
|
|
304
|
-
if (state.parentOrigin === null) {
|
|
305
|
-
state.parentOrigin = origin;
|
|
306
|
-
return true;
|
|
307
|
-
}
|
|
308
|
-
return state.parentOrigin === origin;
|
|
309
|
-
}
|
|
310
|
-
var NativeBridgeTransport = class {
|
|
311
|
-
constructor(host) {
|
|
312
|
-
this.host = host;
|
|
313
|
-
this.kind = "native";
|
|
314
|
-
this.handlers = /* @__PURE__ */ new Set();
|
|
315
|
-
host.receive = (envelope) => {
|
|
316
|
-
let data = envelope;
|
|
317
|
-
if (typeof envelope === "string") {
|
|
318
|
-
try {
|
|
319
|
-
data = JSON.parse(envelope);
|
|
320
|
-
} catch {
|
|
321
|
-
return;
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
if (!data || typeof data !== "object") return;
|
|
325
|
-
this.handlers.forEach((h) => h({ data, origin: null }));
|
|
326
|
-
};
|
|
327
|
-
}
|
|
328
|
-
send(envelope) {
|
|
329
|
-
this.host.postMessage(JSON.stringify(envelope));
|
|
330
|
-
}
|
|
331
|
-
subscribe(handler) {
|
|
332
|
-
this.handlers.add(handler);
|
|
333
|
-
return () => {
|
|
334
|
-
this.handlers.delete(handler);
|
|
335
|
-
};
|
|
336
|
-
}
|
|
337
|
-
};
|
|
338
|
-
var active;
|
|
339
|
-
function getTransport() {
|
|
340
|
-
if (active !== void 0) return active;
|
|
341
|
-
if (!isBrowser()) {
|
|
342
|
-
active = null;
|
|
343
|
-
return active;
|
|
344
|
-
}
|
|
345
|
-
const nativeHost = window.GameHubNativeHost;
|
|
346
|
-
if (nativeHost && typeof nativeHost.postMessage === "function") {
|
|
347
|
-
active = new NativeBridgeTransport(nativeHost);
|
|
348
|
-
} else if (window.parent !== window) {
|
|
349
|
-
active = new PostMessageTransport();
|
|
350
|
-
} else {
|
|
351
|
-
active = null;
|
|
352
|
-
}
|
|
353
|
-
return active;
|
|
354
|
-
}
|
|
355
|
-
function hasHost() {
|
|
356
|
-
return getTransport() !== null;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
// src/bridge.ts
|
|
360
|
-
function parseApiResponse(value) {
|
|
361
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
362
|
-
const response = value;
|
|
363
|
-
if (typeof response.success !== "boolean") return null;
|
|
364
|
-
const parsed = { success: response.success };
|
|
365
|
-
if ("data" in response) parsed.data = response.data;
|
|
366
|
-
if (response.token !== void 0) {
|
|
367
|
-
if (typeof response.token !== "string" || response.token.length > 4e3) {
|
|
368
|
-
return null;
|
|
369
|
-
}
|
|
370
|
-
parsed.token = response.token;
|
|
371
|
-
}
|
|
372
|
-
if (response.error !== void 0) {
|
|
373
|
-
if (!response.error || typeof response.error !== "object" || Array.isArray(response.error)) {
|
|
374
|
-
return null;
|
|
375
|
-
}
|
|
376
|
-
const error2 = response.error;
|
|
377
|
-
if (error2.code !== void 0 && (typeof error2.code !== "string" || error2.code.length > 100) || error2.message !== void 0 && (typeof error2.message !== "string" || error2.message.length > 4e3)) {
|
|
378
|
-
return null;
|
|
379
|
-
}
|
|
380
|
-
const parsedError = {};
|
|
381
|
-
if (typeof error2.code === "string") parsedError.code = error2.code;
|
|
382
|
-
if (typeof error2.message === "string") parsedError.message = error2.message;
|
|
383
|
-
if (error2.details !== void 0) {
|
|
384
|
-
if (!error2.details || typeof error2.details !== "object" || Array.isArray(error2.details)) {
|
|
385
|
-
return null;
|
|
386
|
-
}
|
|
387
|
-
const details = error2.details;
|
|
388
|
-
if (details.terminal !== void 0 && typeof details.terminal !== "boolean" || details.sessionStatus !== void 0 && (typeof details.sessionStatus !== "string" || details.sessionStatus.length > 100) || details.retryAfterMs !== void 0 && (typeof details.retryAfterMs !== "number" || !Number.isFinite(details.retryAfterMs) || details.retryAfterMs < 0)) {
|
|
389
|
-
return null;
|
|
390
|
-
}
|
|
391
|
-
parsedError.details = {
|
|
392
|
-
...typeof details.terminal === "boolean" ? { terminal: details.terminal } : {},
|
|
393
|
-
...typeof details.sessionStatus === "string" ? { sessionStatus: details.sessionStatus } : {},
|
|
394
|
-
...typeof details.retryAfterMs === "number" ? { retryAfterMs: details.retryAfterMs } : {}
|
|
395
|
-
};
|
|
396
|
-
}
|
|
397
|
-
parsed.error = parsedError;
|
|
398
|
-
}
|
|
399
|
-
return parsed;
|
|
400
|
-
}
|
|
401
|
-
function trimToNullable(value) {
|
|
402
|
-
if (value === null) return null;
|
|
403
|
-
if (typeof value !== "string") return void 0;
|
|
404
|
-
const trimmed = value.trim();
|
|
405
|
-
return trimmed ? trimmed : null;
|
|
406
|
-
}
|
|
407
|
-
function mergeBootstrapConfig(config = {}) {
|
|
408
|
-
if (!config || typeof config !== "object" || Array.isArray(config)) return;
|
|
409
|
-
mergeSettings(config.settings);
|
|
410
|
-
if (config.multiplayerSession !== void 0)
|
|
411
|
-
acceptLobbyState(
|
|
412
|
-
config.multiplayerSession ?? {
|
|
413
|
-
session: null,
|
|
414
|
-
busy: false,
|
|
415
|
-
error: null,
|
|
416
|
-
disconnected: false
|
|
417
|
-
}
|
|
418
|
-
);
|
|
419
|
-
if (config.multiplayerEntry === null) state.multiplayerEntry = null;
|
|
420
|
-
else if (config.multiplayerEntry && ["create", "join"].includes(config.multiplayerEntry.action)) {
|
|
421
|
-
const entry = config.multiplayerEntry;
|
|
422
|
-
state.multiplayerEntry = {
|
|
423
|
-
action: entry.action,
|
|
424
|
-
...typeof entry.roomCode === "string" && /^\d{6}$/.test(entry.roomCode) ? { roomCode: entry.roomCode } : {},
|
|
425
|
-
...entry.type === "player" || entry.type === "spectator" ? { type: entry.type } : {}
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
|
-
const apply = (key, raw) => {
|
|
429
|
-
const next = trimToNullable(raw);
|
|
430
|
-
if (next === void 0) return;
|
|
431
|
-
state[key] = next;
|
|
432
|
-
};
|
|
433
|
-
apply("gameSlug", config.gameSlug);
|
|
434
|
-
apply("authToken", config.authToken);
|
|
435
|
-
apply("leagueId", config.leagueId);
|
|
436
|
-
apply("gameId", config.gameId);
|
|
437
|
-
apply("matchId", config.matchId);
|
|
438
|
-
if (config.sessionMode === null || ["authenticated", "embed-guest", "league-guest"].includes(
|
|
439
|
-
config.sessionMode
|
|
440
|
-
)) {
|
|
441
|
-
state.bootstrapSessionMode = config.sessionMode ?? null;
|
|
442
|
-
}
|
|
443
|
-
const applyBootstrap = (key, raw) => {
|
|
444
|
-
const next = trimToNullable(raw);
|
|
445
|
-
if (next === void 0) return;
|
|
446
|
-
state[key] = next;
|
|
447
|
-
};
|
|
448
|
-
applyBootstrap("bootstrapMode", config.mode);
|
|
449
|
-
applyBootstrap("bootstrapPlayerName", config.playerName);
|
|
450
|
-
applyBootstrap("bootstrapPlayerCount", config.playerCount);
|
|
451
|
-
applyBootstrap("bootstrapTeamOneName", config.teamOneName);
|
|
452
|
-
applyBootstrap("bootstrapTeamTwoName", config.teamTwoName);
|
|
453
|
-
applyBootstrap("bootstrapProfileId", config.profileId);
|
|
454
|
-
if (Array.isArray(config.capabilities))
|
|
455
|
-
state.bootstrapCapabilities = config.capabilities.filter((c) => typeof c === "string" && c.length <= 100).slice(0, 32);
|
|
456
|
-
const launch = config.multiplayerLaunch;
|
|
457
|
-
if (launch === null) state.bootstrapLaunch = null;
|
|
458
|
-
else if (launch && launch.version === 2 && (launch.recoveryGraceMs === void 0 || Number.isSafeInteger(launch.recoveryGraceMs) && launch.recoveryGraceMs >= 1e3 && launch.recoveryGraceMs <= 12e4) && [
|
|
459
|
-
"multiplayerSessionId",
|
|
460
|
-
"roundId",
|
|
461
|
-
"attemptId",
|
|
462
|
-
"seatId",
|
|
463
|
-
"hostInstanceId"
|
|
464
|
-
].every(
|
|
465
|
-
(k) => typeof launch[k] === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(String(launch[k]))
|
|
466
|
-
) && typeof launch.gameUrl === "string" && launch.gameUrl.startsWith("/games/") && launch.gameUrl.length < 2048 && ["server", "unverified"].includes(launch.scoreAuthority))
|
|
467
|
-
state.bootstrapLaunch = { ...launch };
|
|
468
|
-
}
|
|
469
|
-
function snapshotBootstrap() {
|
|
470
|
-
return {
|
|
471
|
-
multiplayerEntry: state.multiplayerEntry,
|
|
472
|
-
multiplayerSession: lobbySnapshot(),
|
|
473
|
-
settings: getSettings(),
|
|
474
|
-
gameSlug: state.gameSlug,
|
|
475
|
-
authToken: state.authToken,
|
|
476
|
-
leagueId: state.leagueId,
|
|
477
|
-
gameId: state.gameId,
|
|
478
|
-
matchId: state.matchId,
|
|
479
|
-
sessionMode: state.bootstrapSessionMode,
|
|
480
|
-
mode: state.bootstrapMode,
|
|
481
|
-
playerName: state.bootstrapPlayerName,
|
|
482
|
-
playerCount: state.bootstrapPlayerCount,
|
|
483
|
-
teamOneName: state.bootstrapTeamOneName,
|
|
484
|
-
teamTwoName: state.bootstrapTeamTwoName,
|
|
485
|
-
profileId: state.bootstrapProfileId,
|
|
486
|
-
multiplayerLaunch: state.bootstrapLaunch,
|
|
487
|
-
capabilities: state.bootstrapCapabilities
|
|
488
|
-
};
|
|
489
|
-
}
|
|
490
|
-
function requestBootstrapFromParent() {
|
|
491
|
-
const transport = getTransport();
|
|
492
|
-
if (!transport) {
|
|
493
|
-
return Promise.resolve(null);
|
|
494
|
-
}
|
|
495
|
-
if (state.bootstrapReceived) {
|
|
496
|
-
return Promise.resolve(snapshotBootstrap());
|
|
497
|
-
}
|
|
498
|
-
if (state.bootstrapRequestPromise) {
|
|
499
|
-
return state.bootstrapRequestPromise;
|
|
500
|
-
}
|
|
501
|
-
state.bootstrapRequestPromise = new Promise(
|
|
502
|
-
(resolve) => {
|
|
503
|
-
const messageId = Date.now().toString();
|
|
504
|
-
let settled = false;
|
|
505
|
-
let timeoutId = null;
|
|
506
|
-
let unsubscribe = () => {
|
|
507
|
-
};
|
|
508
|
-
const handler = (msg) => {
|
|
509
|
-
const data = msg.data;
|
|
510
|
-
if (data && data.type === MESSAGE_PREFIX + "_BOOTSTRAP" && data.payload && data.messageId === messageId) {
|
|
511
|
-
if (settled) return;
|
|
512
|
-
if (!acceptParentOrigin(msg.origin)) return;
|
|
513
|
-
settled = true;
|
|
514
|
-
unsubscribe();
|
|
515
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
516
|
-
state.bootstrapReceived = true;
|
|
517
|
-
mergeBootstrapConfig(data.payload);
|
|
518
|
-
resolve(data.payload);
|
|
519
|
-
}
|
|
520
|
-
};
|
|
521
|
-
unsubscribe = transport.subscribe(handler);
|
|
522
|
-
transport.send({
|
|
523
|
-
type: MESSAGE_PREFIX + "_BOOTSTRAP_REQUEST",
|
|
524
|
-
messageId
|
|
525
|
-
});
|
|
526
|
-
timeoutId = setTimeout(() => {
|
|
527
|
-
if (settled) return;
|
|
528
|
-
settled = true;
|
|
529
|
-
unsubscribe();
|
|
530
|
-
resolve(null);
|
|
531
|
-
}, PARENT_REQUEST_TIMEOUT_MS);
|
|
532
|
-
}
|
|
533
|
-
).finally(() => {
|
|
534
|
-
state.bootstrapRequestPromise = null;
|
|
535
|
-
});
|
|
536
|
-
return state.bootstrapRequestPromise;
|
|
537
|
-
}
|
|
538
|
-
function getAuthTokenFromParent() {
|
|
539
|
-
return new Promise((resolve) => {
|
|
540
|
-
const transport = getTransport();
|
|
541
|
-
if (!transport) {
|
|
542
|
-
resolve(null);
|
|
543
|
-
return;
|
|
544
|
-
}
|
|
545
|
-
const messageId = Date.now().toString();
|
|
546
|
-
let settled = false;
|
|
547
|
-
let timeoutId = null;
|
|
548
|
-
let unsubscribe = () => {
|
|
549
|
-
};
|
|
550
|
-
const handler = (msg) => {
|
|
551
|
-
const data = msg.data;
|
|
552
|
-
if (data && data.type === MESSAGE_PREFIX + "_AUTH_RESPONSE" && data.messageId === messageId) {
|
|
553
|
-
if (settled) return;
|
|
554
|
-
if (!acceptParentOrigin(msg.origin)) return;
|
|
555
|
-
settled = true;
|
|
556
|
-
unsubscribe();
|
|
557
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
558
|
-
if (data.leagueId) state.leagueId = data.leagueId;
|
|
559
|
-
if (data.gameId) state.gameId = data.gameId;
|
|
560
|
-
if (data.matchId) state.matchId = data.matchId;
|
|
561
|
-
resolve(data.token || null);
|
|
562
|
-
}
|
|
563
|
-
};
|
|
564
|
-
unsubscribe = transport.subscribe(handler);
|
|
565
|
-
transport.send({ type: MESSAGE_PREFIX + "_AUTH_REQUEST", messageId });
|
|
566
|
-
timeoutId = setTimeout(() => {
|
|
567
|
-
if (settled) return;
|
|
568
|
-
settled = true;
|
|
569
|
-
unsubscribe();
|
|
570
|
-
resolve(null);
|
|
571
|
-
}, PARENT_REQUEST_TIMEOUT_MS);
|
|
572
|
-
});
|
|
573
|
-
}
|
|
574
|
-
var apiRequestSeq = 0;
|
|
575
|
-
function requestApiFromParent(endpoint, options = {}) {
|
|
576
|
-
return new Promise((resolve, reject) => {
|
|
577
|
-
const transport = getTransport();
|
|
578
|
-
if (!transport) {
|
|
579
|
-
reject(new Error("Host bridge unavailable: no host transport"));
|
|
580
|
-
return;
|
|
581
|
-
}
|
|
582
|
-
const messageId = "api_" + Date.now().toString() + "_" + ++apiRequestSeq;
|
|
583
|
-
let settled = false;
|
|
584
|
-
let timeoutId = null;
|
|
585
|
-
let unsubscribe = () => {
|
|
586
|
-
};
|
|
587
|
-
const handler = (msg) => {
|
|
588
|
-
const data = msg.data;
|
|
589
|
-
if (!data || data.type !== MESSAGE_PREFIX + "_API_RESPONSE" || data.messageId !== messageId) {
|
|
590
|
-
return;
|
|
591
|
-
}
|
|
592
|
-
if (settled) return;
|
|
593
|
-
if (!acceptParentOrigin(msg.origin)) return;
|
|
594
|
-
settled = true;
|
|
595
|
-
unsubscribe();
|
|
596
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
597
|
-
const apiResponse = parseApiResponse(data.result);
|
|
598
|
-
if (apiResponse) {
|
|
599
|
-
resolve(apiResponse);
|
|
600
|
-
} else if (!data.ok) {
|
|
601
|
-
reject(new Error(data.error || "Host API request failed"));
|
|
602
|
-
} else {
|
|
603
|
-
reject(new Error("Host API response was invalid"));
|
|
604
|
-
}
|
|
605
|
-
};
|
|
606
|
-
timeoutId = setTimeout(() => {
|
|
607
|
-
if (settled) return;
|
|
608
|
-
settled = true;
|
|
609
|
-
unsubscribe();
|
|
610
|
-
reject(new Error("Host API request timed out"));
|
|
611
|
-
}, HOST_API_TIMEOUT_MS);
|
|
612
|
-
unsubscribe = transport.subscribe(handler);
|
|
613
|
-
transport.send({
|
|
614
|
-
type: MESSAGE_PREFIX + "_API_REQUEST",
|
|
615
|
-
messageId,
|
|
616
|
-
endpoint,
|
|
617
|
-
method: options.method || "GET",
|
|
618
|
-
body: options.body ?? null
|
|
619
|
-
});
|
|
620
|
-
});
|
|
621
|
-
}
|
|
622
|
-
function sendToParent(type, data) {
|
|
623
|
-
const transport = getTransport();
|
|
624
|
-
if (!transport) return;
|
|
625
|
-
try {
|
|
626
|
-
transport.send({
|
|
627
|
-
type: MESSAGE_PREFIX + "_" + type,
|
|
628
|
-
gameSlug: state.gameSlug,
|
|
629
|
-
...data
|
|
630
|
-
});
|
|
631
|
-
} catch {
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
// src/api-client.ts
|
|
636
|
-
async function apiRequest(endpoint, options = {}) {
|
|
637
|
-
if (hasHost()) {
|
|
638
|
-
return requestApiFromParent(endpoint, options);
|
|
639
|
-
}
|
|
640
|
-
const url = state.apiBase + endpoint;
|
|
641
|
-
const headers = {
|
|
642
|
-
"Content-Type": "application/json",
|
|
643
|
-
...options.headers || {}
|
|
644
|
-
};
|
|
645
|
-
if (state.authToken) {
|
|
646
|
-
headers.Authorization = "Bearer " + state.authToken;
|
|
647
|
-
}
|
|
648
|
-
const response = await fetch(url, {
|
|
649
|
-
...options,
|
|
650
|
-
credentials: options.credentials || "same-origin",
|
|
651
|
-
headers,
|
|
652
|
-
body: options.body ? JSON.stringify(options.body) : void 0
|
|
653
|
-
});
|
|
654
|
-
return response.json();
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
// src/session.ts
|
|
658
|
-
var MAX_ATTEMPTS = 1e6;
|
|
659
|
-
var MAX_SCORE = 1e7;
|
|
660
|
-
var MAX_META_BYTES = 32 * 1024;
|
|
661
|
-
var MAX_META_DEPTH = 5;
|
|
662
|
-
var MAX_META_KEYS = 200;
|
|
663
|
-
var MAX_META_KEY_LENGTH = 100;
|
|
664
|
-
var MAX_META_STRING_LENGTH = 2048;
|
|
665
|
-
var MAX_META_ARRAY_LENGTH = 100;
|
|
666
|
-
var FORBIDDEN_META_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
667
|
-
var NON_CLIENT_META_KEYS = /* @__PURE__ */ new Set([
|
|
668
|
-
"attempts",
|
|
669
|
-
"duration",
|
|
670
|
-
"durationMs",
|
|
671
|
-
"timeTaken",
|
|
672
|
-
"serverDurationMs",
|
|
673
|
-
"userId",
|
|
674
|
-
"gameId",
|
|
675
|
-
"source",
|
|
676
|
-
"sessionId",
|
|
677
|
-
"token"
|
|
678
|
-
]);
|
|
679
|
-
function stableJson(value) {
|
|
680
|
-
if (value === null || typeof value !== "object") {
|
|
681
|
-
return JSON.stringify(value) ?? "null";
|
|
682
|
-
}
|
|
683
|
-
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
|
684
|
-
return `{${Object.keys(value).sort().map(
|
|
685
|
-
(key) => `${JSON.stringify(key)}:${stableJson(value[key])}`
|
|
686
|
-
).join(",")}}`;
|
|
687
|
-
}
|
|
688
|
-
function failedResult(code, message, retriable) {
|
|
689
|
-
return {
|
|
690
|
-
success: false,
|
|
691
|
-
status: "failed",
|
|
692
|
-
terminal: false,
|
|
693
|
-
code,
|
|
694
|
-
error: message,
|
|
695
|
-
retriable
|
|
696
|
-
};
|
|
697
|
-
}
|
|
698
|
-
function isValidMetadata(value) {
|
|
699
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
700
|
-
try {
|
|
701
|
-
const prototype = Object.getPrototypeOf(value);
|
|
702
|
-
if (prototype !== Object.prototype && prototype !== null) return false;
|
|
703
|
-
let keyCount = 0;
|
|
704
|
-
const visit = (item, depth) => {
|
|
705
|
-
if (depth > MAX_META_DEPTH) return false;
|
|
706
|
-
if (item === null || typeof item === "boolean") return true;
|
|
707
|
-
if (typeof item === "number") {
|
|
708
|
-
return Number.isFinite(item) && Math.abs(item) <= Number.MAX_SAFE_INTEGER;
|
|
709
|
-
}
|
|
710
|
-
if (typeof item === "string") {
|
|
711
|
-
return item.length <= MAX_META_STRING_LENGTH;
|
|
712
|
-
}
|
|
713
|
-
if (Array.isArray(item)) {
|
|
714
|
-
return item.length <= MAX_META_ARRAY_LENGTH && item.every((entry) => visit(entry, depth + 1));
|
|
715
|
-
}
|
|
716
|
-
if (!item || typeof item !== "object") return false;
|
|
717
|
-
const itemPrototype = Object.getPrototypeOf(item);
|
|
718
|
-
if (itemPrototype !== Object.prototype && itemPrototype !== null) {
|
|
719
|
-
return false;
|
|
720
|
-
}
|
|
721
|
-
for (const [key, entry] of Object.entries(item)) {
|
|
722
|
-
keyCount += 1;
|
|
723
|
-
if (keyCount > MAX_META_KEYS || key.length === 0 || key.length > MAX_META_KEY_LENGTH || FORBIDDEN_META_KEYS.has(key) || !visit(entry, depth + 1)) {
|
|
724
|
-
return false;
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
return true;
|
|
728
|
-
};
|
|
729
|
-
return visit(value, 0) && new TextEncoder().encode(JSON.stringify(value)).byteLength <= MAX_META_BYTES;
|
|
730
|
-
} catch {
|
|
731
|
-
return false;
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
function prepareSubmission(token, score, meta) {
|
|
735
|
-
if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || Math.floor(score) > MAX_SCORE) {
|
|
736
|
-
return {
|
|
737
|
-
ok: false,
|
|
738
|
-
result: failedResult(
|
|
739
|
-
"INVALID_INPUT",
|
|
740
|
-
`Score must be a finite number between 0 and ${MAX_SCORE}`,
|
|
741
|
-
false
|
|
742
|
-
)
|
|
743
|
-
};
|
|
744
|
-
}
|
|
745
|
-
if (!isValidMetadata(meta)) {
|
|
746
|
-
return {
|
|
747
|
-
ok: false,
|
|
748
|
-
result: failedResult(
|
|
749
|
-
"INVALID_INPUT",
|
|
750
|
-
"Score metadata exceeds the allowed bounds",
|
|
751
|
-
false
|
|
752
|
-
)
|
|
753
|
-
};
|
|
754
|
-
}
|
|
755
|
-
let snapshot;
|
|
756
|
-
try {
|
|
757
|
-
snapshot = JSON.parse(JSON.stringify(meta));
|
|
758
|
-
} catch {
|
|
759
|
-
return {
|
|
760
|
-
ok: false,
|
|
761
|
-
result: failedResult(
|
|
762
|
-
"INVALID_INPUT",
|
|
763
|
-
"Score metadata must be JSON serializable",
|
|
764
|
-
false
|
|
765
|
-
)
|
|
766
|
-
};
|
|
767
|
-
}
|
|
768
|
-
const attemptsValue = snapshot.attempts;
|
|
769
|
-
const attempts = typeof attemptsValue === "number" && Number.isFinite(attemptsValue) && attemptsValue >= 0 ? Math.min(Math.floor(attemptsValue), MAX_ATTEMPTS) : 0;
|
|
770
|
-
const clientMeta = Object.fromEntries(
|
|
771
|
-
Object.entries(snapshot).filter(([key]) => !NON_CLIENT_META_KEYS.has(key))
|
|
772
|
-
);
|
|
773
|
-
const integerScore = Math.floor(score);
|
|
774
|
-
return {
|
|
775
|
-
ok: true,
|
|
776
|
-
canonicalPayload: stableJson({
|
|
777
|
-
score: integerScore,
|
|
778
|
-
attempts,
|
|
779
|
-
clientMeta
|
|
780
|
-
}),
|
|
781
|
-
body: { token, score: integerScore, meta: snapshot }
|
|
782
|
-
};
|
|
783
|
-
}
|
|
784
|
-
function clearTerminalSession() {
|
|
785
|
-
state.sessionToken = null;
|
|
786
|
-
state.sessionStartPromise = null;
|
|
787
|
-
state.submissionPromise = null;
|
|
788
|
-
state.pendingSubmission = null;
|
|
789
|
-
}
|
|
790
|
-
async function performStartSession() {
|
|
791
|
-
if (!state.gameSlug) return { success: false, error: "Game slug not set" };
|
|
792
|
-
const isLeagueMatchSession = Boolean(
|
|
793
|
-
state.leagueId && state.gameId && state.matchId
|
|
794
|
-
);
|
|
795
|
-
const isEmbedGuestSession = state.bootstrapSessionMode === "embed-guest";
|
|
796
|
-
const isHostAuthenticatedSession = state.bootstrapSessionMode === "authenticated";
|
|
797
|
-
if (!state.authToken && !isLeagueMatchSession && !isEmbedGuestSession && !isHostAuthenticatedSession) {
|
|
798
|
-
return { success: false, error: "User not authenticated" };
|
|
799
|
-
}
|
|
800
|
-
try {
|
|
801
|
-
let endpoint = "/sessions/start";
|
|
802
|
-
let body = { gameSlug: state.gameSlug };
|
|
803
|
-
if (state.leagueId && state.gameId && state.matchId) {
|
|
804
|
-
endpoint = "/leagues/" + state.leagueId + "/matches/" + state.matchId + "/session";
|
|
805
|
-
body = { gameId: state.gameId };
|
|
806
|
-
} else if (state.leagueId && state.gameId) {
|
|
807
|
-
endpoint = "/leagues/" + state.leagueId + "/sessions";
|
|
808
|
-
body = { gameId: state.gameId };
|
|
809
|
-
}
|
|
810
|
-
const result = await apiRequest(endpoint, { method: "POST", body });
|
|
811
|
-
const data = unwrapResult(result);
|
|
812
|
-
const token = data?.token || result?.token || null;
|
|
813
|
-
if (result.success && typeof token === "string" && token) {
|
|
814
|
-
state.sessionToken = token;
|
|
815
|
-
sendToParent("SESSION_STARTED", { token });
|
|
816
|
-
return { success: true, token };
|
|
817
|
-
}
|
|
818
|
-
return {
|
|
819
|
-
success: false,
|
|
820
|
-
error: result.error?.message || "Failed to start session"
|
|
821
|
-
};
|
|
822
|
-
} catch (err) {
|
|
823
|
-
return { success: false, error: err?.message || "Failed to start session" };
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
async function startSession() {
|
|
827
|
-
if (state.bootstrapLaunch || state.bootstrapCapabilities.includes(MULTIPLAYER_LOBBY_CAPABILITY))
|
|
828
|
-
return { success: false, error: "Multiplayer rounds own their results" };
|
|
829
|
-
if (state.sessionToken) return { success: true, token: state.sessionToken };
|
|
830
|
-
if (state.sessionStartPromise) return await state.sessionStartPromise;
|
|
831
|
-
const promise = performStartSession();
|
|
832
|
-
state.sessionStartPromise = promise;
|
|
833
|
-
try {
|
|
834
|
-
return await promise;
|
|
835
|
-
} finally {
|
|
836
|
-
if (state.sessionStartPromise === promise) state.sessionStartPromise = null;
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
function normalizeSubmissionResult(result, token) {
|
|
840
|
-
const data = unwrapResult(result);
|
|
841
|
-
if (result.success && data?.status === "accepted" && data?.terminal === true && typeof data?.sessionId === "string" && typeof data?.serverDurationMs === "number" && Number.isFinite(data.serverDurationMs) && typeof data?.timeTaken === "number" && Number.isFinite(data.timeTaken)) {
|
|
842
|
-
return {
|
|
843
|
-
success: true,
|
|
844
|
-
status: "accepted",
|
|
845
|
-
terminal: true,
|
|
846
|
-
sessionId: data.sessionId,
|
|
847
|
-
serverDurationMs: data.serverDurationMs,
|
|
848
|
-
timeTaken: data.timeTaken,
|
|
849
|
-
...data.replayed === true ? { replayed: true } : {}
|
|
850
|
-
};
|
|
851
|
-
}
|
|
852
|
-
if (result.success && data?.accepted === true && typeof data?.timeTaken === "number" && Number.isFinite(data.timeTaken)) {
|
|
853
|
-
return {
|
|
854
|
-
success: true,
|
|
855
|
-
status: "accepted",
|
|
856
|
-
terminal: true,
|
|
857
|
-
sessionId: token,
|
|
858
|
-
serverDurationMs: Math.max(0, Math.floor(data.timeTaken * 1e3)),
|
|
859
|
-
timeTaken: Math.max(0, Math.floor(data.timeTaken))
|
|
860
|
-
};
|
|
861
|
-
}
|
|
862
|
-
const apiError = result.error;
|
|
863
|
-
const code = apiError?.code || "SERVER_ERROR";
|
|
864
|
-
const message = apiError?.message || "Score submission failed";
|
|
865
|
-
const details = apiError?.details;
|
|
866
|
-
if (details?.terminal === true) {
|
|
867
|
-
return {
|
|
868
|
-
success: false,
|
|
869
|
-
status: "rejected",
|
|
870
|
-
terminal: true,
|
|
871
|
-
code,
|
|
872
|
-
error: message,
|
|
873
|
-
...typeof details.sessionStatus === "string" ? { sessionStatus: details.sessionStatus } : {}
|
|
874
|
-
};
|
|
875
|
-
}
|
|
876
|
-
if (code === "SUBMISSION_IN_PROGRESS" || code === "RATE_LIMITED") {
|
|
877
|
-
return {
|
|
878
|
-
success: false,
|
|
879
|
-
status: "retriable",
|
|
880
|
-
terminal: false,
|
|
881
|
-
code,
|
|
882
|
-
error: message,
|
|
883
|
-
...typeof details?.retryAfterMs === "number" ? { retryAfterMs: details.retryAfterMs } : {},
|
|
884
|
-
...typeof details?.sessionStatus === "string" ? { sessionStatus: details.sessionStatus } : {}
|
|
885
|
-
};
|
|
886
|
-
}
|
|
887
|
-
return failedResult(code, message, code === "SERVER_ERROR");
|
|
888
|
-
}
|
|
889
|
-
async function performSubmission(pending2) {
|
|
890
|
-
let outcome;
|
|
891
|
-
try {
|
|
892
|
-
const response = await apiRequest("/sessions/submit", {
|
|
893
|
-
method: "POST",
|
|
894
|
-
body: pending2.body
|
|
895
|
-
});
|
|
896
|
-
outcome = normalizeSubmissionResult(response, pending2.token);
|
|
897
|
-
} catch (err) {
|
|
898
|
-
outcome = failedResult(
|
|
899
|
-
"TRANSPORT_ERROR",
|
|
900
|
-
err?.message || "Score submission transport failed",
|
|
901
|
-
true
|
|
902
|
-
);
|
|
903
|
-
}
|
|
904
|
-
if (outcome.success) {
|
|
905
|
-
sendToParent("SCORE_SUBMITTED", {
|
|
906
|
-
score: pending2.body.score,
|
|
907
|
-
sessionId: outcome.sessionId,
|
|
908
|
-
status: outcome.status,
|
|
909
|
-
terminal: outcome.terminal,
|
|
910
|
-
serverDurationMs: outcome.serverDurationMs,
|
|
911
|
-
timeTaken: outcome.timeTaken,
|
|
912
|
-
...outcome.replayed ? { replayed: true } : {}
|
|
913
|
-
});
|
|
914
|
-
clearTerminalSession();
|
|
915
|
-
} else if (outcome.terminal) {
|
|
916
|
-
clearTerminalSession();
|
|
917
|
-
}
|
|
918
|
-
return outcome;
|
|
919
|
-
}
|
|
920
|
-
async function submitScore(score, meta = {}) {
|
|
921
|
-
await ensureInitialized();
|
|
922
|
-
if (state.bootstrapLaunch || state.bootstrapCapabilities.includes(MULTIPLAYER_LOBBY_CAPABILITY))
|
|
923
|
-
return failedResult(
|
|
924
|
-
"FORBIDDEN",
|
|
925
|
-
"Multiplayer rounds own their results",
|
|
926
|
-
false
|
|
927
|
-
);
|
|
928
|
-
if (!state.isInitialized) {
|
|
929
|
-
return failedResult(
|
|
930
|
-
"SDK_NOT_INITIALIZED",
|
|
931
|
-
"SDK could not initialize. Is game slug set?",
|
|
932
|
-
false
|
|
933
|
-
);
|
|
934
|
-
}
|
|
935
|
-
if (!state.sessionToken) {
|
|
936
|
-
if (state.sessionStartPromise) {
|
|
937
|
-
await state.sessionStartPromise;
|
|
938
|
-
} else {
|
|
939
|
-
const sessionResult = await startSession();
|
|
940
|
-
if (!sessionResult.success) {
|
|
941
|
-
return failedResult(
|
|
942
|
-
"SESSION_START_FAILED",
|
|
943
|
-
sessionResult.error || "Could not start session",
|
|
944
|
-
true
|
|
945
|
-
);
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
if (!state.sessionToken) {
|
|
950
|
-
return failedResult(
|
|
951
|
-
"SESSION_START_FAILED",
|
|
952
|
-
"No active session. User may not be authenticated.",
|
|
953
|
-
true
|
|
954
|
-
);
|
|
955
|
-
}
|
|
956
|
-
const prepared = prepareSubmission(state.sessionToken, score, meta);
|
|
957
|
-
if (!prepared.ok) return prepared.result;
|
|
958
|
-
const pending2 = state.pendingSubmission;
|
|
959
|
-
if (pending2 && (pending2.token !== state.sessionToken || pending2.canonicalPayload !== prepared.canonicalPayload)) {
|
|
960
|
-
return failedResult(
|
|
961
|
-
"CONCURRENT_SUBMISSION_CONFLICT",
|
|
962
|
-
"A different payload is already bound to the active session",
|
|
963
|
-
false
|
|
964
|
-
);
|
|
965
|
-
}
|
|
966
|
-
if (state.submissionPromise) return await state.submissionPromise;
|
|
967
|
-
const activePending = pending2 ?? {
|
|
968
|
-
token: state.sessionToken,
|
|
969
|
-
canonicalPayload: prepared.canonicalPayload,
|
|
970
|
-
body: prepared.body
|
|
971
|
-
};
|
|
972
|
-
state.pendingSubmission = activePending;
|
|
973
|
-
const promise = performSubmission(activePending);
|
|
974
|
-
state.submissionPromise = promise;
|
|
975
|
-
try {
|
|
976
|
-
return await promise;
|
|
977
|
-
} finally {
|
|
978
|
-
if (state.submissionPromise === promise) state.submissionPromise = null;
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
async function submitMatchScore(score, meta = {}) {
|
|
982
|
-
if (!state.matchId) {
|
|
983
|
-
return failedResult(
|
|
984
|
-
"MATCH_CONTEXT_MISSING",
|
|
985
|
-
"No matchId found for this game session",
|
|
986
|
-
false
|
|
987
|
-
);
|
|
988
|
-
}
|
|
989
|
-
return await submitScore(score, {
|
|
990
|
-
...meta || {},
|
|
991
|
-
matchId: state.matchId,
|
|
992
|
-
leagueId: state.leagueId || meta.leagueId,
|
|
993
|
-
gameId: state.gameId || meta.gameId
|
|
994
|
-
});
|
|
995
|
-
}
|
|
996
|
-
async function submitMatchResult(result = {}) {
|
|
997
|
-
if (!result || typeof result !== "object") {
|
|
998
|
-
return failedResult(
|
|
999
|
-
"INVALID_INPUT",
|
|
1000
|
-
"match result payload is required",
|
|
1001
|
-
false
|
|
1002
|
-
);
|
|
1003
|
-
}
|
|
1004
|
-
return await submitMatchScore(0, { matchResult: result });
|
|
1005
|
-
}
|
|
1006
|
-
async function getQuestions(options = {}) {
|
|
1007
|
-
await ensureInitialized();
|
|
1008
|
-
const gameIdentifier = state.gameSlug || state.gameId;
|
|
1009
|
-
if (!gameIdentifier) return [];
|
|
1010
|
-
const { difficulty, category, limit } = options;
|
|
1011
|
-
if (difficulty && !["easy", "medium", "hard"].includes(difficulty)) {
|
|
1012
|
-
return [];
|
|
1013
|
-
}
|
|
1014
|
-
if (limit !== void 0 && (typeof limit !== "number" || limit < 1)) {
|
|
1015
|
-
return [];
|
|
1016
|
-
}
|
|
1017
|
-
const profileId = options.profileId || state.bootstrapProfileId || "";
|
|
1018
|
-
try {
|
|
1019
|
-
const params = new URLSearchParams({
|
|
1020
|
-
limit: String(
|
|
1021
|
-
Math.min(limit || QUESTIONS_LIMIT_CAP, QUESTIONS_LIMIT_CAP)
|
|
1022
|
-
),
|
|
1023
|
-
random: "true"
|
|
1024
|
-
});
|
|
1025
|
-
if (state.gameId) params.set("gameId", state.gameId);
|
|
1026
|
-
if (difficulty) params.set("difficulty", difficulty);
|
|
1027
|
-
if (category) params.set("category", String(category));
|
|
1028
|
-
if (profileId) params.set("profileId", profileId);
|
|
1029
|
-
const result = await apiRequest(
|
|
1030
|
-
"/games/" + encodeURIComponent(gameIdentifier) + "/questions?" + params.toString(),
|
|
1031
|
-
{ method: "GET" }
|
|
1032
|
-
);
|
|
1033
|
-
const data = unwrapResult(result);
|
|
1034
|
-
const raw = Array.isArray(data) ? data : Array.isArray(data?.questions) ? data.questions : [];
|
|
1035
|
-
return raw.map(normalizeQuestion);
|
|
1036
|
-
} catch {
|
|
1037
|
-
return [];
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
function normalizeQuestion(raw) {
|
|
1041
|
-
const q = raw;
|
|
1042
|
-
const answer = typeof q.answer === "number" ? String(q.answer) : q.answer;
|
|
1043
|
-
return { ...q, answer };
|
|
1044
|
-
}
|
|
1045
|
-
async function getWords(options = {}) {
|
|
1046
|
-
await ensureInitialized();
|
|
1047
|
-
const gameIdentifier = state.gameSlug || state.gameId;
|
|
1048
|
-
if (!gameIdentifier) return [];
|
|
1049
|
-
const { difficulty, category, tags, limit } = options;
|
|
1050
|
-
if (difficulty && !["easy", "medium", "hard"].includes(difficulty)) {
|
|
1051
|
-
return [];
|
|
1052
|
-
}
|
|
1053
|
-
if (limit !== void 0 && (typeof limit !== "number" || limit < 1)) {
|
|
1054
|
-
return [];
|
|
1055
|
-
}
|
|
1056
|
-
const profileId = options.profileId || state.bootstrapProfileId || "";
|
|
1057
|
-
try {
|
|
1058
|
-
const params = new URLSearchParams({
|
|
1059
|
-
limit: String(Math.min(limit || WORDS_LIMIT_CAP, WORDS_LIMIT_CAP)),
|
|
1060
|
-
random: "true"
|
|
1061
|
-
});
|
|
1062
|
-
if (state.gameId) params.set("gameId", state.gameId);
|
|
1063
|
-
if (difficulty) params.set("difficulty", difficulty);
|
|
1064
|
-
if (category) params.set("category", String(category));
|
|
1065
|
-
if (Array.isArray(tags) && tags.length > 0) {
|
|
1066
|
-
params.set("tags", tags.join(","));
|
|
1067
|
-
}
|
|
1068
|
-
if (profileId) params.set("profileId", profileId);
|
|
1069
|
-
const result = await apiRequest(
|
|
1070
|
-
"/games/" + encodeURIComponent(gameIdentifier) + "/words?" + params.toString(),
|
|
1071
|
-
{ method: "GET" }
|
|
1072
|
-
);
|
|
1073
|
-
const data = unwrapResult(result);
|
|
1074
|
-
const raw = Array.isArray(data) ? data : Array.isArray(data?.words) ? data.words : [];
|
|
1075
|
-
return raw;
|
|
1076
|
-
} catch {
|
|
1077
|
-
return [];
|
|
1078
|
-
}
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
// src/init.ts
|
|
1082
|
-
var environmentDetected = false;
|
|
1083
|
-
var hostListenerInstalled = false;
|
|
1084
|
-
function detectEnvironment() {
|
|
1085
|
-
if (!isBrowser() || environmentDetected) return;
|
|
1086
|
-
environmentDetected = true;
|
|
1087
|
-
state.sdkOrigin = window.location.origin;
|
|
1088
|
-
const runtimePathMatch = window.location.pathname.match(
|
|
1089
|
-
/^(.*)\/(?:uploaded-games|games)\/([a-z0-9-]+)(?:\/|$)/i
|
|
1090
|
-
);
|
|
1091
|
-
let detectedSlug = null;
|
|
1092
|
-
if (runtimePathMatch) {
|
|
1093
|
-
state.runtimeBasePath = runtimePathMatch[1] || "";
|
|
1094
|
-
detectedSlug = runtimePathMatch[2] || null;
|
|
1095
|
-
}
|
|
1096
|
-
state.leagueId = readQueryParam("leagueId");
|
|
1097
|
-
state.gameId = readQueryParam("gameId");
|
|
1098
|
-
state.matchId = readQueryParam("matchId");
|
|
1099
|
-
const scripts = document.getElementsByTagName("script");
|
|
1100
|
-
for (let i = 0; i < scripts.length; i++) {
|
|
1101
|
-
const src = scripts[i].src;
|
|
1102
|
-
if (!src.includes("gamehub-sdk.js")) continue;
|
|
1103
|
-
try {
|
|
1104
|
-
const parsedSrc = new URL(src, window.location.origin);
|
|
1105
|
-
state.sdkOrigin = parsedSrc.origin;
|
|
1106
|
-
const match = parsedSrc.pathname.match(/(.*)\/sdk\/gamehub-sdk\.js$/);
|
|
1107
|
-
state.sdkPathPrefix = match ? match[1] || "" : "";
|
|
1108
|
-
} catch {
|
|
1109
|
-
const match = src.match(/(.*)\/sdk\/gamehub-sdk\.js/);
|
|
1110
|
-
if (match) {
|
|
1111
|
-
const fallbackUrl = new URL(match[1], window.location.origin);
|
|
1112
|
-
state.sdkOrigin = fallbackUrl.origin;
|
|
1113
|
-
state.sdkPathPrefix = fallbackUrl.pathname || "";
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
const slugAttr = scripts[i].getAttribute("data-game-slug");
|
|
1117
|
-
if (slugAttr) detectedSlug = slugAttr;
|
|
1118
|
-
break;
|
|
1119
|
-
}
|
|
1120
|
-
if (!detectedSlug) {
|
|
1121
|
-
const pathMatch = window.location.pathname.match(
|
|
1122
|
-
/\/(?:uploaded-games|games)\/([a-z0-9-]+)\//i
|
|
1123
|
-
);
|
|
1124
|
-
if (pathMatch) detectedSlug = pathMatch[1];
|
|
1125
|
-
}
|
|
1126
|
-
const effectiveBasePath = state.sdkPathPrefix || state.runtimeBasePath || "";
|
|
1127
|
-
state.apiBase = state.sdkOrigin + effectiveBasePath + "/api";
|
|
1128
|
-
state.gameSlug = detectedSlug;
|
|
1129
|
-
}
|
|
1130
|
-
async function autoInit() {
|
|
1131
|
-
if (!isBrowser()) return false;
|
|
1132
|
-
if (state.isInitialized || state.isAutoInitializing) {
|
|
1133
|
-
return state.autoInitPromise;
|
|
1134
|
-
}
|
|
1135
|
-
detectEnvironment();
|
|
1136
|
-
installHostMessageListener();
|
|
1137
|
-
state.isAutoInitializing = true;
|
|
1138
|
-
state.autoInitPromise = (async () => {
|
|
1139
|
-
try {
|
|
1140
|
-
await requestBootstrapFromParent();
|
|
1141
|
-
if (!state.gameSlug) {
|
|
1142
|
-
warn(
|
|
1143
|
-
"Could not resolve game slug. Ensure the host page sends bootstrap config or serves the game under /games/{slug}."
|
|
1144
|
-
);
|
|
1145
|
-
state.isAutoInitializing = false;
|
|
1146
|
-
return false;
|
|
1147
|
-
}
|
|
1148
|
-
if (!state.authToken && !state.bootstrapLaunch && !state.bootstrapCapabilities.includes(MULTIPLAYER_LOBBY_CAPABILITY)) {
|
|
1149
|
-
state.authToken = await getAuthTokenFromParent();
|
|
1150
|
-
}
|
|
1151
|
-
state.isInitialized = true;
|
|
1152
|
-
state.isAutoInitializing = false;
|
|
1153
|
-
sendToParent("INIT", {
|
|
1154
|
-
slug: state.gameSlug,
|
|
1155
|
-
auto: true
|
|
1156
|
-
});
|
|
1157
|
-
if (state.authToken || state.bootstrapSessionMode === "authenticated" || state.bootstrapSessionMode === "embed-guest" || state.leagueId && state.gameId && state.matchId) {
|
|
1158
|
-
void startSession();
|
|
1159
|
-
}
|
|
1160
|
-
return true;
|
|
1161
|
-
} catch (err) {
|
|
1162
|
-
error("Auto-init failed:", err);
|
|
1163
|
-
state.isAutoInitializing = false;
|
|
1164
|
-
return false;
|
|
1165
|
-
}
|
|
1166
|
-
})();
|
|
1167
|
-
return state.autoInitPromise;
|
|
1168
|
-
}
|
|
1169
|
-
async function ensureInitialized() {
|
|
1170
|
-
if (state.isInitialized) return true;
|
|
1171
|
-
if (!isBrowser()) return false;
|
|
1172
|
-
if (state.autoInitPromise) return await state.autoInitPromise;
|
|
1173
|
-
return await autoInit();
|
|
1174
|
-
}
|
|
1175
|
-
function installHostMessageListener() {
|
|
1176
|
-
if (!isBrowser() || hostListenerInstalled) return;
|
|
1177
|
-
const transport = getTransport();
|
|
1178
|
-
if (!transport) return;
|
|
1179
|
-
hostListenerInstalled = true;
|
|
1180
|
-
transport.subscribe((msg) => {
|
|
1181
|
-
const data = msg.data;
|
|
1182
|
-
if (!data || !data.type) return;
|
|
1183
|
-
if (transport.kind !== "native" && (!state.parentOrigin || !acceptParentOrigin(msg.origin))) {
|
|
1184
|
-
return;
|
|
1185
|
-
}
|
|
1186
|
-
const type = data.type;
|
|
1187
|
-
if (type === MESSAGE_PREFIX + "_BOOTSTRAP" && data.payload) {
|
|
1188
|
-
state.bootstrapReceived = true;
|
|
1189
|
-
mergeBootstrapConfig(data.payload);
|
|
1190
|
-
}
|
|
1191
|
-
if (type === MESSAGE_PREFIX + "_MULTIPLAYER_SESSION" && state.bootstrapCapabilities.includes(MULTIPLAYER_LOBBY_CAPABILITY))
|
|
1192
|
-
acceptLobbyState(data.payload);
|
|
1193
|
-
if (type === MESSAGE_PREFIX + "_SET_AUTH") {
|
|
1194
|
-
state.authToken = data.token;
|
|
1195
|
-
if (state.gameSlug && !state.sessionToken && !state.sessionStartPromise && (state.authToken || state.leagueId && state.gameId && state.matchId)) {
|
|
1196
|
-
void startSession();
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
if (type === MESSAGE_PREFIX + "_COMMAND") {
|
|
1200
|
-
const command = data.command;
|
|
1201
|
-
const w = window;
|
|
1202
|
-
if (command === "pause" && typeof w.onGameHubPause === "function") {
|
|
1203
|
-
w.onGameHubPause();
|
|
1204
|
-
} else if (command === "resume" && typeof w.onGameHubResume === "function") {
|
|
1205
|
-
w.onGameHubResume();
|
|
1206
|
-
}
|
|
1207
|
-
}
|
|
1208
|
-
});
|
|
1209
|
-
}
|
|
1210
|
-
|
|
1211
|
-
// src/multiplayer.ts
|
|
1212
|
-
var pending = null;
|
|
1213
|
-
function requestMultiplayerLaunch() {
|
|
1214
|
-
if (!state.bootstrapLaunch || !state.bootstrapCapabilities.includes(MULTIPLAYER_CAPABILITY))
|
|
1215
|
-
return Promise.resolve({
|
|
1216
|
-
status: "terminal",
|
|
1217
|
-
error: {
|
|
1218
|
-
code: "PROTOCOL_UNSUPPORTED",
|
|
1219
|
-
message: "This host does not support multiplayer launch v2",
|
|
1220
|
-
retryable: false
|
|
1221
|
-
}
|
|
1222
|
-
});
|
|
1223
|
-
if (pending) return pending;
|
|
1224
|
-
const launch = state.bootstrapLaunch;
|
|
1225
|
-
const operation = (async () => {
|
|
1226
|
-
try {
|
|
1227
|
-
const response = await requestApiFromParent("/multiplayer/launch", {
|
|
1228
|
-
method: "POST",
|
|
1229
|
-
body: {}
|
|
1230
|
-
});
|
|
1231
|
-
if (state.bootstrapLaunch !== launch)
|
|
1232
|
-
return {
|
|
1233
|
-
status: "terminal",
|
|
1234
|
-
error: {
|
|
1235
|
-
code: "STALE_ATTEMPT",
|
|
1236
|
-
message: "Launch context changed",
|
|
1237
|
-
retryable: false
|
|
1238
|
-
}
|
|
1239
|
-
};
|
|
1240
|
-
const data = response.data;
|
|
1241
|
-
if (response.success && data) {
|
|
1242
|
-
if (data.status === "reserved" && data.launch && [
|
|
1243
|
-
"multiplayerSessionId",
|
|
1244
|
-
"roundId",
|
|
1245
|
-
"attemptId",
|
|
1246
|
-
"seatId",
|
|
1247
|
-
"hostInstanceId"
|
|
1248
|
-
].every(
|
|
1249
|
-
(k) => data.launch[k] === launch[k]
|
|
1250
|
-
) && data.reservation && ["name", "roomId", "sessionId"].every(
|
|
1251
|
-
(k) => typeof data.reservation[k] === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(
|
|
1252
|
-
String(data.reservation[k])
|
|
1253
|
-
)
|
|
1254
|
-
) && /^wss?:\/\//.test(data.wsEndpoint) && data.wsEndpoint.length < 2048 && Number.isSafeInteger(data.generation) && data.generation > 0 && Number.isSafeInteger(data.expiresAt))
|
|
1255
|
-
return data;
|
|
1256
|
-
if ((data.status === "recoverable" || data.status === "terminal") && data.error && typeof data.error.code === "string" && data.error.code.length <= 100 && typeof data.error.message === "string" && data.error.message.length <= 1e3 && typeof data.error.retryable === "boolean")
|
|
1257
|
-
return data;
|
|
1258
|
-
}
|
|
1259
|
-
return {
|
|
1260
|
-
status: "recoverable",
|
|
1261
|
-
error: {
|
|
1262
|
-
code: response.error?.code ?? "UNAVAILABLE",
|
|
1263
|
-
message: response.error?.message ?? "Launch unavailable",
|
|
1264
|
-
retryable: true
|
|
1265
|
-
}
|
|
1266
|
-
};
|
|
1267
|
-
} catch {
|
|
1268
|
-
return {
|
|
1269
|
-
status: "recoverable",
|
|
1270
|
-
error: {
|
|
1271
|
-
code: "UNAVAILABLE",
|
|
1272
|
-
message: "Launch request failed; retry",
|
|
1273
|
-
retryable: true
|
|
1274
|
-
}
|
|
1275
|
-
};
|
|
1276
|
-
}
|
|
1277
|
-
})().finally(() => {
|
|
1278
|
-
if (pending === operation) pending = null;
|
|
1279
|
-
});
|
|
1280
|
-
pending = operation;
|
|
1281
|
-
return operation;
|
|
1282
|
-
}
|
|
1283
|
-
|
|
1284
|
-
// src/match-context.ts
|
|
1285
|
-
async function fetchMatchContext() {
|
|
1286
|
-
if (!state.leagueId || !state.matchId) return null;
|
|
1287
|
-
if (state.matchContext) return state.matchContext;
|
|
1288
|
-
if (state.matchContextPromise) return await state.matchContextPromise;
|
|
1289
|
-
state.matchContextPromise = apiRequest(
|
|
1290
|
-
"/leagues/" + encodeURIComponent(state.leagueId) + "/matches/" + encodeURIComponent(state.matchId),
|
|
1291
|
-
{ method: "GET" }
|
|
1292
|
-
).then((result) => {
|
|
1293
|
-
const data = unwrapResult(result);
|
|
1294
|
-
if (result?.success && data) {
|
|
1295
|
-
state.matchContext = data;
|
|
1296
|
-
return state.matchContext;
|
|
1297
|
-
}
|
|
1298
|
-
return null;
|
|
1299
|
-
}).catch(() => null).finally(() => {
|
|
1300
|
-
state.matchContextPromise = null;
|
|
1301
|
-
});
|
|
1302
|
-
return await state.matchContextPromise;
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
|
-
// src/main.ts
|
|
1306
|
-
function createSdk() {
|
|
1307
|
-
return {
|
|
1308
|
-
version: SDK_VERSION,
|
|
1309
|
-
isInitialized() {
|
|
1310
|
-
return state.isInitialized;
|
|
1311
|
-
},
|
|
1312
|
-
isAuthenticated() {
|
|
1313
|
-
return !!state.authToken;
|
|
1314
|
-
},
|
|
1315
|
-
hasActiveSession() {
|
|
1316
|
-
return !!state.sessionToken;
|
|
1317
|
-
},
|
|
1318
|
-
requestMultiplayerLaunch,
|
|
1319
|
-
requestMultiplayerSession,
|
|
1320
|
-
onMultiplayerSessionChange(listener) {
|
|
1321
|
-
installHostMessageListener();
|
|
1322
|
-
return onMultiplayerSessionChange(listener);
|
|
1323
|
-
},
|
|
1324
|
-
async startSession() {
|
|
1325
|
-
await ensureInitialized();
|
|
1326
|
-
if (state.sessionStartPromise) return await state.sessionStartPromise;
|
|
1327
|
-
return await startSession();
|
|
1328
|
-
},
|
|
1329
|
-
submitScore(score, meta = {}) {
|
|
1330
|
-
return submitScore(score, meta);
|
|
1331
|
-
},
|
|
1332
|
-
submitMatchScore(score, meta = {}) {
|
|
1333
|
-
return submitMatchScore(score, meta);
|
|
1334
|
-
},
|
|
1335
|
-
submitMatchResult(result = {}) {
|
|
1336
|
-
return submitMatchResult(result);
|
|
1337
|
-
},
|
|
1338
|
-
async getMatchContext() {
|
|
1339
|
-
await ensureInitialized();
|
|
1340
|
-
return await fetchMatchContext();
|
|
1341
|
-
},
|
|
1342
|
-
notifyComplete(data = {}) {
|
|
1343
|
-
sendToParent("GAME_COMPLETE", data);
|
|
1344
|
-
},
|
|
1345
|
-
requestClose() {
|
|
1346
|
-
sendToParent("REQUEST_CLOSE", {});
|
|
1347
|
-
},
|
|
1348
|
-
reportQuestion(data) {
|
|
1349
|
-
sendToParent("QUESTION_REPORT", {
|
|
1350
|
-
questionId: data.questionId,
|
|
1351
|
-
prompt: data.prompt,
|
|
1352
|
-
message: data.message,
|
|
1353
|
-
questions: Array.isArray(data.questions) ? data.questions.map((q) => ({
|
|
1354
|
-
questionId: q.questionId,
|
|
1355
|
-
prompt: q.prompt
|
|
1356
|
-
})) : void 0
|
|
1357
|
-
});
|
|
1358
|
-
},
|
|
1359
|
-
reportWord(data) {
|
|
1360
|
-
sendToParent("WORD_REPORT", {
|
|
1361
|
-
wordId: data.wordId,
|
|
1362
|
-
lemma: data.lemma,
|
|
1363
|
-
message: data.message,
|
|
1364
|
-
words: Array.isArray(data.words) ? data.words.map((w) => ({
|
|
1365
|
-
wordId: w.wordId,
|
|
1366
|
-
lemma: w.lemma
|
|
1367
|
-
})) : void 0
|
|
1368
|
-
});
|
|
1369
|
-
},
|
|
1370
|
-
logEvent(eventName, eventData = {}) {
|
|
1371
|
-
sendToParent("LOG_EVENT", {
|
|
1372
|
-
event: eventName,
|
|
1373
|
-
data: eventData
|
|
1374
|
-
});
|
|
1375
|
-
},
|
|
1376
|
-
getGameSlug() {
|
|
1377
|
-
return state.gameSlug;
|
|
1378
|
-
},
|
|
1379
|
-
isInIframe() {
|
|
1380
|
-
return isBrowser() && window.parent !== window;
|
|
1381
|
-
},
|
|
1382
|
-
async ready() {
|
|
1383
|
-
return await ensureInitialized();
|
|
1384
|
-
},
|
|
1385
|
-
getSettings,
|
|
1386
|
-
onSettingsChange(listener) {
|
|
1387
|
-
installHostMessageListener();
|
|
1388
|
-
return onSettingsChange(listener);
|
|
1389
|
-
},
|
|
1390
|
-
getBootstrap() {
|
|
1391
|
-
return {
|
|
1392
|
-
multiplayerEntry: state.multiplayerEntry,
|
|
1393
|
-
multiplayerSession: lobbySnapshot(),
|
|
1394
|
-
settings: getSettings(),
|
|
1395
|
-
gameSlug: state.gameSlug,
|
|
1396
|
-
authToken: state.authToken,
|
|
1397
|
-
leagueId: state.leagueId,
|
|
1398
|
-
gameId: state.gameId,
|
|
1399
|
-
matchId: state.matchId,
|
|
1400
|
-
sessionMode: state.bootstrapSessionMode,
|
|
1401
|
-
mode: state.bootstrapMode,
|
|
1402
|
-
playerName: state.bootstrapPlayerName,
|
|
1403
|
-
playerCount: state.bootstrapPlayerCount,
|
|
1404
|
-
teamOneName: state.bootstrapTeamOneName,
|
|
1405
|
-
teamTwoName: state.bootstrapTeamTwoName,
|
|
1406
|
-
profileId: state.bootstrapProfileId,
|
|
1407
|
-
multiplayerLaunch: state.bootstrapLaunch,
|
|
1408
|
-
capabilities: [...state.bootstrapCapabilities],
|
|
1409
|
-
isBootstrapped: state.bootstrapReceived
|
|
1410
|
-
};
|
|
1411
|
-
},
|
|
1412
|
-
getQuestions(options = {}) {
|
|
1413
|
-
return getQuestions(options);
|
|
1414
|
-
},
|
|
1415
|
-
getWords(options = {}) {
|
|
1416
|
-
return getWords(options);
|
|
1417
|
-
}
|
|
1418
|
-
};
|
|
1419
|
-
}
|
|
1420
|
-
|
|
1421
|
-
// src/browser-entry.ts
|
|
1422
|
-
(function bootstrapSdk() {
|
|
1423
|
-
"use strict";
|
|
1424
|
-
if (!isBrowser()) return;
|
|
1425
|
-
detectEnvironment();
|
|
1426
|
-
installHostMessageListener();
|
|
1427
|
-
const sdk = createSdk();
|
|
1428
|
-
window.GameHubSDK = sdk;
|
|
1429
|
-
if (hasHost()) {
|
|
1430
|
-
sendToParent("READY", { version: SDK_VERSION });
|
|
1431
|
-
}
|
|
1432
|
-
const hasBootSignal = !!state.gameSlug || hasHost();
|
|
1433
|
-
if (!hasBootSignal) return;
|
|
1434
|
-
if (document.readyState === "loading") {
|
|
1435
|
-
document.addEventListener("DOMContentLoaded", () => {
|
|
1436
|
-
autoInit();
|
|
1437
|
-
});
|
|
1438
|
-
} else {
|
|
1439
|
-
autoInit();
|
|
1440
|
-
}
|
|
1441
|
-
})();
|
|
1442
|
-
})();
|
|
1
|
+
"use strict";(()=>{var k="5.5.1",d="GAMEHUB_SDK";var t={multiplayerEntry:null,gameSettings:{musicEnabled:!1},settingsListeners:new Set,bootstrapLaunch:null,bootstrapCapabilities:[],sdkOrigin:"",sdkPathPrefix:"",runtimeBasePath:"",apiBase:"",gameSlug:null,sessionToken:null,authToken:null,leagueId:null,gameId:null,matchId:null,bootstrapSessionMode:null,bootstrapMode:null,bootstrapPlayerName:null,bootstrapPlayerCount:null,bootstrapTeamOneName:null,bootstrapTeamTwoName:null,bootstrapProfileId:null,bootstrapReceived:!1,isInitialized:!1,isAutoInitializing:!1,autoInitPromise:null,bootstrapRequestPromise:null,parentOrigin:null,sessionStartPromise:null,submissionPromise:null,pendingSubmission:null,matchContext:null,matchContextPromise:null};var te="multiplayer.launch.v2",g="multiplayer.lobby.v2";var Ce=["easy","medium","hard"];var re=e=>Ce.includes(e);var q=new Set,xe={session:null,busy:!1,error:null,disconnected:!1},Q=xe,D=e=>typeof e=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e);function se(e){if(!e||typeof e!="object")return null;let r=e;if(typeof r.busy!="boolean"||typeof r.disconnected!="boolean")return null;let o=r.error;if(o!==null&&(!o||!D(o.code)||typeof o.message!="string"||o.message.length>1e3||typeof o.retryable!="boolean"))return null;let s=r.session;if(s!==null){if(!s||![s.multiplayerSessionId,s.hostSeatId,s.ownSeatId].every(D)||typeof s.gameSlug!="string"||!/^[a-z0-9-]{1,100}$/.test(s.gameSlug)||!/^\d{6}$/.test(s.roomCode)||!["waiting","in_round","completed","closed"].includes(s.phase)||!Number.isSafeInteger(s.revision)||s.revision<0||typeof s.rematchAllowed!="boolean"||!Array.isArray(s.seats)||s.seats.length>272)return null;for(let i of[s.invitationUrl,s.spectatorInvitationUrl])if(i!==void 0&&(typeof i!="string"||i.length>2048||!/^https?:\/\//.test(i)))return null;let n=s.playerPolicy;if(!n||![n.minPlayers,n.maxPlayers,n.minHumanPlayers,n.maxBots,n.maxSpectators].every(i=>Number.isSafeInteger(i)&&i>=0&&i<=256)||n.minPlayers<1||n.minHumanPlayers<1||n.maxPlayers<n.minPlayers||n.minHumanPlayers>n.maxPlayers||n.maxBots>n.maxPlayers-n.minHumanPlayers||n.maxSpectators>16||!s.seats.every(i=>i&&D(i.seatId)&&typeof i.displayName=="string"&&i.displayName.length<=80&&["human","bot"].includes(i.kind)&&(i.botLevel===void 0||i.kind==="bot"&&re(i.botLevel))&&["player","spectator"].includes(i.type)&&typeof i.ready=="boolean"&&typeof i.online=="boolean")||s.round!==null&&(!s.round||!D(s.round.roundId)||!["preparing","loading","playing","finishing","completed","aborted","interrupted"].includes(s.round.phase)||s.round.reason!==null&&(typeof s.round.reason!="string"||s.round.reason.length>1e3)))return null}return{busy:r.busy,disconnected:r.disconnected,error:o?{code:o.code,message:o.message,retryable:o.retryable}:null,session:s?{...s.invitationUrl?{invitationUrl:s.invitationUrl}:{},...s.spectatorInvitationUrl?{spectatorInvitationUrl:s.spectatorInvitationUrl}:{},multiplayerSessionId:s.multiplayerSessionId,gameSlug:s.gameSlug,roomCode:s.roomCode,phase:s.phase,revision:s.revision,hostSeatId:s.hostSeatId,ownSeatId:s.ownSeatId,rematchAllowed:s.rematchAllowed,playerPolicy:{minPlayers:s.playerPolicy.minPlayers,maxPlayers:s.playerPolicy.maxPlayers,minHumanPlayers:s.playerPolicy.minHumanPlayers,maxBots:s.playerPolicy.maxBots,maxSpectators:s.playerPolicy.maxSpectators},seats:s.seats.map(n=>({seatId:n.seatId,displayName:n.displayName,kind:n.kind,...n.botLevel?{botLevel:n.botLevel}:{},type:n.type,ready:n.ready,online:n.online})),round:s.round?{roundId:s.round.roundId,phase:s.round.phase,reason:s.round.reason}:null}:null}}function _(e){let r=se(e);if(r){Q=r;for(let o of q)try{o(structuredClone(Q))}catch{}}}function A(){return structuredClone(Q)}function oe(e){let r=o=>e(o);q.add(r);try{r(A())}catch{}return()=>{q.delete(r)}}async function ne(e){if(!t.bootstrapCapabilities.includes(g))return{success:!1,error:{code:"PROTOCOL_UNSUPPORTED",message:"This host does not support multiplayer lobby controls",retryable:!1}};let r=t.gameSlug,o=t.bootstrapLaunch;try{let s=await T("/multiplayer/session",{method:"POST",body:e});if(r!==t.gameSlug||o!==t.bootstrapLaunch)return{success:!1,error:{code:"STALE_ATTEMPT",message:"The multiplayer context changed",retryable:!1}};let n=s.success?se(s.data):null;return n&&(!n.session||n.session.gameSlug===r)?(_(n),{success:!0,data:A()}):{success:!1,error:{code:s.error?.code??"UNAVAILABLE",message:s.error?.message??"Lobby request failed",retryable:s.error?.details?.terminal!==!0}}}catch{return{success:!1,error:{code:"UNAVAILABLE",message:"Lobby request timed out; refresh status before retrying",retryable:!0}}}}function p(){return typeof window<"u"&&typeof document<"u"}function ie(e,...r){console.warn("[GameHubSDK] "+e,...r)}function ae(e,...r){console.error("[GameHubSDK] "+e,...r)}function I(e){return e?e.success&&e.data?e.data:e:null}function U(e){try{return new URLSearchParams(window.location.search).get(e)}catch{let r=window.location.search.match(new RegExp("[?&]"+e+"=([^&]+)"));return r?decodeURIComponent(r[1]):null}}var V=class{constructor(){this.kind="postmessage"}send(r){window.parent.postMessage(r,t.parentOrigin||"*")}subscribe(r){let o=s=>{s.source===window.parent&&(t.parentOrigin&&s.origin!==t.parentOrigin||r({data:s.data,origin:s.origin}))};return window.addEventListener("message",o),()=>window.removeEventListener("message",o)}};function P(e){return e===null?!0:!e||e==="null"?!1:t.parentOrigin===null?(t.parentOrigin=e,!0):t.parentOrigin===e}var F=class{constructor(r){this.host=r;this.kind="native";this.handlers=new Set;r.receive=o=>{let s=o;if(typeof o=="string")try{s=JSON.parse(o)}catch{return}!s||typeof s!="object"||this.handlers.forEach(n=>n({data:s,origin:null}))}}send(r){this.host.postMessage(JSON.stringify(r))}subscribe(r){return this.handlers.add(r),()=>{this.handlers.delete(r)}}},S;function f(){if(S!==void 0)return S;if(!p())return S=null,S;let e=window.GameHubNativeHost;return e&&typeof e.postMessage=="function"?S=new F(e):window.parent!==window?S=new V:S=null,S}function N(){return f()!==null}var v=null,le=new Map,ue=["multiplayerSessionId","roundId","attemptId","seatId","hostInstanceId"];function me(e){if(v)try{f()?.send({type:"GAMEHUB_SDK_LOADING",loadingContext:v,...e})}catch{}}function de(e,r){if(e!==null&&!["loading","waiting-for-players","reconnecting","failed"].includes(e)||r&&!ue.every(s=>typeof r[s]=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(r[s])))return;let o={state:e,...r?{launch:Object.fromEntries(ue.map(s=>[s,r[s]]))}:{}};le.set(r?"multiplayer":"game",o),me(o)}function ce(e){if(!(typeof e!="string"||!/^[a-zA-Z0-9_-]{1,160}$/.test(e)||e===v)){v=e;for(let r of le.values())me(r)}}function M(){return{...t.gameSettings}}function pe(e){try{e(M())}catch{}}function fe(e){if(typeof e!="function")return()=>{};let r=o=>e(o);return t.settingsListeners.add(r),pe(r),()=>{t.settingsListeners.delete(r)}}function ye(e){if(e===void 0)return;let r;if(e===null)r=!1;else if(typeof e=="object"&&!Array.isArray(e)&&typeof e.musicEnabled=="boolean")r=e.musicEnabled;else return;if(r!==t.gameSettings.musicEnabled){t.gameSettings={musicEnabled:r};for(let o of[...t.settingsListeners])t.settingsListeners.has(o)&&pe(o)}}function ve(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e;if(typeof r.success!="boolean")return null;let o={success:r.success};if("data"in r&&(o.data=r.data),r.token!==void 0){if(typeof r.token!="string"||r.token.length>4e3)return null;o.token=r.token}if(r.error!==void 0){if(!r.error||typeof r.error!="object"||Array.isArray(r.error))return null;let s=r.error;if(s.code!==void 0&&(typeof s.code!="string"||s.code.length>100)||s.message!==void 0&&(typeof s.message!="string"||s.message.length>4e3))return null;let n={};if(typeof s.code=="string"&&(n.code=s.code),typeof s.message=="string"&&(n.message=s.message),s.details!==void 0){if(!s.details||typeof s.details!="object"||Array.isArray(s.details))return null;let i=s.details;if(i.terminal!==void 0&&typeof i.terminal!="boolean"||i.sessionStatus!==void 0&&(typeof i.sessionStatus!="string"||i.sessionStatus.length>100)||i.retryAfterMs!==void 0&&(typeof i.retryAfterMs!="number"||!Number.isFinite(i.retryAfterMs)||i.retryAfterMs<0))return null;n.details={...typeof i.terminal=="boolean"?{terminal:i.terminal}:{},...typeof i.sessionStatus=="string"?{sessionStatus:i.sessionStatus}:{},...typeof i.retryAfterMs=="number"?{retryAfterMs:i.retryAfterMs}:{}}}o.error=n}return o}function ge(e){if(e===null)return null;if(typeof e!="string")return;let r=e.trim();return r||null}function W(e={}){if(!e||typeof e!="object"||Array.isArray(e))return;if(ce(e.loadingContext),ye(e.settings),e.multiplayerSession!==void 0&&_(e.multiplayerSession??{session:null,busy:!1,error:null,disconnected:!1}),e.multiplayerEntry===null)t.multiplayerEntry=null;else if(e.multiplayerEntry&&["create","join"].includes(e.multiplayerEntry.action)){let n=e.multiplayerEntry;t.multiplayerEntry={action:n.action,...typeof n.roomCode=="string"&&/^\d{6}$/.test(n.roomCode)?{roomCode:n.roomCode}:{},...n.type==="player"||n.type==="spectator"?{type:n.type}:{}}}let r=(n,i)=>{let a=ge(i);a!==void 0&&(t[n]=a)};r("gameSlug",e.gameSlug),r("authToken",e.authToken),r("leagueId",e.leagueId),r("gameId",e.gameId),r("matchId",e.matchId),(e.sessionMode===null||["authenticated","embed-guest","league-guest"].includes(e.sessionMode))&&(t.bootstrapSessionMode=e.sessionMode??null);let o=(n,i)=>{let a=ge(i);a!==void 0&&(t[n]=a)};o("bootstrapMode",e.mode),o("bootstrapPlayerName",e.playerName),o("bootstrapPlayerCount",e.playerCount),o("bootstrapTeamOneName",e.teamOneName),o("bootstrapTeamTwoName",e.teamTwoName),o("bootstrapProfileId",e.profileId),Array.isArray(e.capabilities)&&(t.bootstrapCapabilities=e.capabilities.filter(n=>typeof n=="string"&&n.length<=100).slice(0,32));let s=e.multiplayerLaunch;s===null?t.bootstrapLaunch=null:s&&s.version===2&&(s.recoveryGraceMs===void 0||Number.isSafeInteger(s.recoveryGraceMs)&&s.recoveryGraceMs>=1e3&&s.recoveryGraceMs<=12e4)&&["multiplayerSessionId","roundId","attemptId","seatId","hostInstanceId"].every(n=>typeof s[n]=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(String(s[n])))&&typeof s.gameUrl=="string"&&s.gameUrl.startsWith("/games/")&&s.gameUrl.length<2048&&["server","unverified"].includes(s.scoreAuthority)&&(t.bootstrapLaunch={...s})}function Be(){return{multiplayerEntry:t.multiplayerEntry,multiplayerSession:A(),settings:M(),gameSlug:t.gameSlug,authToken:t.authToken,leagueId:t.leagueId,gameId:t.gameId,matchId:t.matchId,sessionMode:t.bootstrapSessionMode,mode:t.bootstrapMode,playerName:t.bootstrapPlayerName,playerCount:t.bootstrapPlayerCount,teamOneName:t.bootstrapTeamOneName,teamTwoName:t.bootstrapTeamTwoName,profileId:t.bootstrapProfileId,multiplayerLaunch:t.bootstrapLaunch,capabilities:t.bootstrapCapabilities}}function be(){let e=f();return e?t.bootstrapReceived?Promise.resolve(Be()):t.bootstrapRequestPromise?t.bootstrapRequestPromise:(t.bootstrapRequestPromise=new Promise(r=>{let o=Date.now().toString(),s=!1,n=null,i=()=>{},a=l=>{let u=l.data;if(u&&u.type===d+"_BOOTSTRAP"&&u.payload&&u.messageId===o){if(s||!P(l.origin))return;s=!0,i(),n&&clearTimeout(n),t.bootstrapReceived=!0,W(u.payload),r(u.payload)}};i=e.subscribe(a),e.send({type:d+"_BOOTSTRAP_REQUEST",messageId:o}),n=setTimeout(()=>{s||(s=!0,i(),r(null))},2e3)}).finally(()=>{t.bootstrapRequestPromise=null}),t.bootstrapRequestPromise):Promise.resolve(null)}function he(){return new Promise(e=>{let r=f();if(!r){e(null);return}let o=Date.now().toString(),s=!1,n=null,i=()=>{},a=l=>{let u=l.data;if(u&&u.type===d+"_AUTH_RESPONSE"&&u.messageId===o){if(s||!P(l.origin))return;s=!0,i(),n&&clearTimeout(n),u.leagueId&&(t.leagueId=u.leagueId),u.gameId&&(t.gameId=u.gameId),u.matchId&&(t.matchId=u.matchId),e(u.token||null)}};i=r.subscribe(a),r.send({type:d+"_AUTH_REQUEST",messageId:o}),n=setTimeout(()=>{s||(s=!0,i(),e(null))},2e3)})}var Ge=0;function T(e,r={}){return new Promise((o,s)=>{let n=f();if(!n){s(new Error("Host bridge unavailable: no host transport"));return}let i="api_"+Date.now().toString()+"_"+ ++Ge,a=!1,l=null,u=()=>{},h=j=>{let E=j.data;if(!E||E.type!==d+"_API_RESPONSE"||E.messageId!==i||a||!P(j.origin))return;a=!0,u(),l&&clearTimeout(l);let ee=ve(E.result);ee?o(ee):E.ok?s(new Error("Host API response was invalid")):s(new Error(E.error||"Host API request failed"))};l=setTimeout(()=>{a||(a=!0,u(),s(new Error("Host API request timed out")))},15e3),u=n.subscribe(h),n.send({type:d+"_API_REQUEST",messageId:i,endpoint:e,method:r.method||"GET",body:r.body??null})})}function m(e,r){let o=f();if(o)try{o.send({type:d+"_"+e,gameSlug:t.gameSlug,...r})}catch{}}async function y(e,r={}){if(N())return T(e,r);let o=t.apiBase+e,s={"Content-Type":"application/json",...r.headers||{}};return t.authToken&&(s.Authorization="Bearer "+t.authToken),(await fetch(o,{...r,credentials:r.credentials||"same-origin",headers:s,body:r.body?JSON.stringify(r.body):void 0})).json()}var He=500,je=50,qe=10,Qe=3e3,Ve=/^[A-Za-z0-9_:.-]{1,64}$/,Fe=/^[a-f0-9]{24}$/,B=null,z=0,L=[],w=null,C=null,Y=(e,r,o)=>typeof e=="number"&&Number.isInteger(e)&&e>=r&&e<=o;function We(e){if(!e||typeof e!="object")return null;let{questionId:r,correct:o,choice:s,timeMs:n,level:i}=e;return typeof r!="string"||!Ve.test(r)||typeof o!="boolean"||s!==void 0&&!(typeof s=="string"&&s.length<=100)&&!Y(s,-1e6,1e6)||n!==void 0&&!Y(Math.round(n),0,6e5)||i!==void 0&&!Y(i,0,1e3)?null:{questionId:r,correct:o,...s!==void 0?{choice:s}:{},...n!==void 0?{timeMs:Math.round(n)}:{},...i!==void 0?{level:i}:{}}}function ze(){let e=t.sessionToken;return!e||!Fe.test(e)||t.leagueId||t.bootstrapSessionMode==="embed-guest"?null:e}function Ye(){w||(w=setTimeout(()=>{w=null,G()},Qe))}function Ie(e){try{let r=ze(),o=We(e);if(!r||!o||(r!==B&&(B=r,z=0,L=[]),z>=He))return;L.push({...o,seq:z++}),L.length>=qe?G():Ye()}catch{}}async function G(){if(w&&(clearTimeout(w),w=null),C&&await C,L.length===0||!B)return;let e=B,r=[];for(;L.length;)r.push(L.splice(0,je));C=(async()=>{for(let o of r)try{await y("/sessions/answers",{method:"POST",body:{token:e,answers:o}})}catch{}})();try{await C}finally{C=null}}var Je=1e6,X=1e7,Ke=32*1024,Ze=5,et=200,tt=100,rt=2048,st=100,ot=new Set(["__proto__","prototype","constructor"]),nt=new Set(["attempts","duration","durationMs","timeTaken","serverDurationMs","userId","gameId","source","sessionId","token"]);function $(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map($).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${$(e[r])}`).join(",")}}`}function c(e,r,o){return{success:!1,status:"failed",terminal:!1,code:e,error:r,retriable:o}}function it(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;try{let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return!1;let o=0,s=(n,i)=>{if(i>Ze)return!1;if(n===null||typeof n=="boolean")return!0;if(typeof n=="number")return Number.isFinite(n)&&Math.abs(n)<=Number.MAX_SAFE_INTEGER;if(typeof n=="string")return n.length<=rt;if(Array.isArray(n))return n.length<=st&&n.every(l=>s(l,i+1));if(!n||typeof n!="object")return!1;let a=Object.getPrototypeOf(n);if(a!==Object.prototype&&a!==null)return!1;for(let[l,u]of Object.entries(n))if(o+=1,o>et||l.length===0||l.length>tt||ot.has(l)||!s(u,i+1))return!1;return!0};return s(e,0)&&new TextEncoder().encode(JSON.stringify(e)).byteLength<=Ke}catch{return!1}}function at(e,r,o){if(typeof r!="number"||!Number.isFinite(r)||r<0||Math.floor(r)>X)return{ok:!1,result:c("INVALID_INPUT",`Score must be a finite number between 0 and ${X}`,!1)};if(!it(o))return{ok:!1,result:c("INVALID_INPUT","Score metadata exceeds the allowed bounds",!1)};let s;try{s=JSON.parse(JSON.stringify(o))}catch{return{ok:!1,result:c("INVALID_INPUT","Score metadata must be JSON serializable",!1)}}let n=s.attempts,i=typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.min(Math.floor(n),Je):0,a=Object.fromEntries(Object.entries(s).filter(([u])=>!nt.has(u))),l=Math.floor(r);return{ok:!0,canonicalPayload:$({score:l,attempts:i,clientMeta:a}),body:{token:e,score:l,meta:s}}}function Re(){t.sessionToken=null,t.sessionStartPromise=null,t.submissionPromise=null,t.pendingSubmission=null}function Ee(){let e=!!(t.leagueId&&t.gameId&&t.matchId),r=t.bootstrapSessionMode==="embed-guest",o=t.bootstrapSessionMode==="authenticated";return!t.authToken&&!e&&!r&&!o}async function ut(){if(!t.gameSlug)return{success:!1,error:"Game slug not set"};if(Ee())return{success:!1,error:"User not authenticated"};try{let e="/sessions/start",r={gameSlug:t.gameSlug};t.leagueId&&t.gameId&&t.matchId?(e="/leagues/"+t.leagueId+"/matches/"+t.matchId+"/session",r={gameId:t.gameId}):t.leagueId&&t.gameId&&(e="/leagues/"+t.leagueId+"/sessions",r={gameId:t.gameId});let o=await y(e,{method:"POST",body:r}),n=I(o)?.token||o?.token||null;return o.success&&typeof n=="string"&&n?(t.sessionToken=n,m("SESSION_STARTED",{token:n}),{success:!0,token:n}):{success:!1,error:o.error?.message||"Failed to start session"}}catch(e){return{success:!1,error:e?.message||"Failed to start session"}}}async function O(){if(t.bootstrapLaunch||t.bootstrapCapabilities.includes(g))return{success:!1,error:"Multiplayer rounds own their results"};if(t.sessionToken)return{success:!0,token:t.sessionToken};if(t.sessionStartPromise)return await t.sessionStartPromise;let e=ut();t.sessionStartPromise=e;try{return await e}finally{t.sessionStartPromise===e&&(t.sessionStartPromise=null)}}function lt(e,r){let o=I(e);if(e.success&&o?.status==="accepted"&&o?.terminal===!0&&typeof o?.sessionId=="string"&&typeof o?.serverDurationMs=="number"&&Number.isFinite(o.serverDurationMs)&&typeof o?.timeTaken=="number"&&Number.isFinite(o.timeTaken))return{success:!0,status:"accepted",terminal:!0,sessionId:o.sessionId,serverDurationMs:o.serverDurationMs,timeTaken:o.timeTaken,...o.replayed===!0?{replayed:!0}:{}};if(e.success&&o?.accepted===!0&&typeof o?.timeTaken=="number"&&Number.isFinite(o.timeTaken))return{success:!0,status:"accepted",terminal:!0,sessionId:r,serverDurationMs:Math.max(0,Math.floor(o.timeTaken*1e3)),timeTaken:Math.max(0,Math.floor(o.timeTaken))};let s=e.error,n=s?.code||"SERVER_ERROR",i=s?.message||"Score submission failed",a=s?.details;return a?.terminal===!0?{success:!1,status:"rejected",terminal:!0,code:n,error:i,...typeof a.sessionStatus=="string"?{sessionStatus:a.sessionStatus}:{}}:n==="SUBMISSION_IN_PROGRESS"||n==="RATE_LIMITED"?{success:!1,status:"retriable",terminal:!1,code:n,error:i,...typeof a?.retryAfterMs=="number"?{retryAfterMs:a.retryAfterMs}:{},...typeof a?.sessionStatus=="string"?{sessionStatus:a.sessionStatus}:{}}:c(n,i,n==="SERVER_ERROR")}async function mt(e){let r;try{let o=await y("/sessions/submit",{method:"POST",body:e.body});r=lt(o,e.token)}catch(o){r=c("TRANSPORT_ERROR",o?.message||"Score submission transport failed",!0)}return r.success?(m("SCORE_SUBMITTED",{score:e.body.score,sessionId:r.sessionId,status:r.status,terminal:r.terminal,serverDurationMs:r.serverDurationMs,timeTaken:r.timeTaken,...r.replayed?{replayed:!0}:{}}),Re()):r.terminal&&Re(),r}async function J(e,r={}){if(await b(),t.bootstrapLaunch||t.bootstrapCapabilities.includes(g))return c("FORBIDDEN","Multiplayer rounds own their results",!1);if(!t.isInitialized)return c("SDK_NOT_INITIALIZED","SDK could not initialize. Is game slug set?",!1);if(!t.sessionToken&&Ee()&&typeof e=="number"&&Number.isFinite(e)&&e>=0&&Math.floor(e)<=X&&m("GUEST_SCORE",{score:Math.floor(e)}),!t.sessionToken)if(t.sessionStartPromise)await t.sessionStartPromise;else{let a=await O();if(!a.success)return c("SESSION_START_FAILED",a.error||"Could not start session",!0)}if(!t.sessionToken)return c("SESSION_START_FAILED","No active session. User may not be authenticated.",!0);await G();let o=at(t.sessionToken,e,r);if(!o.ok)return o.result;let s=t.pendingSubmission;if(s&&(s.token!==t.sessionToken||s.canonicalPayload!==o.canonicalPayload))return c("CONCURRENT_SUBMISSION_CONFLICT","A different payload is already bound to the active session",!1);if(t.submissionPromise)return await t.submissionPromise;let n=s??{token:t.sessionToken,canonicalPayload:o.canonicalPayload,body:o.body};t.pendingSubmission=n;let i=mt(n);t.submissionPromise=i;try{return await i}finally{t.submissionPromise===i&&(t.submissionPromise=null)}}async function K(e,r={}){return t.matchId?await J(e,{...r||{},matchId:t.matchId,leagueId:t.leagueId||r.leagueId,gameId:t.gameId||r.gameId}):c("MATCH_CONTEXT_MISSING","No matchId found for this game session",!1)}async function Ae(e={}){return!e||typeof e!="object"?c("INVALID_INPUT","match result payload is required",!1):await K(0,{matchResult:e})}async function Te(e={}){await b();let r=t.gameSlug||t.gameId;if(!r)return[];let{difficulty:o,category:s,limit:n}=e;if(o&&!["easy","medium","hard"].includes(o))return[];if(n!==void 0&&(typeof n!="number"||n<1))return[];let i=e.profileId||t.bootstrapProfileId||"";try{let a=new URLSearchParams({limit:String(Math.min(n||100,100)),random:"true"});t.gameId&&a.set("gameId",t.gameId),o&&a.set("difficulty",o),s&&a.set("category",String(s)),i&&a.set("profileId",i);let l=await y("/games/"+encodeURIComponent(r)+"/questions?"+a.toString(),{method:"GET"}),u=I(l);return(Array.isArray(u)?u:Array.isArray(u?.questions)?u.questions:[]).map(dt)}catch{return[]}}function dt(e){let r=e,o=typeof r.answer=="number"?String(r.answer):r.answer;return{...r,answer:o}}async function Pe(e={}){await b();let r=t.gameSlug||t.gameId;if(!r)return[];let{difficulty:o,category:s,tags:n,limit:i}=e;if(o&&!["easy","medium","hard"].includes(o))return[];if(i!==void 0&&(typeof i!="number"||i<1))return[];let a=e.profileId||t.bootstrapProfileId||"";try{let l=new URLSearchParams({limit:String(Math.min(i||50,50)),random:"true"});t.gameId&&l.set("gameId",t.gameId),o&&l.set("difficulty",o),s&&l.set("category",String(s)),Array.isArray(n)&&n.length>0&&l.set("tags",n.join(",")),a&&l.set("profileId",a);let u=await y("/games/"+encodeURIComponent(r)+"/words?"+l.toString(),{method:"GET"}),h=I(u);return Array.isArray(h)?h:Array.isArray(h?.words)?h.words:[]}catch{return[]}}var Le=!1,we=!1;function Z(){if(!p()||Le)return;Le=!0,t.sdkOrigin=window.location.origin;let e=window.location.pathname.match(/^(.*)\/(?:uploaded-games|games)\/([a-z0-9-]+)(?:\/|$)/i),r=null;e&&(t.runtimeBasePath=e[1]||"",r=e[2]||null),t.leagueId=U("leagueId"),t.gameId=U("gameId"),t.matchId=U("matchId");let o=document.getElementsByTagName("script");for(let n=0;n<o.length;n++){let i=o[n].src;if(!i.includes("gamehub-sdk.js"))continue;try{let l=new URL(i,window.location.origin);t.sdkOrigin=l.origin;let u=l.pathname.match(/(.*)\/sdk\/gamehub-sdk\.js$/);t.sdkPathPrefix=u&&u[1]||""}catch{let l=i.match(/(.*)\/sdk\/gamehub-sdk\.js/);if(l){let u=new URL(l[1],window.location.origin);t.sdkOrigin=u.origin,t.sdkPathPrefix=u.pathname||""}}let a=o[n].getAttribute("data-game-slug");a&&(r=a);break}if(!r){let n=window.location.pathname.match(/\/(?:uploaded-games|games)\/([a-z0-9-]+)\//i);n&&(r=n[1])}let s=t.sdkPathPrefix||t.runtimeBasePath||"";t.apiBase=t.sdkOrigin+s+"/api",t.gameSlug=r}async function H(){return p()?t.isInitialized||t.isAutoInitializing?t.autoInitPromise:(Z(),R(),t.isAutoInitializing=!0,t.autoInitPromise=(async()=>{try{return await be(),t.gameSlug?(!t.authToken&&!t.bootstrapLaunch&&!t.bootstrapCapabilities.includes(g)&&(t.authToken=await he()),t.isInitialized=!0,t.isAutoInitializing=!1,m("INIT",{slug:t.gameSlug,auto:!0}),(t.authToken||t.bootstrapSessionMode==="authenticated"||t.bootstrapSessionMode==="embed-guest"||t.leagueId&&t.gameId&&t.matchId)&&O(),!0):(ie("Could not resolve game slug. Ensure the host page sends bootstrap config or serves the game under /games/{slug}."),t.isAutoInitializing=!1,!1)}catch(e){return ae("Auto-init failed:",e),t.isAutoInitializing=!1,!1}})(),t.autoInitPromise):!1}async function b(){return t.isInitialized?!0:p()?t.autoInitPromise?await t.autoInitPromise:await H():!1}function R(){if(!p()||we)return;let e=f();e&&(we=!0,e.subscribe(r=>{let o=r.data;if(!o||!o.type||e.kind!=="native"&&(!t.parentOrigin||!P(r.origin)))return;let s=o.type;if(s===d+"_BOOTSTRAP"&&o.payload&&(t.bootstrapReceived=!0,W(o.payload)),s===d+"_MULTIPLAYER_SESSION"&&t.bootstrapCapabilities.includes(g)&&_(o.payload),s===d+"_SET_AUTH"&&(t.authToken=o.token,t.gameSlug&&!t.sessionToken&&!t.sessionStartPromise&&(t.authToken||t.leagueId&&t.gameId&&t.matchId)&&O()),s===d+"_COMMAND"){let n=o.command,i=window;n==="pause"&&typeof i.onGameHubPause=="function"?i.onGameHubPause():n==="resume"&&typeof i.onGameHubResume=="function"&&i.onGameHubResume()}}))}var x=null;function Oe(){if(!t.bootstrapLaunch||!t.bootstrapCapabilities.includes(te))return Promise.resolve({status:"terminal",error:{code:"PROTOCOL_UNSUPPORTED",message:"This host does not support multiplayer launch v2",retryable:!1}});if(x)return x;let e=t.bootstrapLaunch,r=(async()=>{try{let o=await T("/multiplayer/launch",{method:"POST",body:{}});if(t.bootstrapLaunch!==e)return{status:"terminal",error:{code:"STALE_ATTEMPT",message:"Launch context changed",retryable:!1}};let s=o.data;return o.success&&s&&(s.status==="reserved"&&s.launch&&["multiplayerSessionId","roundId","attemptId","seatId","hostInstanceId"].every(n=>s.launch[n]===e[n])&&s.reservation&&["name","roomId","sessionId"].every(n=>typeof s.reservation[n]=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(String(s.reservation[n])))&&/^wss?:\/\//.test(s.wsEndpoint)&&s.wsEndpoint.length<2048&&Number.isSafeInteger(s.generation)&&s.generation>0&&Number.isSafeInteger(s.expiresAt)||(s.status==="recoverable"||s.status==="terminal")&&s.error&&typeof s.error.code=="string"&&s.error.code.length<=100&&typeof s.error.message=="string"&&s.error.message.length<=1e3&&typeof s.error.retryable=="boolean")?s:{status:"recoverable",error:{code:o.error?.code??"UNAVAILABLE",message:o.error?.message??"Launch unavailable",retryable:!0}}}catch{return{status:"recoverable",error:{code:"UNAVAILABLE",message:"Launch request failed; retry",retryable:!0}}}})().finally(()=>{x===r&&(x=null)});return x=r,r}async function _e(){return!t.leagueId||!t.matchId?null:t.matchContext?t.matchContext:t.matchContextPromise?await t.matchContextPromise:(t.matchContextPromise=y("/leagues/"+encodeURIComponent(t.leagueId)+"/matches/"+encodeURIComponent(t.matchId),{method:"GET"}).then(e=>{let r=I(e);return e?.success&&r?(t.matchContext=r,t.matchContext):null}).catch(()=>null).finally(()=>{t.matchContextPromise=null}),await t.matchContextPromise)}function Ne(){return{version:k,isInitialized(){return t.isInitialized},isAuthenticated(){return!!t.authToken},hasActiveSession(){return!!t.sessionToken},setLoading(e,r){R(),de(e,r)},requestMultiplayerLaunch:Oe,requestMultiplayerSession:ne,onMultiplayerSessionChange(e){return R(),oe(e)},async startSession(){return await b(),t.sessionStartPromise?await t.sessionStartPromise:await O()},submitScore(e,r={}){return J(e,r)},recordAnswer(e){Ie(e)},submitMatchScore(e,r={}){return K(e,r)},submitMatchResult(e={}){return Ae(e)},async getMatchContext(){return await b(),await _e()},notifyComplete(e={}){m("GAME_COMPLETE",e)},requestClose(){m("REQUEST_CLOSE",{})},reportQuestion(e){m("QUESTION_REPORT",{questionId:e.questionId,prompt:e.prompt,message:e.message,questions:Array.isArray(e.questions)?e.questions.map(r=>({questionId:r.questionId,prompt:r.prompt})):void 0})},reportWord(e){m("WORD_REPORT",{wordId:e.wordId,lemma:e.lemma,message:e.message,words:Array.isArray(e.words)?e.words.map(r=>({wordId:r.wordId,lemma:r.lemma})):void 0})},logEvent(e,r={}){m("LOG_EVENT",{event:e,data:r})},getGameSlug(){return t.gameSlug},isInIframe(){return p()&&window.parent!==window},async ready(){return await b()},getSettings:M,onSettingsChange(e){return R(),fe(e)},getBootstrap(){return{multiplayerEntry:t.multiplayerEntry,multiplayerSession:A(),settings:M(),gameSlug:t.gameSlug,authToken:t.authToken,leagueId:t.leagueId,gameId:t.gameId,matchId:t.matchId,sessionMode:t.bootstrapSessionMode,mode:t.bootstrapMode,playerName:t.bootstrapPlayerName,playerCount:t.bootstrapPlayerCount,teamOneName:t.bootstrapTeamOneName,teamTwoName:t.bootstrapTeamTwoName,profileId:t.bootstrapProfileId,multiplayerLaunch:t.bootstrapLaunch,capabilities:[...t.bootstrapCapabilities],isBootstrapped:t.bootstrapReceived}},getQuestions(e={}){return Te(e)},getWords(e={}){return Pe(e)}}}(function(){"use strict";if(!p())return;Z(),R();let r=Ne();window.GameHubSDK=r,N()&&m("READY",{version:k}),(t.gameSlug||N())&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{H()}):H())})();})();
|
|
1443
2
|
//# sourceMappingURL=gamehub-sdk.js.map
|