@ksaa-nlp/gamehub-sdk 3.11.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +69 -8
  2. package/SPEC.md +183 -35
  3. package/dist/gamehub-sdk.js +490 -77
  4. package/dist/gamehub-sdk.js.map +4 -4
  5. package/dist/src/bridge.d.ts.map +1 -1
  6. package/dist/src/bridge.js +124 -16
  7. package/dist/src/bridge.js.map +1 -1
  8. package/dist/src/constants.d.ts +1 -1
  9. package/dist/src/constants.d.ts.map +1 -1
  10. package/dist/src/constants.js +1 -1
  11. package/dist/src/constants.js.map +1 -1
  12. package/dist/src/init.js +3 -3
  13. package/dist/src/init.js.map +1 -1
  14. package/dist/src/main.d.ts +15 -9
  15. package/dist/src/main.d.ts.map +1 -1
  16. package/dist/src/main.js +12 -1
  17. package/dist/src/main.js.map +1 -1
  18. package/dist/src/multiplayer.d.ts +4 -0
  19. package/dist/src/multiplayer.d.ts.map +1 -0
  20. package/dist/src/multiplayer.js +91 -0
  21. package/dist/src/multiplayer.js.map +1 -0
  22. package/dist/src/server-entry.d.ts +15 -5
  23. package/dist/src/server-entry.d.ts.map +1 -1
  24. package/dist/src/session.d.ts.map +1 -1
  25. package/dist/src/session.js +301 -68
  26. package/dist/src/session.js.map +1 -1
  27. package/dist/src/settings.d.ts +7 -0
  28. package/dist/src/settings.d.ts.map +1 -0
  29. package/dist/src/settings.js +49 -0
  30. package/dist/src/settings.js.map +1 -0
  31. package/dist/src/state.d.ts +17 -2
  32. package/dist/src/state.d.ts.map +1 -1
  33. package/dist/src/state.js +6 -0
  34. package/dist/src/state.js.map +1 -1
  35. package/dist/types/api.d.ts +11 -3
  36. package/dist/types/api.d.ts.map +1 -1
  37. package/dist/types/bootstrap.d.ts +39 -0
  38. package/dist/types/bootstrap.d.ts.map +1 -1
  39. package/dist/types/session.d.ts +35 -6
  40. package/dist/types/session.d.ts.map +1 -1
  41. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  (() => {
3
3
  // src/constants.ts
4
- var SDK_VERSION = "3.11.0";
4
+ var SDK_VERSION = "4.2.0";
5
5
  var MESSAGE_PREFIX = "GAMEHUB_SDK";
6
6
  var PARENT_REQUEST_TIMEOUT_MS = 2e3;
7
7
  var HOST_API_TIMEOUT_MS = 15e3;
@@ -10,6 +10,10 @@
10
10
 
11
11
  // src/state.ts
12
12
  var state = {
13
+ gameSettings: { musicEnabled: false },
14
+ settingsListeners: /* @__PURE__ */ new Set(),
15
+ bootstrapLaunch: null,
16
+ bootstrapCapabilities: [],
13
17
  sdkOrigin: "",
14
18
  sdkPathPrefix: "",
15
19
  runtimeBasePath: "",
@@ -35,10 +39,49 @@
35
39
  bootstrapRequestPromise: null,
36
40
  parentOrigin: null,
37
41
  sessionStartPromise: null,
42
+ submissionPromise: null,
43
+ pendingSubmission: null,
38
44
  matchContext: null,
39
45
  matchContextPromise: null
40
46
  };
41
47
 
48
+ // src/settings.ts
49
+ function getSettings() {
50
+ return { ...state.gameSettings };
51
+ }
52
+ function notify(listener) {
53
+ try {
54
+ listener(getSettings());
55
+ } catch {
56
+ }
57
+ }
58
+ function onSettingsChange(listener) {
59
+ if (typeof listener !== "function") return () => {
60
+ };
61
+ const subscription = (settings) => listener(settings);
62
+ state.settingsListeners.add(subscription);
63
+ notify(subscription);
64
+ return () => {
65
+ state.settingsListeners.delete(subscription);
66
+ };
67
+ }
68
+ function mergeSettings(value) {
69
+ if (value === void 0) return;
70
+ let musicEnabled;
71
+ if (value === null) {
72
+ musicEnabled = false;
73
+ } else if (typeof value === "object" && !Array.isArray(value) && typeof value.musicEnabled === "boolean") {
74
+ musicEnabled = value.musicEnabled;
75
+ } else {
76
+ return;
77
+ }
78
+ if (musicEnabled === state.gameSettings.musicEnabled) return;
79
+ state.gameSettings = { musicEnabled };
80
+ for (const listener of [...state.settingsListeners]) {
81
+ if (state.settingsListeners.has(listener)) notify(listener);
82
+ }
83
+ }
84
+
42
85
  // src/utils.ts
43
86
  function isBrowser() {
44
87
  return typeof window !== "undefined" && typeof document !== "undefined";
@@ -143,6 +186,47 @@
143
186
  }
144
187
 
145
188
  // src/bridge.ts
189
+ function parseApiResponse(value) {
190
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
191
+ const response = value;
192
+ if (typeof response.success !== "boolean") return null;
193
+ const parsed = { success: response.success };
194
+ if ("data" in response) parsed.data = response.data;
195
+ if (response.token !== void 0) {
196
+ if (typeof response.token !== "string" || response.token.length > 4e3) {
197
+ return null;
198
+ }
199
+ parsed.token = response.token;
200
+ }
201
+ if (response.error !== void 0) {
202
+ if (!response.error || typeof response.error !== "object" || Array.isArray(response.error)) {
203
+ return null;
204
+ }
205
+ const error2 = response.error;
206
+ 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)) {
207
+ return null;
208
+ }
209
+ const parsedError = {};
210
+ if (typeof error2.code === "string") parsedError.code = error2.code;
211
+ if (typeof error2.message === "string") parsedError.message = error2.message;
212
+ if (error2.details !== void 0) {
213
+ if (!error2.details || typeof error2.details !== "object" || Array.isArray(error2.details)) {
214
+ return null;
215
+ }
216
+ const details = error2.details;
217
+ 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)) {
218
+ return null;
219
+ }
220
+ parsedError.details = {
221
+ ...typeof details.terminal === "boolean" ? { terminal: details.terminal } : {},
222
+ ...typeof details.sessionStatus === "string" ? { sessionStatus: details.sessionStatus } : {},
223
+ ...typeof details.retryAfterMs === "number" ? { retryAfterMs: details.retryAfterMs } : {}
224
+ };
225
+ }
226
+ parsed.error = parsedError;
227
+ }
228
+ return parsed;
229
+ }
146
230
  function trimToNullable(value) {
147
231
  if (value === null) return null;
148
232
  if (typeof value !== "string") return void 0;
@@ -165,7 +249,8 @@
165
249
  };
