@tesana/sdk 1.0.2 → 1.0.4

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.
@@ -37,7 +37,7 @@
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.2";
40
+ const VERSION = "1.0.4";
41
41
 
42
42
  const LOCAL_CACHE = "tesana.play.v1";
43
43
 
@@ -197,6 +197,60 @@ function onBootstrapUpgrade(fn) {
197
197
  */
198
198
  let adClient = null;
199
199
 
200
+ /**
201
+ * The live localization capability, kept module-scoped for the same reason as
202
+ * the ad client: the host can change the language at any moment, and the game
203
+ * holds a reference to `tesana.l10n` that must not be replaced underneath it.
204
+ * The listener calls `applyLocale`, which re-points this object in place.
205
+ */
206
+ let l10nClient = null;
207
+
208
+ /**
209
+ * The languages the platform can translate into, in display order.
210
+ *
211
+ * Mirrors the service's own list, which is the authority; this copy exists so a
212
+ * language picker can be drawn before the service has answered — and so a page
213
+ * with no host at all, where nothing will ever answer, still has an honest
214
+ * list rather than an empty one.
215
+ */
216
+ const L10N_TARGETS = ["en", "es", "fr", "de", "it", "pt-BR", "ru", "zh", "ja", "ko"];
217
+
218
+ /**
219
+ * Fold whatever a host calls a language onto one of ours.
220
+ *
221
+ * `navigator.language` reports `en-US` and `pt-PT`; a site may store `pt` or
222
+ * `zh`; a player may be handed `de-AT`. None of those are in the list above and
223
+ * all of them mean a language we do translate into, so the base tag is what
224
+ * gets matched and the region is dropped — a game in `pt-BR` is more useful to
225
+ * a `pt-PT` player than one left in English. An unknown tag stays as it is and
226
+ * simply falls back to the source language at the call site.
227
+ */
228
+ function normalizeLocale(tag) {
229
+ const value = String(tag || "").trim().replace(/_/g, "-");
230
+ if (!value) return "";
231
+ const exact = L10N_TARGETS.find((t) => t.toLowerCase() === value.toLowerCase());
232
+ if (exact) return exact;
233
+ const base = value.split("-")[0].toLowerCase();
234
+ return L10N_TARGETS.find((t) => t.split("-")[0].toLowerCase() === base) || value;
235
+ }
236
+
237
+ /** `{name}` in `text`, filled from `values`. The one interpolation rule the SDK and the service share. */
238
+ function fillPlaceholders(text, values) {
239
+ const source = String(text == null ? "" : text);
240
+ if (!values || typeof values !== "object") return source;
241
+ return source.replace(/\{(\w+)\}/g, (whole, key) =>
242
+ Object.prototype.hasOwnProperty.call(values, key) ? String(values[key]) : whole,
243
+ );
244
+ }
245
+
246
+ /** Fold a locale message from the host into the live client, if it is listening. */
247
+ function resyncLocale(data) {
248
+ if (!l10nClient) return;
249
+ const payload = data && typeof data.payload === "object" ? data.payload : data;
250
+ const next = payload && (payload.locale || payload.lang || payload.language);
251
+ if (next) l10nClient.applyLocale(next);
252
+ }
253
+
200
254
  /** A policy message from the host, or `null` when none is in force. */
201
255
  function adPolicyFrom(data) {
202
256
  if (!data || typeof data !== "object") return null;
@@ -366,6 +420,19 @@ function startListening() {
366
420
  }
367
421
  return;
368
422
  }
423
+ // The player changed the site's language. The host is the authority — it
424
+ // resolved which language the player wants, and it owns the setting — so
425
+ // this only carries it down. The game's own text re-renders when it draws
426
+ // again, which is why the skill tells games to redraw from `t()` rather
427
+ // than cache translated strings at startup.
428
+ if (data.type === "tesana-locale") {
429
+ try {
430
+ resyncLocale(data);
431
+ } catch {
432
+ /* a bad locale must never break the listener */
433
+ }
434
+ return;
435
+ }
369
436
  if (data.type === "tesana-ad-show") {
370
437
  try {
371
438
  const requestId = data.requestId || data.request_id;
@@ -415,6 +482,21 @@ function deviceId() {
415
482
  return id;
416
483
  }
417
484
 
485
+ /**
486
+ * The store-native purchase surface a desktop prelude publishes, or null.
487
+ *
488
+ * A desktop, Steam or App Store build has no page above it and no Stripe — the
489
+ * store's own purchase must run instead, and only the native side can open it.
490
+ * `tesana-desktop.js` publishes `TesanaDesktop.storePurchase` on exactly those
491
+ * builds and nothing else, so its presence is the whole signal. Reaching for it
492
+ * on a plain web page finds `undefined` and changes nothing.
493
+ */
494
+ function storeBilling() {
495
+ const desktop = typeof window !== "undefined" ? window.TesanaDesktop : null;
496
+ if (!desktop || typeof desktop.storePurchase !== "function") return null;
497
+ return desktop;
498
+ }
499
+
418
500
  /** How long the host has to answer a sign-in before we give up. */
419
501
  const SIGN_IN_TIMEOUT_MS = 120000;
420
502
 
@@ -474,6 +556,16 @@ export async function init(config = {}) {
474
556
  } catch (err) {
475
557
  client.goOffline(err);
476
558
  }
559
+ // Localization comes after identity, not before: the bundle is fetched with
560
+ // the player's token, so a game that just minted one would otherwise load it
561
+ // unauthenticated and stay in its source language all session. Awaited here
562
+ // so `await __TESANA_READY__` is genuinely enough — the first frame a game
563
+ // draws can already be translated.
564
+ try {
565
+ await client.l10n.reload();
566
+ } catch {
567
+ /* localization must never block the game's start */
568
+ }
477
569
  window.__TESANA_PLAYER__ = client.player.me();
478
570
  // A provisional "offline" answer can upgrade later. Re-point this client in
479
571
  // place — the game holds a reference to it — and re-run the identity step,
@@ -481,7 +573,7 @@ export async function init(config = {}) {
481
573
  // player with a balance frozen at zero.
482
574
  const finishUpgrade = () => {
483
575
  client.configure(buildConfig(mergedConfig()));
484
- client.ensureSession();
576
+ client.ensureSession().then(() => client.l10n.reload());
485
577
  window.__TESANA_PLAYER__ = client.player.me();
486
578
  };
487
579
  onBootstrapUpgrade(finishUpgrade);
@@ -544,6 +636,15 @@ function buildConfig(merged) {
544
636
  adsEnabled: merged.adsEnabled,
545
637
  adFormats: merged.adFormats || merged.ad_formats || [],
546
638
  adMinIntervalMs: merged.adMinIntervalMs ?? merged.ad_min_interval_ms,
639
+ // The player's language, as the host resolved it. The host owns the
640
+ // setting (the site has a language picker and the game does not), so this
641
+ // is read from the bootstrap rather than sniffed here — a game that
642
+ // guessed from `navigator.language` would disagree with the site the
643
+ // player is reading. Absent means an older host: localization then falls
644
+ // back to the source language and the game renders exactly as it did.
645
+ locale: normalizeLocale(
646
+ merged.locale || merged.language || merged.lang || (typeof navigator !== "undefined" && navigator.language) || "",
647
+ ),
547
648
  };
548
649
  }
549
650
 
@@ -555,7 +656,7 @@ function defaultEndpoint() {
555
656
 
556
657
  class TesanaClient {
557
658
  /**
558
- * @param {{ endpoint: string, gameId: string, token: string, rail: string, deviceId: string, multiplayer?: boolean, saveEndpoint?: string, saveToken?: string, offline?: boolean, roomEndpoint?: string, roomToken?: string, player?: object|null, vanityAddress?: string, adsEnabled?: boolean }} opts
659
+ * @param {{ endpoint: string, gameId: string, token: string, rail: string, deviceId: string, multiplayer?: boolean, saveEndpoint?: string, saveToken?: string, offline?: boolean, roomEndpoint?: string, roomToken?: string, player?: object|null, vanityAddress?: string, adsEnabled?: boolean, locale?: string }} opts
559
660
  */
560
661
  constructor(opts) {
561
662
  this.endpoint = opts.endpoint;
@@ -598,6 +699,8 @@ class TesanaClient {
598
699
  ws: null,
599
700
  handlers: [],
600
701
  roomId: null,
702
+ // The current room's share code, or null for a public room.
703
+ code: null,
601
704
  // Reconnect state. `wsUrl` is kept so a dropped socket can re-enter the
602
705
  // same room; `leaving` stops a deliberate leave from being retried.
603
706
  wsUrl: null,
@@ -810,6 +913,16 @@ class TesanaClient {
810
913
  // same object in place, rather than the game holding a stale policy.
811
914
  adClient = this.ads;
812
915
 
916
+ // Localization. A generated game draws its text onto a canvas, so the
917
+ // platform cannot translate the running game the way it translates the
918
+ // site's own pages — the game has to ask, and this is the surface it asks
919
+ // through. The same one rule as the shop: an unreachable service costs a
920
+ // translation and never the game. Every method here has a source-language
921
+ // answer, and `t()` is synchronous, so a menu never waits on a network to
922
+ // draw itself in the player's language.
923
+ this.l10n = this._makeL10n(opts);
924
+ l10nClient = this.l10n;
925
+
813
926
  this.multiplayer = {
814
927
  // Read this before drawing a lobby: when it is false the game is not
815
928
  // allowed rooms yet and the calls below refuse.
@@ -826,14 +939,42 @@ class TesanaClient {
826
939
  .then((r) => r.rooms)
827
940
  .catch(() => [])
828
941
  : Promise.resolve([]),
942
+ // Open a room. It is public and always joinable unless you pass a `code`,
943
+ // which is the only way entry is restricted: the room is then unlisted and
944
+ // only someone with the code can reach it. The resolved code is on
945
+ // `room.code` in the result (the service generates one if you pass
946
+ // `code: true`), so show it to the room.
829
947
  create: (opts) =>
830
948
  this._mpEnabled
831
949
  ? this._mpEnter(this._mpRequest("POST", "/v1/mp/rooms", opts || {}))
832
950
  : this._mpRefuse(),
833
- join: (roomId) =>
834
- this._mpEnabled
835
- ? this._mpEnter(this._mpRequest("POST", `/v1/mp/rooms/${enc(roomId)}/join`))
836
- : this._mpRefuse(),
951
+ // Accept the room a game got from list() as well as from a session. Both
952
+ // read as "the room to join": `list()` rows are keyed `id`, a
953
+ // create/quickJoin/join result carries `roomId`. Taking an object here is
954
+ // what stops a lobby that calls `join(room)` from having to know which.
955
+ join: (room) => {
956
+ if (!this._mpEnabled) return this._mpRefuse();
957
+ const roomId =
958
+ room && typeof room === "object" ? room.id || room.roomId : room;
959
+ // The bug this guards: a game read `room.roomId` off a list() row,
960
+ // where it is undefined, and we asked the service for the room named
961
+ // "undefined" — a 404 indistinguishable from a deleted room. Fail
962
+ // here, by name, so the mistake is legible.
963
+ if (roomId == null || roomId === "") {
964
+ const err = new Error(
965
+ "join() needs a room id — pass a room from list() (its `id`) or a create/join result",
966
+ );
967
+ err.code = "mp_room_id_required";
968
+ return Promise.reject(err);
969
+ }
970
+ return this._mpEnter(
971
+ this._mpRequest("POST", `/v1/mp/rooms/${enc(roomId)}/join`),
972
+ );
973
+ },
974
+ // Join the fullest public room with a free seat, creating one if there is
975
+ // none. Pass `code` to enter a private room instead: the first player to
976
+ // use a code opens that room and the rest join it, and a full one refuses
977
+ // rather than opening a second room under the same code.
837
978
  quickJoin: (opts) =>
838
979
  this._mpEnabled
839
980
  ? this._mpEnter(this._mpRequest("POST", "/v1/mp/quick-join", opts || {}))
@@ -901,6 +1042,12 @@ class TesanaClient {
901
1042
  * @param {{ clientRequestId?: string }} [opts]
902
1043
  */
903
1044
  async _topUp(packId, opts = {}) {
1045
+ // A desktop/Steam build buys through its store, not through a Tesana page.
1046
+ // `hasHost()` is false there (no parent frame) and Stripe is the wrong rail,
1047
+ // so store billing is checked first — its presence is what distinguishes a
1048
+ // storefront build from a page opened straight from the play CDN.
1049
+ const desktop = storeBilling();
1050
+ if (desktop) return this._topUpViaStore(desktop, packId);
904
1051
  if (hasHost()) {
905
1052
  // The host owns checkout: it opens Stripe in a window of its own and
906
1053
  // tells us how it went. We only ask. The message names are the host's,
@@ -933,6 +1080,67 @@ class TesanaClient {
933
1080
  return result;
934
1081
  }
935
1082
 
1083
+ /**
1084
+ * Buy a coin pack through the store this build ships on.
1085
+ *
1086
+ * Two halves, in this order for a reason: the store takes the money, and only
1087
+ * then does the play service turn the store's own transaction id into coins.
1088
+ * The id is the store's, not ours — it is the one thing a client cannot
1089
+ * invent twice, so it is what makes the credit idempotent when the purchase
1090
+ * is replayed after a crash. Reporting before a successful purchase would
1091
+ * credit coins for a purchase that never happened.
1092
+ *
1093
+ * The result is shaped like the web top-up: a purchase returns the new
1094
+ * balance, and a decline is `{ ok: false, code: "cancelled" }` rather than an
1095
+ * exception, because a player closing the store sheet is a normal answer.
1096
+ *
1097
+ * @param {any} desktop `window.TesanaDesktop` with `storePurchase`
1098
+ * @param {string} packId
1099
+ */
1100
+ async _topUpViaStore(desktop, packId) {
1101
+ // Sign in *before* the store sheet, never after.
1102
+ //
1103
+ // Coins are account-scoped, so a player with no account has nothing to hold
1104
+ // them: `redeem` refuses an unlinked player, and a guest is exactly that.
1105
+ // On the web rail the refusal arrives harmlessly first, because the host
1106
+ // runs checkout server-side and no money has moved yet. Here the store
1107
+ // charges on this side of the wire, so a refusal discovered at redemption
1108
+ // is a player who was billed and got nothing — the one outcome worth
1109
+ // blocking a sale over. A launcher that cannot sign anyone in therefore
1110
+ // refuses the sale rather than taking payment it cannot honour.
1111
+ const canBuy = () => !this.offline && !this._isGuestSession();
1112
+ if (!canBuy()) {
1113
+ if (typeof desktop.signIn !== "function") {
1114
+ return { ok: false, purchased: false, code: "login_required" };
1115
+ }
1116
+ const answer = await this._signInViaNative(canBuy);
1117
+ if (!answer || answer.signedIn !== true) {
1118
+ return { ok: false, purchased: false, code: "login_required" };
1119
+ }
1120
+ }
1121
+ const purchase = await desktop.storePurchase({ packId });
1122
+ if (!purchase || purchase.ok !== true) {
1123
+ return {
1124
+ ok: false,
1125
+ purchased: false,
1126
+ code: (purchase && purchase.code) || "cancelled",
1127
+ };
1128
+ }
1129
+ // A store that charged but reported no id cannot be credited — there would
1130
+ // be no way to tell a replay from a new purchase. Surface it as a failure
1131
+ // rather than granting an untraceable lot.
1132
+ if (!purchase.transactionId) {
1133
+ const err = new Error("The store did not return a transaction id.");
1134
+ err.code = "no_transaction_id";
1135
+ throw err;
1136
+ }
1137
+ return this.request("POST", "/v1/economy/redeem", {
1138
+ rail: this.rail,
1139
+ packId,
1140
+ transactionId: purchase.transactionId,
1141
+ });
1142
+ }
1143
+
936
1144
  _mpRefuse() {
937
1145
  const err = new Error("Multiplayer is not available for this game yet");
938
1146
  err.code = "multiplayer_disabled";
@@ -944,11 +1152,27 @@ class TesanaClient {
944
1152
  */
945
1153
  async _mpEnter(session) {
946
1154
  const joined = await session;
947
- await this._mpOpen(joined.wsUrl);
1155
+ // A room that was opened and then could not be entered is reported as what
1156
+ // it is: the room exists. The SDK cannot seat the player — that is the
1157
+ // host's job — but it can name the room so a game retries `join(roomId)`
1158
+ // instead of opening a second one and stranding the first.
1159
+ try {
1160
+ await this._mpOpen(joined.wsUrl);
1161
+ } catch (err) {
1162
+ const roomId = joined.roomId || joined.room?.id || null;
1163
+ const wrapped = new Error(
1164
+ roomId ? `${err?.message || "multiplayer unavailable"} (room ${roomId})` : err?.message || "multiplayer unavailable",
1165
+ );
1166
+ wrapped.code = err?.code || "mp_enter_failed";
1167
+ wrapped.roomId = roomId;
1168
+ throw wrapped;
1169
+ }
948
1170
  this._mp.roomId = joined.roomId || joined.room?.id || null;
1171
+ this._mp.code = joined.room?.code || null;
949
1172
  return {
950
1173
  wsUrl: joined.wsUrl,
951
1174
  roomId: this._mp.roomId,
1175
+ code: this._mp.code,
952
1176
  playerId: joined.playerId || this._player?.id,
953
1177
  room: joined.room,
954
1178
  };
@@ -1125,6 +1349,7 @@ class TesanaClient {
1125
1349
  this._mp.leaving = true;
1126
1350
  this._mpClose();
1127
1351
  this._mp.roomId = null;
1352
+ this._mp.code = null;
1128
1353
  this._mp.wsUrl = null;
1129
1354
  this._mp.reconnectAttempts = 0;
1130
1355
  this._mp.reconnectExhausted = false;
@@ -1223,6 +1448,13 @@ class TesanaClient {
1223
1448
  minIntervalMs: config.adMinIntervalMs,
1224
1449
  });
1225
1450
  }
1451
+ // A later bootstrap may carry the player's language — a provisionally
1452
+ // "offline" answer has none, and the real one arrives a moment later. The
1453
+ // capability is re-pointed in place, exactly as the ad policy is.
1454
+ if (config.locale && this.l10n) {
1455
+ const next = normalizeLocale(config.locale);
1456
+ if (next && next !== this.l10n.locale()) this.l10n.applyLocale(next);
1457
+ }
1226
1458
  this._mpEnabled = config.multiplayer !== false;
1227
1459
  this.multiplayer.enabled = this._mpEnabled;
1228
1460
  return this;
@@ -1456,6 +1688,300 @@ class TesanaClient {
1456
1688
  };
1457
1689
  }
1458
1690
 
1691
+ // -------------------------------------------------------------------- l10n
1692
+ //
1693
+ // Localization, from the game's side. The service owns the dictionary and the
1694
+ // translation; this owns one promise: a game that asks for its text in the
1695
+ // player's language gets something renderable, always.
1696
+ //
1697
+ // Deliberately synchronous where the game needs it to be. `t()` reads a map
1698
+ // that was filled before the first frame, so drawing a localized menu costs no
1699
+ // await and no round trip; only text the game discovers at runtime — a
1700
+ // procedurally generated item name, something the player typed — goes through
1701
+ // the async path. A game that never awaits anything still localizes.
1702
+ _makeL10n(opts) {
1703
+ const state = {
1704
+ locale: normalizeLocale(opts.locale || ""),
1705
+ // The language the game's own strings are written in. Declared by the
1706
+ // build; the service is told the same value, so the two agree rather
1707
+ // than one guessing what the other meant.
1708
+ source: "en",
1709
+ // The platform's list, refined by the service's answer when it arrives.
1710
+ languages: L10N_TARGETS.slice(),
1711
+ // Source text -> translated text, filled before `ready` resolves.
1712
+ bundle: {},
1713
+ // The game's own key -> source text, for `t("ui.play")`.
1714
+ index: {},
1715
+ handlers: [],
1716
+ // `requested`: what the game's source language resolved to (en, de, …)
1717
+ // vs `target`: what is actually being served — the difference is a
1718
+ // language the game did not declare, where the source is the answer.
1719
+ target: "",
1720
+ loaded: false,
1721
+ // The bundle is asked for from three places on a normal boot — `ready`,
1722
+ // `init`'s await, and the post-session reload — and all three want the
1723
+ // same one. `inflight` is the shared request; `loadedFor` is the target
1724
+ // that has already been answered, so a repeat is a no-op rather than a
1725
+ // second round trip for an object we already hold.
1726
+ inflight: null,
1727
+ inflightTarget: "",
1728
+ loadedFor: null,
1729
+ };
1730
+
1731
+ const self = this;
1732
+
1733
+ /** Emit a locale change to every listener, without letting one break the rest. */
1734
+ function emit() {
1735
+ const event = { locale: state.locale, target: state.target, languages: state.languages.slice() };
1736
+ for (const fn of [...state.handlers]) {
1737
+ try {
1738
+ fn(event);
1739
+ } catch {
1740
+ /* a game handler */
1741
+ }
1742
+ }
1743
+ }
1744
+
1745
+ /**
1746
+ * Resolve `key` against the bundle.
1747
+ *
1748
+ * Three shapes, because a game reaches for all three: a key it declared
1749
+ * (`"ui.play"`), the source sentence itself (`"Play"`), and a key with a
1750
+ * fallback for the source text that was never declared. Whatever is not
1751
+ * found comes back as the fallback or the key, which is what makes an
1752
+ * unreachable service a non-event.
1753
+ */
1754
+ function lookup(key, fallback) {
1755
+ const name = String(key == null ? "" : key);
1756
+ const source = state.index[name] || name;
1757
+ const hit = state.bundle[source];
1758
+ if (typeof hit === "string" && hit) return hit;
1759
+ if (typeof fallback === "string" && fallback) return fallback;
1760
+ return source;
1761
+ }
1762
+
1763
+ /**
1764
+ * Load the bundle, at most once per (language, reachability) combination.
1765
+ *
1766
+ * A boot calls this from several independent places — the `ready` promise,
1767
+ * `init`'s await, and the post-session `reload` — and they all want the
1768
+ * same bundle. Coalescing them is not an optimization for its own sake:
1769
+ * every extra request is the player's bundle fetched twice, and a game
1770
+ * that redraws on `onChange` should not be able to multiply it.
1771
+ */
1772
+ function load() {
1773
+ const target = self._canReach() && state.locale && state.locale !== state.source ? state.locale : "";
1774
+ if (state.inflight && state.inflightTarget === target) return state.inflight;
1775
+ if (state.loadedFor === target && state.loaded) return Promise.resolve(state);
1776
+ state.inflightTarget = target;
1777
+ state.inflight = fetchBundle(target).finally(() => {
1778
+ state.inflight = null;
1779
+ });
1780
+ return state.inflight;
1781
+ }
1782
+
1783
+ async function fetchBundle(target) {
1784
+ if (!self._canReach()) {
1785
+ // No address, or no game id: nothing will ever answer, and asking
1786
+ // anyway would throw a relative-URL fetch. The source language is the
1787
+ // honest answer and the game renders exactly as it always did.
1788
+ state.loaded = true;
1789
+ state.loadedFor = target;
1790
+ return state;
1791
+ }
1792
+ try {
1793
+ if (!target) {
1794
+ // Nothing to fetch — and no request at all, either. A source-language
1795
+ // boot needs no bundle (nothing is translated) and no language list
1796
+ // (the platform's known set is already in memory), so a game with no
1797
+ // localization in force makes zero localization requests. That
1798
+ // matters beyond tidiness: it is the same rule as the rest of the
1799
+ // SDK, that a capability nobody asked for must not put bytes on the
1800
+ // wire, and it is what a game running entirely offline relies on.
1801
+ state.target = "";
1802
+ state.loaded = true;
1803
+ state.loadedFor = target;
1804
+ return state;
1805
+ }
1806
+ const data = await self.request(
1807
+ "GET",
1808
+ `/v1/l10n/bundle?target=${enc(target)}`,
1809
+ );
1810
+ if (data && typeof data.translations === "object" && data.translations) {
1811
+ state.bundle = data.translations;
1812
+ }
1813
+ if (data && typeof data.index === "object" && data.index) {
1814
+ state.index = data.index;
1815
+ }
1816
+ if (typeof data?.source === "string" && data.source) state.source = data.source;
1817
+ // `target` is the service's answer about what it actually served.
1818
+ // It is `""` for a language this game has not declared, which is the
1819
+ // signal that the source text IS the answer.
1820
+ state.target = typeof data?.target === "string" && data.target ? data.target : "";
1821
+ // The declared language set arrives with the bundle's own response
1822
+ // rather than a second route. It is one fact about one game, and two
1823
+ // requests to learn it is one more chance for a boot to be slower than
1824
+ // the first frame.
1825
+ if (Array.isArray(data?.languages) && data.languages.length) {
1826
+ // The game's own declared set, in the order it chose — which is how
1827
+ // a game that lists French first gets French first in its picker.
1828
+ state.languages = data.languages.slice();
1829
+ }
1830
+ } catch (err) {
1831
+ // An outage costs the translation, not the game. One deduped line is
1832
+ // enough to make it findable without spamming the console on retry.
1833
+ warnOnce(
1834
+ "l10n-unreachable",
1835
+ `Tesana localization: could not reach the translation service (${(err && err.message) || "request failed"}).`
1836
+ + " The game keeps playing in its source language.",
1837
+ );
1838
+ }
1839
+ state.loaded = true;
1840
+ state.loadedFor = target;
1841
+ return state;
1842
+ }
1843
+
1844
+ return {
1845
+ /**
1846
+ * The player's language, synchronously, as the host resolved it.
1847
+ *
1848
+ * Follows the same tag vocabulary the site uses (`pt-BR`, `zh`), not
1849
+ * AWS's, so a game can pass it straight to `Intl`/`toLocaleString`.
1850
+ */
1851
+ locale: () => state.locale,
1852
+ /** The languages this game offers, the host's order preserved. */
1853
+ languages: () => state.languages.slice(),
1854
+ /** The language text is actually being served in, or `""` when it is the source. */
1855
+ target: () => state.target,
1856
+ /** The language the game's own strings are written in. */
1857
+ source: () => state.source,
1858
+ /** Whether the initial bundle has landed. `t()` works before it does. */
1859
+ get loaded() {
1860
+ return state.loaded;
1861
+ },
1862
+
1863
+ /**
1864
+ * The translated text for `key`, synchronously.
1865
+ *
1866
+ * Prefer this. It is filled before the first frame, so a game never has
1867
+ * to await anything to draw a localized menu — and when the bundle is
1868
+ * empty (a service outage, a language the game never declared) it returns
1869
+ * the source text, which is a rendered game rather than a blank one.
1870
+ *
1871
+ * @param {string} key a declared key, or the source sentence itself
1872
+ * @param {object|string} [vars] `{name}` values, or a fallback string
1873
+ */
1874
+ t: (key, vars) => {
1875
+ // The second argument is both of the things a caller wants to pass:
1876
+ // placeholder values, and a fallback for an undeclared key. A string is
1877
+ // unambiguously a fallback; an object is unambiguously values.
1878
+ const values = vars && typeof vars === "object" ? vars : null;
1879
+ const fallback = typeof vars === "string" ? vars : "";
1880
+ return fillPlaceholders(lookup(key, fallback), values);
1881
+ },
1882
+
1883
+ /**
1884
+ * Translate text the game discovered while running.
1885
+ *
1886
+ * The one path that costs a round trip, so it is the one to keep off the
1887
+ * hot path: ask once, at the moment the text is created (a generated
1888
+ * name, a line of dialogue just chosen), never per frame. Resolves the
1889
+ * source text on any failure, so a `.then` never sees a rejection.
1890
+ *
1891
+ * @param {string} text
1892
+ * @param {{ id?: string, values?: Record<string, unknown>, target?: string }} [opts]
1893
+ */
1894
+ translate: async (text, opts = {}) => {
1895
+ const values = opts.values && typeof opts.values === "object" ? opts.values : null;
1896
+ const target = opts.target || state.target || (state.locale !== state.source ? state.locale : "");
1897
+ // A named string is routed through the id-keyed path, which is what
1898
+ // lets the service remember it under the game's own name and serve it
1899
+ // from cache next time without even a hash lookup.
1900
+ if (opts.id && self._canReach() && target) {
1901
+ try {
1902
+ const data = await self.request("POST", "/v1/l10n/string", {
1903
+ id: String(opts.id),
1904
+ text: String(text == null ? "" : text),
1905
+ values: values || undefined,
1906
+ target,
1907
+ source: state.source,
1908
+ });
1909
+ if (data && typeof data.value === "string" && data.value) return data.value;
1910
+ } catch {
1911
+ /* falls through to the source text below */
1912
+ }
1913
+ }
1914
+ // The anonymous path requires a target to be worth a call. With no
1915
+ // target this *is* the source language, and asking the server to hand
1916
+ // back what it was given is the most expensive no-op available.
1917
+ if (self._canReach() && target) {
1918
+ try {
1919
+ const data = await self.request("POST", "/v1/l10n/translate", {
1920
+ strings: [String(text == null ? "" : text)],
1921
+ target,
1922
+ source: state.source,
1923
+ });
1924
+ const hit = data?.translations?.[String(text)];
1925
+ if (typeof hit === "string" && hit) return fillPlaceholders(hit, values);
1926
+ } catch {
1927
+ /* ditto */
1928
+ }
1929
+ }
1930
+ return fillPlaceholders(String(text == null ? "" : text), values);
1931
+ },
1932
+
1933
+ /**
1934
+ * Subscribe to a language change. Returns an unsubscribe function.
1935
+ *
1936
+ * A game should redraw its text (or call `t()` again) on this rather than
1937
+ * caching translated strings at startup, because the player can change
1938
+ * the site's language without reloading the frame.
1939
+ *
1940
+ * @param {(event: { locale: string, target: string, languages: string[] }) => void} fn
1941
+ */
1942
+ onChange: (fn) => {
1943
+ if (typeof fn !== "function") return () => {};
1944
+ state.handlers.push(fn);
1945
+ return () => {
1946
+ state.handlers = state.handlers.filter((handler) => handler !== fn);
1947
+ };
1948
+ },
1949
+
1950
+ /** Resolves after the initial bundle. A game may await it with `__TESANA_READY__`. */
1951
+ ready: load(),
1952
+
1953
+ /**
1954
+ * Reload the bundle, after an identity or language change.
1955
+ *
1956
+ * The constructor loads immediately from whatever the page already
1957
+ * carries. A game that minted its own token — or a host whose real
1958
+ * bootstrap replaced a provisional "offline" one — has no credential that
1959
+ * first time, so the bundle would be empty and the game would stay in its
1960
+ * source language for the whole session. `init` awaits this after the
1961
+ * identity step, which is what makes the documented
1962
+ * `await window.__TESANA_READY__` sufficient for a localized first frame.
1963
+ */
1964
+ reload: () => load(),
1965
+
1966
+ // ---- internal wiring (used by the bootstrap listener) ----
1967
+ /** A new language from the host. Resolves the same promise the game already holds. */
1968
+ applyLocale(next) {
1969
+ const locale = normalizeLocale(next);
1970
+ if (!locale || locale === state.locale) return state;
1971
+ state.locale = locale;
1972
+ // The old bundle is the *previous* language's, so it is cleared rather
1973
+ // than left to serve: showing a menu in a language the player just
1974
+ // switched away from is worse than showing the source text for the
1975
+ // moment the refill takes. `t()` falls back to source in between.
1976
+ state.bundle = {};
1977
+ state.target = "";
1978
+ emit();
1979
+ load().catch(() => {});
1980
+ return state;
1981
+ },
1982
+ };
1983
+ }
1984
+
1459
1985
  // ------------------------------------------------------------------ saves
1460
1986
  //
1461
1987
  // Writes go to the local cache first, always, so a failed upload is a save
@@ -1508,6 +2034,13 @@ class TesanaClient {
1508
2034
  _signIn() {
1509
2035
  const signedIn = () => !this.offline && !this._isGuestSession();
1510
2036
  if (signedIn()) return Promise.resolve({ signedIn: true });
2037
+ // A desktop/Steam build has no host to draw an account UI. Its launcher is
2038
+ // the sign-in surface, and only it can vouch for the player to the host
2039
+ // with the internal secret that account linking requires — so this asks the
2040
+ // native side to run sign-in and then waits for the bootstrap that carries
2041
+ // the linked token, exactly as the web path waits for the host's answer.
2042
+ const desktop = storeBilling();
2043
+ if (desktop && typeof desktop.signIn === "function") return this._signInViaNative(signedIn);
1511
2044
  post({ type: "tesana-sign-in-request", gameId: this.gameId });
1512
2045
  return new Promise((resolve) => {
1513
2046
  let expiry = null;
@@ -1541,7 +2074,46 @@ class TesanaClient {
1541
2074
 
1542
2075
  /** A guest the site vouches for: saves in the cloud, but has no account to spend from. */
1543
2076
  _isGuestSession() {
1544
- return Boolean(this._player && this._player.isGuest);
2077
+ if (!this._player) return false;
2078
+ // Two signals, because the answer arrives from two places. A host posts
2079
+ // `isGuest: true` in its bootstrap — the web's word for it — while an
2080
+ // identity this client resolves itself (`/v1/player/me`) reports `isLinked`
2081
+ // and no `isGuest` at all. Reading only the first would let a native
2082
+ // session, whose whole point is an account-free identity, pass as a
2083
+ // signed-in player; the store path gates a sale on exactly this, so that
2084
+ // mistake is a card charged for coins we then refuse to grant.
2085
+ return this._player.isGuest === true || this._player.isLinked === false;
2086
+ }
2087
+
2088
+ /**
2089
+ * Ask the native launcher to sign the player in, then wait for the token.
2090
+ *
2091
+ * The launcher is the only party that can reach the host route with the
2092
+ * internal secret that account linking needs, so this hands it the request
2093
+ * and then watches `signedIn()` — which flips the moment the linked bootstrap
2094
+ * replaces the guest one. Polling rather than listening is deliberate: the
2095
+ * bootstrap arrives through the SDK's own upgrade path (`onBootstrapUpgrade`
2096
+ * re-points the client and re-runs identity), and there is no second channel
2097
+ * to subscribe to here.
2098
+ */
2099
+ _signInViaNative(signedIn) {
2100
+ return window.TesanaDesktop.signIn({ gameId: this.gameId }).then((answer) => {
2101
+ if (!answer || answer.ok !== true || answer.signedIn !== true) return { signedIn: false };
2102
+ return new Promise((resolve) => {
2103
+ const waitForToken = (attempt) => {
2104
+ if (signedIn()) return resolve({ signedIn: true });
2105
+ // Report what is actually true when the wait runs out. The web path
2106
+ // predates this and answers optimistically; its launcher-started
2107
+ // sign-in gets a fresh page instead, so it never observes the lie.
2108
+ // Here the caller is a store purchase deciding whether money may
2109
+ // move, and "probably signed in" is not a state a charge may proceed
2110
+ // on — a token that never arrived means no account to hold the coins.
2111
+ if ((attempt || 0) >= 60) return resolve({ signedIn: signedIn() });
2112
+ setTimeout(() => waitForToken((attempt || 0) + 1), 50);
2113
+ };
2114
+ waitForToken(0);
2115
+ });
2116
+ });
1545
2117
  }
1546
2118
 
1547
2119
  }