@tesana/sdk 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tesana.js CHANGED
@@ -46,7 +46,11 @@
46
46
  // (player reports, plus crashes filed on their own), `tesana.config` (values the
47
47
  // creator changes without a rebuild) and `tesana.share` (invite links into a
48
48
  // room or a level).
49
- const VERSION = "1.2.0";
49
+ //
50
+ // 1.3.0 files a game's level events, its quits and a play heartbeat every 15 s
51
+ // in Tesana's own event registry (`POST /api/e`, TES-2197), from Tesana's play
52
+ // hosts only, and adds `tesana.gameplay.levelFail(levelId, reason?)`.
53
+ const VERSION = "1.3.0";
50
54
 
51
55
  const LOCAL_CACHE = "tesana.play.v1";
52
56
 
@@ -846,6 +850,9 @@ function gameplayDeliver(event) {
846
850
  // on a page with nobody above it to receive the event itself.
847
851
  rememberEvent(event);
848
852
  if (typeof window === "undefined") return false;
853
+ // The registry's copy for the collector (TES-2197), whatever happens below:
854
+ // a desktop build has no page above it and still reports its levels.
855
+ eventsFromGameplay(event);
849
856
  const bridge = window.__TESANA_EVENT__;
850
857
  if (typeof bridge === "function") {
851
858
  bridge(event);
@@ -917,6 +924,26 @@ function gameplayHelper(type, shorthand) {
917
924
  };
918
925
  }
919
926
 
927
+ /**
928
+ * A level is lost: `levelFail(levelId, reason?)` or `levelFail({ levelId, reason })`.
929
+ *
930
+ * The play-events endpoint has no "failed" type, so the host is handed a
931
+ * custom `level_fail` event with the reason as context; the collector gets
932
+ * `game.level.ended@1` with `outcome: "failed"` (TES-2197).
933
+ */
934
+ function levelFail(props, reason) {
935
+ try {
936
+ if (!gameplayAllowed()) return false;
937
+ const given = typeof props === "string" || typeof props === "number"
938
+ ? { levelId: props }
939
+ : { ...gameplayProps(props) };
940
+ if (reason !== undefined && given.reason === undefined) given.reason = reason;
941
+ return gameplayDeliver(gameplayEvent("custom", LEVEL_FAIL, given));
942
+ } catch {
943
+ return false;
944
+ }
945
+ }
946
+
920
947
  /**
921
948
  * The progression events every game with levels, waves, runs or deaths should
922
949
  * send. `levelId` is the join key: give it the same stable value in each call
@@ -927,6 +954,8 @@ const gameplay = Object.freeze({
927
954
  levelStart: gameplayHelper("level_start", "levelId"),
928
955
  /** A level is cleared: `{ levelId }`. */
929
956
  levelComplete: gameplayHelper("level_complete", "levelId"),
957
+ /** A level is lost (out of lives, out of time): `levelFail(levelId, reason?)`. */
958
+ levelFail,
930
959
  /** The player died: `{ levelId, x?, y?, z?, name? }` (`name` is the cause). */
931
960
  death: gameplayHelper("death", "levelId"),
932
961
  /** A checkpoint is reached: `{ levelId, name? }`. */
@@ -935,6 +964,449 @@ const gameplay = Object.freeze({
935
964
  score: gameplayHelper("score", "value"),
936
965
  });
937
966
 
967
+ // ---------------------------------------------------------------------------
968
+ // First-party events: level events, quits and play heartbeats (P-5, TES-2197)
969
+ // ---------------------------------------------------------------------------
970
+ //
971
+ // The same moments, filed in Tesana's own event registry: the collector
972
+ // (`POST /api/e` on the API) stores them with the game's id, so a creator, and
973
+ // their game's agents, can see where players fail and where they quit, and the
974
+ // time tracker counts player time from the heartbeats (plan 14b). The types are
975
+ // the backend's (`one_tap/events/registry.py`), and nothing else is sent:
976
+ //
977
+ // game.level.started@1 { level?, level_index? }
978
+ // game.level.ended@1 { level?, outcome: "completed" | "failed", duration_ms?, reason? }
979
+ // game.session.quit@1 { level?, in_level, seconds }
980
+ // play.session.heartbeat@1 { state: "open" | "active", level? }
981
+ //
982
+ // Where it is sent, and where it never is:
983
+ //
984
+ // - From Tesana's play hosts only: `play.tesana.ai` to production's API,
985
+ // `play-staging.tesana.ai` to staging's. Or to the collector a host names
986
+ // in its bootstrap (`eventsEndpoint`, for a desktop build's prelude). A game on
987
+ // localhost, a file, a preview sandbox or anyone else's page sends nothing,
988
+ // so local tests and previews never reach production analytics.
989
+ // - Off until the page is known to be a real play page, not a Studio preview
990
+ // (TES-2640): the host says `studio: false`, or names its collector, or
991
+ // posts a play token without the `studio` claim the play service stamps on
992
+ // a Studio test session. Until then events only wait; a Studio session
993
+ // (`studio: true`, or a token claiming it) drops them and sends nothing.
994
+ // - Never from a QA rig (`__TESANA_QA_RIG__`), a browser driven by automation
995
+ // (`navigator.webdriver`), a test's DOM (jsdom), or a host that says
996
+ // `events: false`.
997
+ // - Only with the game's id: the play id the host names the game by (its
998
+ // public id, which the collector resolves) or a site id. No id, nothing.
999
+ // - No device id (TES-2639): the SDK's device id can be traded for that
1000
+ // guest's play token, so it never leaves for analytics. The browser is
1001
+ // named by its own random `anonymous_id`.
1002
+ //
1003
+ // A heartbeat marks 15 s of time in front (TES-2641): the clock runs only while
1004
+ // the page is visible and resumes where it stopped, so coming back to the tab
1005
+ // sends nothing at once and a player flicking between tabs is not over-counted.
1006
+ //
1007
+ // It follows the gameplay rules: it never throws and never blocks. Events wait
1008
+ // in a small queue and go as one batch every 30 s (at once at 50), and what is
1009
+ // left goes by `navigator.sendBeacon` the moment the page is hidden or closed.
1010
+ // Each event carries its own UUID, so a batch that arrives twice is stored
1011
+ // once. Offline, a batch is dropped rather than kept. Properties are the game's
1012
+ // own level ids and reasons, capped like the gameplay calls; no personal data.
1013
+
1014
+ //: The collector for each of Tesana's play hosts. Any other host sends nothing.
1015
+ const EVENTS_COLLECTORS = new Map([
1016
+ ["play.tesana.ai", "https://api.tesana.ai/api/e"],
1017
+ ["play-staging.tesana.ai", "https://api-staging.onetap.build/api/e"],
1018
+ ]);
1019
+ //: A collector a host names: https, or plain http on this machine for a developer.
1020
+ const EVENTS_URL = /^(https:\/\/[^\s/]+|http:\/\/(127\.0\.0\.1|localhost)(:\d+)?)\/\S*$/i;
1021
+ const EVENTS_FLUSH_MS = 30000;
1022
+ const EVENTS_BATCH_MAX = 50;
1023
+ const EVENTS_QUEUE_MAX = 200;
1024
+ //: The registry's heartbeat: every 15 s in front; active means input in the last 30 s.
1025
+ const EVENTS_HEARTBEAT_MS = 15000;
1026
+ const EVENTS_ACTIVE_MS = 30000;
1027
+ //: A session ends after 30 minutes with no event.
1028
+ const EVENTS_SESSION_GAP_MS = 30 * 60 * 1000;
1029
+ const EVENTS_STRING_MAX = 64;
1030
+ const EVENTS_INPUTS = ["pointerdown", "pointermove", "keydown", "touchstart", "wheel"];
1031
+ const EVENT_UUID = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;
1032
+ const LEVEL_FAIL = "level_fail";
1033
+
1034
+ const eventsState = {
1035
+ //: "pending" until a bootstrap names the game and shows a real play page,
1036
+ //: then "on"; "off" (queue dropped) for a Studio session or no collector.
1037
+ state: "pending",
1038
+ url: "",
1039
+ shared: null,
1040
+ queue: [],
1041
+ timer: null,
1042
+ //: The heartbeat's timer, the visible time left until the next beat, and
1043
+ //: since when the page has been visible.
1044
+ heartbeat: null,
1045
+ beatDueIn: EVENTS_HEARTBEAT_MS,
1046
+ visibleSince: 0,
1047
+ session: "",
1048
+ lastEventAt: 0,
1049
+ lastInputAt: 0,
1050
+ pads: {},
1051
+ bootAt: Date.now(),
1052
+ //: The level being played, `{ id, at }`, and the last one played.
1053
+ level: null,
1054
+ lastLevel: "",
1055
+ quitSent: false,
1056
+ win: null,
1057
+ };
1058
+
1059
+ /** A v4 UUID, from the platform's crypto when it has one. */
1060
+ function eventsUuid() {
1061
+ try {
1062
+ const cryptoApi = globalThis.crypto;
1063
+ if (cryptoApi && typeof cryptoApi.randomUUID === "function") return cryptoApi.randomUUID();
1064
+ if (cryptoApi && typeof cryptoApi.getRandomValues === "function") {
1065
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
1066
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
1067
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
1068
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1069
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1070
+ }
1071
+ } catch {
1072
+ /* fall through */
1073
+ }
1074
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
1075
+ const r = Math.floor(Math.random() * 16);
1076
+ return (ch === "x" ? r : (r & 0x3) | 0x8).toString(16);
1077
+ });
1078
+ }
1079
+
1080
+ function eventsUnref(timer) {
1081
+ if (timer && typeof timer.unref === "function") timer.unref();
1082
+ return timer;
1083
+ }
1084
+
1085
+ /** Where this page's events go, or "" when it must send nothing. */
1086
+ function eventsCollector(merged) {
1087
+ if (typeof window === "undefined" || window.__TESANA_QA_RIG__ === true) return "";
1088
+ if (typeof navigator !== "undefined" && navigator) {
1089
+ if (navigator.webdriver === true) return "";
1090
+ // A test's DOM (the engine's tests load this SDK into jsdom).
1091
+ if (/\bjsdom\//.test(String(navigator.userAgent || ""))) return "";
1092
+ }
1093
+ if (merged.events === false) return "";
1094
+ if (merged.eventsEndpoint !== undefined) {
1095
+ const named = typeof merged.eventsEndpoint === "string" ? merged.eventsEndpoint.trim() : "";
1096
+ return EVENTS_URL.test(named) ? named : "";
1097
+ }
1098
+ const host = window.location && window.location.hostname;
1099
+ return (typeof host === "string" && EVENTS_COLLECTORS.get(host.toLowerCase())) || "";
1100
+ }
1101
+
1102
+ /** The game, as the collector takes it: a site id, else a play (public) id. */
1103
+ function eventsGame(merged) {
1104
+ for (const raw of [merged.gameId, merged.publicId]) {
1105
+ if (typeof raw === "number" && Number.isSafeInteger(raw) && raw > 0) return { game_id: raw };
1106
+ const text = typeof raw === "string" ? raw.trim() : "";
1107
+ if (/^[1-9][0-9]{0,15}$/.test(text)) return { game_id: Number(text) };
1108
+ if (EVENT_UUID.test(text)) return { play_game_id: text.toLowerCase() };
1109
+ }
1110
+ return null;
1111
+ }
1112
+
1113
+ /** A play token's claims, read without checking them (the play service does). */
1114
+ function eventsClaims(token) {
1115
+ try {
1116
+ if (typeof token !== "string") return null;
1117
+ const parts = token.split(".");
1118
+ if (parts.length !== 3 || typeof atob !== "function") return null;
1119
+ const body = parts[1].replace(/-/g, "+").replace(/_/g, "/");
1120
+ const claims = JSON.parse(atob(body + "=".repeat((4 - (body.length % 4)) % 4)));
1121
+ return claims && typeof claims === "object" && !Array.isArray(claims) ? claims : null;
1122
+ } catch {
1123
+ return null;
1124
+ }
1125
+ }
1126
+
1127
+ /**
1128
+ * Whether this is a real play page (TES-2640): "yes", "no" for a Studio test
1129
+ * session, or "" while it isn't known. Studio previews run on the same play
1130
+ * host as real plays, so the host alone can't tell them apart.
1131
+ */
1132
+ function eventsPlayPage(merged) {
1133
+ const tokens = [merged.token, merged.playToken, merged.playerToken, merged.saveToken]
1134
+ .map(eventsClaims)
1135
+ .filter(Boolean);
1136
+ if (merged.studio === true || tokens.some((claims) => claims.studio === true)) return "no";
1137
+ if (merged.studio === false || merged.eventsEndpoint !== undefined || tokens.length) return "yes";
1138
+ return "";
1139
+ }
1140
+
1141
+ /** This browser's anonymous id: the collector's cookie wins when it has one. */
1142
+ function eventsAnonymousId() {
1143
+ const cached = readCache().anonymousId;
1144
+ if (typeof cached === "string" && EVENT_UUID.test(cached)) return cached;
1145
+ const id = eventsUuid();
1146
+ writeCache({ anonymousId: id });
1147
+ return id;
1148
+ }
1149
+
1150
+ function eventsHidden() {
1151
+ return typeof document !== "undefined" && Boolean(document) && document.visibilityState === "hidden";
1152
+ }
1153
+
1154
+ /**
1155
+ * Point the emitter at this page's bootstrap. Called by `init()` and again on
1156
+ * every bootstrap upgrade: a provisional answer may not name the game or carry
1157
+ * a token yet, and the real one says whether this is a Studio test session.
1158
+ */
1159
+ function eventsConfigure(merged) {
1160
+ try {
1161
+ if (typeof window === "undefined") return;
1162
+ const url = eventsCollector(merged);
1163
+ const page = url ? eventsPlayPage(merged) : "no";
1164
+ if (page === "no") {
1165
+ eventsOff();
1166
+ return;
1167
+ }
1168
+ const game = eventsGame(merged);
1169
+ if (!game || page !== "yes") return;
1170
+ const build = String(merged.build || merged.buildId || merged.buildVersion || "").slice(0, 64);
1171
+ eventsState.url = url;
1172
+ eventsState.shared = {
1173
+ surface: window.TesanaDesktop ? "desktop" : "sdk",
1174
+ app_version: VERSION,
1175
+ ...(build ? { build_sha: build } : {}),
1176
+ anonymous_id: eventsAnonymousId(),
1177
+ ...game,
1178
+ };
1179
+ eventsState.state = "on";
1180
+ eventsListen();
1181
+ eventsStartHeartbeat();
1182
+ eventsSchedule();
1183
+ } catch {
1184
+ /* analytics must never break boot */
1185
+ }
1186
+ }
1187
+
1188
+ function eventsOff() {
1189
+ eventsState.state = "off";
1190
+ eventsState.queue.length = 0;
1191
+ eventsStopHeartbeat();
1192
+ if (eventsState.timer) clearTimeout(eventsState.timer);
1193
+ eventsState.timer = null;
1194
+ }
1195
+
1196
+ function eventsEnqueue(type, props) {
1197
+ try {
1198
+ if (eventsState.state === "off" || typeof window === "undefined") return;
1199
+ const now = Date.now();
1200
+ if (!eventsState.session || now - eventsState.lastEventAt > EVENTS_SESSION_GAP_MS) {
1201
+ eventsState.session = eventsUuid();
1202
+ }
1203
+ eventsState.lastEventAt = now;
1204
+ if (eventsState.queue.length >= EVENTS_QUEUE_MAX) eventsState.queue.shift();
1205
+ eventsState.queue.push({
1206
+ event_id: eventsUuid(),
1207
+ type,
1208
+ occurred_at: new Date(now).toISOString(),
1209
+ session_id: eventsState.session,
1210
+ props,
1211
+ });
1212
+ eventsSchedule();
1213
+ } catch {
1214
+ /* never */
1215
+ }
1216
+ }
1217
+
1218
+ function eventsSchedule() {
1219
+ if (eventsState.state !== "on" || !eventsState.queue.length) return;
1220
+ if (eventsState.queue.length >= EVENTS_BATCH_MAX) {
1221
+ eventsFlush();
1222
+ return;
1223
+ }
1224
+ if (!eventsState.timer) eventsState.timer = eventsUnref(setTimeout(eventsFlush, EVENTS_FLUSH_MS));
1225
+ }
1226
+
1227
+ /** Send everything queued, now. Fire and forget: nothing waits on the answer. */
1228
+ function eventsFlush() {
1229
+ try {
1230
+ if (eventsState.timer) clearTimeout(eventsState.timer);
1231
+ eventsState.timer = null;
1232
+ if (eventsState.state !== "on" || !eventsState.queue.length) return;
1233
+ if (typeof navigator !== "undefined" && navigator && navigator.onLine === false) {
1234
+ eventsState.queue.length = 0;
1235
+ return;
1236
+ }
1237
+ while (eventsState.queue.length) {
1238
+ const batch = eventsState.queue.splice(0, EVENTS_BATCH_MAX);
1239
+ eventsSend(JSON.stringify({ sent_at: new Date().toISOString(), ...eventsState.shared, events: batch }));
1240
+ }
1241
+ } catch {
1242
+ /* never */
1243
+ }
1244
+ }
1245
+
1246
+ /**
1247
+ * One batch, as JSON labelled text: the one body a beacon may carry to another
1248
+ * origin without asking first, and the collector reads it as JSON. The answer
1249
+ * is never read, so the collector needs no CORS for this.
1250
+ */
1251
+ function eventsSend(body) {
1252
+ try {
1253
+ if (typeof navigator !== "undefined" && navigator && typeof navigator.sendBeacon === "function") {
1254
+ if (navigator.sendBeacon(eventsState.url, body)) return;
1255
+ }
1256
+ } catch {
1257
+ /* try fetch */
1258
+ }
1259
+ try {
1260
+ if (typeof fetch !== "function") return;
1261
+ const sent = fetch(eventsState.url, {
1262
+ method: "POST",
1263
+ body,
1264
+ keepalive: true,
1265
+ mode: "no-cors",
1266
+ credentials: "include",
1267
+ headers: { "Content-Type": "text/plain" },
1268
+ });
1269
+ if (sent && typeof sent.catch === "function") sent.catch(() => {});
1270
+ } catch {
1271
+ /* dropped */
1272
+ }
1273
+ }
1274
+
1275
+ /** Input since the last tick from a gamepad: its state's timestamp moved. */
1276
+ function eventsNotePads() {
1277
+ try {
1278
+ if (typeof navigator === "undefined" || !navigator || typeof navigator.getGamepads !== "function") return;
1279
+ for (const pad of navigator.getGamepads() || []) {
1280
+ if (!pad) continue;
1281
+ const seen = eventsState.pads[pad.index];
1282
+ if (seen !== undefined && seen !== pad.timestamp) eventsState.lastInputAt = Date.now();
1283
+ eventsState.pads[pad.index] = pad.timestamp;
1284
+ }
1285
+ } catch {
1286
+ /* a frame without the gamepad permission */
1287
+ }
1288
+ }
1289
+
1290
+ function eventsBeat() {
1291
+ eventsNotePads();
1292
+ const props = { state: Date.now() - eventsState.lastInputAt <= EVENTS_ACTIVE_MS ? "active" : "open" };
1293
+ if (eventsState.level && eventsState.level.id) props.level = eventsState.level.id;
1294
+ eventsEnqueue("play.session.heartbeat@1", props);
1295
+ }
1296
+
1297
+ /** Run the heartbeat clock while the page is visible: the next beat is due
1298
+ * after the visible time it still owes, never at once on a return. */
1299
+ function eventsStartHeartbeat() {
1300
+ if (eventsState.heartbeat || eventsState.state !== "on" || eventsHidden()) return;
1301
+ eventsState.visibleSince = Date.now();
1302
+ eventsState.heartbeat = eventsUnref(setTimeout(eventsTick, eventsState.beatDueIn));
1303
+ }
1304
+
1305
+ function eventsTick() {
1306
+ eventsState.heartbeat = null;
1307
+ if (eventsState.state !== "on") return;
1308
+ if (eventsHidden()) {
1309
+ // Hidden without a visibilitychange: count the time up to now and wait.
1310
+ eventsState.beatDueIn = Math.max(0, eventsState.beatDueIn - (Date.now() - eventsState.visibleSince));
1311
+ return;
1312
+ }
1313
+ eventsBeat();
1314
+ eventsState.beatDueIn = EVENTS_HEARTBEAT_MS;
1315
+ eventsStartHeartbeat();
1316
+ }
1317
+
1318
+ /** Stop the clock, keeping the visible time already run toward the next beat. */
1319
+ function eventsStopHeartbeat() {
1320
+ if (!eventsState.heartbeat) return;
1321
+ clearTimeout(eventsState.heartbeat);
1322
+ eventsState.heartbeat = null;
1323
+ eventsState.beatDueIn = Math.max(0, eventsState.beatDueIn - (Date.now() - eventsState.visibleSince));
1324
+ }
1325
+
1326
+ /** The player left the game: once per page, naming the level they were in. */
1327
+ function eventsQuit() {
1328
+ if (eventsState.quitSent || eventsState.state !== "on") return;
1329
+ eventsState.quitSent = true;
1330
+ const current = eventsState.level;
1331
+ const props = {
1332
+ in_level: Boolean(current),
1333
+ seconds: Math.max(0, Math.round((Date.now() - eventsState.bootAt) / 1000)),
1334
+ };
1335
+ const where = current ? current.id : eventsState.lastLevel;
1336
+ if (where) props.level = where;
1337
+ eventsEnqueue("game.session.quit@1", props);
1338
+ }
1339
+
1340
+ /** Once per window: input for "active", and hidden, closed or restored pages. */
1341
+ function eventsListen() {
1342
+ if (eventsState.win === window) return;
1343
+ eventsState.win = window;
1344
+ try {
1345
+ const noteInput = () => {
1346
+ eventsState.lastInputAt = Date.now();
1347
+ };
1348
+ for (const name of EVENTS_INPUTS) window.addEventListener(name, noteInput, { capture: true, passive: true });
1349
+ window.addEventListener("pagehide", () => {
1350
+ eventsStopHeartbeat();
1351
+ eventsQuit();
1352
+ eventsFlush();
1353
+ });
1354
+ // Back from the back-forward cache: the same play goes on.
1355
+ window.addEventListener("pageshow", (event) => {
1356
+ if (!event || !event.persisted) return;
1357
+ eventsState.quitSent = false;
1358
+ eventsStartHeartbeat();
1359
+ });
1360
+ if (typeof document !== "undefined" && document && typeof document.addEventListener === "function") {
1361
+ document.addEventListener("visibilitychange", () => {
1362
+ if (eventsHidden()) {
1363
+ eventsStopHeartbeat();
1364
+ eventsFlush();
1365
+ } else {
1366
+ eventsStartHeartbeat();
1367
+ }
1368
+ });
1369
+ }
1370
+ } catch {
1371
+ /* a page with no event target still plays */
1372
+ }
1373
+ }
1374
+
1375
+ /** The registry's copy of a gameplay event the game reported. */
1376
+ function eventsFromGameplay(event) {
1377
+ try {
1378
+ const level = event.level_id || "";
1379
+ if (event.type === "level_start") {
1380
+ eventsState.level = { id: level, at: Date.now() };
1381
+ const props = {};
1382
+ if (level) props.level = level;
1383
+ if (event.level_index !== undefined) props.level_index = event.level_index;
1384
+ eventsEnqueue("game.level.started@1", props);
1385
+ } else if (event.type === "level_complete") {
1386
+ eventsLevelEnded(level, "completed", undefined);
1387
+ } else if (event.type === "custom" && event.name === LEVEL_FAIL) {
1388
+ eventsLevelEnded(level, "failed", event.payload && event.payload.reason);
1389
+ }
1390
+ } catch {
1391
+ /* never */
1392
+ }
1393
+ }
1394
+
1395
+ function eventsLevelEnded(level, outcome, reason) {
1396
+ const current = eventsState.level;
1397
+ const id = level || (current ? current.id : "");
1398
+ const props = { outcome };
1399
+ if (id) props.level = id;
1400
+ if (current && current.id === id) {
1401
+ props.duration_ms = Math.max(0, Date.now() - current.at);
1402
+ eventsState.level = null;
1403
+ }
1404
+ const why = outcome === "failed" ? gameplayId(reason, EVENTS_STRING_MAX) : undefined;
1405
+ if (why) props.reason = why;
1406
+ if (id) eventsState.lastLevel = id;
1407
+ eventsEnqueue("game.level.ended@1", props);
1408
+ }
1409
+
938
1410
  // ---------------------------------------------------------------------------
939
1411
  // Feedback and crash capture: `tesana.feedback`
940
1412
  // ---------------------------------------------------------------------------
@@ -1374,6 +1846,8 @@ export async function init(config = {}) {
1374
1846
  const boot = await waitBootstrap();
1375
1847
  const client = new TesanaClient(buildConfig(mergedConfig()));
1376
1848
  feedbackClient = client;
1849
+ // Level events, quits and heartbeats for the collector; needs no session.
1850
+ eventsConfigure(mergedConfig());
1377
1851
  // Remote config needs no session, so it starts now and never holds up boot:
1378
1852
  // until it lands, `config.get` answers from the last session's copy.
1379
1853
  client.config.reload().catch(() => {});
@@ -1417,6 +1891,7 @@ export async function init(config = {}) {
1417
1891
  const finishUpgrade = () => {
1418
1892
  const before = client.gameId;
1419
1893
  client.configure(buildConfig(mergedConfig()));
1894
+ eventsConfigure(mergedConfig());
1420
1895
  client.ensureSession().then(() => client.l10n.reload());
1421
1896
  // A provisional answer may not have named the game, so its config was
1422
1897
  // never asked for. Only then: a token refresh is an upgrade too, and one
@@ -1640,8 +2115,9 @@ class TesanaClient {
1640
2115
  //
1641
2116
  // With no host — a game opened straight from the play CDN — there is
1642
2117
  // nobody to draw a confirmation and no page to open checkout on, so
1643
- // the game falls back to the direct call it has always made. That path
1644
- // carries its own token and is exactly as safe as it was.
2118
+ // the game falls back to the direct call it has always made. The play
2119
+ // service refuses it (403 `host_required`): only the host's own token
2120
+ // may spend (TES-379).
1645
2121
  if (!hasHost()) {
1646
2122
  return this.request("POST", "/v1/shop/buy", {
1647
2123
  sku,