@tesana/sdk 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@
2
2
  * Tesana play-time SDK. Vanilla JS, no npm in games.
3
3
  * Host injects window.__TESANA__ or postMessage { type: "tesana-bootstrap", ... }.
4
4
  * v1 is player identity, per-game saves, optional open-lobby multiplayer,
5
- * cloud saves, and the in-game coin economy.
5
+ * cloud saves, the in-game coin economy, and gameplay analytics.
6
6
  *
7
7
  * THIS FILE IS THE ONE COPY. It is the source of truth for `window.Tesana`:
8
8
  * the engine injects the built artifact into every game and the CDN serves it
@@ -37,7 +37,11 @@
37
37
  // 1.0.0 ships six services together: saves, shop, leaderboards, achievements,
38
38
  // a vanity address (`tesana.vanity`) and in-game ads (`tesana.ads`). These are
39
39
  // the first release, so there is no earlier number to stay compatible with.
40
- const VERSION = "1.0.4";
40
+ //
41
+ // 1.1.0 adds gameplay analytics, `tesana.track` and `tesana.gameplay.*`. The
42
+ // engine's analytics skill already taught them, so a game following it threw a
43
+ // TypeError on its first death; this is the release that makes those calls real.
44
+ const VERSION = "1.1.0";
41
45
 
42
46
  const LOCAL_CACHE = "tesana.play.v1";
43
47
 
@@ -53,6 +57,21 @@ const LOCAL_CACHE = "tesana.play.v1";
53
57
  const MP_RECONNECT_BASE_MS = 1000;
54
58
  const MP_RECONNECT_MAX_MS = 30000;
55
59
  const MP_RECONNECT_MAX_ATTEMPTS = 8;
60
+ //: How long to wait for the host to answer a bootstrap request before giving
61
+ //: up on that attempt. The answer is a token mint; a host that is slow must not
62
+ //: hold a request open indefinitely.
63
+ const MP_HOST_ASK_TIMEOUT_MS = 5000;
64
+ //: How long `create`/`quickJoin` will wait for a room that is being placed.
65
+ //:
66
+ //: Room creation on GameLift is asynchronous, so the service answers 202 with
67
+ //: no `wsUrl` and a `retryAfterMs` instead of holding the request open. The
68
+ //: client polls until the room is ready or this budget runs out. It is longer
69
+ //: than the service's own placement poll (90s) only in the sense that it gives
70
+ //: up first: a client should decide for itself how long it will wait, and a
71
+ //: game can watch `onStatus` rather than being blocked.
72
+ const MP_PLACING_TIMEOUT_MS = 45000;
73
+ //: Default gap between placement polls, used when the service does not say.
74
+ const MP_PLACING_RETRY_MS = 1500;
56
75
 
57
76
  /**
58
77
  * A polite, dns-safe label: lowercase letters, digits and internal hyphens,
@@ -126,6 +145,18 @@ const bootstrapWaiters = [];
126
145
  // can re-point them in place. A game holds a reference to its client, so it
127
146
  // must not be rebuilt — only upgraded.
128
147
  const upgradeHandlers = [];
148
+ // Whether a bootstrap the client asked for is in flight. It is what makes a
149
+ // late answer an update rather than an unsolicited message that re-points a
150
+ // live session.
151
+ let bootstrapRequestPending = false;
152
+ // The in-flight ask, so a burst of refused calls mints once rather than once
153
+ // per caller. The host does its own rate-limiting; this only removes the
154
+ // duplicate round-trips a simultaneous burst would otherwise make.
155
+ let bootstrapAskPromise = null;
156
+ //: Bumped every time a host answer replaces the live bootstrap. A caller that
157
+ //: asked for a fresh token can tell whether it actually arrived by watching
158
+ //: this, without having to hold a listener of its own.
159
+ let bootstrapGeneration = 0;
129
160
 
130
161
  /**
131
162
  * Diagnostics that should say their piece once per session, not once per call.
@@ -150,17 +181,34 @@ function isGuestBootstrap(data) {
150
181
  }
151
182
 
152
183
  /** Fold a host's answer into the live config, upgrading a provisional one. */