166
250
  }
167
251
  function mergeBootstrapConfig(config = {}) {
168
- if (!config || typeof config !== "object") return;
252
+ if (!config || typeof config !== "object" || Array.isArray(config)) return;
253
+ mergeSettings(config.settings);
169
254
  const apply = (key, raw) => {
170
255
  const next = trimToNullable(raw);
171
256
  if (next === void 0) return;
@@ -192,6 +277,20 @@
192
277
  applyBootstrap("bootstrapTeamOneName", config.teamOneName);
193
278
  applyBootstrap("bootstrapTeamTwoName", config.teamTwoName);
194
279
  applyBootstrap("bootstrapProfileId", config.profileId);
280
+ if (Array.isArray(config.capabilities))
281
+ state.bootstrapCapabilities = config.capabilities.filter((c) => typeof c === "string" && c.length <= 100).slice(0, 32);
282
+ const launch = config.multiplayerLaunch;
283
+ if (launch === null) state.bootstrapLaunch = null;
284
+ else if (launch && launch.version === 2 && (launch.recoveryGraceMs === void 0 || Number.isSafeInteger(launch.recoveryGraceMs) && launch.recoveryGraceMs >= 1e3 && launch.recoveryGraceMs <= 12e4) && [
285
+ "multiplayerSessionId",
286
+ "roundId",
287
+ "attemptId",
288
+ "seatId",
289
+ "hostInstanceId"
290
+ ].every(
291
+ (k) => typeof launch[k] === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(String(launch[k]))
292
+ ) && typeof launch.gameUrl === "string" && launch.gameUrl.startsWith("/games/") && launch.gameUrl.length < 2048 && ["server", "unverified"].includes(launch.scoreAuthority))
293
+ state.bootstrapLaunch = { ...launch };
195
294
  const mp = parseMultiplayer(config.multiplayer);
196
295
  if (mp !== void 0) {
197
296
  state.bootstrapMultiplayer = mp;
@@ -199,6 +298,7 @@
199
298
  }
200
299
  function snapshotBootstrap() {
201
300
  return {
301
+ settings: getSettings(),
202
302
  gameSlug: state.gameSlug,
203
303
  authToken: state.authToken,
204
304
  leagueId: state.leagueId,
@@ -211,7 +311,9 @@
211
311
  teamOneName: state.bootstrapTeamOneName,
212
312
  teamTwoName: state.bootstrapTeamTwoName,
213
313
  profileId: state.bootstrapProfileId,
214
- multiplayer: state.bootstrapMultiplayer
314
+ multiplayer: state.bootstrapMultiplayer,
315
+ multiplayerLaunch: state.bootstrapLaunch,
316
+ capabilities: state.bootstrapCapabilities
215
317
  };
216
318
  }
217
319
  function requestBootstrapFromParent() {
@@ -321,12 +423,21 @@
321
423
  settled = true;
322
424
  unsubscribe();
323
425
  if (timeoutId) clearTimeout(timeoutId);
324
- if (data.ok) {
325
- resolve(data.result ?? {});
326
- } else {
426
+ const apiResponse = parseApiResponse(data.result);
427
+ if (apiResponse) {
428
+ resolve(apiResponse);
429
+ } else if (!data.ok) {
327
430
  reject(new Error(data.error || "Host API request failed"));
431
+ } else {
432
+ reject(new Error("Host API response was invalid"));
328
433
  }
329
434
  };
435
+ timeoutId = setTimeout(() => {
436
+ if (settled) return;
437
+ settled = true;
438
+ unsubscribe();
439
+ reject(new Error("Host API request timed out"));
440
+ }, HOST_API_TIMEOUT_MS);
330
441
  unsubscribe = transport.subscribe(handler);
331
442
  transport.send({
332
443
  type: MESSAGE_PREFIX + "_API_REQUEST",
@@ -335,22 +446,19 @@
335
446
  method: options.method || "GET",
336
447
  body: options.body ?? null
337
448
  });
338
- timeoutId = setTimeout(() => {
339
- if (settled) return;
340
- settled = true;
341
- unsubscribe();
342
- reject(new Error("Host API request timed out"));
343
- }, HOST_API_TIMEOUT_MS);
344
449
  });
345
450
  }
