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