@teactjs/runtime 0.1.0-alpha.5 → 0.1.0-alpha.6

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.
Files changed (2) hide show
  1. package/dist/index.js +35 -2845
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -848,65 +848,6 @@ var require_react = __commonJS((exports, module) => {
848
848
  }
849
849
  });
850
850
 
851
- // ../../node_modules/.bun/use-sync-external-store@1.6.0+b1ab299f0a400331/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js
852
- var require_use_sync_external_store_shim_development = __commonJS((exports) => {
853
- var React6 = __toESM(require_react());
854
- (function() {
855
- function is(x, y) {
856
- return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y;
857
- }
858
- function useSyncExternalStore$2(subscribe, getSnapshot) {
859
- didWarnOld18Alpha || React6.startTransition === undefined || (didWarnOld18Alpha = true, console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));
860
- var value = getSnapshot();
861
- if (!didWarnUncachedGetSnapshot) {
862
- var cachedValue = getSnapshot();
863
- objectIs(value, cachedValue) || (console.error("The result of getSnapshot should be cached to avoid an infinite loop"), didWarnUncachedGetSnapshot = true);
864
- }
865
- cachedValue = useState5({
866
- inst: { value, getSnapshot }
867
- });
868
- var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
869
- useLayoutEffect2(function() {
870
- inst.value = value;
871
- inst.getSnapshot = getSnapshot;
872
- checkIfSnapshotChanged(inst) && forceUpdate({ inst });
873
- }, [subscribe, value, getSnapshot]);
874
- useEffect3(function() {
875
- checkIfSnapshotChanged(inst) && forceUpdate({ inst });
876
- return subscribe(function() {
877
- checkIfSnapshotChanged(inst) && forceUpdate({ inst });
878
- });
879
- }, [subscribe]);
880
- useDebugValue2(value);
881
- return value;
882
- }
883
- function checkIfSnapshotChanged(inst) {
884
- var latestGetSnapshot = inst.getSnapshot;
885
- inst = inst.value;
886
- try {
887
- var nextValue = latestGetSnapshot();
888
- return !objectIs(inst, nextValue);
889
- } catch (error) {
890
- return true;
891
- }
892
- }
893
- function useSyncExternalStore$1(subscribe, getSnapshot) {
894
- return getSnapshot();
895
- }
896
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
897
- var objectIs = typeof Object.is === "function" ? Object.is : is, useState5 = React6.useState, useEffect3 = React6.useEffect, useLayoutEffect2 = React6.useLayoutEffect, useDebugValue2 = React6.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim = typeof window === "undefined" || typeof window.document === "undefined" || typeof window.document.createElement === "undefined" ? useSyncExternalStore$1 : useSyncExternalStore$2;
898
- exports.useSyncExternalStore = React6.useSyncExternalStore !== undefined ? React6.useSyncExternalStore : shim;
899
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
900
- })();
901
- });
902
-
903
- // ../../node_modules/.bun/use-sync-external-store@1.6.0+b1ab299f0a400331/node_modules/use-sync-external-store/shim/index.js
904
- var require_shim = __commonJS((exports, module) => {
905
- if (false) {} else {
906
- module.exports = require_use_sync_external_store_shim_development();
907
- }
908
- });
909
-
910
851
  // src/bot.ts
911
852
  var import_react3 = __toESM(require_react(), 1);
912
853
  import { createRoot } from "@teactjs/renderer";
@@ -2236,2799 +2177,48 @@ function useEventData(event) {
2236
2177
  return extractEventData(event, raw);
2237
2178
  }
2238
2179
  // src/i18n.ts