346
451
  function sendToParent(type, data) {
347
452
  const transport = getTransport();
348
453
  if (!transport) return;
349
- transport.send({
350
- type: MESSAGE_PREFIX + "_" + type,
351
- gameSlug: state.gameSlug,
352
- ...data
353
- });
454
+ try {
455
+ transport.send({
456
+ type: MESSAGE_PREFIX + "_" + type,
457
+ gameSlug: state.gameSlug,
458
+ ...data
459
+ });
460
+ } catch {
461
+ }
354
462
  }
355
463
 
356
464
  // src/api-client.ts
@@ -376,7 +484,139 @@
376
484
  }
377
485
 
378
486
  // src/session.ts
379
- async function startSession() {
487
+ var MAX_ATTEMPTS = 1e6;
488
+ var MAX_SCORE = 1e7;
489
+ var MAX_META_BYTES = 32 * 1024;
490
+ var MAX_META_DEPTH = 5;
491
+ var MAX_META_KEYS = 200;
492
+ var MAX_META_KEY_LENGTH = 100;
493
+ var MAX_META_STRING_LENGTH = 2048;
494
+ var MAX_META_ARRAY_LENGTH = 100;
495
+ var FORBIDDEN_META_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
496
+ var NON_CLIENT_META_KEYS = /* @__PURE__ */ new Set([
497
+ "attempts",
498
+ "duration",
499
+ "durationMs",
500
+ "timeTaken",
501
+ "serverDurationMs",
502
+ "userId",
503
+ "gameId",
504
+ "source",
505
+ "sessionId",
506
+ "token"
507
+ ]);
508
+ function stableJson(value) {
509
+ if (value === null || typeof value !== "object") {
510
+ return JSON.stringify(value) ?? "null";
511
+ }
512
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
513
+ return `{${Object.keys(value).sort().map(
514
+ (key) => `${JSON.stringify(key)}:${stableJson(value[key])}`
515
+ ).join(",")}}`;
516
+ }
517
+ function failedResult(code, message, retriable) {
518
+ return {
519
+ success: false,
520
+ status: "failed",
521
+ terminal: false,
522
+ code,
523
+ error: message,
524
+ retriable
525
+ };
526
+ }
527
+ function isValidMetadata(value) {
528
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
529
+ try {
530
+ const prototype = Object.getPrototypeOf(value);
531
+ if (prototype !== Object.prototype && prototype !== null) return false;
532
+ let keyCount = 0;
533
+ const visit = (item, depth) => {
534
+ if (depth > MAX_META_DEPTH) return false;
535
+ if (item === null || typeof item === "boolean") return true;
536
+ if (typeof item === "number") {
537
+ return Number.isFinite(item) && Math.abs(item) <= Number.MAX_SAFE_INTEGER;
538
+ }
539
+ if (typeof item === "string") {
540
+ return item.length <= MAX_META_STRING_LENGTH;
541
+ }
542
+ if (Array.isArray(item)) {
543
+ return item.length <= MAX_META_ARRAY_LENGTH && item.every((entry) => visit(entry, depth + 1));
544
+ }
545
+ if (!item || typeof item !== "object") return false;
546
+ const itemPrototype = Object.getPrototypeOf(item);
547
+ if (itemPrototype !== Object.prototype && itemPrototype !== null) {
548
+ return false;
549
+ }
550
+ for (const [key, entry] of Object.entries(item)) {
551
+ keyCount += 1;
552
+ if (keyCount > MAX_META_KEYS || key.length === 0 || key.length > MAX_META_KEY_LENGTH || FORBIDDEN_META_KEYS.has(key) || !visit(entry, depth + 1)) {
553
+ return false;
554
+ }
555
+ }
556
+ return true;
557
+ };
558
+ return visit(value, 0) && new TextEncoder().encode(JSON.stringify(value)).byteLength <= MAX_META_BYTES;
559
+ } catch {
560
+ return false;
561
+ }
562
+ }
563
+ function prepareSubmission(token, score, meta) {
564
+ if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || Math.floor(score) > MAX_SCORE) {
565
+ return {
566
+ ok: false,
567
+ result: failedResult(
568
+ "INVALID_INPUT",
569
+ `Score must be a finite number between 0 and ${MAX_SCORE}`,
570
+ false
571
+ )
572
+ };
573
+ }
574
+ if (!isValidMetadata(meta)) {
575
+ return {
576
+ ok: false,
577
+ result: failedResult(
578
+ "INVALID_INPUT",
579
+ "Score metadata exceeds the allowed bounds",
580
+ false
581
+ )
582
+ };
583
+ }
584
+ let snapshot;
585
+ try {
586
+ snapshot = JSON.parse(JSON.stringify(meta));
587
+ } catch {
588
+ return {
589
+ ok: false,
590
+ result: failedResult(
591
+ "INVALID_INPUT",
592
+ "Score metadata must be JSON serializable",
593
+ false
594
+ )
595
+ };
596
+ }
597
+ const attemptsValue = snapshot.attempts;
598
+ const attempts = typeof attemptsValue === "number" && Number.isFinite(attemptsValue) && attemptsValue >= 0 ? Math.min(Math.floor(attemptsValue), MAX_ATTEMPTS) : 0;
599
+ const clientMeta = Object.fromEntries(
600
+ Object.entries(snapshot).filter(([key]) => !NON_CLIENT_META_KEYS.has(key))
601
+ );
602
+ const integerScore = Math.floor(score);
603
+ return {
604
+ ok: true,
605
+ canonicalPayload: stableJson({
606
+ score: integerScore,
607
+ attempts,
608
+ clientMeta
609
+ }),
610
+ body: { token, score: integerScore, meta: snapshot }
611
+ };
612
+ }
613
+ function clearTerminalSession() {
614
+ state.sessionToken = null;
615
+ state.sessionStartPromise = null;
616
+ state.submissionPromise = null;
617
+ state.pendingSubmission = null;
618
+ }
619
+ async function performStartSession() {
380
620
  if (!state.gameSlug) return { success: false, error: "Game slug not set" };
381
621
  const isLeagueMatchSession = Boolean(
382
622
  state.leagueId && state.gameId && state.matchId
@@ -386,7 +626,6 @@
386
626
  if (!state.authToken && !isLeagueMatchSession && !isEmbedGuestSession && !isHostAuthenticatedSession) {
387
627
  return { success: false, error: "User not authenticated" };
388
628
  }
389
- if (state.sessionToken) return { success: true, token: state.sessionToken };
390
629
  try {
391
630
  let endpoint = "/sessions/start";
392
631
  let body = { gameSlug: state.gameSlug };
@@ -397,90 +636,178 @@
397
636
  endpoint = "/leagues/" + state.leagueId + "/sessions";
398
637
  body = { gameId: state.gameId };
399
638
  }
400
- const result = await apiRequest(endpoint, {
401
- method: "POST",
402
- body
403
- });
639
+ const result = await apiRequest(endpoint, { method: "POST", body });
404
640
  const data = unwrapResult(result);
405
- if (result.success || data?.token) {
406
- state.sessionToken = data?.token || result?.token || null;
407
- sendToParent("SESSION_STARTED", { token: state.sessionToken });
408
- return { success: true, token: state.sessionToken };
641
+ const token = data?.token || result?.token || null;
642
+ if (result.success && typeof token === "string" && token) {
643
+ state.sessionToken = token;
644
+ sendToParent("SESSION_STARTED", { token });
645
+ return { success: true, token };
409
646
  }
410
647
  return {
411
648
  success: false,
412
649
  error: result.error?.message || "Failed to start session"
413
650
  };
414
651
  } catch (err) {
415
- return { success: false, error: err.message };
652
+ return { success: false, error: err?.message || "Failed to start session" };
416
653
  }
417
654
  }
418
- async function submitScore(score, meta = {}) {
419
- await ensureInitialized();
420
- if (!state.isInitialized) {
655
+ async function startSession() {
656
+ if (state.bootstrapLaunch)
657
+ return { success: false, error: "Multiplayer rounds own their results" };
658
+ if (state.sessionToken) return { success: true, token: state.sessionToken };
659
+ if (state.sessionStartPromise) return await state.sessionStartPromise;
660
+ const promise = performStartSession();
661
+ state.sessionStartPromise = promise;
662
+ try {
663
+ return await promise;
664
+ } finally {
665
+ if (state.sessionStartPromise === promise) state.sessionStartPromise = null;
666
+ }
667
+ }
668
+ function normalizeSubmissionResult(result, token) {
669
+ const data = unwrapResult(result);
670
+ 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)) {
671
+ return {
672
+ success: true,
673
+ status: "accepted",
674
+ terminal: true,
675
+ sessionId: data.sessionId,
676
+ serverDurationMs: data.serverDurationMs,
677
+ timeTaken: data.timeTaken,
678
+ ...data.replayed === true ? { replayed: true } : {}
679
+ };
680
+ }
681
+ if (result.success && data?.accepted === true && typeof data?.timeTaken === "number" && Number.isFinite(data.timeTaken)) {
682
+ return {
683
+ success: true,
684
+ status: "accepted",
685
+ terminal: true,
686
+ sessionId: token,
687
+ serverDurationMs: Math.max(0, Math.floor(data.timeTaken * 1e3)),
688
+ timeTaken: Math.max(0, Math.floor(data.timeTaken))
689
+ };
690
+ }
691
+ const apiError = result.error;
692
+ const code = apiError?.code || "SERVER_ERROR";
693
+ const message = apiError?.message || "Score submission failed";
694
+ const details = apiError?.details;
695
+ if (details?.terminal === true) {
696
+ return {
697
+ success: false,
698
+ status: "rejected",
699
+ terminal: true,
700
+ code,
701
+ error: message,
702
+ ...typeof details.sessionStatus === "string" ? { sessionStatus: details.sessionStatus } : {}
703
+ };
704
+ }
705
+ if (code === "SUBMISSION_IN_PROGRESS" || code === "RATE_LIMITED") {
421
706
  return {
422
707
  success: false,
423
- error: "SDK could not initialize. Is game slug set?"
708
+ status: "retriable",
709
+ terminal: false,
710
+ code,
711
+ error: message,
712
+ ...typeof details?.retryAfterMs === "number" ? { retryAfterMs: details.retryAfterMs } : {},
713
+ ...typeof details?.sessionStatus === "string" ? { sessionStatus: details.sessionStatus } : {}
424
714
  };
425
715
  }
716
+ return failedResult(code, message, code === "SERVER_ERROR");
717
+ }
718
+ async function performSubmission(pending2) {
719
+ let outcome;
720
+ try {
721
+ const response = await apiRequest("/sessions/submit", {
722
+ method: "POST",
723
+ body: pending2.body
724
+ });
725
+ outcome = normalizeSubmissionResult(response, pending2.token);
726
+ } catch (err) {
727
+ outcome = failedResult(
728
+ "TRANSPORT_ERROR",
729
+ err?.message || "Score submission transport failed",
730
+ true
731
+ );
732
+ }
733
+ if (outcome.success) {
734
+ sendToParent("SCORE_SUBMITTED", {
735
+ score: pending2.body.score,
736
+ sessionId: outcome.sessionId,
737
+ status: outcome.status,
738
+ terminal: outcome.terminal,
739
+ serverDurationMs: outcome.serverDurationMs,
740
+ timeTaken: outcome.timeTaken,
741
+ ...outcome.replayed ? { replayed: true } : {}
742
+ });
743
+ clearTerminalSession();
744
+ } else if (outcome.terminal) {
745
+ clearTerminalSession();
746
+ }
747
+ return outcome;
748
+ }
749
+ async function submitScore(score, meta = {}) {
750
+ await ensureInitialized();
751
+ if (!state.isInitialized) {
752
+ return failedResult(
753
+ "SDK_NOT_INITIALIZED",
754
+ "SDK could not initialize. Is game slug set?",
755
+ false
756
+ );
757
+ }
426
758
  if (!state.sessionToken) {
427
759
  if (state.sessionStartPromise) {
428
760
  await state.sessionStartPromise;
429
761
  } else {
430
762
  const sessionResult = await startSession();
431
763
  if (!sessionResult.success) {
432
- return {
433
- success: false,
434
- error: sessionResult.error || "Could not start session"
435
- };
764
+ return failedResult(
765
+ "SESSION_START_FAILED",
766
+ sessionResult.error || "Could not start session",
767
+ true
768
+ );
436
769
  }
437
770
  }
438
771
  }
439
772
  if (!state.sessionToken) {
440
- return {
441
- success: false,
442
- error: "No active session. User may not be authenticated."
443
- };
773
+ return failedResult(
774
+ "SESSION_START_FAILED",
775
+ "No active session. User may not be authenticated.",
776
+ true
777
+ );
444
778
  }
445
- if (typeof score !== "number" || score < 0) {
446
- return { success: false, error: "Score must be a non-negative number" };
779
+ const prepared = prepareSubmission(state.sessionToken, score, meta);
780
+ if (!prepared.ok) return prepared.result;
781
+ const pending2 = state.pendingSubmission;
782
+ if (pending2 && (pending2.token !== state.sessionToken || pending2.canonicalPayload !== prepared.canonicalPayload)) {
783
+ return failedResult(
784
+ "CONCURRENT_SUBMISSION_CONFLICT",
785
+ "A different payload is already bound to the active session",
786
+ false
787
+ );
447
788
  }
789
+ if (state.submissionPromise) return await state.submissionPromise;
790
+ const activePending = pending2 ?? {
791
+ token: state.sessionToken,
792
+ canonicalPayload: prepared.canonicalPayload,
793
+ body: prepared.body
794
+ };
795
+ state.pendingSubmission = activePending;
796
+ const promise = performSubmission(activePending);
797
+ state.submissionPromise = promise;
448
798
  try {
449
- const result = await apiRequest("/sessions/submit", {
450
- method: "POST",
451
- body: {
452
- token: state.sessionToken,
453
- score: Math.floor(score),
454
- meta
455
- }
456
- });
457
- const data = unwrapResult(result);
458
- if (result.success || data?.accepted) {
459
- sendToParent("SCORE_SUBMITTED", {
460
- score,
461
- accepted: data?.accepted,
462
- timeTaken: data?.timeTaken
463
- });
464
- return {
465
- success: true,
466
- accepted: data?.accepted,
467
- timeTaken: data?.timeTaken
468
- };
469
- }
470
- return {
471
- success: false,
472
- error: result.error?.message || "Score rejected"
473
- };
474
- } catch (err) {
475
- return { success: false, error: err.message };
799
+ return await promise;
800
+ } finally {
801
+ if (state.submissionPromise === promise) state.submissionPromise = null;
476
802
  }
477
803
  }
478
804
  async function submitMatchScore(score, meta = {}) {
479
805
  if (!state.matchId) {
480
- return {
481
- success: false,
482
- error: "No matchId found for this game session"
483
- };
806
+ return failedResult(
807
+ "MATCH_CONTEXT_MISSING",
808
+ "No matchId found for this game session",
809
+ false
810
+ );
484
811
  }
485
812
  return await submitScore(score, {
486
813
  ...meta || {},
@@ -491,7 +818,11 @@
491
818
  }
492
819
  async function submitMatchResult(result = {}) {
493
820
  if (!result || typeof result !== "object") {
494
- return { success: false, error: "match result payload is required" };
821
+ return failedResult(
822
+ "INVALID_INPUT",
823
+ "match result payload is required",
824
+ false
825
+ );
495
826
  }
496
827
  return await submitMatchScore(0, { matchResult: result });
497
828
  }
@@ -637,7 +968,7 @@
637
968
  state.isAutoInitializing = false;
638
969
  return false;
639
970
  }
640
- if (!state.authToken) {
971
+ if (!state.authToken && !state.bootstrapLaunch) {
641
972
  state.authToken = await getAuthTokenFromParent();
642
973
  }
643
974
  state.isInitialized = true;
@@ -647,7 +978,7 @@
647
978
  auto: true
648
979
  });
649
980
  if (state.authToken || state.bootstrapSessionMode === "authenticated" || state.bootstrapSessionMode === "embed-guest" || state.leagueId && state.gameId && state.matchId) {
650
- state.sessionStartPromise = startSession();
981
+ void startSession();
651
982
  }
652
983
  return true;
653
984
  } catch (err) {
@@ -683,7 +1014,7 @@
683
1014
  if (type === MESSAGE_PREFIX + "_SET_AUTH") {
684
1015
  state.authToken = data.token;
685
1016
  if (state.gameSlug && !state.sessionToken && !state.sessionStartPromise && (state.authToken || state.leagueId && state.gameId && state.matchId)) {
686
- state.sessionStartPromise = startSession();
1017
+ void startSession();
687
1018
  }
688
1019
  }
689
1020
  if (type === MESSAGE_PREFIX + "_COMMAND") {
@@ -698,6 +1029,79 @@
698
1029
  });
699
1030
  }
