gt-react 11.0.7 β†’ 11.0.9

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,777 +0,0 @@
1
- "use client";
2
- import { I18nStore, ReactI18nCache, createRenderPipeline, declareVar, decodeMsg, decodeOptions, decodeVars, defaultResetLocaleCookieName, derive, getDefaultLocale, getFormatLocales, getI18nConfig, getLocaleProperties, getLocales, getReactI18nCache, getReadonlyConditionStore, getTranslationsSnapshot, getTranslationsSnapshot as getTranslationsSnapshot$1, getVersionId, gtFallback, initializeI18nConfig, internalInitializeGTSRA, mFallback, msg, resolveCanonicalLocale, setI18nStore, setReactI18nCache, setReactI18nCache as setReactI18nCache$1, t } from "@generaltranslation/react-core/pure";
3
- import { GtInternalRuntimeTranslateJsx, GtInternalRuntimeTranslateString, I18nCache, createConditionStoreSingleton, getCookieValue, getI18nConfig as getI18nConfig$1, getRuntimeEnvironment, parseAcceptLanguage } from "gt-i18n/internal";
4
- import { useCallback, useMemo, useRef } from "react";
5
- import { useConditionStore, useCustomMapping, useDefaultLocale, useEnableI18n, useFormatLocales, useGT, useInternalLocaleSelector, useInternalRegionSelector, useLocale, useLocaleDirection, useLocaleProperties, useLocales, useMessages, useRegion, useTranslations } from "@generaltranslation/react-core/hooks";
6
- import { Branch, Currency, DateTime, Derive, GtInternalTranslateJsx, GtInternalVar, I18nStore as I18nStore$1, InternalGTProvider, InternalLocaleSelector, InternalRegionSelector, Num, Plural, RelativeTime, T, Var } from "@generaltranslation/react-core/components";
7
- import { jsx } from "react/jsx-runtime";
8
- //#region src/i18n-cache/constants.ts
9
- const DEFAULT_HTML_TAG_OPTIONS = {
10
- updateHtmlLangTag: true,
11
- updateHtmlDirTag: true
12
- };
13
- //#endregion
14
- //#region src/i18n-cache/LocalStorageTranslationCache.ts
15
- const STORAGE_KEY_PREFIX = "gt:tx:";
16
- const PURGE_TIMESTAMP_PREFIX = "gt:tx:purge:";
17
- const FLUSH_INTERVAL = 500;
18
- const DEFAULT_MAX_SIZE = 1e6;
19
- const DEFAULT_TTL_MS = 864e5;
20
- const DEFAULT_PURGE_INTERVAL_MS = 3e5;
21
- const PURGE_TARGET_RATIO = .8;
22
- const activeIntervals = /* @__PURE__ */ new Map();
23
- /**
24
- * A localStorage-backed translation cache for a single locale.
25
- * Used in development mode only to persist runtime translations across page refreshes.
26
- *
27
- * Entries are stored with per-entry expiry timestamps and the cache is purged
28
- * when estimated size exceeds the configured maximum.
29
- */
30
- var LocalStorageTranslationCache = class {
31
- /**
32
- * @param locale - The locale this cache is for
33
- * @param projectId - The project id (namespaces localStorage keys)
34
- * @param init - Optional initial translations to merge on top of localStorage data.
35
- * init values take priority over stale localStorage entries.
36
- * @param maxSize - Maximum cache size in characters (default: ~1M)
37
- * @param ttl - TTL in milliseconds for each entry (default: 24 hours)
38
- * @param purgeInterval - Background purge check interval in ms (default: 5 min)
39
- */
40
- constructor({ locale, projectId, init, maxSize, ttl, purgeInterval }) {
41
- this._writeBuffer = {};
42
- this._flushTimer = null;
43
- this._estimatedSize = 0;
44
- this._storageKey = `${STORAGE_KEY_PREFIX}${projectId}:${locale}`;
45
- this._purgeTimestampKey = `${PURGE_TIMESTAMP_PREFIX}${projectId}:${locale}`;
46
- this._maxSize = maxSize ?? DEFAULT_MAX_SIZE;
47
- this._ttl = ttl ?? DEFAULT_TTL_MS;
48
- this._purgeInterval = purgeInterval ?? DEFAULT_PURGE_INTERVAL_MS;
49
- if (init) this.initStorage(init);
50
- if (activeIntervals.has(this._storageKey)) clearInterval(activeIntervals.get(this._storageKey));
51
- const intervalId = setInterval(() => this._backgroundPurge(), this._purgeInterval);
52
- activeIntervals.set(this._storageKey, intervalId);
53
- }
54
- /**
55
- * Returns the full translation map (cache + pending buffer writes).
56
- * Filters out expired entries. Buffer entries take priority.
57
- */
58
- getInternalCache() {
59
- const now = Date.now();
60
- const cache = this._readFromStorage();
61
- const result = {};
62
- for (const [key, entry] of Object.entries(cache)) if (entry.exp > now) result[key] = entry.t;
63
- Object.assign(result, this._writeBuffer);
64
- return result;
65
- }
66
- /**
67
- * Queue a translation for writing to localStorage.
68
- * Writes are batched via a debounced flush.
69
- */
70
- write(hash, translation) {
71
- this._writeBuffer[hash] = translation;
72
- this._scheduleFlush();
73
- }
74
- /**
75
- * Remove specific entries from the cache by hash.
76
- */
77
- purge(hashes) {
78
- const cache = this._readFromStorage();
79
- for (const hash of hashes) delete cache[hash];
80
- this._writeRaw(JSON.stringify(cache));
81
- }
82
- /**
83
- * Schedule a flush of the write buffer.
84
- * Uses a leading throttle β€” the first write in a burst schedules a flush
85
- * after FLUSH_INTERVAL ms; subsequent writes before the timer fires are
86
- * batched into the same flush.
87
- */
88
- _scheduleFlush() {
89
- if (this._flushTimer) return;
90
- this._flushTimer = setTimeout(() => {
91
- this._flushTimer = null;
92
- this._flush();
93
- }, FLUSH_INTERVAL);
94
- }
95
- /**
96
- * Merge the write buffer into the cache and persist to localStorage.
97
- * Purges before writing if estimated size exceeds max.
98
- */
99
- _flush() {
100
- if (Object.keys(this._writeBuffer).length === 0) return;
101
- try {
102
- const cache = this._readFromStorage();
103
- const now = Date.now();
104
- if (this._estimatedSize > this._maxSize) this._purgeCache(cache, now);
105
- const exp = now + this._ttl;
106
- for (const [key, value] of Object.entries(this._writeBuffer)) cache[key] = {
107
- t: value,
108
- exp
109
- };
110
- this._writeRaw(JSON.stringify(cache));
111
- } catch {}
112
- this._writeBuffer = {};
113
- }
114
- /**
115
- * Purge entries from the cache in place.
116
- * Phase 1: Remove expired entries.
117
- * Phase 2: If still over target, drop oldest entries by expiry time.
118
- */
119
- _purgeCache(cache, now) {
120
- const keysBeforePurge = Object.keys(cache);
121
- if (keysBeforePurge.length === 0) return;
122
- const avgEntrySize = this._estimatedSize / keysBeforePurge.length;
123
- deleteExpiredEntries(cache, now);
124
- const targetSize = this._maxSize * PURGE_TARGET_RATIO;
125
- const maxEntries = Math.floor(targetSize / avgEntrySize);
126
- const remaining = Object.entries(cache);
127
- if (remaining.length > maxEntries) {
128
- remaining.sort((a, b) => a[1].exp - b[1].exp);
129
- const toDrop = remaining.length - maxEntries;
130
- for (let i = 0; i < toDrop; i++) delete cache[remaining[i][0]];
131
- }
132
- }
133
- /**
134
- * Background purge triggered by setInterval.
135
- * Checks the last purge timestamp to avoid redundant work across tabs,
136
- * then removes expired entries. Only writes back if something changed.
137
- * Timestamp is updated after the purge completes.
138
- */
139
- _backgroundPurge() {
140
- try {
141
- const raw = localStorage.getItem(this._purgeTimestampKey);
142
- const lastPurge = raw ? parseInt(raw, 10) : 0;
143
- const now = Date.now();
144
- if (now - lastPurge < this._purgeInterval) return;
145
- const cache = this._readFromStorage();
146
- const keysBefore = Object.keys(cache).length;
147
- deleteExpiredEntries(cache, now);
148
- if (Object.keys(cache).length < keysBefore) this._writeRaw(JSON.stringify(cache));
149
- localStorage.setItem(this._purgeTimestampKey, String(now));
150
- } catch {}
151
- }
152
- /**
153
- * Read and parse translations from localStorage.
154
- * Recalibrates estimated size as a side effect.
155
- * Returns empty object on any error (unavailable, corrupt data, etc.)
156
- */
157
- _readFromStorage() {
158
- try {
159
- const raw = localStorage.getItem(this._storageKey);
160
- if (!raw) {
161
- this._estimatedSize = 0;
162
- return {};
163
- }
164
- this._estimatedSize = raw.length;
165
- return JSON.parse(raw);
166
- } catch {
167
- this._estimatedSize = 0;
168
- return {};
169
- }
170
- }
171
- /**
172
- * Persist new entries to localStorage with expiry timestamps.
173
- * Reads current cache, merges buffer on top, writes back.
174
- */
175
- initStorage(buffer) {
176
- try {
177
- const cache = this._readFromStorage();
178
- const exp = Date.now() + this._ttl;
179
- for (const [key, value] of Object.entries(buffer)) cache[key] = {
180
- t: value,
181
- exp
182
- };
183
- this._writeRaw(JSON.stringify(cache));
184
- } catch {}
185
- }
186
- /**
187
- * Write a pre-serialized string to localStorage and recalibrate estimate.
188
- */
189
- _writeRaw(serialized) {
190
- try {
191
- localStorage.setItem(this._storageKey, serialized);
192
- this._estimatedSize = serialized.length;
193
- } catch {}
194
- }
195
- };
196
- /**
197
- * Helper function deletes expired entries from a cache in place.
198
- */
199
- function deleteExpiredEntries(cache, now = Date.now()) {
200
- for (const key of Object.keys(cache)) if (cache[key].exp <= now) delete cache[key];
201
- }
202
- //#endregion
203
- //#region ../core/dist/api-BOEGbEF6.mjs
204
- function ensureSentence(text) {
205
- const trimmed = text.trim();
206
- if (!trimmed) return "";
207
- return /[.!?)]$/.test(trimmed) ? trimmed : `${trimmed}.`;
208
- }
209
- function stripSentence(text) {
210
- const trimmed = text.trim();
211
- let end = trimmed.length;
212
- while (end > 0) {
213
- const char = trimmed[end - 1];
214
- if (char !== "." && char !== "!" && char !== "?") break;
215
- end -= 1;
216
- }
217
- return trimmed.slice(0, end);
218
- }
219
- function lowercaseFirstWord(text) {
220
- return text.replace(/^[A-Z][a-z]/, (match) => match.toLowerCase());
221
- }
222
- function formatDetails(details) {
223
- if (!details) return "";
224
- const detailText = Array.isArray(details) ? details.join(", ") : details;
225
- if (!detailText.trim()) return "";
226
- return ensureSentence(`Details: ${detailText}`);
227
- }
228
- function createDiagnosticMessage({ source, severity, whatHappened, reassurance, why, fix, wayOut, details, docsUrl }) {
229
- const prefix = source ? severity ? `${source} ${severity}:` : `${source}:` : severity ? `${severity}:` : "";
230
- const whatAndWhy = why ? `${stripSentence(whatHappened)} because ${lowercaseFirstWord(stripSentence(why))}` : whatHappened;
231
- const shouldCombineWayOut = !!fix && !!wayOut && /^[a-z]/.test(stripSentence(wayOut));
232
- const messageParts = [
233
- whatAndWhy,
234
- reassurance,
235
- shouldCombineWayOut ? `${stripSentence(fix)}, or ${lowercaseFirstWord(stripSentence(wayOut))}` : fix,
236
- shouldCombineWayOut ? void 0 : wayOut,
237
- formatDetails(details)
238
- ].filter((part) => !!part).map(ensureSentence);
239
- if (docsUrl) messageParts.push(`Learn more: ${docsUrl}`);
240
- const message = messageParts.join(" ");
241
- return prefix ? `${prefix} ${message}` : message;
242
- }
243
- //#endregion
244
- //#region src/i18n-cache/BrowserI18nCache.ts
245
- /**
246
- * I18nCache implementation for Browser.
247
- */
248
- var BrowserI18nCache = class extends I18nCache {
249
- constructor(config) {
250
- const { htmlTagOptions, ...managerConfig } = config;
251
- const localStorageCaches = {};
252
- const i18nConfig = getI18nConfig$1();
253
- const devHotReloadEnabled = !!config.loadTranslations && i18nConfig.isDevHotReloadEnabled();
254
- const projectId = i18nConfig.getProjectId();
255
- const loadTranslations = devHotReloadEnabled ? wrapLoaderWithLocalStorage(config.loadTranslations, projectId, localStorageCaches) : config.loadTranslations;
256
- super({
257
- ...managerConfig,
258
- loadTranslations
259
- });
260
- this._devHotReloadJsx = false;
261
- this._localStorageCaches = localStorageCaches;
262
- this._devHotReloadJsx = devHotReloadEnabled;
263
- this.htmlTagOptions = {
264
- ...DEFAULT_HTML_TAG_OPTIONS,
265
- ...htmlTagOptions
266
- };
267
- if (devHotReloadEnabled) this.onTranslationsCacheMiss = ({ locale, hash, translation }) => {
268
- const cache = localStorageCaches[locale];
269
- if (cache) cache.write(hash, translation);
270
- else localStorageCaches[locale] = new LocalStorageTranslationCache({
271
- locale,
272
- projectId,
273
- init: { [hash]: translation }
274
- });
275
- };
276
- }
277
- /**
278
- * Whether dev hot reload JSX (Suspense-based <T>) is active
279
- */
280
- isDevHotReloadJsx() {
281
- return this._devHotReloadJsx;
282
- }
283
- /**
284
- * Get or create a LocalStorageTranslationCache for the given locale.
285
- * Instances are lazily created and cached per locale.
286
- * Returns undefined if not in development mode.
287
- */
288
- getLocalStorageTranslationCache(locale, init) {
289
- if (getRuntimeEnvironment() !== "development") return void 0;
290
- if (!this._localStorageCaches[locale]) this._localStorageCaches[locale] = new LocalStorageTranslationCache({
291
- locale,
292
- projectId: this.config.projectId,
293
- init
294
- });
295
- return this._localStorageCaches[locale];
296
- }
297
- /**
298
- * Update the html tag (lang, dir)
299
- *
300
- * @deprecated, TODO: we should use a different system for managing this html tag
301
- * this should just be for managing translations
302
- */
303
- updateHtmlTag(locale, htmlTagOptions) {
304
- const htmlLocale = htmlTagOptions?.lang || locale;
305
- const i18nConfig = getI18nConfig$1();
306
- const canonicalLocale = i18nConfig.resolveCanonicalLocale(htmlLocale);
307
- if (!i18nConfig.isValidLocale(canonicalLocale)) {
308
- console.warn(createInvalidLocaleWarning(htmlLocale));
309
- return;
310
- }
311
- const localeDirection = htmlTagOptions?.dir || i18nConfig.getLocaleDirection(canonicalLocale);
312
- const mergedHtmlTagOptions = {
313
- ...this.htmlTagOptions,
314
- ...htmlTagOptions
315
- };
316
- if (mergedHtmlTagOptions.updateHtmlLangTag) document.documentElement.lang = canonicalLocale;
317
- if (mergedHtmlTagOptions.updateHtmlDirTag) document.documentElement.dir = localeDirection;
318
- }
319
- };
320
- /**
321
- * Wraps a translation loader to merge localStorage translations in dev mode.
322
- * On each call: runs the original loader, seeds a LocalStorageTranslationCache
323
- * with the result (loader wins over stale localStorage), and returns the merged
324
- * translations β€” preserving runtime tx() translations from previous sessions.
325
- *
326
- * TODO: this should be moved to wrapping in I18nStore
327
- */
328
- function wrapLoaderWithLocalStorage(originalLoader, projectId, localStorageCaches) {
329
- return async (locale) => {
330
- const loaderTranslations = await originalLoader(locale);
331
- localStorageCaches[locale] ||= new LocalStorageTranslationCache({
332
- locale,
333
- projectId,
334
- init: loaderTranslations
335
- });
336
- return localStorageCaches[locale].getInternalCache();
337
- };
338
- }
339
- const createInvalidLocaleWarning = (locale) => createDiagnosticMessage({
340
- source: "gt-react",
341
- severity: "Warning",
342
- whatHappened: `Locale "${locale}" is not valid`,
343
- fix: "Use a valid BCP 47 locale code or add a custom mapping"
344
- });
345
- //#endregion
346
- //#region src/condition-store/cookies.ts
347
- /**
348
- * Minimally parses a cookie value for a given cookie name
349
- * @param cookieName - The name of the cookie
350
- * @returns The locale from the cookie or undefined if not found or invalid
351
- */
352
- function getCookieValue$1({ cookieName }) {
353
- if (typeof document === "undefined") return void 0;
354
- return getCookieValue(document.cookie, cookieName);
355
- }
356
- /**
357
- * Sets a cookie value for a given cookie name
358
- * @param cookieName - The name of the cookie
359
- * @param value - The value to set
360
- * @returns The value that was set
361
- */
362
- function setCookieValue({ cookieName, value }) {
363
- if (typeof document === "undefined") return;
364
- document.cookie = `${cookieName}=${value};path=/`;
365
- }
366
- //#endregion
367
- //#region src/condition-store/readBrowserLocale.ts
368
- function readBrowserLocale(localeCookieName) {
369
- const candidates = [];
370
- const cookieLocale = getCookieValue$1({ cookieName: localeCookieName });
371
- if (cookieLocale) candidates.push(cookieLocale);
372
- const navigatorLocales = navigator?.languages || [];
373
- candidates.push(...navigatorLocales);
374
- return candidates;
375
- }
376
- //#endregion
377
- //#region src/condition-store/BrowserConditionStore.ts
378
- /**
379
- * Condition store implementation for Browser.
380
- */
381
- var BrowserConditionStore = class {
382
- constructor(config) {
383
- this.getLocale = () => {
384
- return getBrowserLocale(this.customGetLocale);
385
- };
386
- this.setLocale = (locale) => {
387
- this.updateLocale(locale);
388
- setCookieValue({
389
- cookieName: defaultResetLocaleCookieName,
390
- value: "true"
391
- });
392
- this.reload();
393
- };
394
- this.getRegion = () => {
395
- const cookieRegion = getCookieValue$1({ cookieName: getI18nConfig().getRegionCookieName() });
396
- if (cookieRegion) return cookieRegion;
397
- return this.customGetRegion?.();
398
- };
399
- this.setRegion = (region) => {
400
- this.updateRegion(region);
401
- this.reload();
402
- };
403
- this.getEnableI18n = () => {
404
- const cookieEnableI18n = getCookieValue$1({ cookieName: getI18nConfig().getEnableI18nCookieName() });
405
- if (cookieEnableI18n === void 0) return this.customGetEnableI18n?.() ?? true;
406
- return cookieEnableI18n === "true";
407
- };
408
- this.setEnableI18n = (enableI18n) => {
409
- this.updateEnableI18n(enableI18n);
410
- this.reload();
411
- };
412
- this.updateLocale = (locale) => {
413
- const i18nConfig = getI18nConfig();
414
- setCookieValue({
415
- cookieName: i18nConfig.getLocaleCookieName(),
416
- value: i18nConfig.resolveSupportedLocale(locale)
417
- });
418
- };
419
- this.updateRegion = (region) => {
420
- setCookieValue({
421
- cookieName: getI18nConfig().getRegionCookieName(),
422
- value: region ?? ""
423
- });
424
- };
425
- this.updateEnableI18n = (enableI18n) => {
426
- setCookieValue({
427
- cookieName: getI18nConfig().getEnableI18nCookieName(),
428
- value: enableI18n ? "true" : "false"
429
- });
430
- };
431
- this.reload = () => {
432
- const state = {
433
- locale: this.getLocale(),
434
- region: this.getRegion(),
435
- enableI18n: this.getEnableI18n()
436
- };
437
- this.customReload(state);
438
- };
439
- const i18nConfig = getI18nConfig();
440
- this.customReload = config._reload ?? (() => typeof window !== "undefined" ? window.location.reload() : void 0);
441
- this.customGetLocale = config._getLocale;
442
- this.customGetRegion = config._getRegion;
443
- this.customGetEnableI18n = config._getEnableI18n;
444
- setCookieValue({
445
- cookieName: i18nConfig.getLocaleCookieName(),
446
- value: i18nConfig.resolveSupportedLocale(config.locale)
447
- });
448
- if (config.region !== void 0) setCookieValue({
449
- cookieName: i18nConfig.getRegionCookieName(),
450
- value: config.region
451
- });
452
- this.updateEnableI18n(config.enableI18n ?? true);
453
- }
454
- };
455
- function getBrowserLocale(getLocale) {
456
- const i18nConfig = getI18nConfig();
457
- const candidates = readBrowserLocale(i18nConfig.getLocaleCookieName());
458
- if (getLocale) candidates.push(getLocale());
459
- return i18nConfig.resolveSupportedLocale(candidates);
460
- }
461
- //#endregion
462
- //#region src/condition-store/singleton-operations.ts
463
- const conditionStoreNotInitializedError = createDiagnosticMessage({
464
- source: "gt-react",
465
- severity: "Error",
466
- whatHappened: "Cannot read GT runtime context before it has been initialized",
467
- why: "the internal ConditionStore singleton is unavailable",
468
- fix: "Call initializeGT() (or initializeGTSPA() in SPA apps) before rendering and add a <GTProvider> at the root of your component tree."
469
- });
470
- const { setConditionStore: setReadonlyConditionStore, isConditionStoreInitialized: isReadonlyConditionStoreInitialized } = createConditionStoreSingleton(conditionStoreNotInitializedError);
471
- const { getConditionStore: getBrowserConditionStore, setConditionStore: setBrowserConditionStore, isConditionStoreInitialized: isBrowserConditionStoreInitialized } = createConditionStoreSingleton(conditionStoreNotInitializedError);
472
- //#endregion
473
- //#region src/condition-store/createBrowserConditionStore.ts
474
- /**
475
- * Factory to create a BrowserConditionStore for Singleton
476
- *
477
- * This exists so we can keep the locale param as required in the constructor
478
- *
479
- * Server-provided props are the first candidates for hydration consistency.
480
- * Cookies fill in missing values to persist state across page reloads.
481
- *
482
- * Cookie names come from the I18nConfig singleton so custom names passed to
483
- * initializeGT() apply here without being threaded through provider props.
484
- */
485
- function createOrUpdateBrowserConditionStore(config) {
486
- const locale = determineLocale(config);
487
- const region = determineRegion(config);
488
- const enableI18n = determineEnableI18n(config);
489
- if (isBrowserConditionStoreInitialized()) {
490
- const conditionStore = getBrowserConditionStore();
491
- conditionStore.updateLocale(locale);
492
- if (region !== void 0) conditionStore.updateRegion(region);
493
- conditionStore.updateEnableI18n(enableI18n);
494
- return conditionStore;
495
- }
496
- const conditionStore = new BrowserConditionStore({
497
- ...config,
498
- locale,
499
- region,
500
- enableI18n
501
- });
502
- setBrowserConditionStore(conditionStore);
503
- return conditionStore;
504
- }
505
- function determineLocale({ _getLocale: getLocale, locale }) {
506
- const i18nConfig = getI18nConfig();
507
- const candidates = [];
508
- if (locale) candidates.push(...Array.isArray(locale) ? locale : [locale]);
509
- if (getLocale) candidates.push(getLocale());
510
- candidates.push(...readBrowserLocale(i18nConfig.getLocaleCookieName()));
511
- return i18nConfig.resolveSupportedLocale(candidates);
512
- }
513
- function determineRegion({ _getRegion: getRegion, region }) {
514
- return getCookieValue$1({ cookieName: getI18nConfig().getRegionCookieName() }) || getRegion?.() || region;
515
- }
516
- function determineEnableI18n({ enableI18n, _getEnableI18n: getEnableI18n }) {
517
- if (enableI18n !== void 0) return enableI18n;
518
- const cookieEnableI18n = getCookieValue$1({ cookieName: getI18nConfig().getEnableI18nCookieName() });
519
- if (cookieEnableI18n === void 0) return getEnableI18n?.() ?? true;
520
- return cookieEnableI18n === "true";
521
- }
522
- //#endregion
523
- //#region src/setup/runtimeCredentials.ts
524
- function addRuntimeCredentials(config) {
525
- const credentials = getRuntimeCredentials();
526
- return {
527
- ...config,
528
- projectId: config.projectId || credentials.projectId,
529
- devApiKey: config.devApiKey || credentials.devApiKey
530
- };
531
- }
532
- function getRuntimeCredentials() {
533
- return {
534
- projectId: readImportMetaVite(() => import.meta.env?.VITE_GT_PROJECT_ID) || readProcessEnvViteProjectId(),
535
- devApiKey: getRuntimeEnvironment() === "development" ? readImportMetaVite(() => import.meta.env?.DEV ? import.meta.env?.VITE_GT_DEV_API_KEY : void 0) || readProcessEnvViteDevApiKey() : void 0
536
- };
537
- }
538
- function readImportMetaVite(readValue) {
539
- try {
540
- return normalizeEnvValue(readValue());
541
- } catch {
542
- return;
543
- }
544
- }
545
- function readProcessEnvViteProjectId() {
546
- try {
547
- return normalizeEnvValue(process.env.VITE_GT_PROJECT_ID);
548
- } catch {
549
- return;
550
- }
551
- }
552
- function readProcessEnvViteDevApiKey() {
553
- try {
554
- return normalizeEnvValue(process.env.VITE_GT_DEV_API_KEY);
555
- } catch {
556
- return;
557
- }
558
- }
559
- function normalizeEnvValue(value) {
560
- return value || void 0;
561
- }
562
- //#endregion
563
- //#region src/setup/initializeGTSPA.ts
564
- /**
565
- * Initialize GT for an SPA
566
- * - i18nCache
567
- * - conditionStore
568
- * - i18nStore
569
- *
570
- * This is SPA for browser runtime
571
- */
572
- async function initializeGTSPA(config) {
573
- const runtimeConfig = addRuntimeCredentials(config);
574
- initializeI18nConfig(runtimeConfig, "SPA");
575
- setReactI18nCache$1(new BrowserI18nCache(runtimeConfig));
576
- createOrUpdateBrowserConditionStore(runtimeConfig);
577
- setI18nStore(new I18nStore());
578
- await getTranslationsSnapshot$1(getReadonlyConditionStore().getLocale());
579
- }
580
- //#endregion
581
- //#region src/setup/initializeGTSRA.ts
582
- /**
583
- * Initialize GT for server-rendered React runtimes.
584
- */
585
- function initializeGTSRA(config) {
586
- internalInitializeGTSRA(addRuntimeCredentials(config));
587
- }
588
- //#endregion
589
- //#region src/functions/parseLocale.ts
590
- /**
591
- * Resolve the user's locale from a Web Request.
592
- *
593
- * The configured locale cookie takes precedence over the Accept-Language
594
- * header. If neither contains a supported locale, the configured default
595
- * locale is returned.
596
- *
597
- * This is intended for incoming server requests. A Request created in the
598
- * browser does not automatically include document cookies or Accept-Language.
599
- */
600
- function parseLocale(request) {
601
- const i18nConfig = getI18nConfig();
602
- const candidates = [];
603
- const cookieLocale = getCookieValue(request.headers.get("cookie"), i18nConfig.getLocaleCookieName());
604
- if (cookieLocale) candidates.push(cookieLocale);
605
- candidates.push(...parseAcceptLanguage(request.headers.get("accept-language")));
606
- return i18nConfig.resolveSupportedLocale(candidates);
607
- }
608
- //#endregion
609
- //#region src/hooks/conditions-store.ts
610
- /**
611
- * Returns a function that sets the locale
612
- */
613
- function useSetLocale() {
614
- const conditionStore = useConditionStore();
615
- return useCallback((locale) => {
616
- conditionStore.setLocale(locale);
617
- }, [conditionStore]);
618
- }
619
- /**
620
- * Returns a function that sets the region
621
- */
622
- function useSetRegion() {
623
- const conditionStore = useConditionStore();
624
- return useCallback((region) => {
625
- conditionStore.setRegion(region);
626
- }, [conditionStore]);
627
- }
628
- /**
629
- * Returns a function that sets the enableI18n flag in the condition store.
630
- */
631
- function useSetEnableI18n() {
632
- const conditionStore = useConditionStore();
633
- return useCallback((enableI18n) => {
634
- conditionStore.setEnableI18n(enableI18n);
635
- }, [conditionStore]);
636
- }
637
- //#endregion
638
- //#region src/components/useLocaleSelector.ts
639
- /**
640
- * Gets the list of properties for using a locale selector.
641
- * Provides locale management utilities for the application.
642
- *
643
- * @param locales an optional list of locales to use for the drop down. These locales must be a subset of the locales provided by the `<GTProvider>` context. When not provided, the list of locales from the `<GTProvider>` context is used.
644
- *
645
- * @returns {Object} An object containing locale-related utilities:
646
- * @returns {string} return.locale - The currently selected locale.
647
- * @returns {string[]} return.locales - The list of all available locales.
648
- * @returns {function} return.setLocale - Function to update the current locale.
649
- * @returns {(locale: string) => LocaleProperties} return.getLocaleProperties - Function to retrieve properties for a given locale.
650
- */
651
- function useLocaleSelector(locales) {
652
- return {
653
- setLocale: useSetLocale(),
654
- ...useInternalLocaleSelector(locales)
655
- };
656
- }
657
- //#endregion
658
- //#region src/components/useRegionSelector.ts
659
- /**
660
- * Gets the list of properties for using a region selector.
661
- * Provides region management utilities for the application.
662
- *
663
- * @param {Object} [options] - Optional configuration object.
664
- * @param {string[]} [options.regions] - An optional array of ISO 3166 region codes to display. If not provided, regions are inferred from supported locales.
665
- * @param {Object} [options.customMapping] - Optional mapping to override region display names, emojis, or associated locales.
666
- * @param {boolean} [options.prioritizeCurrentLocaleRegion=true] - If true, the region corresponding to the current locale is prioritized in the list.
667
- * @param {boolean} [options.sortRegionsAlphabetically=true] - If true, regions are sorted alphabetically by display name.
668
- *
669
- * @returns {Object} An object containing region-related utilities:
670
- * @returns {string | undefined} return.region - The currently selected region code.
671
- * @returns {function} return.setRegion - Function to update the current region.
672
- * @returns {string[]} return.regions - The ordered list of available region codes.
673
- * @returns {Map<string, RegionData>} return.regionData - Map of region codes to their display data (name, emoji, locale).
674
- * @returns {string} return.locale - The current locale.
675
- * @returns {function} return.setLocale - Function to update the current locale.
676
- */
677
- function useRegionSelector(options) {
678
- return {
679
- setRegion: useSetRegion(),
680
- setLocale: useSetLocale(),
681
- ...useInternalRegionSelector(options)
682
- };
683
- }
684
- //#endregion
685
- //#region src/components/LocaleSelector.tsx
686
- /**
687
- * A dropdown component that allows users to select a locale.
688
- * @param {string[]} [locales] - An optional list of locales to use for the dropdown. If not provided, the list of locales from the `<GTProvider>` context is used.
689
- * @param {object} [customNames] - (deprecated) An optional object to map locales to custom names. Use `customMapping` instead.
690
- * @param {CustomMapping} [customMapping] - An optional object to map locales to custom display names, emojis, or other properties.
691
- * @returns {React.ReactElement | null} The rendered locale dropdown component or null to prevent rendering.
692
- */
693
- function LocaleSelector({ locales: _locales, ...props }) {
694
- const { locale, locales, getLocaleProperties, setLocale } = useLocaleSelector(_locales);
695
- return /* @__PURE__ */ jsx(InternalLocaleSelector, {
696
- locale,
697
- locales,
698
- setLocale,
699
- getLocaleProperties,
700
- ...props
701
- });
702
- }
703
- //#endregion
704
- //#region src/components/RegionSelector.tsx
705
- /**
706
- * A dropdown component that allows users to select a region.
707
- * @param {string[]} [regions] - An optional array of ISO 3166 region codes to display. If not provided, regions are inferred from the supported locales in the `<GTProvider>` context.
708
- * @param {React.ReactNode} [placeholder] - Optional placeholder node to display as the first option when no region is selected.
709
- * @param {object} [customMapping] - An optional object to map region codes to custom display names, emojis, or associated locales.
710
- * @param {boolean} [prioritizeCurrentLocaleRegion] - If true, the region corresponding to the current locale is prioritized in the list.
711
- * @param {boolean} [sortRegionsAlphabetically] - If true, regions are sorted alphabetically by display name.
712
- * @param {boolean} [asLocaleSelector=false] - If true, selecting a region will also update the locale to the region's associated locale.
713
- * @returns {React.ReactElement | null} The rendered region dropdown component or null to prevent rendering.
714
- *
715
- * @example
716
- * ```tsx
717
- * <RegionSelector
718
- * regions={['US', 'CA']}
719
- * customMapping={{ US: { name: "United States", emoji: "πŸ‡ΊπŸ‡Έ" } }}
720
- * placeholder="Select a region"
721
- * />
722
- * ```
723
- */
724
- function RegionSelector({ regions: _regions, customMapping, prioritizeCurrentLocaleRegion, sortRegionsAlphabetically, asLocaleSelector = false, ...props }) {
725
- const { region, regions, regionData, locale, setRegion, setLocale } = useRegionSelector({
726
- regions: _regions,
727
- customMapping,
728
- prioritizeCurrentLocaleRegion,
729
- sortRegionsAlphabetically
730
- });
731
- const changeRegion = (region) => {
732
- if (asLocaleSelector) {
733
- const regionLocale = regionData.get(region)?.locale;
734
- if (regionLocale && locale !== regionLocale) setLocale(regionLocale);
735
- }
736
- setRegion(region);
737
- };
738
- return /* @__PURE__ */ jsx(InternalRegionSelector, {
739
- region,
740
- regions,
741
- regionData,
742
- setRegion: changeRegion,
743
- ...props
744
- });
745
- }
746
- //#endregion
747
- //#region src/provider/BrowserGTProvider.tsx
748
- /**
749
- * Consumes snapshot from server
750
- * Implementation for client-side only
751
- */
752
- function BrowserGTProvider(props) {
753
- const conditionStore = useMemo(() => {
754
- return createOrUpdateBrowserConditionStore(props);
755
- }, [
756
- props.locale,
757
- props.region,
758
- props.enableI18n,
759
- props._reload
760
- ]);
761
- const i18nStoreRef = useRef(null);
762
- if (i18nStoreRef.current == null) i18nStoreRef.current = new I18nStore$1();
763
- return /* @__PURE__ */ jsx(InternalGTProvider, {
764
- ...props,
765
- conditionStore,
766
- i18nStore: i18nStoreRef.current
767
- });
768
- }
769
- //#endregion
770
- //#region src/index.types.ts
771
- async function Tx(_props) {
772
- throw new Error("Tx is only supported via RSC");
773
- }
774
- //#endregion
775
- export { Branch, Currency, DateTime, Derive, BrowserGTProvider as GTProvider, GtInternalRuntimeTranslateJsx, GtInternalRuntimeTranslateString, GtInternalTranslateJsx, GtInternalVar, LocaleSelector, Num, Plural, ReactI18nCache, RegionSelector, RelativeTime, T, Tx, Var, createRenderPipeline, declareVar, decodeMsg, decodeOptions, decodeVars, derive, getDefaultLocale, getFormatLocales, getLocaleProperties, getLocales, getReactI18nCache, getTranslationsSnapshot, getVersionId, gtFallback, initializeGTSRA as initializeGT, initializeGTSPA, mFallback, msg, parseLocale, resolveCanonicalLocale, setReactI18nCache, t, useCustomMapping, useDefaultLocale, useEnableI18n, useFormatLocales, useGT, useLocale, useLocaleDirection, useLocaleProperties, useLocaleSelector, useLocales, useMessages, useRegion, useRegionSelector, useSetEnableI18n, useSetLocale, useSetRegion, useTranslations };
776
-
777
- //# sourceMappingURL=index.types.mjs.map