2239
- var import_react15 = __toESM(require_react(), 1);
2240
-
2241
- // ../../node_modules/.bun/i18next@26.0.3+1fb4c65d43e298b9/node_modules/i18next/dist/esm/i18next.js
2242
- var isString = (obj) => typeof obj === "string";
2243
- var defer = () => {
2244
- let res;
2245
- let rej;
2246
- const promise = new Promise((resolve2, reject) => {
2247
- res = resolve2;
2248
- rej = reject;
2249
- });
2250
- promise.resolve = res;
2251
- promise.reject = rej;
2252
- return promise;
2253
- };
2254
- var makeString = (object) => {
2255
- if (object == null)
2256
- return "";
2257
- return String(object);
2258
- };
2259
- var copy = (a, s, t) => {
2260
- a.forEach((m) => {
2261
- if (s[m])
2262
- t[m] = s[m];
2180
+ var import_react12 = __toESM(require_react(), 1);
2181
+ import i18next from "i18next";
2182
+ import { initReactI18next, useTranslation, I18nextProvider } from "react-i18next";
2183
+ var LocaleCtx = import_react12.createContext(null);
2184
+ function createI18n(config) {
2185
+ const instance = i18next.createInstance();
2186
+ instance.use(initReactI18next).init({
2187
+ resources: config.resources,
2188
+ lng: config.defaultLocale,
2189
+ fallbackLng: config.fallbackLocale ?? config.defaultLocale,
2190
+ interpolation: { escapeValue: false }
2263
2191
  });
2264
- };
2265
- var lastOfPathSeparatorRegExp = /###/g;
2266
- var cleanKey = (key) => key && key.includes("###") ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
2267
- var canNotTraverseDeeper = (object) => !object || isString(object);
2268
- var getLastOfPath = (object, path, Empty) => {
2269
- const stack = !isString(path) ? path : path.split(".");
2270
- let stackIndex = 0;
2271
- while (stackIndex < stack.length - 1) {
2272
- if (canNotTraverseDeeper(object))
2273
- return {};
2274
- const key = cleanKey(stack[stackIndex]);
2275
- if (!object[key] && Empty)
2276
- object[key] = new Empty;
2277
- if (Object.prototype.hasOwnProperty.call(object, key)) {
2278
- object = object[key];
2279
- } else {
2280
- object = {};
2281
- }
2282
- ++stackIndex;
2283
- }
2284
- if (canNotTraverseDeeper(object))
2285
- return {};
2286
- return {
2287
- obj: object,
2288
- k: cleanKey(stack[stackIndex])
2289
- };
2290
- };
2291
- var setPath = (object, path, newValue) => {
2292
- const {
2293
- obj,
2294
- k
2295
- } = getLastOfPath(object, path, Object);
2296
- if (obj !== undefined || path.length === 1) {
2297
- obj[k] = newValue;
2298
- return;
2299
- }
2300
- let e = path[path.length - 1];
2301
- let p = path.slice(0, path.length - 1);
2302
- let last = getLastOfPath(object, p, Object);
2303
- while (last.obj === undefined && p.length) {
2304
- e = `${p[p.length - 1]}.${e}`;
2305
- p = p.slice(0, p.length - 1);
2306
- last = getLastOfPath(object, p, Object);
2307
- if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") {
2308
- last.obj = undefined;
2309
- }
2310
- }
2311
- last.obj[`${last.k}.${e}`] = newValue;
2312
- };
2313
- var pushPath = (object, path, newValue, concat) => {
2314
- const {
2315
- obj,
2316
- k
2317
- } = getLastOfPath(object, path, Object);
2318
- obj[k] = obj[k] || [];
2319
- obj[k].push(newValue);
2320
- };
2321
- var getPath = (object, path) => {
2322
- const {
2323
- obj,
2324
- k
2325
- } = getLastOfPath(object, path);
2326
- if (!obj)
2327
- return;
2328
- if (!Object.prototype.hasOwnProperty.call(obj, k))
2329
- return;
2330
- return obj[k];
2331
- };
2332
- var getPathWithDefaults = (data, defaultData, key) => {
2333
- const value = getPath(data, key);
2334
- if (value !== undefined) {
2335
- return value;
2336
- }
2337
- return getPath(defaultData, key);
2338
- };
2339
- var deepExtend = (target, source, overwrite) => {
2340
- for (const prop in source) {
2341
- if (prop !== "__proto__" && prop !== "constructor") {
2342
- if (prop in target) {
2343
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
2344
- if (overwrite)
2345
- target[prop] = source[prop];
2346
- } else {
2347
- deepExtend(target[prop], source[prop], overwrite);
2348
- }
2349
- } else {
2350
- target[prop] = source[prop];
2351
- }
2352
- }
2353
- }
2354
- return target;
2355
- };
2356
- var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
2357
- var _entityMap = {
2358
- "&": "&amp;",
2359
- "<": "&lt;",
2360
- ">": "&gt;",
2361
- '"': "&quot;",
2362
- "'": "&#39;",
2363
- "/": "&#x2F;"
2364
- };
2365
- var escape = (data) => {
2366
- if (isString(data)) {
2367
- return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
2368
- }
2369
- return data;
2370
- };
2371
-
2372
- class RegExpCache {
2373
- constructor(capacity) {
2374
- this.capacity = capacity;
2375
- this.regExpMap = new Map;
2376
- this.regExpQueue = [];
2377
- }
2378
- getRegExp(pattern) {
2379
- const regExpFromCache = this.regExpMap.get(pattern);
2380
- if (regExpFromCache !== undefined) {
2381
- return regExpFromCache;
2382
- }
2383
- const regExpNew = new RegExp(pattern);
2384
- if (this.regExpQueue.length === this.capacity) {
2385
- this.regExpMap.delete(this.regExpQueue.shift());
2386
- }
2387
- this.regExpMap.set(pattern, regExpNew);
2388
- this.regExpQueue.push(pattern);
2389
- return regExpNew;
2390
- }
2391
- }
2392
- var chars = [" ", ",", "?", "!", ";"];
2393
- var looksLikeObjectPathRegExpCache = new RegExpCache(20);
2394
- var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
2395
- nsSeparator = nsSeparator || "";
2396
- keySeparator = keySeparator || "";
2397
- const possibleChars = chars.filter((c) => !nsSeparator.includes(c) && !keySeparator.includes(c));
2398
- if (possibleChars.length === 0)
2399
- return true;
2400
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
2401
- let matched = !r.test(key);
2402
- if (!matched) {
2403
- const ki = key.indexOf(keySeparator);
2404
- if (ki > 0 && !r.test(key.substring(0, ki))) {
2405
- matched = true;
2406
- }
2407
- }
2408
- return matched;
2409
- };
2410
- var deepFind = (obj, path, keySeparator = ".") => {
2411
- if (!obj)
2412
- return;
2413
- if (obj[path]) {
2414
- if (!Object.prototype.hasOwnProperty.call(obj, path))
2415
- return;
2416
- return obj[path];
2417
- }
2418
- const tokens = path.split(keySeparator);
2419
- let current = obj;
2420
- for (let i = 0;i < tokens.length; ) {
2421
- if (!current || typeof current !== "object") {
2422
- return;
2423
- }
2424
- let next;
2425
- let nextPath = "";
2426
- for (let j = i;j < tokens.length; ++j) {
2427
- if (j !== i) {
2428
- nextPath += keySeparator;
2429
- }
2430
- nextPath += tokens[j];
2431
- next = current[nextPath];
2432
- if (next !== undefined) {
2433
- if (["string", "number", "boolean"].includes(typeof next) && j < tokens.length - 1) {
2434
- continue;
2435
- }
2436
- i += j - i + 1;
2437
- break;
2438
- }
2439
- }
2440
- current = next;
2441
- }
2442
- return current;
2443
- };
2444
- var getCleanedCode = (code) => code?.replace(/_/g, "-");
2445
- var consoleLogger = {
2446
- type: "logger",
2447
- log(args) {
2448
- this.output("log", args);
2449
- },
2450
- warn(args) {
2451
- this.output("warn", args);
2452
- },
2453
- error(args) {
2454
- this.output("error", args);
2455
- },
2456
- output(type, args) {
2457
- console?.[type]?.apply?.(console, args);
2458
- }
2459
- };
2460
-
2461
- class Logger {
2462
- constructor(concreteLogger, options = {}) {
2463
- this.init(concreteLogger, options);
2464
- }
2465
- init(concreteLogger, options = {}) {
2466
- this.prefix = options.prefix || "i18next:";
2467
- this.logger = concreteLogger || consoleLogger;
2468
- this.options = options;
2469
- this.debug = options.debug;
2470
- }
2471
- log(...args) {
2472
- return this.forward(args, "log", "", true);
2473
- }
2474
- warn(...args) {
2475
- return this.forward(args, "warn", "", true);
2476
- }
2477
- error(...args) {
2478
- return this.forward(args, "error", "");
2479
- }
2480
- deprecate(...args) {
2481
- return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
2482
- }
2483
- forward(args, lvl, prefix, debugOnly) {
2484
- if (debugOnly && !this.debug)
2485
- return null;
2486
- if (isString(args[0]))
2487
- args[0] = `${prefix}${this.prefix} ${args[0]}`;
2488
- return this.logger[lvl](args);
2489
- }
2490
- create(moduleName) {
2491
- return new Logger(this.logger, {
2492
- ...{
2493
- prefix: `${this.prefix}:${moduleName}:`
2494
- },
2495
- ...this.options
2496
- });
2497
- }
2498
- clone(options) {
2499
- options = options || this.options;
2500
- options.prefix = options.prefix || this.prefix;
2501
- return new Logger(this.logger, options);
2502
- }
2503
- }
2504
- var baseLogger = new Logger;
2505
-
2506
- class EventEmitter {
2507
- constructor() {
2508
- this.observers = {};
2509
- }
2510
- on(events, listener) {
2511
- events.split(" ").forEach((event) => {
2512
- if (!this.observers[event])
2513
- this.observers[event] = new Map;
2514
- const numListeners = this.observers[event].get(listener) || 0;
2515
- this.observers[event].set(listener, numListeners + 1);
2516
- });
2517
- return this;
2518
- }
2519
- off(event, listener) {
2520
- if (!this.observers[event])
2521
- return;
2522
- if (!listener) {
2523
- delete this.observers[event];
2524
- return;
2525
- }
2526
- this.observers[event].delete(listener);
2527
- }
2528
- once(event, listener) {
2529
- const wrapper = (...args) => {
2530
- listener(...args);
2531
- this.off(event, wrapper);
2532
- };
2533
- this.on(event, wrapper);
2534
- return this;
2535
- }
2536
- emit(event, ...args) {
2537
- if (this.observers[event]) {
2538
- const cloned = Array.from(this.observers[event].entries());
2539
- cloned.forEach(([observer, numTimesAdded]) => {
2540
- for (let i = 0;i < numTimesAdded; i++) {
2541
- observer(...args);
2542
- }
2543
- });
2544
- }
2545
- if (this.observers["*"]) {
2546
- const cloned = Array.from(this.observers["*"].entries());
2547
- cloned.forEach(([observer, numTimesAdded]) => {
2548
- for (let i = 0;i < numTimesAdded; i++) {
2549
- observer(event, ...args);
2550
- }
2551
- });
2552
- }
2553
- }
2554
- }
2555
-
2556
- class ResourceStore extends EventEmitter {
2557
- constructor(data, options = {
2558
- ns: ["translation"],
2559
- defaultNS: "translation"
2560
- }) {
2561
- super();
2562
- this.data = data || {};
2563
- this.options = options;
2564
- if (this.options.keySeparator === undefined) {
2565
- this.options.keySeparator = ".";
2566
- }
2567
- if (this.options.ignoreJSONStructure === undefined) {
2568
- this.options.ignoreJSONStructure = true;
2569
- }
2570
- }
2571
- addNamespaces(ns) {
2572
- if (!this.options.ns.includes(ns)) {
2573
- this.options.ns.push(ns);
2574
- }
2575
- }
2576
- removeNamespaces(ns) {
2577
- const index = this.options.ns.indexOf(ns);
2578
- if (index > -1) {
2579
- this.options.ns.splice(index, 1);
2580
- }
2581
- }
2582
- getResource(lng, ns, key, options = {}) {
2583
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
2584
- const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
2585
- let path;
2586
- if (lng.includes(".")) {
2587
- path = lng.split(".");
2588
- } else {
2589
- path = [lng, ns];
2590
- if (key) {
2591
- if (Array.isArray(key)) {
2592
- path.push(...key);
2593
- } else if (isString(key) && keySeparator) {
2594
- path.push(...key.split(keySeparator));
2595
- } else {
2596
- path.push(key);
2597
- }
2598
- }
2599
- }
2600
- const result = getPath(this.data, path);
2601
- if (!result && !ns && !key && lng.includes(".")) {
2602
- lng = path[0];
2603
- ns = path[1];
2604
- key = path.slice(2).join(".");
2605
- }
2606
- if (result || !ignoreJSONStructure || !isString(key))
2607
- return result;
2608
- return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
2609
- }
2610
- addResource(lng, ns, key, value, options = {
2611
- silent: false
2612
- }) {
2613
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
2614
- let path = [lng, ns];
2615
- if (key)
2616
- path = path.concat(keySeparator ? key.split(keySeparator) : key);
2617
- if (lng.includes(".")) {
2618
- path = lng.split(".");
2619
- value = ns;
2620
- ns = path[1];
2621
- }
2622
- this.addNamespaces(ns);
2623
- setPath(this.data, path, value);
2624
- if (!options.silent)
2625
- this.emit("added", lng, ns, key, value);
2626
- }
2627
- addResources(lng, ns, resources, options = {
2628
- silent: false
2629
- }) {
2630
- for (const m in resources) {
2631
- if (isString(resources[m]) || Array.isArray(resources[m]))
2632
- this.addResource(lng, ns, m, resources[m], {
2633
- silent: true
2634
- });
2635
- }
2636
- if (!options.silent)
2637
- this.emit("added", lng, ns, resources);
2638
- }
2639
- addResourceBundle(lng, ns, resources, deep, overwrite, options = {
2640
- silent: false,
2641
- skipCopy: false
2642
- }) {
2643
- let path = [lng, ns];
2644
- if (lng.includes(".")) {
2645
- path = lng.split(".");
2646
- deep = resources;
2647
- resources = ns;
2648
- ns = path[1];
2649
- }
2650
- this.addNamespaces(ns);
2651
- let pack = getPath(this.data, path) || {};
2652
- if (!options.skipCopy)
2653
- resources = JSON.parse(JSON.stringify(resources));
2654
- if (deep) {
2655
- deepExtend(pack, resources, overwrite);
2656
- } else {
2657
- pack = {
2658
- ...pack,
2659
- ...resources
2660
- };
2661
- }
2662
- setPath(this.data, path, pack);
2663
- if (!options.silent)
2664
- this.emit("added", lng, ns, resources);
2665
- }
2666
- removeResourceBundle(lng, ns) {
2667
- if (this.hasResourceBundle(lng, ns)) {
2668
- delete this.data[lng][ns];
2669
- }
2670
- this.removeNamespaces(ns);
2671
- this.emit("removed", lng, ns);
2672
- }
2673
- hasResourceBundle(lng, ns) {
2674
- return this.getResource(lng, ns) !== undefined;
2675
- }
2676
- getResourceBundle(lng, ns) {
2677
- if (!ns)
2678
- ns = this.options.defaultNS;
2679
- return this.getResource(lng, ns);
2680
- }
2681
- getDataByLanguage(lng) {
2682
- return this.data[lng];
2683
- }
2684
- hasLanguageSomeTranslations(lng) {
2685
- const data = this.getDataByLanguage(lng);
2686
- const n = data && Object.keys(data) || [];
2687
- return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
2688
- }
2689
- toJSON() {
2690
- return this.data;
2192
+ function Provider({ children }) {
2193
+ const [locale, setLocaleState] = import_react12.useState(config.defaultLocale);
2194
+ const setLocale = import_react12.useCallback((lng) => {
2195
+ setLocaleState(lng);
2196
+ }, []);
2197
+ const ctxValue = import_react12.useMemo(() => ({ locale, setLocale }), [locale, setLocale]);
2198
+ return import_react12.default.createElement(LocaleCtx.Provider, { value: ctxValue }, import_react12.default.createElement(I18nextProvider, { i18n: instance }, children));
2691
2199
  }
2200
+ return { Provider, instance };
2692
2201
  }
2693
- var postProcessor = {
2694
- processors: {},
2695
- addPostProcessor(module) {
2696
- this.processors[module.name] = module;
2697
- },
2698
- handle(processors, value, key, options, translator) {
2699
- processors.forEach((processor) => {
2700
- value = this.processors[processor]?.process(value, key, options, translator) ?? value;
2701
- });
2702
- return value;
2703
- }
2704
- };
2705
- var PATH_KEY = Symbol("i18next/PATH_KEY");
2706
- function createProxy() {
2707
- const state = [];
2708
- const handler = Object.create(null);
2709
- let proxy;
2710
- handler.get = (target, key) => {
2711
- proxy?.revoke?.();
2712
- if (key === PATH_KEY)
2713
- return state;
2714
- state.push(key);
2715
- proxy = Proxy.revocable(target, handler);
2716
- return proxy.proxy;
2717
- };
2718
- return Proxy.revocable(Object.create(null), handler).proxy;
2719
- }
2720
- function keysFromSelector(selector, opts) {
2721
- const {
2722
- [PATH_KEY]: path
2723
- } = selector(createProxy());
2724
- const keySeparator = opts?.keySeparator ?? ".";
2725
- const nsSeparator = opts?.nsSeparator ?? ":";
2726
- if (path.length > 1 && nsSeparator) {
2727
- const ns = opts?.ns;
2728
- const nsArray = Array.isArray(ns) ? ns : null;
2729
- if (nsArray && nsArray.length > 1 && nsArray.slice(1).includes(path[0])) {
2730
- return `${path[0]}${nsSeparator}${path.slice(1).join(keySeparator)}`;
2731
- }
2732
- }
2733
- return path.join(keySeparator);
2734
- }
2735
- var shouldHandleAsObject = (res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number";
2736
-
2737
- class Translator extends EventEmitter {
2738
- constructor(services, options = {}) {
2739
- super();
2740
- copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
2741
- this.options = options;
2742
- if (this.options.keySeparator === undefined) {
2743
- this.options.keySeparator = ".";
2744
- }
2745
- this.logger = baseLogger.create("translator");
2746
- this.checkedLoadedFor = {};
2747
- }
2748
- changeLanguage(lng) {
2749
- if (lng)
2750
- this.language = lng;
2751
- }
2752
- exists(key, o = {
2753
- interpolation: {}
2754
- }) {
2755
- const opt = {
2756
- ...o
2757
- };
2758
- if (key == null)
2759
- return false;
2760
- const resolved = this.resolve(key, opt);
2761
- if (resolved?.res === undefined)
2762
- return false;
2763
- const isObject = shouldHandleAsObject(resolved.res);
2764
- if (opt.returnObjects === false && isObject) {
2765
- return false;
2766
- }
2767
- return true;
2768
- }
2769
- extractFromKey(key, opt) {
2770
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
2771
- if (nsSeparator === undefined)
2772
- nsSeparator = ":";
2773
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
2774
- let namespaces = opt.ns || this.options.defaultNS || [];
2775
- const wouldCheckForNsInKey = nsSeparator && key.includes(nsSeparator);
2776
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
2777
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
2778
- const m = key.match(this.interpolator.nestingRegexp);
2779
- if (m && m.length > 0) {
2780
- return {
2781
- key,
2782
- namespaces: isString(namespaces) ? [namespaces] : namespaces
2783
- };
2784
- }
2785
- const parts = key.split(nsSeparator);
2786
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.includes(parts[0]))
2787
- namespaces = parts.shift();
2788
- key = parts.join(keySeparator);
2789
- }
2790
- return {
2791
- key,
2792
- namespaces: isString(namespaces) ? [namespaces] : namespaces
2793
- };
2794
- }
2795
- translate(keys, o, lastKey) {
2796
- let opt = typeof o === "object" ? {
2797
- ...o
2798
- } : o;
2799
- if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) {
2800
- opt = this.options.overloadTranslationOptionHandler(arguments);
2801
- }
2802
- if (typeof opt === "object")
2803
- opt = {
2804
- ...opt
2805
- };
2806
- if (!opt)
2807
- opt = {};
2808
- if (keys == null)
2809
- return "";
2810
- if (typeof keys === "function")
2811
- keys = keysFromSelector(keys, {
2812
- ...this.options,
2813
- ...opt
2814
- });
2815
- if (!Array.isArray(keys))
2816
- keys = [String(keys)];
2817
- keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
2818
- ...this.options,
2819
- ...opt
2820
- }) : String(k));
2821
- const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
2822
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
2823
- const {
2824
- key,
2825
- namespaces
2826
- } = this.extractFromKey(keys[keys.length - 1], opt);
2827
- const namespace = namespaces[namespaces.length - 1];
2828
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
2829
- if (nsSeparator === undefined)
2830
- nsSeparator = ":";
2831
- const lng = opt.lng || this.language;
2832
- const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
2833
- if (lng?.toLowerCase() === "cimode") {
2834
- if (appendNamespaceToCIMode) {
2835
- if (returnDetails) {
2836
- return {
2837
- res: `${namespace}${nsSeparator}${key}`,
2838
- usedKey: key,
2839
- exactUsedKey: key,
2840
- usedLng: lng,
2841
- usedNS: namespace,
2842
- usedParams: this.getUsedParamsDetails(opt)
2843
- };
2844
- }
2845
- return `${namespace}${nsSeparator}${key}`;
2846
- }
2847
- if (returnDetails) {
2848
- return {
2849
- res: key,
2850
- usedKey: key,
2851
- exactUsedKey: key,
2852
- usedLng: lng,
2853
- usedNS: namespace,
2854
- usedParams: this.getUsedParamsDetails(opt)
2855
- };
2856
- }
2857
- return key;
2858
- }
2859
- const resolved = this.resolve(keys, opt);
2860
- let res = resolved?.res;
2861
- const resUsedKey = resolved?.usedKey || key;
2862
- const resExactUsedKey = resolved?.exactUsedKey || key;
2863
- const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
2864
- const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
2865
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
2866
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
2867
- const hasDefaultValue = Translator.hasDefaultValue(opt);
2868
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : "";
2869
- const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
2870
- ordinal: false
2871
- }) : "";
2872
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
2873
- const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
2874
- let resForObjHndl = res;
2875
- if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
2876
- resForObjHndl = defaultValue;
2877
- }
2878
- const handleAsObject = shouldHandleAsObject(resForObjHndl);
2879
- const resType = Object.prototype.toString.apply(resForObjHndl);
2880
- if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && !noObject.includes(resType) && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
2881
- if (!opt.returnObjects && !this.options.returnObjects) {
2882
- if (!this.options.returnedObjectHandler) {
2883
- this.logger.warn("accessing an object - but returnObjects options is not enabled!");
2884
- }
2885
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
2886
- ...opt,
2887
- ns: namespaces
2888
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
2889
- if (returnDetails) {
2890
- resolved.res = r;
2891
- resolved.usedParams = this.getUsedParamsDetails(opt);
2892
- return resolved;
2893
- }
2894
- return r;
2895
- }
2896
- if (keySeparator) {
2897
- const resTypeIsArray = Array.isArray(resForObjHndl);
2898
- const copy2 = resTypeIsArray ? [] : {};
2899
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
2900
- for (const m in resForObjHndl) {
2901
- if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
2902
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
2903
- if (hasDefaultValue && !res) {
2904
- copy2[m] = this.translate(deepKey, {
2905
- ...opt,
2906
- defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
2907
- ...{
2908
- joinArrays: false,
2909
- ns: namespaces
2910
- }
2911
- });
2912
- } else {
2913
- copy2[m] = this.translate(deepKey, {
2914
- ...opt,
2915
- ...{
2916
- joinArrays: false,
2917
- ns: namespaces
2918
- }
2919
- });
2920
- }
2921
- if (copy2[m] === deepKey)
2922
- copy2[m] = resForObjHndl[m];
2923
- }
2924
- }
2925
- res = copy2;
2926
- }
2927
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
2928
- res = res.join(joinArrays);
2929
- if (res)
2930
- res = this.extendTranslation(res, keys, opt, lastKey);
2931
- } else {
2932
- let usedDefault = false;
2933
- let usedKey = false;
2934
- if (!this.isValidLookup(res) && hasDefaultValue) {
2935
- usedDefault = true;
2936
- res = defaultValue;
2937
- }
2938
- if (!this.isValidLookup(res)) {
2939
- usedKey = true;
2940
- res = key;
2941
- }
2942
- const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
2943
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
2944
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
2945
- if (usedKey || usedDefault || updateMissing) {
2946
- this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
2947
- if (keySeparator) {
2948
- const fk = this.resolve(key, {
2949
- ...opt,
2950
- keySeparator: false
2951
- });
2952
- if (fk && fk.res)
2953
- this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
2954
- }
2955
- let lngs = [];
2956
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
2957
- if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
2958
- for (let i = 0;i < fallbackLngs.length; i++) {
2959
- lngs.push(fallbackLngs[i]);
2960
- }
2961
- } else if (this.options.saveMissingTo === "all") {
2962
- lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
2963
- } else {
2964
- lngs.push(opt.lng || this.language);
2965
- }
2966
- const send = (l, k, specificDefaultValue) => {
2967
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
2968
- if (this.options.missingKeyHandler) {
2969
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
2970
- } else if (this.backendConnector?.saveMissing) {
2971
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
2972
- }
2973
- this.emit("missingKey", l, namespace, k, res);
2974
- };
2975
- if (this.options.saveMissing) {
2976
- if (this.options.saveMissingPlurals && needsPluralHandling) {
2977
- lngs.forEach((language) => {
2978
- const suffixes = this.pluralResolver.getSuffixes(language, opt);
2979
- if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && !suffixes.includes(`${this.options.pluralSeparator}zero`)) {
2980
- suffixes.push(`${this.options.pluralSeparator}zero`);
2981
- }
2982
- suffixes.forEach((suffix) => {
2983
- send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
2984
- });
2985
- });
2986
- } else {
2987
- send(lngs, key, defaultValue);
2988
- }
2989
- }
2990
- }
2991
- res = this.extendTranslation(res, keys, opt, resolved, lastKey);
2992
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
2993
- res = `${namespace}${nsSeparator}${key}`;
2994
- }
2995
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
2996
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
2997
- }
2998
- }
2999
- if (returnDetails) {
3000
- resolved.res = res;
3001
- resolved.usedParams = this.getUsedParamsDetails(opt);
3002
- return resolved;
3003
- }
3004
- return res;
3005
- }
3006
- extendTranslation(res, key, opt, resolved, lastKey) {
3007
- if (this.i18nFormat?.parse) {
3008
- res = this.i18nFormat.parse(res, {
3009
- ...this.options.interpolation.defaultVariables,
3010
- ...opt
3011
- }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
3012
- resolved
3013
- });
3014
- } else if (!opt.skipInterpolation) {
3015
- if (opt.interpolation)
3016
- this.interpolator.init({
3017
- ...opt,
3018
- ...{
3019
- interpolation: {
3020
- ...this.options.interpolation,
3021
- ...opt.interpolation
3022
- }
3023
- }
3024
- });
3025
- const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
3026
- let nestBef;
3027
- if (skipOnVariables) {
3028
- const nb = res.match(this.interpolator.nestingRegexp);
3029
- nestBef = nb && nb.length;
3030
- }
3031
- let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
3032
- if (this.options.interpolation.defaultVariables)
3033
- data = {
3034
- ...this.options.interpolation.defaultVariables,
3035
- ...data
3036
- };
3037
- res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
3038
- if (skipOnVariables) {
3039
- const na = res.match(this.interpolator.nestingRegexp);
3040
- const nestAft = na && na.length;
3041
- if (nestBef < nestAft)
3042
- opt.nest = false;
3043
- }
3044
- if (!opt.lng && resolved && resolved.res)
3045
- opt.lng = this.language || resolved.usedLng;
3046
- if (opt.nest !== false)
3047
- res = this.interpolator.nest(res, (...args) => {
3048
- if (lastKey?.[0] === args[0] && !opt.context) {
3049
- this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
3050
- return null;
3051
- }
3052
- return this.translate(...args, key);
3053
- }, opt);
3054
- if (opt.interpolation)
3055
- this.interpolator.reset();
3056
- }
3057
- const postProcess = opt.postProcess || this.options.postProcess;
3058
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
3059
- if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
3060
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
3061
- i18nResolved: {
3062
- ...resolved,
3063
- usedParams: this.getUsedParamsDetails(opt)
3064
- },
3065
- ...opt
3066
- } : opt, this);
3067
- }
3068
- return res;
3069
- }
3070
- resolve(keys, opt = {}) {
3071
- let found;
3072
- let usedKey;
3073
- let exactUsedKey;
3074
- let usedLng;
3075
- let usedNS;
3076
- if (isString(keys))
3077
- keys = [keys];
3078
- if (Array.isArray(keys))
3079
- keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
3080
- ...this.options,
3081
- ...opt
3082
- }) : k);
3083
- keys.forEach((k) => {
3084
- if (this.isValidLookup(found))
3085
- return;
3086
- const extracted = this.extractFromKey(k, opt);
3087
- const key = extracted.key;
3088
- usedKey = key;
3089
- let namespaces = extracted.namespaces;
3090
- if (this.options.fallbackNS)
3091
- namespaces = namespaces.concat(this.options.fallbackNS);
3092
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
3093
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
3094
- const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === "number") && opt.context !== "";
3095
- const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
3096
- namespaces.forEach((ns) => {
3097
- if (this.isValidLookup(found))
3098
- return;
3099
- usedNS = ns;
3100
- if (!this.checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
3101
- this.checkedLoadedFor[`${codes[0]}-${ns}`] = true;
3102
- this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
3103
- }
3104
- codes.forEach((code) => {
3105
- if (this.isValidLookup(found))
3106
- return;
3107
- usedLng = code;
3108
- const finalKeys = [key];
3109
- if (this.i18nFormat?.addLookupKeys) {
3110
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
3111
- } else {
3112
- let pluralSuffix;
3113
- if (needsPluralHandling)
3114
- pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
3115
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
3116
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
3117
- if (needsPluralHandling) {
3118
- if (opt.ordinal && pluralSuffix.startsWith(ordinalPrefix)) {
3119
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
3120
- }
3121
- finalKeys.push(key + pluralSuffix);
3122
- if (needsZeroSuffixLookup) {
3123
- finalKeys.push(key + zeroSuffix);
3124
- }
3125
- }
3126
- if (needsContextHandling) {
3127
- const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`;
3128
- finalKeys.push(contextKey);
3129
- if (needsPluralHandling) {
3130
- if (opt.ordinal && pluralSuffix.startsWith(ordinalPrefix)) {
3131
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
3132
- }
3133
- finalKeys.push(contextKey + pluralSuffix);
3134
- if (needsZeroSuffixLookup) {
3135
- finalKeys.push(contextKey + zeroSuffix);
3136
- }
3137
- }
3138
- }
3139
- }
3140
- let possibleKey;
3141
- while (possibleKey = finalKeys.pop()) {
3142
- if (!this.isValidLookup(found)) {
3143
- exactUsedKey = possibleKey;
3144
- found = this.getResource(code, ns, possibleKey, opt);
3145
- }
3146
- }
3147
- });
3148
- });
3149
- });
3150
- return {
3151
- res: found,
3152
- usedKey,
3153
- exactUsedKey,
3154
- usedLng,
3155
- usedNS
3156
- };
3157
- }
3158
- isValidLookup(res) {
3159
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
3160
- }
3161
- getResource(code, ns, key, options = {}) {
3162
- if (this.i18nFormat?.getResource)
3163
- return this.i18nFormat.getResource(code, ns, key, options);
3164
- return this.resourceStore.getResource(code, ns, key, options);
3165
- }
3166
- getUsedParamsDetails(options = {}) {
3167
- const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
3168
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
3169
- let data = useOptionsReplaceForData ? options.replace : options;
3170
- if (useOptionsReplaceForData && typeof options.count !== "undefined") {
3171
- data.count = options.count;
3172
- }
3173
- if (this.options.interpolation.defaultVariables) {
3174
- data = {
3175
- ...this.options.interpolation.defaultVariables,
3176
- ...data
3177
- };
3178
- }
3179
- if (!useOptionsReplaceForData) {
3180
- data = {
3181
- ...data
3182
- };
3183
- for (const key of optionsKeys) {
3184
- delete data[key];
3185
- }
3186
- }
3187
- return data;
3188
- }
3189
- static hasDefaultValue(options) {
3190
- const prefix = "defaultValue";
3191
- for (const option in options) {
3192
- if (Object.prototype.hasOwnProperty.call(options, option) && option.startsWith(prefix) && options[option] !== undefined) {
3193
- return true;
3194
- }
3195
- }
3196
- return false;
3197
- }
3198
- }
3199
-
3200
- class LanguageUtil {
3201
- constructor(options) {
3202
- this.options = options;
3203
- this.supportedLngs = this.options.supportedLngs || false;
3204
- this.logger = baseLogger.create("languageUtils");
3205
- }
3206
- getScriptPartFromCode(code) {
3207
- code = getCleanedCode(code);
3208
- if (!code || !code.includes("-"))
3209
- return null;
3210
- const p = code.split("-");
3211
- if (p.length === 2)
3212
- return null;
3213
- p.pop();
3214
- if (p[p.length - 1].toLowerCase() === "x")
3215
- return null;
3216
- return this.formatLanguageCode(p.join("-"));
3217
- }
3218
- getLanguagePartFromCode(code) {
3219
- code = getCleanedCode(code);
3220
- if (!code || !code.includes("-"))
3221
- return code;
3222
- const p = code.split("-");
3223
- return this.formatLanguageCode(p[0]);
3224
- }
3225
- formatLanguageCode(code) {
3226
- if (isString(code) && code.includes("-")) {
3227
- let formattedCode;
3228
- try {
3229
- formattedCode = Intl.getCanonicalLocales(code)[0];
3230
- } catch (e) {}
3231
- if (formattedCode && this.options.lowerCaseLng) {
3232
- formattedCode = formattedCode.toLowerCase();
3233
- }
3234
- if (formattedCode)
3235
- return formattedCode;
3236
- if (this.options.lowerCaseLng) {
3237
- return code.toLowerCase();
3238
- }
3239
- return code;
3240
- }
3241
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
3242
- }
3243
- isSupportedCode(code) {
3244
- if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
3245
- code = this.getLanguagePartFromCode(code);
3246
- }
3247
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.includes(code);
3248
- }
3249
- getBestMatchFromCodes(codes) {
3250
- if (!codes)
3251
- return null;
3252
- let found;
3253
- codes.forEach((code) => {
3254
- if (found)
3255
- return;
3256
- const cleanedLng = this.formatLanguageCode(code);
3257
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng))
3258
- found = cleanedLng;
3259
- });
3260
- if (!found && this.options.supportedLngs) {
3261
- codes.forEach((code) => {
3262
- if (found)
3263
- return;
3264
- const lngScOnly = this.getScriptPartFromCode(code);
3265
- if (this.isSupportedCode(lngScOnly))
3266
- return found = lngScOnly;
3267
- const lngOnly = this.getLanguagePartFromCode(code);
3268
- if (this.isSupportedCode(lngOnly))
3269
- return found = lngOnly;
3270
- found = this.options.supportedLngs.find((supportedLng) => {
3271
- if (supportedLng === lngOnly)
3272
- return true;
3273
- if (!supportedLng.includes("-") && !lngOnly.includes("-"))
3274
- return false;
3275
- if (supportedLng.includes("-") && !lngOnly.includes("-") && supportedLng.slice(0, supportedLng.indexOf("-")) === lngOnly)
3276
- return true;
3277
- if (supportedLng.startsWith(lngOnly) && lngOnly.length > 1)
3278
- return true;
3279
- return false;
3280
- });
3281
- });
3282
- }
3283
- if (!found)
3284
- found = this.getFallbackCodes(this.options.fallbackLng)[0];
3285
- return found;
3286
- }
3287
- getFallbackCodes(fallbacks, code) {
3288
- if (!fallbacks)
3289
- return [];
3290
- if (typeof fallbacks === "function")
3291
- fallbacks = fallbacks(code);
3292
- if (isString(fallbacks))
3293
- fallbacks = [fallbacks];
3294
- if (Array.isArray(fallbacks))
3295
- return fallbacks;
3296
- if (!code)
3297
- return fallbacks.default || [];
3298
- let found = fallbacks[code];
3299
- if (!found)
3300
- found = fallbacks[this.getScriptPartFromCode(code)];
3301
- if (!found)
3302
- found = fallbacks[this.formatLanguageCode(code)];
3303
- if (!found)
3304
- found = fallbacks[this.getLanguagePartFromCode(code)];
3305
- if (!found)
3306
- found = fallbacks.default;
3307
- return found || [];
3308
- }
3309
- toResolveHierarchy(code, fallbackCode) {
3310
- const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
3311
- const codes = [];
3312
- const addCode = (c) => {
3313
- if (!c)
3314
- return;
3315
- if (this.isSupportedCode(c)) {
3316
- codes.push(c);
3317
- } else {
3318
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
3319
- }
3320
- };
3321
- if (isString(code) && (code.includes("-") || code.includes("_"))) {
3322
- if (this.options.load !== "languageOnly")
3323
- addCode(this.formatLanguageCode(code));
3324
- if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly")
3325
- addCode(this.getScriptPartFromCode(code));
3326
- if (this.options.load !== "currentOnly")
3327
- addCode(this.getLanguagePartFromCode(code));
3328
- } else if (isString(code)) {
3329
- addCode(this.formatLanguageCode(code));
3330
- }
3331
- fallbackCodes.forEach((fc) => {
3332
- if (!codes.includes(fc))
3333
- addCode(this.formatLanguageCode(fc));
3334
- });
3335
- return codes;
3336
- }
3337
- }
3338
- var suffixesOrder = {
3339
- zero: 0,
3340
- one: 1,
3341
- two: 2,
3342
- few: 3,
3343
- many: 4,
3344
- other: 5
3345
- };
3346
- var dummyRule = {
3347
- select: (count) => count === 1 ? "one" : "other",
3348
- resolvedOptions: () => ({
3349
- pluralCategories: ["one", "other"]
3350
- })
3351
- };
3352
-
3353
- class PluralResolver {
3354
- constructor(languageUtils, options = {}) {
3355
- this.languageUtils = languageUtils;
3356
- this.options = options;
3357
- this.logger = baseLogger.create("pluralResolver");
3358
- this.pluralRulesCache = {};
3359
- }
3360
- clearCache() {
3361
- this.pluralRulesCache = {};
3362
- }
3363
- getRule(code, options = {}) {
3364
- const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
3365
- const type = options.ordinal ? "ordinal" : "cardinal";
3366
- const cacheKey = JSON.stringify({
3367
- cleanedCode,
3368
- type
3369
- });
3370
- if (cacheKey in this.pluralRulesCache) {
3371
- return this.pluralRulesCache[cacheKey];
3372
- }
3373
- let rule;
3374
- try {
3375
- rule = new Intl.PluralRules(cleanedCode, {
3376
- type
3377
- });
3378
- } catch (err) {
3379
- if (typeof Intl === "undefined") {
3380
- this.logger.error("No Intl support, please use an Intl polyfill!");
3381
- return dummyRule;
3382
- }
3383
- if (!code.match(/-|_/))
3384
- return dummyRule;
3385
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
3386
- rule = this.getRule(lngPart, options);
3387
- }
3388
- this.pluralRulesCache[cacheKey] = rule;
3389
- return rule;
3390
- }
3391
- needsPlural(code, options = {}) {
3392
- let rule = this.getRule(code, options);
3393
- if (!rule)
3394
- rule = this.getRule("dev", options);
3395
- return rule?.resolvedOptions().pluralCategories.length > 1;
3396
- }
3397
- getPluralFormsOfKey(code, key, options = {}) {
3398
- return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
3399
- }
3400
- getSuffixes(code, options = {}) {
3401
- let rule = this.getRule(code, options);
3402
- if (!rule)
3403
- rule = this.getRule("dev", options);
3404
- if (!rule)
3405
- return [];
3406
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
3407
- }
3408
- getSuffix(code, count, options = {}) {
3409
- const rule = this.getRule(code, options);
3410
- if (rule) {
3411
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
3412
- }
3413
- this.logger.warn(`no plural rule found for: ${code}`);
3414
- return this.getSuffix("dev", count, options);
3415
- }
3416
- }
3417
- var deepFindWithDefaults = (data, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => {
3418
- let path = getPathWithDefaults(data, defaultData, key);
3419
- if (!path && ignoreJSONStructure && isString(key)) {
3420
- path = deepFind(data, key, keySeparator);
3421
- if (path === undefined)
3422
- path = deepFind(defaultData, key, keySeparator);
3423
- }
3424
- return path;
3425
- };
3426
- var regexSafe = (val) => val.replace(/\$/g, "$$$$");
3427
-
3428
- class Interpolator {
3429
- constructor(options = {}) {
3430
- this.logger = baseLogger.create("interpolator");
3431
- this.options = options;
3432
- this.format = options?.interpolation?.format || ((value) => value);
3433
- this.init(options);
3434
- }
3435
- init(options = {}) {
3436
- if (!options.interpolation)
3437
- options.interpolation = {
3438
- escapeValue: true
3439
- };
3440
- const {
3441
- escape: escape$1,
3442
- escapeValue,
3443
- useRawValueToEscape,
3444
- prefix,
3445
- prefixEscaped,
3446
- suffix,
3447
- suffixEscaped,
3448
- formatSeparator,
3449
- unescapeSuffix,
3450
- unescapePrefix,
3451
- nestingPrefix,
3452
- nestingPrefixEscaped,
3453
- nestingSuffix,
3454
- nestingSuffixEscaped,
3455
- nestingOptionsSeparator,
3456
- maxReplaces,
3457
- alwaysFormat
3458
- } = options.interpolation;
3459
- this.escape = escape$1 !== undefined ? escape$1 : escape;
3460
- this.escapeValue = escapeValue !== undefined ? escapeValue : true;
3461
- this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
3462
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
3463
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
3464
- this.formatSeparator = formatSeparator || ",";
3465
- this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
3466
- this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
3467
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
3468
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
3469
- this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
3470
- this.maxReplaces = maxReplaces || 1000;
3471
- this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
3472
- this.resetRegExp();
3473
- }
3474
- reset() {
3475
- if (this.options)
3476
- this.init(this.options);
3477
- }
3478
- resetRegExp() {
3479
- const getOrResetRegExp = (existingRegExp, pattern) => {
3480
- if (existingRegExp?.source === pattern) {
3481
- existingRegExp.lastIndex = 0;
3482
- return existingRegExp;
3483
- }
3484
- return new RegExp(pattern, "g");
3485
- };
3486
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
3487
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
3488
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
3489
- }
3490
- interpolate(str, data, lng, options) {
3491
- let match;
3492
- let value;
3493
- let replaces;
3494
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
3495
- const handleFormat = (key) => {
3496
- if (!key.includes(this.formatSeparator)) {
3497
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
3498
- return this.alwaysFormat ? this.format(path, undefined, lng, {
3499
- ...options,
3500
- ...data,
3501
- interpolationkey: key
3502
- }) : path;
3503
- }
3504
- const p = key.split(this.formatSeparator);
3505
- const k = p.shift().trim();
3506
- const f = p.join(this.formatSeparator).trim();
3507
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
3508
- ...options,
3509
- ...data,
3510
- interpolationkey: k
3511
- });
3512
- };
3513
- this.resetRegExp();
3514
- const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
3515
- const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
3516
- const todos = [{
3517
- regex: this.regexpUnescape,
3518
- safeValue: (val) => regexSafe(val)
3519
- }, {
3520
- regex: this.regexp,
3521
- safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
3522
- }];
3523
- todos.forEach((todo) => {
3524
- replaces = 0;
3525
- while (match = todo.regex.exec(str)) {
3526
- const matchedVar = match[1].trim();
3527
- value = handleFormat(matchedVar);
3528
- if (value === undefined) {
3529
- if (typeof missingInterpolationHandler === "function") {
3530
- const temp = missingInterpolationHandler(str, match, options);
3531
- value = isString(temp) ? temp : "";
3532
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
3533
- value = "";
3534
- } else if (skipOnVariables) {
3535
- value = match[0];
3536
- continue;
3537
- } else {
3538
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
3539
- value = "";
3540
- }
3541
- } else if (!isString(value) && !this.useRawValueToEscape) {
3542
- value = makeString(value);
3543
- }
3544
- const safeValue = todo.safeValue(value);
3545
- str = str.replace(match[0], safeValue);
3546
- if (skipOnVariables) {
3547
- todo.regex.lastIndex += value.length;
3548
- todo.regex.lastIndex -= match[0].length;
3549
- } else {
3550
- todo.regex.lastIndex = 0;
3551
- }
3552
- replaces++;
3553
- if (replaces >= this.maxReplaces) {
3554
- break;
3555
- }
3556
- }
3557
- });
3558
- return str;
3559
- }
3560
- nest(str, fc, options = {}) {
3561
- let match;
3562
- let value;
3563
- let clonedOptions;
3564
- const handleHasOptions = (key, inheritedOptions) => {
3565
- const sep = this.nestingOptionsSeparator;
3566
- if (!key.includes(sep))
3567
- return key;
3568
- const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`));
3569
- let optionsString = `{${c[1]}`;
3570
- key = c[0];
3571
- optionsString = this.interpolate(optionsString, clonedOptions);
3572
- const matchedSingleQuotes = optionsString.match(/'/g);
3573
- const matchedDoubleQuotes = optionsString.match(/"/g);
3574
- if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) {
3575
- optionsString = optionsString.replace(/'/g, '"');
3576
- }
3577
- try {
3578
- clonedOptions = JSON.parse(optionsString);
3579
- if (inheritedOptions)
3580
- clonedOptions = {
3581
- ...inheritedOptions,
3582
- ...clonedOptions
3583
- };
3584
- } catch (e) {
3585
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
3586
- return `${key}${sep}${optionsString}`;
3587
- }
3588
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.includes(this.prefix))
3589
- delete clonedOptions.defaultValue;
3590
- return key;
3591
- };
3592
- while (match = this.nestingRegexp.exec(str)) {
3593
- let formatters = [];
3594
- clonedOptions = {
3595
- ...options
3596
- };
3597
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
3598
- clonedOptions.applyPostProcessor = false;
3599
- delete clonedOptions.defaultValue;
3600
- const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf("}") + 1 : match[1].indexOf(this.formatSeparator);
3601
- if (keyEndIndex !== -1) {
3602
- formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean);
3603
- match[1] = match[1].slice(0, keyEndIndex);
3604
- }
3605
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
3606
- if (value && match[0] === str && !isString(value))
3607
- return value;
3608
- if (!isString(value))
3609
- value = makeString(value);
3610
- if (!value) {
3611
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
3612
- value = "";
3613
- }
3614
- if (formatters.length) {
3615
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
3616
- ...options,
3617
- interpolationkey: match[1].trim()
3618
- }), value.trim());
3619
- }
3620
- str = str.replace(match[0], value);
3621
- this.regexp.lastIndex = 0;
3622
- }
3623
- return str;
3624
- }
3625
- }
3626
- var parseFormatStr = (formatStr) => {
3627
- let formatName = formatStr.toLowerCase().trim();
3628
- const formatOptions = {};
3629
- if (formatStr.includes("(")) {
3630
- const p = formatStr.split("(");
3631
- formatName = p[0].toLowerCase().trim();
3632
- const optStr = p[1].slice(0, -1);
3633
- if (formatName === "currency" && !optStr.includes(":")) {
3634
- if (!formatOptions.currency)
3635
- formatOptions.currency = optStr.trim();
3636
- } else if (formatName === "relativetime" && !optStr.includes(":")) {
3637
- if (!formatOptions.range)
3638
- formatOptions.range = optStr.trim();
3639
- } else {
3640
- const opts = optStr.split(";");
3641
- opts.forEach((opt) => {
3642
- if (opt) {
3643
- const [key, ...rest] = opt.split(":");
3644
- const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
3645
- const trimmedKey = key.trim();
3646
- if (!formatOptions[trimmedKey])
3647
- formatOptions[trimmedKey] = val;
3648
- if (val === "false")
3649
- formatOptions[trimmedKey] = false;
3650
- if (val === "true")
3651
- formatOptions[trimmedKey] = true;
3652
- if (!isNaN(val))
3653
- formatOptions[trimmedKey] = parseInt(val, 10);
3654
- }
3655
- });
3656
- }
3657
- }
3658
- return {
3659
- formatName,
3660
- formatOptions
3661
- };
3662
- };
3663
- var createCachedFormatter = (fn) => {
3664
- const cache = {};
3665
- return (v, l, o) => {
3666
- let optForCache = o;
3667
- if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
3668
- optForCache = {
3669
- ...optForCache,
3670
- [o.interpolationkey]: undefined
3671
- };
3672
- }
3673
- const key = l + JSON.stringify(optForCache);
3674
- let frm = cache[key];
3675
- if (!frm) {
3676
- frm = fn(getCleanedCode(l), o);
3677
- cache[key] = frm;
3678
- }
3679
- return frm(v);
3680
- };
3681
- };
3682
- var createNonCachedFormatter = (fn) => (v, l, o) => fn(getCleanedCode(l), o)(v);
3683
-
3684
- class Formatter {
3685
- constructor(options = {}) {
3686
- this.logger = baseLogger.create("formatter");
3687
- this.options = options;
3688
- this.init(options);
3689
- }
3690
- init(services, options = {
3691
- interpolation: {}
3692
- }) {
3693
- this.formatSeparator = options.interpolation.formatSeparator || ",";
3694
- const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
3695
- this.formats = {
3696
- number: cf((lng, opt) => {
3697
- const formatter = new Intl.NumberFormat(lng, {
3698
- ...opt
3699
- });
3700
- return (val) => formatter.format(val);
3701
- }),
3702
- currency: cf((lng, opt) => {
3703
- const formatter = new Intl.NumberFormat(lng, {
3704
- ...opt,
3705
- style: "currency"
3706
- });
3707
- return (val) => formatter.format(val);
3708
- }),
3709
- datetime: cf((lng, opt) => {
3710
- const formatter = new Intl.DateTimeFormat(lng, {
3711
- ...opt
3712
- });
3713
- return (val) => formatter.format(val);
3714
- }),
3715
- relativetime: cf((lng, opt) => {
3716
- const formatter = new Intl.RelativeTimeFormat(lng, {
3717
- ...opt
3718
- });
3719
- return (val) => formatter.format(val, opt.range || "day");
3720
- }),
3721
- list: cf((lng, opt) => {
3722
- const formatter = new Intl.ListFormat(lng, {
3723
- ...opt
3724
- });
3725
- return (val) => formatter.format(val);
3726
- })
3727
- };
3728
- }
3729
- add(name, fc) {
3730
- this.formats[name.toLowerCase().trim()] = fc;
3731
- }
3732
- addCached(name, fc) {
3733
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
3734
- }
3735
- format(value, format, lng, options = {}) {
3736
- if (!format)
3737
- return value;
3738
- if (value == null)
3739
- return value;
3740
- const formats = format.split(this.formatSeparator);
3741
- if (formats.length > 1 && formats[0].indexOf("(") > 1 && !formats[0].includes(")") && formats.find((f) => f.includes(")"))) {
3742
- const lastIndex = formats.findIndex((f) => f.includes(")"));
3743
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
3744
- }
3745
- const result = formats.reduce((mem, f) => {
3746
- const {
3747
- formatName,
3748
- formatOptions
3749
- } = parseFormatStr(f);
3750
- if (this.formats[formatName]) {
3751
- let formatted = mem;
3752
- try {
3753
- const valOptions = options?.formatParams?.[options.interpolationkey] || {};
3754
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
3755
- formatted = this.formats[formatName](mem, l, {
3756
- ...formatOptions,
3757
- ...options,
3758
- ...valOptions
3759
- });
3760
- } catch (error) {
3761
- this.logger.warn(error);
3762
- }
3763
- return formatted;
3764
- } else {
3765
- this.logger.warn(`there was no format function for ${formatName}`);
3766
- }
3767
- return mem;
3768
- }, value);
3769
- return result;
3770
- }
3771
- }
3772
- var removePending = (q, name) => {
3773
- if (q.pending[name] !== undefined) {
3774
- delete q.pending[name];
3775
- q.pendingCount--;
3776
- }
3777
- };
3778
-
3779
- class Connector extends EventEmitter {
3780
- constructor(backend, store, services, options = {}) {
3781
- super();
3782
- this.backend = backend;
3783
- this.store = store;
3784
- this.services = services;
3785
- this.languageUtils = services.languageUtils;
3786
- this.options = options;
3787
- this.logger = baseLogger.create("backendConnector");
3788
- this.waitingReads = [];
3789
- this.maxParallelReads = options.maxParallelReads || 10;
3790
- this.readingCalls = 0;
3791
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
3792
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
3793
- this.state = {};
3794
- this.queue = [];
3795
- this.backend?.init?.(services, options.backend, options);
3796
- }
3797
- queueLoad(languages, namespaces, options, callback) {
3798
- const toLoad = {};
3799
- const pending = {};
3800
- const toLoadLanguages = {};
3801
- const toLoadNamespaces = {};
3802
- languages.forEach((lng) => {
3803
- let hasAllNamespaces = true;
3804
- namespaces.forEach((ns) => {
3805
- const name = `${lng}|${ns}`;
3806
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
3807
- this.state[name] = 2;
3808
- } else if (this.state[name] < 0)
3809
- ;
3810
- else if (this.state[name] === 1) {
3811
- if (pending[name] === undefined)
3812
- pending[name] = true;
3813
- } else {
3814
- this.state[name] = 1;
3815
- hasAllNamespaces = false;
3816
- if (pending[name] === undefined)
3817
- pending[name] = true;
3818
- if (toLoad[name] === undefined)
3819
- toLoad[name] = true;
3820
- if (toLoadNamespaces[ns] === undefined)
3821
- toLoadNamespaces[ns] = true;
3822
- }
3823
- });
3824
- if (!hasAllNamespaces)
3825
- toLoadLanguages[lng] = true;
3826
- });
3827
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
3828
- this.queue.push({
3829
- pending,
3830
- pendingCount: Object.keys(pending).length,
3831
- loaded: {},
3832
- errors: [],
3833
- callback
3834
- });
3835
- }
3836
- return {
3837
- toLoad: Object.keys(toLoad),
3838
- pending: Object.keys(pending),
3839
- toLoadLanguages: Object.keys(toLoadLanguages),
3840
- toLoadNamespaces: Object.keys(toLoadNamespaces)
3841
- };
3842
- }
3843
- loaded(name, err, data) {
3844
- const s = name.split("|");
3845
- const lng = s[0];
3846
- const ns = s[1];
3847
- if (err)
3848
- this.emit("failedLoading", lng, ns, err);
3849
- if (!err && data) {
3850
- this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
3851
- skipCopy: true
3852
- });
3853
- }
3854
- this.state[name] = err ? -1 : 2;
3855
- if (err && data)
3856
- this.state[name] = 0;
3857
- const loaded = {};
3858
- this.queue.forEach((q) => {
3859
- pushPath(q.loaded, [lng], ns);
3860
- removePending(q, name);
3861
- if (err)
3862
- q.errors.push(err);
3863
- if (q.pendingCount === 0 && !q.done) {
3864
- Object.keys(q.loaded).forEach((l) => {
3865
- if (!loaded[l])
3866
- loaded[l] = {};
3867
- const loadedKeys = q.loaded[l];
3868
- if (loadedKeys.length) {
3869
- loadedKeys.forEach((n) => {
3870
- if (loaded[l][n] === undefined)
3871
- loaded[l][n] = true;
3872
- });
3873
- }
3874
- });
3875
- q.done = true;
3876
- if (q.errors.length) {
3877
- q.callback(q.errors);
3878
- } else {
3879
- q.callback();
3880
- }
3881
- }
3882
- });
3883
- this.emit("loaded", loaded);
3884
- this.queue = this.queue.filter((q) => !q.done);
3885
- }
3886
- read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
3887
- if (!lng.length)
3888
- return callback(null, {});
3889
- if (this.readingCalls >= this.maxParallelReads) {
3890
- this.waitingReads.push({
3891
- lng,
3892
- ns,
3893
- fcName,
3894
- tried,
3895
- wait,
3896
- callback
3897
- });
3898
- return;
3899
- }
3900
- this.readingCalls++;
3901
- const resolver = (err, data) => {
3902
- this.readingCalls--;
3903
- if (this.waitingReads.length > 0) {
3904
- const next = this.waitingReads.shift();
3905
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
3906
- }
3907
- if (err && data && tried < this.maxRetries) {
3908
- setTimeout(() => {
3909
- this.read(lng, ns, fcName, tried + 1, wait * 2, callback);
3910
- }, wait);
3911
- return;
3912
- }
3913
- callback(err, data);
3914
- };
3915
- const fc = this.backend[fcName].bind(this.backend);
3916
- if (fc.length === 2) {
3917
- try {
3918
- const r = fc(lng, ns);
3919
- if (r && typeof r.then === "function") {
3920
- r.then((data) => resolver(null, data)).catch(resolver);
3921
- } else {
3922
- resolver(null, r);
3923
- }
3924
- } catch (err) {
3925
- resolver(err);
3926
- }
3927
- return;
3928
- }
3929
- return fc(lng, ns, resolver);
3930
- }
3931
- prepareLoading(languages, namespaces, options = {}, callback) {
3932
- if (!this.backend) {
3933
- this.logger.warn("No backend was added via i18next.use. Will not load resources.");
3934
- return callback && callback();
3935
- }
3936
- if (isString(languages))
3937
- languages = this.languageUtils.toResolveHierarchy(languages);
3938
- if (isString(namespaces))
3939
- namespaces = [namespaces];
3940
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
3941
- if (!toLoad.toLoad.length) {
3942
- if (!toLoad.pending.length)
3943
- callback();
3944
- return null;
3945
- }
3946
- toLoad.toLoad.forEach((name) => {
3947
- this.loadOne(name);
3948
- });
3949
- }
3950
- load(languages, namespaces, callback) {
3951
- this.prepareLoading(languages, namespaces, {}, callback);
3952
- }
3953
- reload(languages, namespaces, callback) {
3954
- this.prepareLoading(languages, namespaces, {
3955
- reload: true
3956
- }, callback);
3957
- }
3958
- loadOne(name, prefix = "") {
3959
- const s = name.split("|");
3960
- const lng = s[0];
3961
- const ns = s[1];
3962
- this.read(lng, ns, "read", undefined, undefined, (err, data) => {
3963
- if (err)
3964
- this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
3965
- if (!err && data)
3966
- this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
3967
- this.loaded(name, err, data);
3968
- });
3969
- }
3970
- saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
3971
- if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
3972
- this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
3973
- return;
3974
- }
3975
- if (key === undefined || key === null || key === "")
3976
- return;
3977
- if (this.backend?.create) {
3978
- const opts = {
3979
- ...options,
3980
- isUpdate
3981
- };
3982
- const fc = this.backend.create.bind(this.backend);
3983
- if (fc.length < 6) {
3984
- try {
3985
- let r;
3986
- if (fc.length === 5) {
3987
- r = fc(languages, namespace, key, fallbackValue, opts);
3988
- } else {
3989
- r = fc(languages, namespace, key, fallbackValue);
3990
- }
3991
- if (r && typeof r.then === "function") {
3992
- r.then((data) => clb(null, data)).catch(clb);
3993
- } else {
3994
- clb(null, r);
3995
- }
3996
- } catch (err) {
3997
- clb(err);
3998
- }
3999
- } else {
4000
- fc(languages, namespace, key, fallbackValue, clb, opts);
4001
- }
4002
- }
4003
- if (!languages || !languages[0])
4004
- return;
4005
- this.store.addResource(languages[0], namespace, key, fallbackValue);
4006
- }
4007
- }
4008
- var get = () => ({
4009
- debug: false,
4010
- initAsync: true,
4011
- ns: ["translation"],
4012
- defaultNS: ["translation"],
4013
- fallbackLng: ["dev"],
4014
- fallbackNS: false,
4015
- supportedLngs: false,
4016
- nonExplicitSupportedLngs: false,
4017
- load: "all",
4018
- preload: false,
4019
- keySeparator: ".",
4020
- nsSeparator: ":",
4021
- pluralSeparator: "_",
4022
- contextSeparator: "_",
4023
- partialBundledLanguages: false,
4024
- saveMissing: false,
4025
- updateMissing: false,
4026
- saveMissingTo: "fallback",
4027
- saveMissingPlurals: true,
4028
- missingKeyHandler: false,
4029
- missingInterpolationHandler: false,
4030
- postProcess: false,
4031
- postProcessPassResolved: false,
4032
- returnNull: false,
4033
- returnEmptyString: true,
4034
- returnObjects: false,
4035
- joinArrays: false,
4036
- returnedObjectHandler: false,
4037
- parseMissingKeyHandler: false,
4038
- appendNamespaceToMissingKey: false,
4039
- appendNamespaceToCIMode: false,
4040
- overloadTranslationOptionHandler: (args) => {
4041
- let ret = {};
4042
- if (typeof args[1] === "object")
4043
- ret = args[1];
4044
- if (isString(args[1]))
4045
- ret.defaultValue = args[1];
4046
- if (isString(args[2]))
4047
- ret.tDescription = args[2];
4048
- if (typeof args[2] === "object" || typeof args[3] === "object") {
4049
- const options = args[3] || args[2];
4050
- Object.keys(options).forEach((key) => {
4051
- ret[key] = options[key];
4052
- });
4053
- }
4054
- return ret;
4055
- },
4056
- interpolation: {
4057
- escapeValue: true,
4058
- prefix: "{{",
4059
- suffix: "}}",
4060
- formatSeparator: ",",
4061
- unescapePrefix: "-",
4062
- nestingPrefix: "$t(",
4063
- nestingSuffix: ")",
4064
- nestingOptionsSeparator: ",",
4065
- maxReplaces: 1000,
4066
- skipOnVariables: true
4067
- },
4068
- cacheInBuiltFormats: true
4069
- });
4070
- var transformOptions = (options) => {
4071
- if (isString(options.ns))
4072
- options.ns = [options.ns];
4073
- if (isString(options.fallbackLng))
4074
- options.fallbackLng = [options.fallbackLng];
4075
- if (isString(options.fallbackNS))
4076
- options.fallbackNS = [options.fallbackNS];
4077
- if (options.supportedLngs && !options.supportedLngs.includes("cimode")) {
4078
- options.supportedLngs = options.supportedLngs.concat(["cimode"]);
4079
- }
4080
- return options;
4081
- };
4082
- var noop = () => {};
4083
- var bindMemberFunctions = (inst) => {
4084
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
4085
- mems.forEach((mem) => {
4086
- if (typeof inst[mem] === "function") {
4087
- inst[mem] = inst[mem].bind(inst);
4088
- }
4089
- });
4090
- };
4091
-
4092
- class I18n extends EventEmitter {
4093
- constructor(options = {}, callback) {
4094
- super();
4095
- this.options = transformOptions(options);
4096
- this.services = {};
4097
- this.logger = baseLogger;
4098
- this.modules = {
4099
- external: []
4100
- };
4101
- bindMemberFunctions(this);
4102
- if (callback && !this.isInitialized && !options.isClone) {
4103
- if (!this.options.initAsync) {
4104
- this.init(options, callback);
4105
- return this;
4106
- }
4107
- setTimeout(() => {
4108
- this.init(options, callback);
4109
- }, 0);
4110
- }
4111
- }
4112
- init(options = {}, callback) {
4113
- this.isInitializing = true;
4114
- if (typeof options === "function") {
4115
- callback = options;
4116
- options = {};
4117
- }
4118
- if (options.defaultNS == null && options.ns) {
4119
- if (isString(options.ns)) {
4120
- options.defaultNS = options.ns;
4121
- } else if (!options.ns.includes("translation")) {
4122
- options.defaultNS = options.ns[0];
4123
- }
4124
- }
4125
- const defOpts = get();
4126
- this.options = {
4127
- ...defOpts,
4128
- ...this.options,
4129
- ...transformOptions(options)
4130
- };
4131
- this.options.interpolation = {
4132
- ...defOpts.interpolation,
4133
- ...this.options.interpolation
4134
- };
4135
- if (options.keySeparator !== undefined) {
4136
- this.options.userDefinedKeySeparator = options.keySeparator;
4137
- }
4138
- if (options.nsSeparator !== undefined) {
4139
- this.options.userDefinedNsSeparator = options.nsSeparator;
4140
- }
4141
- if (typeof this.options.overloadTranslationOptionHandler !== "function") {
4142
- this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;
4143
- }
4144
- const createClassOnDemand = (ClassOrObject) => {
4145
- if (!ClassOrObject)
4146
- return null;
4147
- if (typeof ClassOrObject === "function")
4148
- return new ClassOrObject;
4149
- return ClassOrObject;
4150
- };
4151
- if (!this.options.isClone) {
4152
- if (this.modules.logger) {
4153
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
4154
- } else {
4155
- baseLogger.init(null, this.options);
4156
- }
4157
- let formatter;
4158
- if (this.modules.formatter) {
4159
- formatter = this.modules.formatter;
4160
- } else {
4161
- formatter = Formatter;
4162
- }
4163
- const lu = new LanguageUtil(this.options);
4164
- this.store = new ResourceStore(this.options.resources, this.options);
4165
- const s = this.services;
4166
- s.logger = baseLogger;
4167
- s.resourceStore = this.store;
4168
- s.languageUtils = lu;
4169
- s.pluralResolver = new PluralResolver(lu, {
4170
- prepend: this.options.pluralSeparator
4171
- });
4172
- if (formatter) {
4173
- s.formatter = createClassOnDemand(formatter);
4174
- if (s.formatter.init)
4175
- s.formatter.init(s, this.options);
4176
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
4177
- }
4178
- s.interpolator = new Interpolator(this.options);
4179
- s.utils = {
4180
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
4181
- };
4182
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
4183
- s.backendConnector.on("*", (event, ...args) => {
4184
- this.emit(event, ...args);
4185
- });
4186
- if (this.modules.languageDetector) {
4187
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
4188
- if (s.languageDetector.init)
4189
- s.languageDetector.init(s, this.options.detection, this.options);
4190
- }
4191
- if (this.modules.i18nFormat) {
4192
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
4193
- if (s.i18nFormat.init)
4194
- s.i18nFormat.init(this);
4195
- }
4196
- this.translator = new Translator(this.services, this.options);
4197
- this.translator.on("*", (event, ...args) => {
4198
- this.emit(event, ...args);
4199
- });
4200
- this.modules.external.forEach((m) => {
4201
- if (m.init)
4202
- m.init(this);
4203
- });
4204
- }
4205
- this.format = this.options.interpolation.format;
4206
- if (!callback)
4207
- callback = noop;
4208
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
4209
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
4210
- if (codes.length > 0 && codes[0] !== "dev")
4211
- this.options.lng = codes[0];
4212
- }
4213
- if (!this.services.languageDetector && !this.options.lng) {
4214
- this.logger.warn("init: no languageDetector is used and no lng is defined");
4215
- }
4216
- const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
4217
- storeApi.forEach((fcName) => {
4218
- this[fcName] = (...args) => this.store[fcName](...args);
4219
- });
4220
- const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
4221
- storeApiChained.forEach((fcName) => {
4222
- this[fcName] = (...args) => {
4223
- this.store[fcName](...args);
4224
- return this;
4225
- };
4226
- });
4227
- const deferred = defer();
4228
- const load = () => {
4229
- const finish = (err, t) => {
4230
- this.isInitializing = false;
4231
- if (this.isInitialized && !this.initializedStoreOnce)
4232
- this.logger.warn("init: i18next is already initialized. You should call init just once!");
4233
- this.isInitialized = true;
4234
- if (!this.options.isClone)
4235
- this.logger.log("initialized", this.options);
4236
- this.emit("initialized", this.options);
4237
- deferred.resolve(t);
4238
- callback(err, t);
4239
- };
4240
- if (this.languages && !this.isInitialized)
4241
- return finish(null, this.t.bind(this));
4242
- this.changeLanguage(this.options.lng, finish);
4243
- };
4244
- if (this.options.resources || !this.options.initAsync) {
4245
- load();
4246
- } else {
4247
- setTimeout(load, 0);
4248
- }
4249
- return deferred;
4250
- }
4251
- loadResources(language, callback = noop) {
4252
- let usedCallback = callback;
4253
- const usedLng = isString(language) ? language : this.language;
4254
- if (typeof language === "function")
4255
- usedCallback = language;
4256
- if (!this.options.resources || this.options.partialBundledLanguages) {
4257
- if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0))
4258
- return usedCallback();
4259
- const toLoad = [];
4260
- const append = (lng) => {
4261
- if (!lng)
4262
- return;
4263
- if (lng === "cimode")
4264
- return;
4265
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
4266
- lngs.forEach((l) => {
4267
- if (l === "cimode")
4268
- return;
4269
- if (!toLoad.includes(l))
4270
- toLoad.push(l);
4271
- });
4272
- };
4273
- if (!usedLng) {
4274
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
4275
- fallbacks.forEach((l) => append(l));
4276
- } else {
4277
- append(usedLng);
4278
- }
4279
- this.options.preload?.forEach?.((l) => append(l));
4280
- this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
4281
- if (!e && !this.resolvedLanguage && this.language)
4282
- this.setResolvedLanguage(this.language);
4283
- usedCallback(e);
4284
- });
4285
- } else {
4286
- usedCallback(null);
4287
- }
4288
- }
4289
- reloadResources(lngs, ns, callback) {
4290
- const deferred = defer();
4291
- if (typeof lngs === "function") {
4292
- callback = lngs;
4293
- lngs = undefined;
4294
- }
4295
- if (typeof ns === "function") {
4296
- callback = ns;
4297
- ns = undefined;
4298
- }
4299
- if (!lngs)
4300
- lngs = this.languages;
4301
- if (!ns)
4302
- ns = this.options.ns;
4303
- if (!callback)
4304
- callback = noop;
4305
- this.services.backendConnector.reload(lngs, ns, (err) => {
4306
- deferred.resolve();
4307
- callback(err);
4308
- });
4309
- return deferred;
4310
- }
4311
- use(module) {
4312
- if (!module)
4313
- throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
4314
- if (!module.type)
4315
- throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
4316
- if (module.type === "backend") {
4317
- this.modules.backend = module;
4318
- }
4319
- if (module.type === "logger" || module.log && module.warn && module.error) {
4320
- this.modules.logger = module;
4321
- }
4322
- if (module.type === "languageDetector") {
4323
- this.modules.languageDetector = module;
4324
- }
4325
- if (module.type === "i18nFormat") {
4326
- this.modules.i18nFormat = module;
4327
- }
4328
- if (module.type === "postProcessor") {
4329
- postProcessor.addPostProcessor(module);
4330
- }
4331
- if (module.type === "formatter") {
4332
- this.modules.formatter = module;
4333
- }
4334
- if (module.type === "3rdParty") {
4335
- this.modules.external.push(module);
4336
- }
4337
- return this;
4338
- }
4339
- setResolvedLanguage(l) {
4340
- if (!l || !this.languages)
4341
- return;
4342
- if (["cimode", "dev"].includes(l))
4343
- return;
4344
- for (let li = 0;li < this.languages.length; li++) {
4345
- const lngInLngs = this.languages[li];
4346
- if (["cimode", "dev"].includes(lngInLngs))
4347
- continue;
4348
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
4349
- this.resolvedLanguage = lngInLngs;
4350
- break;
4351
- }
4352
- }
4353
- if (!this.resolvedLanguage && !this.languages.includes(l) && this.store.hasLanguageSomeTranslations(l)) {
4354
- this.resolvedLanguage = l;
4355
- this.languages.unshift(l);
4356
- }
4357
- }
4358
- changeLanguage(lng, callback) {
4359
- this.isLanguageChangingTo = lng;
4360
- const deferred = defer();
4361
- this.emit("languageChanging", lng);
4362
- const setLngProps = (l) => {
4363
- this.language = l;
4364
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
4365
- this.resolvedLanguage = undefined;
4366
- this.setResolvedLanguage(l);
4367
- };
4368
- const done = (err, l) => {
4369
- if (l) {
4370
- if (this.isLanguageChangingTo === lng) {
4371
- setLngProps(l);
4372
- this.translator.changeLanguage(l);
4373
- this.isLanguageChangingTo = undefined;
4374
- this.emit("languageChanged", l);
4375
- this.logger.log("languageChanged", l);
4376
- }
4377
- } else {
4378
- this.isLanguageChangingTo = undefined;
4379
- }
4380
- deferred.resolve((...args) => this.t(...args));
4381
- if (callback)
4382
- callback(err, (...args) => this.t(...args));
4383
- };
4384
- const setLng = (lngs) => {
4385
- if (!lng && !lngs && this.services.languageDetector)
4386
- lngs = [];
4387
- const fl = isString(lngs) ? lngs : lngs && lngs[0];
4388
- const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
4389
- if (l) {
4390
- if (!this.language) {
4391
- setLngProps(l);
4392
- }
4393
- if (!this.translator.language)
4394
- this.translator.changeLanguage(l);
4395
- this.services.languageDetector?.cacheUserLanguage?.(l);
4396
- }
4397
- this.loadResources(l, (err) => {
4398
- done(err, l);
4399
- });
4400
- };
4401
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
4402
- setLng(this.services.languageDetector.detect());
4403
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
4404
- if (this.services.languageDetector.detect.length === 0) {
4405
- this.services.languageDetector.detect().then(setLng);
4406
- } else {
4407
- this.services.languageDetector.detect(setLng);
4408
- }
4409
- } else {
4410
- setLng(lng);
4411
- }
4412
- return deferred;
4413
- }
4414
- getFixedT(lng, ns, keyPrefix) {
4415
- const fixedT = (key, opts, ...rest) => {
4416
- let o;
4417
- if (typeof opts !== "object") {
4418
- o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
4419
- } else {
4420
- o = {
4421
- ...opts
4422
- };
4423
- }
4424
- o.lng = o.lng || fixedT.lng;
4425
- o.lngs = o.lngs || fixedT.lngs;
4426
- o.ns = o.ns || fixedT.ns;
4427
- if (o.keyPrefix !== "")
4428
- o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
4429
- const selectorOpts = {
4430
- ...this.options,
4431
- ...o
4432
- };
4433
- if (typeof o.keyPrefix === "function")
4434
- o.keyPrefix = keysFromSelector(o.keyPrefix, selectorOpts);
4435
- const keySeparator = this.options.keySeparator || ".";
4436
- let resultKey;
4437
- if (o.keyPrefix && Array.isArray(key)) {
4438
- resultKey = key.map((k) => {
4439
- if (typeof k === "function")
4440
- k = keysFromSelector(k, selectorOpts);
4441
- return `${o.keyPrefix}${keySeparator}${k}`;
4442
- });
4443
- } else {
4444
- if (typeof key === "function")
4445
- key = keysFromSelector(key, selectorOpts);
4446
- resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
4447
- }
4448
- return this.t(resultKey, o);
4449
- };
4450
- if (isString(lng)) {
4451
- fixedT.lng = lng;
4452
- } else {
4453
- fixedT.lngs = lng;
4454
- }
4455
- fixedT.ns = ns;
4456
- fixedT.keyPrefix = keyPrefix;
4457
- return fixedT;
4458
- }
4459
- t(...args) {
4460
- return this.translator?.translate(...args);
4461
- }
4462
- exists(...args) {
4463
- return this.translator?.exists(...args);
4464
- }
4465
- setDefaultNamespace(ns) {
4466
- this.options.defaultNS = ns;
4467
- }
4468
- hasLoadedNamespace(ns, options = {}) {
4469
- if (!this.isInitialized) {
4470
- this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
4471
- return false;
4472
- }
4473
- if (!this.languages || !this.languages.length) {
4474
- this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
4475
- return false;
4476
- }
4477
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
4478
- const fallbackLng = this.options ? this.options.fallbackLng : false;
4479
- const lastLng = this.languages[this.languages.length - 1];
4480
- if (lng.toLowerCase() === "cimode")
4481
- return true;
4482
- const loadNotPending = (l, n) => {
4483
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
4484
- return loadState === -1 || loadState === 0 || loadState === 2;
4485
- };
4486
- if (options.precheck) {
4487
- const preResult = options.precheck(this, loadNotPending);
4488
- if (preResult !== undefined)
4489
- return preResult;
4490
- }
4491
- if (this.hasResourceBundle(lng, ns))
4492
- return true;
4493
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages)
4494
- return true;
4495
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns)))
4496
- return true;
4497
- return false;
4498
- }
4499
- loadNamespaces(ns, callback) {
4500
- const deferred = defer();
4501
- if (!this.options.ns) {
4502
- if (callback)
4503
- callback();
4504
- return Promise.resolve();
4505
- }
4506
- if (isString(ns))
4507
- ns = [ns];
4508
- ns.forEach((n) => {
4509
- if (!this.options.ns.includes(n))
4510
- this.options.ns.push(n);
4511
- });
4512
- this.loadResources((err) => {
4513
- deferred.resolve();
4514
- if (callback)
4515
- callback(err);
4516
- });
4517
- return deferred;
4518
- }
4519
- loadLanguages(lngs, callback) {
4520
- const deferred = defer();
4521
- if (isString(lngs))
4522
- lngs = [lngs];
4523
- const preloaded = this.options.preload || [];
4524
- const newLngs = lngs.filter((lng) => !preloaded.includes(lng) && this.services.languageUtils.isSupportedCode(lng));
4525
- if (!newLngs.length) {
4526
- if (callback)
4527
- callback();
4528
- return Promise.resolve();
4529
- }
4530
- this.options.preload = preloaded.concat(newLngs);
4531
- this.loadResources((err) => {
4532
- deferred.resolve();
4533
- if (callback)
4534
- callback(err);
4535
- });
4536
- return deferred;
4537
- }
4538
- dir(lng) {
4539
- if (!lng)
4540
- lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
4541
- if (!lng)
4542
- return "rtl";
4543
- try {
4544
- const l = new Intl.Locale(lng);
4545
- if (l && l.getTextInfo) {
4546
- const ti = l.getTextInfo();
4547
- if (ti && ti.direction)
4548
- return ti.direction;
4549
- }
4550
- } catch (e) {}
4551
- const rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"];
4552
- const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
4553
- if (lng.toLowerCase().indexOf("-latn") > 1)
4554
- return "ltr";
4555
- return rtlLngs.includes(languageUtils.getLanguagePartFromCode(lng)) || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
4556
- }
4557
- static createInstance(options = {}, callback) {
4558
- const instance = new I18n(options, callback);
4559
- instance.createInstance = I18n.createInstance;
4560
- return instance;
4561
- }
4562
- cloneInstance(options = {}, callback = noop) {
4563
- const forkResourceStore = options.forkResourceStore;
4564
- if (forkResourceStore)
4565
- delete options.forkResourceStore;
4566
- const mergedOptions = {
4567
- ...this.options,
4568
- ...options,
4569
- ...{
4570
- isClone: true
4571
- }
4572
- };
4573
- const clone = new I18n(mergedOptions);
4574
- if (options.debug !== undefined || options.prefix !== undefined) {
4575
- clone.logger = clone.logger.clone(options);
4576
- }
4577
- const membersToCopy = ["store", "services", "language"];
4578
- membersToCopy.forEach((m) => {
4579
- clone[m] = this[m];
4580
- });
4581
- clone.services = {
4582
- ...this.services
4583
- };
4584
- clone.services.utils = {
4585
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
4586
- };
4587
- if (forkResourceStore) {
4588
- const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
4589
- prev[l] = {
4590
- ...this.store.data[l]
4591
- };
4592
- prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
4593
- acc[n] = {
4594
- ...prev[l][n]
4595
- };
4596
- return acc;
4597
- }, prev[l]);
4598
- return prev;
4599
- }, {});
4600
- clone.store = new ResourceStore(clonedData, mergedOptions);
4601
- clone.services.resourceStore = clone.store;
4602
- }
4603
- if (options.interpolation) {
4604
- const defOpts = get();
4605
- const mergedInterpolation = {
4606
- ...defOpts.interpolation,
4607
- ...this.options.interpolation,
4608
- ...options.interpolation
4609
- };
4610
- const mergedForInterpolator = {
4611
- ...mergedOptions,
4612
- interpolation: mergedInterpolation
4613
- };
4614
- clone.services.interpolator = new Interpolator(mergedForInterpolator);
4615
- }
4616
- clone.translator = new Translator(clone.services, mergedOptions);
4617
- clone.translator.on("*", (event, ...args) => {
4618
- clone.emit(event, ...args);
4619
- });
4620
- clone.init(mergedOptions, callback);
4621
- clone.translator.options = mergedOptions;
4622
- clone.translator.backendConnector.services.utils = {
4623
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
4624
- };
4625
- return clone;
4626
- }
4627
- toJSON() {
4628
- return {
4629
- options: this.options,
4630
- store: this.store,
4631
- language: this.language,
4632
- languages: this.languages,
4633
- resolvedLanguage: this.resolvedLanguage
4634
- };
4635
- }
4636
- }
4637
- var instance = I18n.createInstance();
4638
- var createInstance = instance.createInstance;
4639
- var dir = instance.dir;
4640
- var init = instance.init;
4641
- var loadResources = instance.loadResources;
4642
- var reloadResources = instance.reloadResources;
4643
- var use = instance.use;
4644
- var changeLanguage = instance.changeLanguage;
4645
- var getFixedT = instance.getFixedT;
4646
- var t = instance.t;
4647
- var exists = instance.exists;
4648
- var setDefaultNamespace = instance.setDefaultNamespace;
4649
- var hasLoadedNamespace = instance.hasLoadedNamespace;
4650
- var loadNamespaces = instance.loadNamespaces;
4651
- var loadLanguages = instance.loadLanguages;
4652
-
4653
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/utils.js
4654
- var warn = (i18n, code, msg, rest) => {
4655
- const args = [msg, {
4656
- code,
4657
- ...rest || {}
4658
- }];
4659
- if (i18n?.services?.logger?.forward) {
4660
- return i18n.services.logger.forward(args, "warn", "react-i18next::", true);
4661
- }
4662
- if (isString2(args[0]))
4663
- args[0] = `react-i18next:: ${args[0]}`;
4664
- if (i18n?.services?.logger?.warn) {
4665
- i18n.services.logger.warn(...args);
4666
- } else if (console?.warn) {
4667
- console.warn(...args);
4668
- }
4669
- };
4670
- var alreadyWarned = {};
4671
- var warnOnce = (i18n, code, msg, rest) => {
4672
- if (isString2(msg) && alreadyWarned[msg])
4673
- return;
4674
- if (isString2(msg))
4675
- alreadyWarned[msg] = new Date;
4676
- warn(i18n, code, msg, rest);
4677
- };
4678
- var loadedClb = (i18n, cb) => () => {
4679
- if (i18n.isInitialized) {
4680
- cb();
4681
- } else {
4682
- const initialized = () => {
4683
- setTimeout(() => {
4684
- i18n.off("initialized", initialized);
4685
- }, 0);
4686
- cb();
4687
- };
4688
- i18n.on("initialized", initialized);
4689
- }
4690
- };
4691
- var loadNamespaces2 = (i18n, ns, cb) => {
4692
- i18n.loadNamespaces(ns, loadedClb(i18n, cb));
4693
- };
4694
- var loadLanguages2 = (i18n, lng, ns, cb) => {
4695
- if (isString2(ns))
4696
- ns = [ns];
4697
- if (i18n.options.preload && i18n.options.preload.indexOf(lng) > -1)
4698
- return loadNamespaces2(i18n, ns, cb);
4699
- ns.forEach((n) => {
4700
- if (i18n.options.ns.indexOf(n) < 0)
4701
- i18n.options.ns.push(n);
4702
- });
4703
- i18n.loadLanguages(lng, loadedClb(i18n, cb));
4704
- };
4705
- var hasLoadedNamespace2 = (ns, i18n, options = {}) => {
4706
- if (!i18n.languages || !i18n.languages.length) {
4707
- warnOnce(i18n, "NO_LANGUAGES", "i18n.languages were undefined or empty", {
4708
- languages: i18n.languages
4709
- });
4710
- return true;
4711
- }
4712
- return i18n.hasLoadedNamespace(ns, {
4713
- lng: options.lng,
4714
- precheck: (i18nInstance, loadNotPending) => {
4715
- if (options.bindI18n && options.bindI18n.indexOf("languageChanging") > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns))
4716
- return false;
4717
- }
4718
- });
4719
- };
4720
- var isString2 = (obj) => typeof obj === "string";
4721
- var isObject = (obj) => typeof obj === "object" && obj !== null;
4722
-
4723
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/unescape.js
4724
- var matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
4725
- var htmlEntities = {
4726
- "&amp;": "&",
4727
- "&#38;": "&",
4728
- "&lt;": "<",
4729
- "&#60;": "<",
4730
- "&gt;": ">",
4731
- "&#62;": ">",
4732
- "&apos;": "'",
4733
- "&#39;": "'",
4734
- "&quot;": '"',
4735
- "&#34;": '"',
4736
- "&nbsp;": " ",
4737
- "&#160;": " ",
4738
- "&copy;": "\xA9",
4739
- "&#169;": "\xA9",
4740
- "&reg;": "\xAE",
4741
- "&#174;": "\xAE",
4742
- "&hellip;": "\u2026",
4743
- "&#8230;": "\u2026",
4744
- "&#x2F;": "/",
4745
- "&#47;": "/"
4746
- };
4747
- var unescapeHtmlEntity = (m) => htmlEntities[m];
4748
- var unescape = (text) => text.replace(matchHtmlEntity, unescapeHtmlEntity);
4749
-
4750
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/defaults.js
4751
- var defaultOptions = {
4752
- bindI18n: "languageChanged",
4753
- bindI18nStore: "",
4754
- transEmptyNodeValue: "",
4755
- transSupportBasicHtmlNodes: true,
4756
- transWrapTextNodes: "",
4757
- transKeepBasicHtmlNodesFor: ["br", "strong", "i", "p"],
4758
- useSuspense: true,
4759
- unescape,
4760
- transDefaultProps: undefined
4761
- };
4762
- var setDefaults = (options = {}) => {
4763
- defaultOptions = {
4764
- ...defaultOptions,
4765
- ...options
4766
- };
4767
- };
4768
- var getDefaults = () => defaultOptions;
4769
-
4770
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/i18nInstance.js
4771
- var i18nInstance;
4772
- var setI18n = (instance2) => {
4773
- i18nInstance = instance2;
4774
- };
4775
- var getI18n = () => i18nInstance;
4776
-
4777
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/context.js
4778
- var import_react12 = __toESM(require_react(), 1);
4779
-
4780
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/initReactI18next.js
4781
- var initReactI18next = {
4782
- type: "3rdParty",
4783
- init(instance2) {
4784
- setDefaults(instance2.options.react);
4785
- setI18n(instance2);
4786
- }
4787
- };
4788
-
4789
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/context.js
4790
- var I18nContext = import_react12.createContext();
4791
-
4792
- class ReportNamespaces {
4793
- constructor() {
4794
- this.usedNamespaces = {};
4795
- }
4796
- addUsedNamespaces(namespaces) {
4797
- namespaces.forEach((ns) => {
4798
- if (!this.usedNamespaces[ns])
4799
- this.usedNamespaces[ns] = true;
4800
- });
4801
- }
4802
- getUsedNamespaces() {
4803
- return Object.keys(this.usedNamespaces);
4804
- }
4805
- }
4806
-
4807
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/useTranslation.js
4808
- var import_react13 = __toESM(require_react(), 1);
4809
- var import_shim = __toESM(require_shim(), 1);
4810
- var notReadyT = (k, optsOrDefaultValue) => {
4811
- if (isString2(optsOrDefaultValue))
4812
- return optsOrDefaultValue;
4813
- if (isObject(optsOrDefaultValue) && isString2(optsOrDefaultValue.defaultValue))
4814
- return optsOrDefaultValue.defaultValue;
4815
- if (typeof k === "function")
4816
- return "";
4817
- if (Array.isArray(k)) {
4818
- const last = k[k.length - 1];
4819
- return typeof last === "function" ? "" : last;
4820
- }
4821
- return k;
4822
- };
4823
- var notReadySnapshot = {
4824
- t: notReadyT,
4825
- ready: false
4826
- };
4827
- var dummySubscribe = () => () => {};
4828
- var useTranslation = (ns, props = {}) => {
4829
- const {
4830
- i18n: i18nFromProps
4831
- } = props;
4832
- const {
4833
- i18n: i18nFromContext,
4834
- defaultNS: defaultNSFromContext
4835
- } = import_react13.useContext(I18nContext) || {};
4836
- const i18n = i18nFromProps || i18nFromContext || getI18n();
4837
- if (i18n && !i18n.reportNamespaces)
4838
- i18n.reportNamespaces = new ReportNamespaces;
4839
- if (!i18n) {
4840
- warnOnce(i18n, "NO_I18NEXT_INSTANCE", "useTranslation: You will need to pass in an i18next instance by using initReactI18next");
4841
- }
4842
- const i18nOptions = import_react13.useMemo(() => ({
4843
- ...getDefaults(),
4844
- ...i18n?.options?.react,
4845
- ...props
4846
- }), [i18n, props]);
4847
- const {
4848
- useSuspense,
4849
- keyPrefix
4850
- } = i18nOptions;
4851
- const nsOrContext = ns || defaultNSFromContext || i18n?.options?.defaultNS;
4852
- const unstableNamespaces = isString2(nsOrContext) ? [nsOrContext] : nsOrContext || ["translation"];
4853
- const namespaces = import_react13.useMemo(() => unstableNamespaces, unstableNamespaces);
4854
- i18n?.reportNamespaces?.addUsedNamespaces?.(namespaces);
4855
- const revisionRef = import_react13.useRef(0);
4856
- const subscribe = import_react13.useCallback((callback) => {
4857
- if (!i18n)
4858
- return dummySubscribe;
4859
- const {
4860
- bindI18n,
4861
- bindI18nStore
4862
- } = i18nOptions;
4863
- const wrappedCallback = () => {
4864
- revisionRef.current += 1;
4865
- callback();
4866
- };
4867
- if (bindI18n)
4868
- i18n.on(bindI18n, wrappedCallback);
4869
- if (bindI18nStore)
4870
- i18n.store.on(bindI18nStore, wrappedCallback);
4871
- return () => {
4872
- if (bindI18n)
4873
- bindI18n.split(" ").forEach((e) => i18n.off(e, wrappedCallback));
4874
- if (bindI18nStore)
4875
- bindI18nStore.split(" ").forEach((e) => i18n.store.off(e, wrappedCallback));
4876
- };
4877
- }, [i18n, i18nOptions]);
4878
- const snapshotRef = import_react13.useRef();
4879
- const getSnapshot = import_react13.useCallback(() => {
4880
- if (!i18n) {
4881
- return notReadySnapshot;
4882
- }
4883
- const calculatedReady = !!(i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every((n) => hasLoadedNamespace2(n, i18n, i18nOptions));
4884
- const currentLng = props.lng || i18n.language;
4885
- const currentRevision = revisionRef.current;
4886
- const lastSnapshot = snapshotRef.current;
4887
- if (lastSnapshot && lastSnapshot.ready === calculatedReady && lastSnapshot.lng === currentLng && lastSnapshot.keyPrefix === keyPrefix && lastSnapshot.revision === currentRevision) {
4888
- return lastSnapshot;
4889
- }
4890
- const calculatedT = i18n.getFixedT(currentLng, i18nOptions.nsMode === "fallback" ? namespaces : namespaces[0], keyPrefix);
4891
- const newSnapshot = {
4892
- t: calculatedT,
4893
- ready: calculatedReady,
4894
- lng: currentLng,
4895
- keyPrefix,
4896
- revision: currentRevision
4897
- };
4898
- snapshotRef.current = newSnapshot;
4899
- return newSnapshot;
4900
- }, [i18n, namespaces, keyPrefix, i18nOptions, props.lng]);
4901
- const [loadCount, setLoadCount] = import_react13.useState(0);
4902
- const {
4903
- t: t2,
4904
- ready
4905
- } = import_shim.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
4906
- import_react13.useEffect(() => {
4907
- if (i18n && !ready && !useSuspense) {
4908
- const onLoaded = () => setLoadCount((c) => c + 1);
4909
- if (props.lng) {
4910
- loadLanguages2(i18n, props.lng, namespaces, onLoaded);
4911
- } else {
4912
- loadNamespaces2(i18n, namespaces, onLoaded);
4913
- }
4914
- }
4915
- }, [i18n, props.lng, namespaces, ready, useSuspense, loadCount]);
4916
- const finalI18n = i18n || {};
4917
- const wrapperRef = import_react13.useRef(null);
4918
- const wrapperLangRef = import_react13.useRef();
4919
- const createI18nWrapper = (original) => {
4920
- const descriptors = Object.getOwnPropertyDescriptors(original);
4921
- if (descriptors.__original)
4922
- delete descriptors.__original;
4923
- const wrapper = Object.create(Object.getPrototypeOf(original), descriptors);
4924
- if (!Object.prototype.hasOwnProperty.call(wrapper, "__original")) {
4925
- try {
4926
- Object.defineProperty(wrapper, "__original", {
4927
- value: original,
4928
- writable: false,
4929
- enumerable: false,
4930
- configurable: false
4931
- });
4932
- } catch (_) {}
4933
- }
4934
- return wrapper;
4935
- };
4936
- const ret = import_react13.useMemo(() => {
4937
- const original = finalI18n;
4938
- const lang = original?.language;
4939
- let i18nWrapper = original;
4940
- if (original) {
4941
- if (wrapperRef.current && wrapperRef.current.__original === original) {
4942
- if (wrapperLangRef.current !== lang) {
4943
- i18nWrapper = createI18nWrapper(original);
4944
- wrapperRef.current = i18nWrapper;
4945
- wrapperLangRef.current = lang;
4946
- } else {
4947
- i18nWrapper = wrapperRef.current;
4948
- }
4949
- } else {
4950
- i18nWrapper = createI18nWrapper(original);
4951
- wrapperRef.current = i18nWrapper;
4952
- wrapperLangRef.current = lang;
4953
- }
4954
- }
4955
- const effectiveT = !ready && !useSuspense ? (...args) => {
4956
- warnOnce(i18n, "USE_T_BEFORE_READY", "useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t.");
4957
- return t2(...args);
4958
- } : t2;
4959
- const arr = [effectiveT, i18nWrapper, ready];
4960
- arr.t = effectiveT;
4961
- arr.i18n = i18nWrapper;
4962
- arr.ready = ready;
4963
- return arr;
4964
- }, [t2, finalI18n, ready, finalI18n.resolvedLanguage, finalI18n.language, finalI18n.languages]);
4965
- if (i18n && useSuspense && !ready) {
4966
- throw new Promise((resolve2) => {
4967
- const onLoaded = () => resolve2();
4968
- if (props.lng) {
4969
- loadLanguages2(i18n, props.lng, namespaces, onLoaded);
4970
- } else {
4971
- loadNamespaces2(i18n, namespaces, onLoaded);
4972
- }
4973
- });
4974
- }
4975
- return ret;
4976
- };
4977
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/I18nextProvider.js
4978
- var import_react14 = __toESM(require_react(), 1);
4979
- function I18nextProvider({
4980
- i18n,
4981
- defaultNS,
4982
- children
4983
- }) {
4984
- const value = import_react14.useMemo(() => ({
4985
- i18n,
4986
- defaultNS
4987
- }), [i18n, defaultNS]);
4988
- return import_react14.createElement(I18nContext.Provider, {
4989
- value
4990
- }, children);
4991
- }
4992
- // src/i18n.ts
4993
- var LocaleCtx = import_react15.createContext(null);
4994
- function createI18n(config) {
4995
- const instance2 = instance.createInstance();
4996
- instance2.use(initReactI18next).init({
4997
- resources: config.resources,
4998
- lng: config.defaultLocale,
4999
- fallbackLng: config.fallbackLocale ?? config.defaultLocale,
5000
- interpolation: { escapeValue: false }
5001
- });
5002
- function Provider({ children }) {
5003
- const [locale, setLocaleState] = import_react15.useState(config.defaultLocale);
5004
- const setLocale = import_react15.useCallback((lng) => {
5005
- setLocaleState(lng);
5006
- }, []);
5007
- const ctxValue = import_react15.useMemo(() => ({ locale, setLocale }), [locale, setLocale]);
5008
- return import_react15.default.createElement(LocaleCtx.Provider, { value: ctxValue }, import_react15.default.createElement(I18nextProvider, { i18n: instance2 }, children));
5009
- }
5010
- return { Provider, instance: instance2 };
5011
- }
5012
- function useLocale() {
5013
- const localeCtx = import_react15.useContext(LocaleCtx);
5014
- const { i18n } = useTranslation();
5015
- const locale = localeCtx?.locale ?? i18n.language;
5016
- const t2 = import_react15.useMemo(() => i18n.getFixedT(locale), [i18n, locale]);
5017
- return {
5018
- t: t2,
5019
- locale,
5020
- setLocale: localeCtx?.setLocale ?? (() => {}),
5021
- availableLocales: Object.keys(i18n.options.resources ?? {})
2202
+ function useLocale() {
2203
+ const localeCtx = import_react12.useContext(LocaleCtx);
2204
+ const { i18n } = useTranslation();
2205
+ const locale = localeCtx?.locale ?? i18n.language;
2206
+ const t = import_react12.useMemo(() => i18n.getFixedT(locale), [i18n, locale]);
2207
+ return {
2208
+ t,
2209
+ locale,
2210
+ setLocale: localeCtx?.setLocale ?? (() => {}),
2211
+ availableLocales: Object.keys(i18n.options.resources ?? {})
5022
2212
  };
5023
2213
  }
5024
2214
  // src/invoice.ts
5025
- var import_react16 = __toESM(require_react(), 1);
2215
+ var import_react13 = __toESM(require_react(), 1);
5026
2216
  function useInvoice(config) {
5027
2217
  const bot = useBot();
5028
- const [status, setStatus] = import_react16.useState("idle");
5029
- const [receipt, setReceipt] = import_react16.useState(null);
5030
- const [error, setError] = import_react16.useState(null);
5031
- const configRef = import_react16.useRef(config);
2218
+ const [status, setStatus] = import_react13.useState("idle");
2219
+ const [receipt, setReceipt] = import_react13.useState(null);
2220
+ const [error, setError] = import_react13.useState(null);
2221
+ const configRef = import_react13.useRef(config);
5032
2222
  configRef.current = config;
5033
2223
  useOn("successful_payment", (data) => {
5034
2224
  if (data?.invoice_payload === configRef.current.payload) {
@@ -5043,7 +2233,7 @@ function useInvoice(config) {
5043
2233
  });
5044
2234
  }
5045
2235
  });
5046
- const send = import_react16.useCallback(async () => {
2236
+ const send = import_react13.useCallback(async () => {
5047
2237
  const raw = bot.raw;
5048
2238
  if (!raw?.api)
5049
2239
  return;