700
1031
 
1032
+ // src/multiplayer.ts
1033
+ var pending = null;
1034
+ function requestMultiplayerLaunch() {
1035
+ if (!state.bootstrapLaunch || !state.bootstrapCapabilities.includes("multiplayer.launch.v2"))
1036
+ return Promise.resolve({
1037
+ status: "terminal",
1038
+ error: {
1039
+ code: "PROTOCOL_UNSUPPORTED",
1040
+ message: "This host does not support multiplayer launch v2",
1041
+ retryable: false
1042
+ }
1043
+ });
1044
+ if (pending) return pending;
1045
+ const launch = state.bootstrapLaunch;
1046
+ const operation = (async () => {
1047
+ try {
1048
+ const response = await requestApiFromParent("/multiplayer/launch", {
1049
+ method: "POST",
1050
+ body: {}
1051
+ });
1052
+ if (state.bootstrapLaunch !== launch)
1053
+ return {
1054
+ status: "terminal",
1055
+ error: {
1056
+ code: "STALE_ATTEMPT",
1057
+ message: "Launch context changed",
1058
+ retryable: false
1059
+ }
1060
+ };
1061
+ const data = response.data;
1062
+ if (response.success && data) {
1063
+ if (data.status === "reserved" && data.launch && [
1064
+ "multiplayerSessionId",
1065
+ "roundId",
1066
+ "attemptId",
1067
+ "seatId",
1068
+ "hostInstanceId"
1069
+ ].every(
1070
+ (k) => data.launch[k] === launch[k]
1071
+ ) && data.reservation && ["name", "roomId", "sessionId"].every(
1072
+ (k) => typeof data.reservation[k] === "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(
1073
+ String(data.reservation[k])
1074
+ )
1075
+ ) && /^wss?:\/\//.test(data.wsEndpoint) && data.wsEndpoint.length < 2048 && Number.isSafeInteger(data.generation) && data.generation > 0 && Number.isSafeInteger(data.expiresAt))
1076
+ return data;
1077
+ 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")
1078
+ return data;
1079
+ }
1080
+ return {
1081
+ status: "recoverable",
1082
+ error: {
1083
+ code: response.error?.code ?? "UNAVAILABLE",
1084
+ message: response.error?.message ?? "Launch unavailable",
1085
+ retryable: true
1086
+ }
1087
+ };
1088
+ } catch {
1089
+ return {
1090
+ status: "recoverable",
1091
+ error: {
1092
+ code: "UNAVAILABLE",
1093
+ message: "Launch request failed; retry",
1094
+ retryable: true
1095
+ }
1096
+ };
1097
+ }
1098
+ })().finally(() => {
1099
+ if (pending === operation) pending = null;
1100
+ });
1101
+ pending = operation;
1102
+ return operation;
1103
+ }
1104
+
701
1105
  // src/match-context.ts
