@tesana/sdk 1.0.3 → 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.
- package/dist/tesana.esm.js +452 -8
- package/dist/tesana.iife.js +453 -9
- package/package.json +1 -1
- package/src/tesana.js +452 -8
package/dist/tesana.esm.js
CHANGED
|
@@ -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.
|
|
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;
|
|
@@ -489,6 +556,16 @@ export async function init(config = {}) {
|
|
|
489
556
|
} catch (err) {
|
|
490
557
|
client.goOffline(err);
|
|
491
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
|
+
}
|
|
492
569
|
window.__TESANA_PLAYER__ = client.player.me();
|
|
493
570
|
// A provisional "offline" answer can upgrade later. Re-point this client in
|
|
494
571
|
// place — the game holds a reference to it — and re-run the identity step,
|
|
@@ -496,7 +573,7 @@ export async function init(config = {}) {
|
|
|
496
573
|
// player with a balance frozen at zero.
|
|
497
574
|
const finishUpgrade = () => {
|
|
498
575
|
client.configure(buildConfig(mergedConfig()));
|
|
499
|
-
client.ensureSession();
|
|
576
|
+
client.ensureSession().then(() => client.l10n.reload());
|
|
500
577
|
window.__TESANA_PLAYER__ = client.player.me();
|
|
501
578
|
};
|
|
502
579
|
onBootstrapUpgrade(finishUpgrade);
|
|
@@ -559,6 +636,15 @@ function buildConfig(merged) {
|
|
|
559
636
|
adsEnabled: merged.adsEnabled,
|
|
560
637
|
adFormats: merged.adFormats || merged.ad_formats || [],
|
|
561
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
|
+
),
|
|
562
648
|
};
|
|
563
649
|
}
|
|
564
650
|
|
|
@@ -570,7 +656,7 @@ function defaultEndpoint() {
|
|
|
570
656
|
|
|
571
657
|
class TesanaClient {
|
|
572
658
|
/**
|
|
573
|
-
* @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
|
|
574
660
|
*/
|
|
575
661
|
constructor(opts) {
|
|
576
662
|
this.endpoint = opts.endpoint;
|
|
@@ -613,6 +699,8 @@ class TesanaClient {
|
|
|
613
699
|
ws: null,
|
|
614
700
|
handlers: [],
|
|
615
701
|
roomId: null,
|
|
702
|
+
// The current room's share code, or null for a public room.
|
|
703
|
+
code: null,
|
|
616
704
|
// Reconnect state. `wsUrl` is kept so a dropped socket can re-enter the
|
|
617
705
|
// same room; `leaving` stops a deliberate leave from being retried.
|
|
618
706
|
wsUrl: null,
|
|
@@ -825,6 +913,16 @@ class TesanaClient {
|
|
|
825
913
|
// same object in place, rather than the game holding a stale policy.
|
|
826
914
|
adClient = this.ads;
|
|
827
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
|
+
|
|
828
926
|
this.multiplayer = {
|
|
829
927
|
// Read this before drawing a lobby: when it is false the game is not
|
|
830
928
|
// allowed rooms yet and the calls below refuse.
|
|
@@ -841,14 +939,42 @@ class TesanaClient {
|
|
|
841
939
|
.then((r) => r.rooms)
|
|
842
940
|
.catch(() => [])
|
|
843
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.
|
|
844
947
|
create: (opts) =>
|
|
845
948
|
this._mpEnabled
|
|
846
949
|
? this._mpEnter(this._mpRequest("POST", "/v1/mp/rooms", opts || {}))
|
|
847
950
|
: this._mpRefuse(),
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
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.
|
|
852
978
|
quickJoin: (opts) =>
|
|
853
979
|
this._mpEnabled
|
|
854
980
|
? this._mpEnter(this._mpRequest("POST", "/v1/mp/quick-join", opts || {}))
|
|
@@ -1026,11 +1152,27 @@ class TesanaClient {
|
|
|
1026
1152
|
*/
|
|
1027
1153
|
async _mpEnter(session) {
|
|
1028
1154
|
const joined = await session;
|
|
1029
|
-
|
|
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
|
+
}
|
|
1030
1170
|
this._mp.roomId = joined.roomId || joined.room?.id || null;
|
|
1171
|
+
this._mp.code = joined.room?.code || null;
|
|
1031
1172
|
return {
|
|
1032
1173
|
wsUrl: joined.wsUrl,
|
|
1033
1174
|
roomId: this._mp.roomId,
|
|
1175
|
+
code: this._mp.code,
|
|
1034
1176
|
playerId: joined.playerId || this._player?.id,
|
|
1035
1177
|
room: joined.room,
|
|
1036
1178
|
};
|
|
@@ -1207,6 +1349,7 @@ class TesanaClient {
|
|
|
1207
1349
|
this._mp.leaving = true;
|
|
1208
1350
|
this._mpClose();
|
|
1209
1351
|
this._mp.roomId = null;
|
|
1352
|
+
this._mp.code = null;
|
|
1210
1353
|
this._mp.wsUrl = null;
|
|
1211
1354
|
this._mp.reconnectAttempts = 0;
|
|
1212
1355
|
this._mp.reconnectExhausted = false;
|
|
@@ -1305,6 +1448,13 @@ class TesanaClient {
|
|
|
1305
1448
|
minIntervalMs: config.adMinIntervalMs,
|
|
1306
1449
|
});
|
|
1307
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
|
+
}
|
|
1308
1458
|
this._mpEnabled = config.multiplayer !== false;
|
|
1309
1459
|
this.multiplayer.enabled = this._mpEnabled;
|
|
1310
1460
|
return this;
|
|
@@ -1538,6 +1688,300 @@ class TesanaClient {
|
|
|
1538
1688
|
};
|
|
1539
1689
|
}
|
|
1540
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
|
+
|
|
1541
1985
|
// ------------------------------------------------------------------ saves
|
|
1542
1986
|
//
|
|
1543
1987
|
// Writes go to the local cache first, always, so a failed upload is a save
|