153
- function applyBootstrap(data) {
184
+ function applyBootstrap(data, opts = {}) {
154
185
  const next = data && typeof data === "object" ? data : {};
186
+ // Whether the client asked for this answer. A bootstrap it asked for is a
187
+ // refresh — its token aged out and the host minted another — and may update a
188
+ // live session. One it did not ask for may not, or anything able to post into
189
+ // the frame could re-point a running game's credential and identity.
190
+ const asked = opts.force || bootstrapRequestPending;
191
+ bootstrapRequestPending = false;
155
192
  if (bootstrap) {
156
193
  // A real host has already answered — unless that answer was a guest and
157
194
  // this one is the account they just signed in to.
158
- if (!bootstrap.offline && !(isGuestBootstrap(bootstrap) && !next.offline && !isGuestBootstrap(next))) return;
195
+ if (!bootstrap.offline && !(isGuestBootstrap(bootstrap) && !next.offline && !isGuestBootstrap(next))) {
196
+ if (asked) {
197
+ // A forced update may refresh credentials (token, save token, room
198
+ // token) but never the player's identity: the player is who the
199
+ // signing-in page said they are, and a stale or mismatched answer must
200
+ // not silently become them.
201
+ if (bootstrap.player && next.player !== undefined) delete next.player;
202
+ } else {
203
+ return;
204
+ }
205
+ }
159
206
  // Still offline, unless it now carries a room token: a signed-out
160
207
  // visitor's multiplayer arrives after the site has already said "offline".
161
- if (next.offline && !(next.roomToken && !bootstrap.roomToken)) return;
208
+ if (next.offline && !(next.roomToken && !bootstrap.roomToken) && !asked) return;
162
209
  }
163
210
  bootstrap = next;
211
+ bootstrapGeneration += 1;
164
212
  window.__TESANA__ = { ...(window.__TESANA__ || {}), ...next };
165
213
  const waiting = bootstrapWaiters.splice(0);
166
214
  for (const resolve of waiting) resolve(bootstrap);
@@ -402,6 +450,8 @@ function startListening() {
402
450
  // The site posts `{ type, payload }`; a baked or spliced bootstrap is the
403
451
  // payload itself. Accept both, so one SDK reads either host.
404
452
  if (data.type === "tesana-bootstrap") {
453
+ // `applyBootstrap` decides whether this answer may update a live session:
454
+ // one the client asked for may, one it did not may not.
405
455
  applyBootstrap(data.payload && typeof data.payload === "object" ? data.payload : data);
406
456
  return;
407
457
  }
@@ -464,16 +514,73 @@ function waitBootstrap(timeoutMs = 1500) {
464
514
  if (bootstrap) return Promise.resolve(bootstrap);
465
515
 
466
516
  startListening();
467
- // Ask, rather than wait to be told. The frame can finish loading before the
468
- // site has minted the session, and a request is what makes the site post the
469
- // second time — without it a signed-in player's real bootstrap never arrives.
470
- post({ type: "tesana-bootstrap-request" });
471
517
  return new Promise((resolve) => {
518
+ // The waiter is registered before the ask goes out. A host that answers
519
+ // from the same tick — a test double, or a same-document frame — would
520
+ // otherwise be answered into an empty list and the game would fall to
521
+ // "offline" a second and a half later for no reason.
472
522
  bootstrapWaiters.push(resolve);
473
523
  setTimeout(() => applyBootstrap({ offline: true }), timeoutMs);
524
+ // Ask, rather than wait to be told. The frame can finish loading before the
525
+ // site has minted the session, and a request is what makes the site post the
526
+ // second time — without it a signed-in player's real bootstrap never arrives.
527
+ askHostForBootstrap();
474
528
  });
475
529
  }
476
530
 
531
+ /** Ask the host to post a bootstrap. Shared by boot and refresh, so the flag
532
+ * that makes an answer an update is set in exactly one place. The message name
533
+ * is what tells the host whether to re-mint or merely re-post. */
534
+ function askHostForBootstrap(type = "tesana-bootstrap-request") {
535
+ bootstrapRequestPending = true;
536
+ post({ type });
537
+ }
538
+
539
+ /**
540
+ * Ask the host for a fresh bootstrap after a credential was refused.
541
+ *
542
+ * This is the SDK half of token expiry. A player token lives two hours and
543
+ * used to be re-minted only on a page load, so after two hours a blip was
544
+ * permanent until the player reloaded. Asking the host re-mints through it, and
545
+ * the answer flows back through the same upgrade path identity and ads already
546
+ * use, so a live game is re-pointed in place.
547
+ *
548
+ * Resolves with the new bootstrap, or `null` when there is no host or the host
549
+ * did not answer in time. Concurrent callers share one ask: a game that has
550
+ * been open for hours hits a burst of refusals at once, and one mint is what
551
+ * all of them needed. The host rate-limits the mints themselves.
552
+ *
553
+ * @returns {Promise<object|null>}
554
+ */
555
+ function requestHostBootstrap() {
556
+ if (typeof window === "undefined") return Promise.resolve(null);
557
+ if (bootstrapAskPromise) return bootstrapAskPromise;
558
+ startListening();
559
+ const askedAt = bootstrapGeneration;
560
+ // A refresh, named as one. The host re-mints on this and merely re-posts on a
561
+ // boot request, so the two are never confused.
562
+ askHostForBootstrap("tesana-bootstrap-refresh");
563
+ bootstrapAskPromise = new Promise((resolve) => {
564
+ let done = false;
565
+ const finish = (value) => {
566
+ if (done) return;
567
+ done = true;
568
+ clearInterval(poll);
569
+ clearTimeout(expiry);
570
+ bootstrapAskPromise = null;
571
+ resolve(value);
572
+ };
573
+ // The bootstrap is delivered by the module-level listener, so watch the
574
+ // generation rather than registering a second listener — the token the host
575
+ // mints is scoped to this frame and is not ours to consume only here.
576
+ const poll = setInterval(() => {
577
+ if (bootstrapGeneration !== askedAt) finish(bootstrap);
578
+ }, 25);
579
+ const expiry = setTimeout(() => finish(null), MP_HOST_ASK_TIMEOUT_MS);
580
+ });
581
+ return bootstrapAskPromise;
582
+ }
583
+
477
584
  function deviceId() {
478
585
  const cache = readCache();
479
586
  if (cache.deviceId) return cache.deviceId;
@@ -518,6 +625,308 @@ function post(message) {
518
625
  }
519
626
  }
520
627
 
628
+ // ---------------------------------------------------------------------------
629
+ // Gameplay analytics: `tesana.track` and `tesana.gameplay`
630
+ // ---------------------------------------------------------------------------
631
+ //
632
+ // A game reports what happened in it (a level started, the player died, a run
633
+ // ended with a score) so its creator can see where players get stuck and where
634
+ // they quit. The pipe already exists end to end: the runtime shell injected
635
+ // into every web build exposes `window.__TESANA_EVENT__`, the Tesana page above
636
+ // the game buffers `tesana-gameplay-event` messages and files them against the
637
+ // play session with a token only it holds, and the ingest endpoint stores them.
638
+ // These functions are the game's end of that pipe.
639
+ //
640
+ // Three rules shape everything below:
641
+ //
642
+ // - **Never throw.** The engine tells the AI to call these inline, at the
643
+ // moment a player dies, with no guard. A TypeError here would turn a death
644
+ // into a crash, so every entry point is wrapped and answers `false` when it
645
+ // drops something.
646
+ // - **Match the ingest endpoint's caps.** The server keeps at most 20 payload
647
+ // keys, 40-character keys, 64-character strings and 2,000 characters in all,
648
+ // and throws away the whole payload when it is over. Trimming here means a
649
+ // slightly-too-big event loses a key rather than all of its context.
650
+ // - **Discrete moments, not frames.** A game that reports on every frame
651
+ // would fill the table and answer nothing, so events are rate limited per
652
+ // second and capped per page load.
653
+ //
654
+ // They are synchronous and need no `init()`: they never touch the play service,
655
+ // only the page, so a game can report a level start on its first frame.
656
+
657
+ //: The message the host's play tracking listens for. Mirrored by the web host
658
+ //: (`PLAY_MESSAGES.gameplayEvent`) and the runtime shell.
659
+ const GAMEPLAY_MESSAGE = "tesana-gameplay-event";
660
+
661
+ //: The event types the ingest endpoint understands, minus the two the shell
662
+ //: owns (`session_end`, `error`). `track()` with one of these names files the
663
+ //: event under that type; any other name is a `custom` event.
664
+ const GAMEPLAY_EVENT_TYPES = new Set(["level_start", "level_complete", "death", "checkpoint", "score"]);
665
+ const GAMEPLAY_TYPE_ALIASES = { levelStart: "level_start", levelComplete: "level_complete" };
666
+
667
+ //: The ingest endpoint's own limits (`games/api/play_events.py`).
668
+ const GAMEPLAY_NAME_MAX = 64;
669
+ const GAMEPLAY_STRING_MAX = 64;
670
+ const GAMEPLAY_KEY_MAX = 40;
671
+ const GAMEPLAY_PROPS_MAX_KEYS = 20;
672
+ const GAMEPLAY_PROPS_MAX_CHARS = 2000;
673
+
674
+ //: At most this many events in any one second. Ten a second is exactly what
675
+ //: one host flush can carry (100 events every 10 seconds), and far above what a
676
+ //: game reporting real moments ever needs.
677
+ const GAMEPLAY_RATE_PER_SECOND = 10;
678
+ //: At most this many events per page load. An honest session sends tens; a
679
+ //: game stuck reporting at the rate limit for an hour would send 36,000.
680
+ const GAMEPLAY_SESSION_MAX = 1000;
681
+
682
+ //: Props promoted to the event's own columns rather than kept as context.
683
+ const GAMEPLAY_LEVEL_ID_KEYS = ["levelId", "level_id", "level"];
684
+ const GAMEPLAY_LEVEL_INDEX_KEYS = ["levelIndex", "level_index"];
685
+ const GAMEPLAY_NUMBER_KEYS = ["x", "y", "z", "value"];
686
+ const GAMEPLAY_PROMOTED = new Set([
687
+ ...GAMEPLAY_LEVEL_ID_KEYS,
688
+ ...GAMEPLAY_LEVEL_INDEX_KEYS,
689
+ ...GAMEPLAY_NUMBER_KEYS,
690
+ "name",
691
+ ]);
692
+
693
+ let gameplaySecond = -1;
694
+ let gameplayInSecond = 0;
695
+ let gameplaySent = 0;
696
+
697
+ /** A finite number, or `undefined`. Numeric strings count; NaN never does. */
698
+ function gameplayNumber(value) {
699
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
700
+ if (typeof value === "string" && value.trim() !== "") {
701
+ const parsed = Number(value);
702
+ return Number.isFinite(parsed) ? parsed : undefined;
703
+ }
704
+ return undefined;
705
+ }
706
+
707
+ /** A trimmed, capped string id from a string or a number, or `undefined`. */
708
+ function gameplayId(value, limit) {
709
+ if (typeof value === "number") {
710
+ if (!Number.isFinite(value)) return undefined;
711
+ return String(value).slice(0, limit);
712
+ }
713
+ if (typeof value !== "string") return undefined;
714
+ const text = value.trim().slice(0, limit);
715
+ return text || undefined;
716
+ }
717
+
718
+ /** The first of `keys` that `props` holds a value for. */
719
+ function gameplayFirst(props, keys) {
720
+ for (const key of keys) {
721
+ if (props[key] !== undefined && props[key] !== null) return props[key];
722
+ }
723
+ return undefined;
724
+ }
725
+
726
+ /**
727
+ * Roughly how long the server's `repr()` of this payload will be.
728
+ *
729
+ * The endpoint measures Python's `repr`, not JSON: it writes `1.0` for `1` and
730
+ * puts a space after each colon and comma. Four characters per key is a safe
731
+ * margin over both differences, so a payload that passes here passes there.
732
+ */
733
+ function gameplayPayloadSize(payload, keys) {
734
+ return JSON.stringify(payload).length + 4 * keys;
735
+ }
736
+
737
+ /**
738
+ * Keep the scalar context a game passed, within the endpoint's caps.
739
+ *
740
+ * @param {object} props
741
+ * @param {boolean} keepName keep a `name` prop as context (a custom event, whose
742
+ * own name is the event's name) rather than treating it as the name column
743
+ */
744
+ function gameplayPayload(props, keepName) {
745
+ const payload = {};
746
+ let kept = 0;
747
+ for (const rawKey of Object.keys(props)) {
748
+ if (kept >= GAMEPLAY_PROPS_MAX_KEYS) break;
749
+ if (GAMEPLAY_PROMOTED.has(rawKey) && !(keepName && rawKey === "name")) continue;
750
+ const key = String(rawKey).trim().slice(0, GAMEPLAY_KEY_MAX);
751
+ if (!key || Object.prototype.hasOwnProperty.call(payload, key)) continue;
752
+ let value;
753
+ try {
754
+ value = props[rawKey];
755
+ } catch {
756
+ continue;
757
+ }
758
+ if (typeof value === "string") {
759
+ value = value.slice(0, GAMEPLAY_STRING_MAX);
760
+ } else if (typeof value === "number") {
761
+ if (!Number.isFinite(value)) continue;
762
+ } else if (typeof value !== "boolean" && value !== null) {
763
+ // Objects, arrays, functions, undefined, symbols and bigints are not
764
+ // stored: the analytics layer queries flat keys, and a nested shape it
765
+ // did not expect is a foot-gun rather than a feature.
766
+ continue;
767
+ }
768
+ payload[key] = value;
769
+ if (gameplayPayloadSize(payload, kept + 1) > GAMEPLAY_PROPS_MAX_CHARS) {
770
+ delete payload[key];
771
+ continue;
772
+ }
773
+ kept += 1;
774
+ }
775
+ return kept ? payload : null;
776
+ }
777
+
778
+ /**
779
+ * Build the event the host files, in the shape `POST /play/events` accepts.
780
+ *
781
+ * @param {string} type one of the ingest endpoint's event types
782
+ * @param {string|undefined} name the event's own name (a custom event, a death's cause)
783
+ * @param {object} props what the game passed
784
+ */
785
+ function gameplayEvent(type, name, props) {
786
+ const event = { type };
787
+ const named = name !== undefined ? name : gameplayId(props.name, GAMEPLAY_NAME_MAX);
788
+ if (named) event.name = named;
789
+ const levelId = gameplayId(gameplayFirst(props, GAMEPLAY_LEVEL_ID_KEYS), GAMEPLAY_STRING_MAX);
790
+ if (levelId) event.level_id = levelId;
791
+ const levelIndex = gameplayNumber(gameplayFirst(props, GAMEPLAY_LEVEL_INDEX_KEYS));
792
+ if (levelIndex !== undefined) event.level_index = Math.max(0, Math.floor(levelIndex));
793
+ for (const key of GAMEPLAY_NUMBER_KEYS) {
794
+ const number = gameplayNumber(props[key]);
795
+ if (number !== undefined) event[key] = number;
796
+ }
797
+ // A custom event's own name is already its name, so a `name` prop is kept as
798
+ // context like any other key instead of overwriting it.
799
+ const payload = gameplayPayload(props, type === "custom");
800
+ if (payload) event.payload = payload;
801
+ event.ts = Date.now();
802
+ return event;
803
+ }
804
+
805
+ /** Whether one more event fits this second and this page load. */
806
+ function gameplayAllowed() {
807
+ if (gameplaySent >= GAMEPLAY_SESSION_MAX) {
808
+ warnOnce(
809
+ "gameplay-session-max",
810
+ `tesana.track: ${GAMEPLAY_SESSION_MAX} events this session; further events are dropped. Report discrete moments (a level, a death, a run's end), never every frame.`,
811
+ );
812
+ return false;
813
+ }
814
+ const second = Math.floor(Date.now() / 1000);
815
+ if (second !== gameplaySecond) {
816
+ gameplaySecond = second;
817
+ gameplayInSecond = 0;
818
+ }
819
+ if (gameplayInSecond >= GAMEPLAY_RATE_PER_SECOND) {
820
+ warnOnce(
821
+ "gameplay-rate",
822
+ `tesana.track: more than ${GAMEPLAY_RATE_PER_SECOND} events in one second; the extra ones are dropped. Report discrete moments, never every frame.`,
823
+ );
824
+ return false;
825
+ }
826
+ gameplayInSecond += 1;
827
+ gameplaySent += 1;
828
+ return true;
829
+ }
830
+
831
+ /**
832
+ * Hand an event to whoever files it. `true` when it was handed on.
833
+ *
834
+ * The shell's `__TESANA_EVENT__` comes first: it posts the same message, and
835
+ * going through it lets the shell name the last level in its `session_end`.
836
+ * Without the shell, the message goes straight to the Tesana page above. With
837
+ * neither there is nobody to tell, and the event is dropped.
838
+ */
839
+ function gameplayDeliver(event) {
840
+ if (typeof window === "undefined") return false;
841
+ const bridge = window.__TESANA_EVENT__;
842
+ if (typeof bridge === "function") {
843
+ bridge(event);
844
+ return true;
845
+ }
846
+ if (!hasHost()) return false;
847
+ post({ type: GAMEPLAY_MESSAGE, event });
848
+ return true;
849
+ }
850
+
851
+ /** The game's props as a plain object, whatever it actually passed. */
852
+ function gameplayProps(props) {
853
+ return props && typeof props === "object" && !Array.isArray(props) ? props : {};
854
+ }
855
+
856
+ /**
857
+ * Report something that happened in the game.
858
+ *
859
+ * `name` is the game's own name for it (`"powerup_picked"`). A name that is one
860
+ * of the platform's types (`"death"`, `"level_start"`, `"level_complete"`,
861
+ * `"checkpoint"`, `"score"`) is filed as that type. `props` is a small object of
862
+ * scalars; `levelId`, `levelIndex`, `x`, `y`, `z` and `value` become columns and
863
+ * anything else rides along as context.
864
+ *
865
+ * Synchronous, never throws, and never returns a promise: `true` when the event
866
+ * was handed on, `false` when it was dropped (a bad name, too many events, or
867
+ * nothing above the game to hand it to).
868
+ *
869
+ * @param {string} name
870
+ * @param {Record<string, string|number|boolean|null>} [props]
871
+ * @returns {boolean}
872
+ */
873
+ function track(name, props) {
874
+ try {
875
+ const label = gameplayId(name, GAMEPLAY_NAME_MAX);
876
+ if (!label) {
877
+ warnOnce("gameplay-name", "tesana.track: the first argument must be a non-empty event name.");
878
+ return false;
879
+ }
880
+ if (!gameplayAllowed()) return false;
881
+ const builtIn = GAMEPLAY_TYPE_ALIASES[label] || label;
882
+ const event = GAMEPLAY_EVENT_TYPES.has(builtIn)
883
+ ? gameplayEvent(builtIn, undefined, gameplayProps(props))
884
+ : gameplayEvent("custom", label, gameplayProps(props));
885
+ return gameplayDeliver(event);
886
+ } catch {
887
+ return false;
888
+ }
889
+ }
890
+
891
+ /**
892
+ * One gameplay helper. `props` may also be a bare level id (`levelStart(3)`), or
893
+ * for `score` a bare value (`score(1200)`).
894
+ *
895
+ * @param {string} type
896
+ * @param {"levelId"|"value"} shorthand
897
+ */
898
+ function gameplayHelper(type, shorthand) {
899
+ return function report(props) {
900
+ try {
901
+ if (!gameplayAllowed()) return false;
902
+ const given = typeof props === "string" || typeof props === "number"
903
+ ? { [shorthand]: props }
904
+ : gameplayProps(props);
905
+ return gameplayDeliver(gameplayEvent(type, undefined, given));
906
+ } catch {
907
+ return false;
908
+ }
909
+ };
910
+ }
911
+
912
+ /**
913
+ * The progression events every game with levels, waves, runs or deaths should
914
+ * send. `levelId` is the join key: give it the same stable value in each call
915
+ * for one level, so a funnel can line them up.
916
+ */
917
+ const gameplay = Object.freeze({
918
+ /** A level, stage, wave or area begins: `{ levelId, levelIndex? }`. */
919
+ levelStart: gameplayHelper("level_start", "levelId"),
920
+ /** A level is cleared: `{ levelId }`. */
921
+ levelComplete: gameplayHelper("level_complete", "levelId"),
922
+ /** The player died: `{ levelId, x?, y?, z?, name? }` (`name` is the cause). */
923
+ death: gameplayHelper("death", "levelId"),
924
+ /** A checkpoint is reached: `{ levelId, name? }`. */
925
+ checkpoint: gameplayHelper("checkpoint", "levelId"),
926
+ /** A run ended: `{ value, levelId? }`. */
927
+ score: gameplayHelper("score", "value"),
928
+ });
929
+
521
930
  /**
522
931
  * @param {TesanaConfig} [config]
523
932
  */
@@ -645,6 +1054,9 @@ function buildConfig(merged) {
645
1054
  locale: normalizeLocale(
646
1055
  merged.locale || merged.language || merged.lang || (typeof navigator !== "undefined" && navigator.language) || "",
647
1056
  ),
1057
+ // How a dropped room socket is retried. A game can shrink the waits (a
1058
+ // test, or a game with unusual tolerance); the defaults are the fleet's.
1059
+ multiplayerReconnect: merged.multiplayerReconnect || undefined,
648
1060
  };
649
1061
  }
650
1062
 
@@ -707,6 +1119,10 @@ class TesanaClient {
707
1119
  leaving: false,
708
1120
  reconnectTimer: null,
709
1121
  reconnectAttempts: 0,
1122
+ // The code of the last close we saw. 4401 means the grant was refused —
1123
+ // expired, most likely — and a fresh one has to be minted before the next
1124
+ // reconnect can succeed. Cleared once a reconnect has used it.
1125
+ lastCloseCode: null,
710
1126
  reconnectExhausted: false,
711
1127
  statusHandlers: [],
712
1128
  // Overridable so a test (or a game with unusual tolerance) can shorten
@@ -923,6 +1339,12 @@ class TesanaClient {
923
1339
  this.l10n = this._makeL10n(opts);
924
1340
  l10nClient = this.l10n;
925
1341
 
1342
+ // Gameplay analytics. The same functions as `Tesana.track` and
1343
+ // `Tesana.gameplay` on the global, so a game can call them before its
1344
+ // `await __TESANA_READY__` resolves; none of them depends on this client.
1345
+ this.track = track;
1346
+ this.gameplay = gameplay;
1347
+
926
1348
  this.multiplayer = {
927
1349
  // Read this before drawing a lobby: when it is false the game is not
928
1350
  // allowed rooms yet and the calls below refuse.
@@ -1151,7 +1573,7 @@ class TesanaClient {
1151
1573
  * @param {Promise<{ wsUrl: string, roomId?: string, room?: object, playerId?: string }>} session
1152
1574
  */
1153
1575
  async _mpEnter(session) {
1154
- const joined = await session;
1576
+ const joined = await this._mpAwaitPlacement(await session);
1155
1577
  // A room that was opened and then could not be entered is reported as what
1156
1578
  // it is: the room exists. The SDK cannot seat the player — that is the
1157
1579
  // host's job — but it can name the room so a game retries `join(roomId)`
@@ -1178,6 +1600,56 @@ class TesanaClient {
1178
1600
  };
1179
1601
  }
1180
1602
 
1603
+ /**
1604
+ * Wait out a room that is still being placed, then hand back its session.
1605
+ *
1606
+ * Room creation on GameLift outlives a single HTTP request — a cold fleet can
1607
+ * take minutes — so the service answers 202 with the room's identity, the
1608
+ * caller's seat, and `retryAfterMs`, and no `wsUrl`. Treating that as a failed
1609
+ * create is what used to leave a ghost: the room existed, its creator was
1610
+ * seated, and the client believed nothing had happened. So the client polls
1611
+ * the same room it was handed (`join` re-issues the seat, it does not take a
1612
+ * second) until the address exists or the wait budget runs out.
1613
+ *
1614
+ * The budget is the client's own. A game that would rather show a spinner and
1615
+ * decide for itself calls `join(roomId)` after `create` rejects with
1616
+ * `mp_room_placing`, and this consumes the same code path.
1617
+ *
1618
+ * @param {{ wsUrl?: string, roomId?: string, state?: string, retryAfterMs?: number, room?: object }} session
1619
+ */
1620
+ async _mpAwaitPlacement(session) {
1621
+ if (!session || session.wsUrl || session.state !== "placing") return session;
1622
+ const roomId = session.roomId || session.room?.id;
1623
+ if (!roomId) return session;
1624
+ this._mpEmitStatus({ status: "placing", roomId });
1625
+ // Instance-overridable so a game (or a test) can decide how long it will
1626
+ // wait for placement without reaching into module scope.
1627
+ const budget = Number(this._mpPlacingTimeoutMs) || MP_PLACING_TIMEOUT_MS;
1628
+ const deadline = Date.now() + budget;
1629
+ let current = session;
1630
+ while (!current?.wsUrl && Date.now() < deadline) {
1631
+ const gap = Math.max(250, Number(current.retryAfterMs) || MP_PLACING_RETRY_MS);
1632
+ await new Promise((resolve) => setTimeout(resolve, Math.min(gap, Math.max(0, deadline - Date.now()))));
1633
+ if (Date.now() >= deadline) break;
1634
+ try {
1635
+ current = await this._mpRequest("POST", `/v1/mp/rooms/${enc(roomId)}/join`, {});
1636
+ } catch (err) {
1637
+ // A 404 here is a room that ended between polls, which is a real
1638
+ // failure; anything else is worth another try until the budget is gone.
1639
+ if (err?.status === 404) throw err;
1640
+ }
1641
+ }
1642
+ if (!current?.wsUrl) {
1643
+ // The room is still real, so the code names it and says so — a game can
1644
+ // choose to keep waiting with `join(roomId)` rather than start over.
1645
+ const err = new Error("Room is still starting");
1646
+ err.code = "mp_room_placing";
1647
+ err.roomId = roomId;
1648
+ throw err;
1649
+ }
1650
+ return current;
1651
+ }
1652
+
1181
1653
  /**
1182
1654
  * @param {string} wsUrl
1183
1655
  */
@@ -1236,13 +1708,22 @@ class TesanaClient {
1236
1708
  if (this._mp.ws === ws) this._mp.ws = null;
1237
1709
  if (!opened) {
1238
1710
  clearTimeout(timer);
1239
- reject(new Error(event.reason || "multiplayer closed"));
1711
+ const err = new Error(event.reason || "multiplayer closed");
1712
+ // The code is carried, not just the reason: 4401 is an expired or
1713
+ // rejected grant, which a re-mint can fix, while 4403 is the game
1714
+ // being denied rooms, which it cannot. Recovery keys off this.
1715
+ err.code = event.code || 1006;
1716
+ // Recorded for the same reason: a reconnect whose fresh grant is
1717
+ // *also* refused must mint again rather than retry a dead URL.
1718
+ if (this._mp.wsUrl) this._mp.lastCloseCode = event.code || null;
1719
+ reject(err);
1240
1720
  return;
1241
1721
  }
1242
1722
  // The socket dropped after we were in the room. That is a scale-in,
1243
1723
  // a deploy, or a network blip — none of which the player caused, and
1244
1724
  // all of which used to leave them silently alone in a match. Retry
1245
1725
  // unless they actually meant to leave.
1726
+ this._mp.lastCloseCode = event.code || null;
1246
1727
  this._mpScheduleReconnect();
1247
1728
  };
1248
1729
  });
@@ -1274,7 +1755,7 @@ class TesanaClient {
1274
1755
  mp.reconnectTimer = setTimeout(() => {
1275
1756
  mp.reconnectTimer = null;
1276
1757
  if (mp.leaving) return;
1277
- this._mpOpen(mp.wsUrl).catch(() => {
1758
+ this._mpReconnectAttempt().catch(() => {
1278
1759
  // Still not up — schedule the next attempt, which is where the
1279
1760
  // attempt count grows and the backoff widens.
1280
1761
  this._mpScheduleReconnect();
@@ -1282,6 +1763,56 @@ class TesanaClient {
1282
1763
  }, delay);
1283
1764
  }
1284
1765
 
1766
+ /**
1767
+ * One reconnect: get a current grant if the last one was refused, then try the
1768
+ * room again.
1769
+ *
1770
+ * The grant the client holds is embedded in `wsUrl` and was minted when it
1771
+ * first joined. A game open longer than the token's life therefore cannot
1772
+ * re-enter on a reconnect, and the backoff above only retries the same dead
1773
+ * URL — the player sits in "reconnecting" until they reload. Re-requesting the
1774
+ * room session mints a fresh URL, and `mpJoin` is idempotent, so asking as an
1775
+ * already-seated player re-issues the same seat rather than a second one.
1776
+ *
1777
+ * The fresh grant itself comes from the ordinary 401 path in `_send`: the join
1778
+ * goes out with the token the client already has, comes back refused, and is
1779
+ * retried once with one minted token. That is deliberate — it keeps the mint in
1780
+ * the one place that knows how to do it, so a stale socket and a stale HTTP
1781
+ * call recover identically and only ever ask the host once between them.
1782
+ */
1783
+ async _mpReconnectAttempt() {
1784
+ const mp = this._mp;
1785
+ let wsUrl = mp.wsUrl;
1786
+ // 4401 — the grant was refused, so the URL itself is dead and a fresh one is
1787
+ // required. 4409 — the room is being re-placed and has no address yet, so
1788
+ // the URL the client holds is not usable either. Both are fixed by asking
1789
+ // for the room again; 4403 (the game is denied rooms) and 4404 (the room is
1790
+ // gone) are not, and fall through to the URL we have so the attempt is still
1791
+ // counted and the backoff still applies.
1792
+ if ((mp.lastCloseCode === 4401 || mp.lastCloseCode === 4409) && mp.roomId) {
1793
+ try {
1794
+ // `_mpAwaitPlacement` is harmless when the room is already up (it
1795
+ // returns the session untouched) and necessary when a reconnect lands
1796
+ // during a re-placement — a 4409 close, or a room swept and reopened,
1797
+ // answers with no `wsUrl`, and retrying the old URL would never work.
1798
+ const session = await this._mpAwaitPlacement(
1799
+ await this._mpRequest("POST", `/v1/mp/rooms/${enc(mp.roomId)}/join`),
1800
+ );
1801
+ if (session && session.wsUrl) {
1802
+ wsUrl = session.wsUrl;
1803
+ mp.wsUrl = wsUrl;
1804
+ mp.code = session.room?.code ?? mp.code;
1805
+ }
1806
+ } catch {
1807
+ // The room is gone, or the fresh grant was refused too. Fall through to
1808
+ // the URL we have: the room may have been replaced under the same id,
1809
+ // and if it has not, the next attempt retries this same path.
1810
+ }
1811
+ }
1812
+ mp.lastCloseCode = null;
1813
+ return this._mpOpen(wsUrl);
1814
+ }
1815
+
1285
1816
  _mpEmitStatus(status) {
1286
1817
  for (const fn of this._mp.statusHandlers) {
1287
1818
  try {
@@ -1315,7 +1846,14 @@ class TesanaClient {
1315
1846
  */
1316
1847
  _mpSend(data) {
1317
1848
  const ws = this._mp.ws;
1318
- if (!ws || ws.readyState !== 1) throw new Error("Not in a room");
1849
+ if (!ws || ws.readyState !== 1) {
1850
+ // Not a room failure — a socket that is between attempts. Tagged so a
1851
+ // game can tell it from a real refusal, and so a caller that has an
1852
+ // outbox can wait for the reconnect rather than drop the message.
1853
+ const err = new Error("Not in a room");
1854
+ err.code = "mp_not_connected";
1855
+ throw err;
1856
+ }
1319
1857
  ws.send(JSON.stringify(data && typeof data === "object" ? data : { value: data }));
1320
1858
  }
1321
1859
 
@@ -1353,6 +1891,7 @@ class TesanaClient {
1353
1891
  this._mp.wsUrl = null;
1354
1892
  this._mp.reconnectAttempts = 0;
1355
1893
  this._mp.reconnectExhausted = false;
1894
+ this._mp.lastCloseCode = null;
1356
1895
  try {
1357
1896
  if (!roomId) return { ok: true, room: null };
1358
1897
  try {
@@ -1374,24 +1913,13 @@ class TesanaClient {
1374
1913
  return this._send(this._baseFor(), this._authFor(), method, path, body);
1375
1914
  }
1376
1915
 
1377
- /** Whether multiplayer rides a rooms-only token while everything else is offline. */
1378
- _roomsOnly() {
1379
- return Boolean(this.offline && this.roomEndpoint && this.roomToken);
1380
- }
1381
-
1382
- _mpRequest(method, path, body) {
1383
- return this._roomsOnly()
1384
- ? this._send(this.roomEndpoint, this.roomToken, method, path, body)
1385
- : this.request(method, path, body);
1386
- }
1387
-
1388
- async _send(base, authToken, method, path, body) {
1916
+ /** One transport attempt, with no retry and no body parsing. */
1917
+ async _fetchSend(base, authToken, method, path, body) {
1389
1918
  const headers = { "content-type": "application/json" };
1390
1919
  if (authToken) headers.authorization = `Bearer ${authToken}`;
1391
1920
  if (this.deviceId) headers["x-tesana-device"] = this.deviceId;
1392
- let res;
1393
1921
  try {
1394
- res = await fetch(`${base}${path}`, {
1922
+ return await fetch(`${base}${path}`, {
1395
1923
  method,
1396
1924
  headers,
1397
1925
  body: body == null || method === "GET" ? undefined : JSON.stringify(body),
@@ -1404,6 +1932,34 @@ class TesanaClient {
1404
1932
  // still has, reported as missing.
1405
1933
  throw err;
1406
1934
  }
1935
+ }
1936
+
1937
+ /** Whether multiplayer rides a rooms-only token while everything else is offline. */
1938
+ _roomsOnly() {
1939
+ return Boolean(this.offline && this.roomEndpoint && this.roomToken);
1940
+ }
1941
+
1942
+ _mpRequest(method, path, body) {
1943
+ return this._roomsOnly()
1944
+ ? this._send(this.roomEndpoint, this.roomToken, method, path, body)
1945
+ : this.request(method, path, body);
1946
+ }
1947
+
1948
+ async _send(base, authToken, method, path, body) {
1949
+ let res = await this._fetchSend(base, authToken, method, path, body);
1950
+ // A refused credential is usually age, not refusal: the player token lives
1951
+ // two hours. Ask the host to re-mint and retry once with the new one. The
1952
+ // retry is guarded on the token actually changing, so a genuinely
1953
+ // unauthorized player fails exactly as they did before rather than looping.
1954
+ if (res.status === 401) {
1955
+ // The ask may land on a host we cannot reach, so `asked` is null and the
1956
+ // retry is skipped — the 401 below is thrown exactly as it always was.
1957
+ const asked = await requestHostBootstrap();
1958
+ const next = base === this.roomEndpoint ? this.roomToken : this._authFor();
1959
+ if (asked && next && next !== authToken) {
1960
+ res = await this._fetchSend(base, next, method, path, body);
1961
+ }
1962
+ }
1407
1963
  const data = await res.json().catch(() => ({}));
1408
1964
  if (!res.ok) {
1409
1965
  const error = new Error(data.message || res.statusText);
@@ -2122,5 +2678,5 @@ function enc(value) {
2122
2678
  return encodeURIComponent(String(value));
2123
2679
  }
2124
2680
 
2125
- export const Tesana = { init, TesanaClient, version: VERSION };
2681
+ export const Tesana = { init, TesanaClient, version: VERSION, track, gameplay };
2126
2682
  export default Tesana;