702
1106
  async function fetchMatchContext() {
703
1107
  if (!state.leagueId || !state.matchId) return null;
@@ -732,6 +1136,7 @@
732
1136
  hasActiveSession() {
733
1137
  return !!state.sessionToken;
734
1138
  },
1139
+ requestMultiplayerLaunch,
735
1140
  async startSession() {
736
1141
  await ensureInitialized();
737
1142
  if (state.sessionStartPromise) return await state.sessionStartPromise;
@@ -793,8 +1198,14 @@
793
1198
  async ready() {
794
1199
  return await ensureInitialized();
795
1200
  },
1201
+ getSettings,
1202
+ onSettingsChange(listener) {
1203
+ installHostMessageListener();
1204
+ return onSettingsChange(listener);
1205
+ },
796
1206
  getBootstrap() {
797
1207
  return {
1208
+ settings: getSettings(),
798
1209
  gameSlug: state.gameSlug,
799
1210
  authToken: state.authToken,
800
1211
  leagueId: state.leagueId,
@@ -808,6 +1219,8 @@
808
1219
  teamTwoName: state.bootstrapTeamTwoName,
809
1220
  profileId: state.bootstrapProfileId,
810
1221
  multiplayer: state.bootstrapMultiplayer,
1222
+ multiplayerLaunch: state.bootstrapLaunch,
1223
+ capabilities: [...state.bootstrapCapabilities],
811
1224
  isBootstrapped: state.bootstrapReceived
812
1225
  };
813
1226
  },