react-i18next 16.0.0 → 16.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,871 +1,3055 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactI18next = {}, global.React));
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactI18next = {}, global.React));
5
5
  })(this, (function (exports, react) { 'use strict';
6
6
 
7
- function getDefaultExportFromCjs (x) {
8
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9
- }
7
+ const isString$1 = obj => typeof obj === 'string';
8
+ const defer = () => {
9
+ let res;
10
+ let rej;
11
+ const promise = new Promise((resolve, reject) => {
12
+ res = resolve;
13
+ rej = reject;
14
+ });
15
+ promise.resolve = res;
16
+ promise.reject = rej;
17
+ return promise;
18
+ };
19
+ const makeString = object => {
20
+ if (object == null) return '';
21
+ return '' + object;
22
+ };
23
+ const copy = (a, s, t) => {
24
+ a.forEach(m => {
25
+ if (s[m]) t[m] = s[m];
26
+ });
27
+ };
28
+ const lastOfPathSeparatorRegExp = /###/g;
29
+ const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
30
+ const canNotTraverseDeeper = object => !object || isString$1(object);
31
+ const getLastOfPath = (object, path, Empty) => {
32
+ const stack = !isString$1(path) ? path : path.split('.');
33
+ let stackIndex = 0;
34
+ while (stackIndex < stack.length - 1) {
35
+ if (canNotTraverseDeeper(object)) return {};
36
+ const key = cleanKey(stack[stackIndex]);
37
+ if (!object[key] && Empty) object[key] = new Empty();
38
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
39
+ object = object[key];
40
+ } else {
41
+ object = {};
42
+ }
43
+ ++stackIndex;
44
+ }
45
+ if (canNotTraverseDeeper(object)) return {};
46
+ return {
47
+ obj: object,
48
+ k: cleanKey(stack[stackIndex])
49
+ };
50
+ };
51
+ const setPath = (object, path, newValue) => {
52
+ const {
53
+ obj,
54
+ k
55
+ } = getLastOfPath(object, path, Object);
56
+ if (obj !== undefined || path.length === 1) {
57
+ obj[k] = newValue;
58
+ return;
59
+ }
60
+ let e = path[path.length - 1];
61
+ let p = path.slice(0, path.length - 1);
62
+ let last = getLastOfPath(object, p, Object);
63
+ while (last.obj === undefined && p.length) {
64
+ e = `${p[p.length - 1]}.${e}`;
65
+ p = p.slice(0, p.length - 1);
66
+ last = getLastOfPath(object, p, Object);
67
+ if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
68
+ last.obj = undefined;
69
+ }
70
+ }
71
+ last.obj[`${last.k}.${e}`] = newValue;
72
+ };
73
+ const pushPath = (object, path, newValue, concat) => {
74
+ const {
75
+ obj,
76
+ k
77
+ } = getLastOfPath(object, path, Object);
78
+ obj[k] = obj[k] || [];
79
+ obj[k].push(newValue);
80
+ };
81
+ const getPath = (object, path) => {
82
+ const {
83
+ obj,
84
+ k
85
+ } = getLastOfPath(object, path);
86
+ if (!obj) return undefined;
87
+ if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;
88
+ return obj[k];
89
+ };
90
+ const getPathWithDefaults = (data, defaultData, key) => {
91
+ const value = getPath(data, key);
92
+ if (value !== undefined) {
93
+ return value;
94
+ }
95
+ return getPath(defaultData, key);
96
+ };
97
+ const deepExtend = (target, source, overwrite) => {
98
+ for (const prop in source) {
99
+ if (prop !== '__proto__' && prop !== 'constructor') {
100
+ if (prop in target) {
101
+ if (isString$1(target[prop]) || target[prop] instanceof String || isString$1(source[prop]) || source[prop] instanceof String) {
102
+ if (overwrite) target[prop] = source[prop];
103
+ } else {
104
+ deepExtend(target[prop], source[prop], overwrite);
105
+ }
106
+ } else {
107
+ target[prop] = source[prop];
108
+ }
109
+ }
110
+ }
111
+ return target;
112
+ };
113
+ const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
114
+ var _entityMap = {
115
+ '&': '&amp;',
116
+ '<': '&lt;',
117
+ '>': '&gt;',
118
+ '"': '&quot;',
119
+ "'": '&#39;',
120
+ '/': '&#x2F;'
121
+ };
122
+ const escape = data => {
123
+ if (isString$1(data)) {
124
+ return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
125
+ }
126
+ return data;
127
+ };
128
+ class RegExpCache {
129
+ constructor(capacity) {
130
+ this.capacity = capacity;
131
+ this.regExpMap = new Map();
132
+ this.regExpQueue = [];
133
+ }
134
+ getRegExp(pattern) {
135
+ const regExpFromCache = this.regExpMap.get(pattern);
136
+ if (regExpFromCache !== undefined) {
137
+ return regExpFromCache;
138
+ }
139
+ const regExpNew = new RegExp(pattern);
140
+ if (this.regExpQueue.length === this.capacity) {
141
+ this.regExpMap.delete(this.regExpQueue.shift());
142
+ }
143
+ this.regExpMap.set(pattern, regExpNew);
144
+ this.regExpQueue.push(pattern);
145
+ return regExpNew;
146
+ }
147
+ }
148
+ const chars = [' ', ',', '?', '!', ';'];
149
+ const looksLikeObjectPathRegExpCache = new RegExpCache(20);
150
+ const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
151
+ nsSeparator = nsSeparator || '';
152
+ keySeparator = keySeparator || '';
153
+ const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
154
+ if (possibleChars.length === 0) return true;
155
+ const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
156
+ let matched = !r.test(key);
157
+ if (!matched) {
158
+ const ki = key.indexOf(keySeparator);
159
+ if (ki > 0 && !r.test(key.substring(0, ki))) {
160
+ matched = true;
161
+ }
162
+ }
163
+ return matched;
164
+ };
165
+ const deepFind = (obj, path, keySeparator = '.') => {
166
+ if (!obj) return undefined;
167
+ if (obj[path]) {
168
+ if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;
169
+ return obj[path];
170
+ }
171
+ const tokens = path.split(keySeparator);
172
+ let current = obj;
173
+ for (let i = 0; i < tokens.length;) {
174
+ if (!current || typeof current !== 'object') {
175
+ return undefined;
176
+ }
177
+ let next;
178
+ let nextPath = '';
179
+ for (let j = i; j < tokens.length; ++j) {
180
+ if (j !== i) {
181
+ nextPath += keySeparator;
182
+ }
183
+ nextPath += tokens[j];
184
+ next = current[nextPath];
185
+ if (next !== undefined) {
186
+ if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
187
+ continue;
188
+ }
189
+ i += j - i + 1;
190
+ break;
191
+ }
192
+ }
193
+ current = next;
194
+ }
195
+ return current;
196
+ };
197
+ const getCleanedCode = code => code?.replace('_', '-');
198
+ const consoleLogger = {
199
+ type: 'logger',
200
+ log(args) {
201
+ this.output('log', args);
202
+ },
203
+ warn(args) {
204
+ this.output('warn', args);
205
+ },
206
+ error(args) {
207
+ this.output('error', args);
208
+ },
209
+ output(type, args) {
210
+ console?.[type]?.apply?.(console, args);
211
+ }
212
+ };
213
+ class Logger {
214
+ constructor(concreteLogger, options = {}) {
215
+ this.init(concreteLogger, options);
216
+ }
217
+ init(concreteLogger, options = {}) {
218
+ this.prefix = options.prefix || 'i18next:';
219
+ this.logger = concreteLogger || consoleLogger;
220
+ this.options = options;
221
+ this.debug = options.debug;
222
+ }
223
+ log(...args) {
224
+ return this.forward(args, 'log', '', true);
225
+ }
226
+ warn(...args) {
227
+ return this.forward(args, 'warn', '', true);
228
+ }
229
+ error(...args) {
230
+ return this.forward(args, 'error', '');
231
+ }
232
+ deprecate(...args) {
233
+ return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
234
+ }
235
+ forward(args, lvl, prefix, debugOnly) {
236
+ if (debugOnly && !this.debug) return null;
237
+ if (isString$1(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
238
+ return this.logger[lvl](args);
239
+ }
240
+ create(moduleName) {
241
+ return new Logger(this.logger, {
242
+ ...{
243
+ prefix: `${this.prefix}:${moduleName}:`
244
+ },
245
+ ...this.options
246
+ });
247
+ }
248
+ clone(options) {
249
+ options = options || this.options;
250
+ options.prefix = options.prefix || this.prefix;
251
+ return new Logger(this.logger, options);
252
+ }
253
+ }
254
+ var baseLogger = new Logger();
255
+ class EventEmitter {
256
+ constructor() {
257
+ this.observers = {};
258
+ }
259
+ on(events, listener) {
260
+ events.split(' ').forEach(event => {
261
+ if (!this.observers[event]) this.observers[event] = new Map();
262
+ const numListeners = this.observers[event].get(listener) || 0;
263
+ this.observers[event].set(listener, numListeners + 1);
264
+ });
265
+ return this;
266
+ }
267
+ off(event, listener) {
268
+ if (!this.observers[event]) return;
269
+ if (!listener) {
270
+ delete this.observers[event];
271
+ return;
272
+ }
273
+ this.observers[event].delete(listener);
274
+ }
275
+ emit(event, ...args) {
276
+ if (this.observers[event]) {
277
+ const cloned = Array.from(this.observers[event].entries());
278
+ cloned.forEach(([observer, numTimesAdded]) => {
279
+ for (let i = 0; i < numTimesAdded; i++) {
280
+ observer(...args);
281
+ }
282
+ });
283
+ }
284
+ if (this.observers['*']) {
285
+ const cloned = Array.from(this.observers['*'].entries());
286
+ cloned.forEach(([observer, numTimesAdded]) => {
287
+ for (let i = 0; i < numTimesAdded; i++) {
288
+ observer.apply(observer, [event, ...args]);
289
+ }
290
+ });
291
+ }
292
+ }
293
+ }
294
+ class ResourceStore extends EventEmitter {
295
+ constructor(data, options = {
296
+ ns: ['translation'],
297
+ defaultNS: 'translation'
298
+ }) {
299
+ super();
300
+ this.data = data || {};
301
+ this.options = options;
302
+ if (this.options.keySeparator === undefined) {
303
+ this.options.keySeparator = '.';
304
+ }
305
+ if (this.options.ignoreJSONStructure === undefined) {
306
+ this.options.ignoreJSONStructure = true;
307
+ }
308
+ }
309
+ addNamespaces(ns) {
310
+ if (this.options.ns.indexOf(ns) < 0) {
311
+ this.options.ns.push(ns);
312
+ }
313
+ }
314
+ removeNamespaces(ns) {
315
+ const index = this.options.ns.indexOf(ns);
316
+ if (index > -1) {
317
+ this.options.ns.splice(index, 1);
318
+ }
319
+ }
320
+ getResource(lng, ns, key, options = {}) {
321
+ const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
322
+ const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
323
+ let path;
324
+ if (lng.indexOf('.') > -1) {
325
+ path = lng.split('.');
326
+ } else {
327
+ path = [lng, ns];
328
+ if (key) {
329
+ if (Array.isArray(key)) {
330
+ path.push(...key);
331
+ } else if (isString$1(key) && keySeparator) {
332
+ path.push(...key.split(keySeparator));
333
+ } else {
334
+ path.push(key);
335
+ }
336
+ }
337
+ }
338
+ const result = getPath(this.data, path);
339
+ if (!result && !ns && !key && lng.indexOf('.') > -1) {
340
+ lng = path[0];
341
+ ns = path[1];
342
+ key = path.slice(2).join('.');
343
+ }
344
+ if (result || !ignoreJSONStructure || !isString$1(key)) return result;
345
+ return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
346
+ }
347
+ addResource(lng, ns, key, value, options = {
348
+ silent: false
349
+ }) {
350
+ const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
351
+ let path = [lng, ns];
352
+ if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
353
+ if (lng.indexOf('.') > -1) {
354
+ path = lng.split('.');
355
+ value = ns;
356
+ ns = path[1];
357
+ }
358
+ this.addNamespaces(ns);
359
+ setPath(this.data, path, value);
360
+ if (!options.silent) this.emit('added', lng, ns, key, value);
361
+ }
362
+ addResources(lng, ns, resources, options = {
363
+ silent: false
364
+ }) {
365
+ for (const m in resources) {
366
+ if (isString$1(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
367
+ silent: true
368
+ });
369
+ }
370
+ if (!options.silent) this.emit('added', lng, ns, resources);
371
+ }
372
+ addResourceBundle(lng, ns, resources, deep, overwrite, options = {
373
+ silent: false,
374
+ skipCopy: false
375
+ }) {
376
+ let path = [lng, ns];
377
+ if (lng.indexOf('.') > -1) {
378
+ path = lng.split('.');
379
+ deep = resources;
380
+ resources = ns;
381
+ ns = path[1];
382
+ }
383
+ this.addNamespaces(ns);
384
+ let pack = getPath(this.data, path) || {};
385
+ if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
386
+ if (deep) {
387
+ deepExtend(pack, resources, overwrite);
388
+ } else {
389
+ pack = {
390
+ ...pack,
391
+ ...resources
392
+ };
393
+ }
394
+ setPath(this.data, path, pack);
395
+ if (!options.silent) this.emit('added', lng, ns, resources);
396
+ }
397
+ removeResourceBundle(lng, ns) {
398
+ if (this.hasResourceBundle(lng, ns)) {
399
+ delete this.data[lng][ns];
400
+ }
401
+ this.removeNamespaces(ns);
402
+ this.emit('removed', lng, ns);
403
+ }
404
+ hasResourceBundle(lng, ns) {
405
+ return this.getResource(lng, ns) !== undefined;
406
+ }
407
+ getResourceBundle(lng, ns) {
408
+ if (!ns) ns = this.options.defaultNS;
409
+ return this.getResource(lng, ns);
410
+ }
411
+ getDataByLanguage(lng) {
412
+ return this.data[lng];
413
+ }
414
+ hasLanguageSomeTranslations(lng) {
415
+ const data = this.getDataByLanguage(lng);
416
+ const n = data && Object.keys(data) || [];
417
+ return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
418
+ }
419
+ toJSON() {
420
+ return this.data;
421
+ }
422
+ }
423
+ var postProcessor = {
424
+ processors: {},
425
+ addPostProcessor(module) {
426
+ this.processors[module.name] = module;
427
+ },
428
+ handle(processors, value, key, options, translator) {
429
+ processors.forEach(processor => {
430
+ value = this.processors[processor]?.process(value, key, options, translator) ?? value;
431
+ });
432
+ return value;
433
+ }
434
+ };
435
+ const PATH_KEY = Symbol('i18next/PATH_KEY');
436
+ function createProxy() {
437
+ const state = [];
438
+ const handler = Object.create(null);
439
+ let proxy;
440
+ handler.get = (target, key) => {
441
+ proxy?.revoke?.();
442
+ if (key === PATH_KEY) return state;
443
+ state.push(key);
444
+ proxy = Proxy.revocable(target, handler);
445
+ return proxy.proxy;
446
+ };
447
+ return Proxy.revocable(Object.create(null), handler).proxy;
448
+ }
449
+ function keysFromSelector(selector, opts) {
450
+ const {
451
+ [PATH_KEY]: path
452
+ } = selector(createProxy());
453
+ return path.join(opts?.keySeparator ?? '.');
454
+ }
455
+ const checkedLoadedFor = {};
456
+ const shouldHandleAsObject = res => !isString$1(res) && typeof res !== 'boolean' && typeof res !== 'number';
457
+ class Translator extends EventEmitter {
458
+ constructor(services, options = {}) {
459
+ super();
460
+ copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
461
+ this.options = options;
462
+ if (this.options.keySeparator === undefined) {
463
+ this.options.keySeparator = '.';
464
+ }
465
+ this.logger = baseLogger.create('translator');
466
+ }
467
+ changeLanguage(lng) {
468
+ if (lng) this.language = lng;
469
+ }
470
+ exists(key, o = {
471
+ interpolation: {}
472
+ }) {
473
+ const opt = {
474
+ ...o
475
+ };
476
+ if (key == null) return false;
477
+ const resolved = this.resolve(key, opt);
478
+ return resolved?.res !== undefined;
479
+ }
480
+ extractFromKey(key, opt) {
481
+ let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
482
+ if (nsSeparator === undefined) nsSeparator = ':';
483
+ const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
484
+ let namespaces = opt.ns || this.options.defaultNS || [];
485
+ const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
486
+ const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
487
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
488
+ const m = key.match(this.interpolator.nestingRegexp);
489
+ if (m && m.length > 0) {
490
+ return {
491
+ key,
492
+ namespaces: isString$1(namespaces) ? [namespaces] : namespaces
493
+ };
494
+ }
495
+ const parts = key.split(nsSeparator);
496
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
497
+ key = parts.join(keySeparator);
498
+ }
499
+ return {
500
+ key,
501
+ namespaces: isString$1(namespaces) ? [namespaces] : namespaces
502
+ };
503
+ }
504
+ translate(keys, o, lastKey) {
505
+ let opt = typeof o === 'object' ? {
506
+ ...o
507
+ } : o;
508
+ if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {
509
+ opt = this.options.overloadTranslationOptionHandler(arguments);
510
+ }
511
+ if (typeof opt === 'object') opt = {
512
+ ...opt
513
+ };
514
+ if (!opt) opt = {};
515
+ if (keys == null) return '';
516
+ if (typeof keys === 'function') keys = keysFromSelector(keys, {
517
+ ...this.options,
518
+ ...opt
519
+ });
520
+ if (!Array.isArray(keys)) keys = [String(keys)];
521
+ const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
522
+ const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
523
+ const {
524
+ key,
525
+ namespaces
526
+ } = this.extractFromKey(keys[keys.length - 1], opt);
527
+ const namespace = namespaces[namespaces.length - 1];
528
+ let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
529
+ if (nsSeparator === undefined) nsSeparator = ':';
530
+ const lng = opt.lng || this.language;
531
+ const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
532
+ if (lng?.toLowerCase() === 'cimode') {
533
+ if (appendNamespaceToCIMode) {
534
+ if (returnDetails) {
535
+ return {
536
+ res: `${namespace}${nsSeparator}${key}`,
537
+ usedKey: key,
538
+ exactUsedKey: key,
539
+ usedLng: lng,
540
+ usedNS: namespace,
541
+ usedParams: this.getUsedParamsDetails(opt)
542
+ };
543
+ }
544
+ return `${namespace}${nsSeparator}${key}`;
545
+ }
546
+ if (returnDetails) {
547
+ return {
548
+ res: key,
549
+ usedKey: key,
550
+ exactUsedKey: key,
551
+ usedLng: lng,
552
+ usedNS: namespace,
553
+ usedParams: this.getUsedParamsDetails(opt)
554
+ };
555
+ }
556
+ return key;
557
+ }
558
+ const resolved = this.resolve(keys, opt);
559
+ let res = resolved?.res;
560
+ const resUsedKey = resolved?.usedKey || key;
561
+ const resExactUsedKey = resolved?.exactUsedKey || key;
562
+ const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
563
+ const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
564
+ const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
565
+ const needsPluralHandling = opt.count !== undefined && !isString$1(opt.count);
566
+ const hasDefaultValue = Translator.hasDefaultValue(opt);
567
+ const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';
568
+ const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
569
+ ordinal: false
570
+ }) : '';
571
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
572
+ const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
573
+ let resForObjHndl = res;
574
+ if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
575
+ resForObjHndl = defaultValue;
576
+ }
577
+ const handleAsObject = shouldHandleAsObject(resForObjHndl);
578
+ const resType = Object.prototype.toString.apply(resForObjHndl);
579
+ if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString$1(joinArrays) && Array.isArray(resForObjHndl))) {
580
+ if (!opt.returnObjects && !this.options.returnObjects) {
581
+ if (!this.options.returnedObjectHandler) {
582
+ this.logger.warn('accessing an object - but returnObjects options is not enabled!');
583
+ }
584
+ const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
585
+ ...opt,
586
+ ns: namespaces
587
+ }) : `key '${key} (${this.language})' returned an object instead of string.`;
588
+ if (returnDetails) {
589
+ resolved.res = r;
590
+ resolved.usedParams = this.getUsedParamsDetails(opt);
591
+ return resolved;
592
+ }
593
+ return r;
594
+ }
595
+ if (keySeparator) {
596
+ const resTypeIsArray = Array.isArray(resForObjHndl);
597
+ const copy = resTypeIsArray ? [] : {};
598
+ const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
599
+ for (const m in resForObjHndl) {
600
+ if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
601
+ const deepKey = `${newKeyToUse}${keySeparator}${m}`;
602
+ if (hasDefaultValue && !res) {
603
+ copy[m] = this.translate(deepKey, {
604
+ ...opt,
605
+ defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
606
+ ...{
607
+ joinArrays: false,
608
+ ns: namespaces
609
+ }
610
+ });
611
+ } else {
612
+ copy[m] = this.translate(deepKey, {
613
+ ...opt,
614
+ ...{
615
+ joinArrays: false,
616
+ ns: namespaces
617
+ }
618
+ });
619
+ }
620
+ if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
621
+ }
622
+ }
623
+ res = copy;
624
+ }
625
+ } else if (handleAsObjectInI18nFormat && isString$1(joinArrays) && Array.isArray(res)) {
626
+ res = res.join(joinArrays);
627
+ if (res) res = this.extendTranslation(res, keys, opt, lastKey);
628
+ } else {
629
+ let usedDefault = false;
630
+ let usedKey = false;
631
+ if (!this.isValidLookup(res) && hasDefaultValue) {
632
+ usedDefault = true;
633
+ res = defaultValue;
634
+ }
635
+ if (!this.isValidLookup(res)) {
636
+ usedKey = true;
637
+ res = key;
638
+ }
639
+ const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
640
+ const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
641
+ const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
642
+ if (usedKey || usedDefault || updateMissing) {
643
+ this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
644
+ if (keySeparator) {
645
+ const fk = this.resolve(key, {
646
+ ...opt,
647
+ keySeparator: false
648
+ });
649
+ if (fk && fk.res) 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.');
650
+ }
651
+ let lngs = [];
652
+ const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
653
+ if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
654
+ for (let i = 0; i < fallbackLngs.length; i++) {
655
+ lngs.push(fallbackLngs[i]);
656
+ }
657
+ } else if (this.options.saveMissingTo === 'all') {
658
+ lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
659
+ } else {
660
+ lngs.push(opt.lng || this.language);
661
+ }
662
+ const send = (l, k, specificDefaultValue) => {
663
+ const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
664
+ if (this.options.missingKeyHandler) {
665
+ this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
666
+ } else if (this.backendConnector?.saveMissing) {
667
+ this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
668
+ }
669
+ this.emit('missingKey', l, namespace, k, res);
670
+ };
671
+ if (this.options.saveMissing) {
672
+ if (this.options.saveMissingPlurals && needsPluralHandling) {
673
+ lngs.forEach(language => {
674
+ const suffixes = this.pluralResolver.getSuffixes(language, opt);
675
+ if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
676
+ suffixes.push(`${this.options.pluralSeparator}zero`);
677
+ }
678
+ suffixes.forEach(suffix => {
679
+ send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
680
+ });
681
+ });
682
+ } else {
683
+ send(lngs, key, defaultValue);
684
+ }
685
+ }
686
+ }
687
+ res = this.extendTranslation(res, keys, opt, resolved, lastKey);
688
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
689
+ res = `${namespace}${nsSeparator}${key}`;
690
+ }
691
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
692
+ res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
693
+ }
694
+ }
695
+ if (returnDetails) {
696
+ resolved.res = res;
697
+ resolved.usedParams = this.getUsedParamsDetails(opt);
698
+ return resolved;
699
+ }
700
+ return res;
701
+ }
702
+ extendTranslation(res, key, opt, resolved, lastKey) {
703
+ if (this.i18nFormat?.parse) {
704
+ res = this.i18nFormat.parse(res, {
705
+ ...this.options.interpolation.defaultVariables,
706
+ ...opt
707
+ }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
708
+ resolved
709
+ });
710
+ } else if (!opt.skipInterpolation) {
711
+ if (opt.interpolation) this.interpolator.init({
712
+ ...opt,
713
+ ...{
714
+ interpolation: {
715
+ ...this.options.interpolation,
716
+ ...opt.interpolation
717
+ }
718
+ }
719
+ });
720
+ const skipOnVariables = isString$1(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
721
+ let nestBef;
722
+ if (skipOnVariables) {
723
+ const nb = res.match(this.interpolator.nestingRegexp);
724
+ nestBef = nb && nb.length;
725
+ }
726
+ let data = opt.replace && !isString$1(opt.replace) ? opt.replace : opt;
727
+ if (this.options.interpolation.defaultVariables) data = {
728
+ ...this.options.interpolation.defaultVariables,
729
+ ...data
730
+ };
731
+ res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
732
+ if (skipOnVariables) {
733
+ const na = res.match(this.interpolator.nestingRegexp);
734
+ const nestAft = na && na.length;
735
+ if (nestBef < nestAft) opt.nest = false;
736
+ }
737
+ if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
738
+ if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
739
+ if (lastKey?.[0] === args[0] && !opt.context) {
740
+ this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
741
+ return null;
742
+ }
743
+ return this.translate(...args, key);
744
+ }, opt);
745
+ if (opt.interpolation) this.interpolator.reset();
746
+ }
747
+ const postProcess = opt.postProcess || this.options.postProcess;
748
+ const postProcessorNames = isString$1(postProcess) ? [postProcess] : postProcess;
749
+ if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
750
+ res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
751
+ i18nResolved: {
752
+ ...resolved,
753
+ usedParams: this.getUsedParamsDetails(opt)
754
+ },
755
+ ...opt
756
+ } : opt, this);
757
+ }
758
+ return res;
759
+ }
760
+ resolve(keys, opt = {}) {
761
+ let found;
762
+ let usedKey;
763
+ let exactUsedKey;
764
+ let usedLng;
765
+ let usedNS;
766
+ if (isString$1(keys)) keys = [keys];
767
+ keys.forEach(k => {
768
+ if (this.isValidLookup(found)) return;
769
+ const extracted = this.extractFromKey(k, opt);
770
+ const key = extracted.key;
771
+ usedKey = key;
772
+ let namespaces = extracted.namespaces;
773
+ if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
774
+ const needsPluralHandling = opt.count !== undefined && !isString$1(opt.count);
775
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
776
+ const needsContextHandling = opt.context !== undefined && (isString$1(opt.context) || typeof opt.context === 'number') && opt.context !== '';
777
+ const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
778
+ namespaces.forEach(ns => {
779
+ if (this.isValidLookup(found)) return;
780
+ usedNS = ns;
781
+ if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
782
+ checkedLoadedFor[`${codes[0]}-${ns}`] = true;
783
+ 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!!!');
784
+ }
785
+ codes.forEach(code => {
786
+ if (this.isValidLookup(found)) return;
787
+ usedLng = code;
788
+ const finalKeys = [key];
789
+ if (this.i18nFormat?.addLookupKeys) {
790
+ this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
791
+ } else {
792
+ let pluralSuffix;
793
+ if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
794
+ const zeroSuffix = `${this.options.pluralSeparator}zero`;
795
+ const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
796
+ if (needsPluralHandling) {
797
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
798
+ finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
799
+ }
800
+ finalKeys.push(key + pluralSuffix);
801
+ if (needsZeroSuffixLookup) {
802
+ finalKeys.push(key + zeroSuffix);
803
+ }
804
+ }
805
+ if (needsContextHandling) {
806
+ const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;
807
+ finalKeys.push(contextKey);
808
+ if (needsPluralHandling) {
809
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
810
+ finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
811
+ }
812
+ finalKeys.push(contextKey + pluralSuffix);
813
+ if (needsZeroSuffixLookup) {
814
+ finalKeys.push(contextKey + zeroSuffix);
815
+ }
816
+ }
817
+ }
818
+ }
819
+ let possibleKey;
820
+ while (possibleKey = finalKeys.pop()) {
821
+ if (!this.isValidLookup(found)) {
822
+ exactUsedKey = possibleKey;
823
+ found = this.getResource(code, ns, possibleKey, opt);
824
+ }
825
+ }
826
+ });
827
+ });
828
+ });
829
+ return {
830
+ res: found,
831
+ usedKey,
832
+ exactUsedKey,
833
+ usedLng,
834
+ usedNS
835
+ };
836
+ }
837
+ isValidLookup(res) {
838
+ return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
839
+ }
840
+ getResource(code, ns, key, options = {}) {
841
+ if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
842
+ return this.resourceStore.getResource(code, ns, key, options);
843
+ }
844
+ getUsedParamsDetails(options = {}) {
845
+ const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
846
+ const useOptionsReplaceForData = options.replace && !isString$1(options.replace);
847
+ let data = useOptionsReplaceForData ? options.replace : options;
848
+ if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
849
+ data.count = options.count;
850
+ }
851
+ if (this.options.interpolation.defaultVariables) {
852
+ data = {
853
+ ...this.options.interpolation.defaultVariables,
854
+ ...data
855
+ };
856
+ }
857
+ if (!useOptionsReplaceForData) {
858
+ data = {
859
+ ...data
860
+ };
861
+ for (const key of optionsKeys) {
862
+ delete data[key];
863
+ }
864
+ }
865
+ return data;
866
+ }
867
+ static hasDefaultValue(options) {
868
+ const prefix = 'defaultValue';
869
+ for (const option in options) {
870
+ if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
871
+ return true;
872
+ }
873
+ }
874
+ return false;
875
+ }
876
+ }
877
+ class LanguageUtil {
878
+ constructor(options) {
879
+ this.options = options;
880
+ this.supportedLngs = this.options.supportedLngs || false;
881
+ this.logger = baseLogger.create('languageUtils');
882
+ }
883
+ getScriptPartFromCode(code) {
884
+ code = getCleanedCode(code);
885
+ if (!code || code.indexOf('-') < 0) return null;
886
+ const p = code.split('-');
887
+ if (p.length === 2) return null;
888
+ p.pop();
889
+ if (p[p.length - 1].toLowerCase() === 'x') return null;
890
+ return this.formatLanguageCode(p.join('-'));
891
+ }
892
+ getLanguagePartFromCode(code) {
893
+ code = getCleanedCode(code);
894
+ if (!code || code.indexOf('-') < 0) return code;
895
+ const p = code.split('-');
896
+ return this.formatLanguageCode(p[0]);
897
+ }
898
+ formatLanguageCode(code) {
899
+ if (isString$1(code) && code.indexOf('-') > -1) {
900
+ let formattedCode;
901
+ try {
902
+ formattedCode = Intl.getCanonicalLocales(code)[0];
903
+ } catch (e) {}
904
+ if (formattedCode && this.options.lowerCaseLng) {
905
+ formattedCode = formattedCode.toLowerCase();
906
+ }
907
+ if (formattedCode) return formattedCode;
908
+ if (this.options.lowerCaseLng) {
909
+ return code.toLowerCase();
910
+ }
911
+ return code;
912
+ }
913
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
914
+ }
915
+ isSupportedCode(code) {
916
+ if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
917
+ code = this.getLanguagePartFromCode(code);
918
+ }
919
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
920
+ }
921
+ getBestMatchFromCodes(codes) {
922
+ if (!codes) return null;
923
+ let found;
924
+ codes.forEach(code => {
925
+ if (found) return;
926
+ const cleanedLng = this.formatLanguageCode(code);
927
+ if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
928
+ });
929
+ if (!found && this.options.supportedLngs) {
930
+ codes.forEach(code => {
931
+ if (found) return;
932
+ const lngScOnly = this.getScriptPartFromCode(code);
933
+ if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
934
+ const lngOnly = this.getLanguagePartFromCode(code);
935
+ if (this.isSupportedCode(lngOnly)) return found = lngOnly;
936
+ found = this.options.supportedLngs.find(supportedLng => {
937
+ if (supportedLng === lngOnly) return supportedLng;
938
+ if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
939
+ if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
940
+ if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
941
+ });
942
+ });
943
+ }
944
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
945
+ return found;
946
+ }
947
+ getFallbackCodes(fallbacks, code) {
948
+ if (!fallbacks) return [];
949
+ if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
950
+ if (isString$1(fallbacks)) fallbacks = [fallbacks];
951
+ if (Array.isArray(fallbacks)) return fallbacks;
952
+ if (!code) return fallbacks.default || [];
953
+ let found = fallbacks[code];
954
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
955
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
956
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
957
+ if (!found) found = fallbacks.default;
958
+ return found || [];
959
+ }
960
+ toResolveHierarchy(code, fallbackCode) {
961
+ const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
962
+ const codes = [];
963
+ const addCode = c => {
964
+ if (!c) return;
965
+ if (this.isSupportedCode(c)) {
966
+ codes.push(c);
967
+ } else {
968
+ this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
969
+ }
970
+ };
971
+ if (isString$1(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
972
+ if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
973
+ if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
974
+ if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
975
+ } else if (isString$1(code)) {
976
+ addCode(this.formatLanguageCode(code));
977
+ }
978
+ fallbackCodes.forEach(fc => {
979
+ if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
980
+ });
981
+ return codes;
982
+ }
983
+ }
984
+ const suffixesOrder = {
985
+ zero: 0,
986
+ one: 1,
987
+ two: 2,
988
+ few: 3,
989
+ many: 4,
990
+ other: 5
991
+ };
992
+ const dummyRule = {
993
+ select: count => count === 1 ? 'one' : 'other',
994
+ resolvedOptions: () => ({
995
+ pluralCategories: ['one', 'other']
996
+ })
997
+ };
998
+ class PluralResolver {
999
+ constructor(languageUtils, options = {}) {
1000
+ this.languageUtils = languageUtils;
1001
+ this.options = options;
1002
+ this.logger = baseLogger.create('pluralResolver');
1003
+ this.pluralRulesCache = {};
1004
+ }
1005
+ addRule(lng, obj) {
1006
+ this.rules[lng] = obj;
1007
+ }
1008
+ clearCache() {
1009
+ this.pluralRulesCache = {};
1010
+ }
1011
+ getRule(code, options = {}) {
1012
+ const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
1013
+ const type = options.ordinal ? 'ordinal' : 'cardinal';
1014
+ const cacheKey = JSON.stringify({
1015
+ cleanedCode,
1016
+ type
1017
+ });
1018
+ if (cacheKey in this.pluralRulesCache) {
1019
+ return this.pluralRulesCache[cacheKey];
1020
+ }
1021
+ let rule;
1022
+ try {
1023
+ rule = new Intl.PluralRules(cleanedCode, {
1024
+ type
1025
+ });
1026
+ } catch (err) {
1027
+ if (!Intl) {
1028
+ this.logger.error('No Intl support, please use an Intl polyfill!');
1029
+ return dummyRule;
1030
+ }
1031
+ if (!code.match(/-|_/)) return dummyRule;
1032
+ const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1033
+ rule = this.getRule(lngPart, options);
1034
+ }
1035
+ this.pluralRulesCache[cacheKey] = rule;
1036
+ return rule;
1037
+ }
1038
+ needsPlural(code, options = {}) {
1039
+ let rule = this.getRule(code, options);
1040
+ if (!rule) rule = this.getRule('dev', options);
1041
+ return rule?.resolvedOptions().pluralCategories.length > 1;
1042
+ }
1043
+ getPluralFormsOfKey(code, key, options = {}) {
1044
+ return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
1045
+ }
1046
+ getSuffixes(code, options = {}) {
1047
+ let rule = this.getRule(code, options);
1048
+ if (!rule) rule = this.getRule('dev', options);
1049
+ if (!rule) return [];
1050
+ return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
1051
+ }
1052
+ getSuffix(code, count, options = {}) {
1053
+ const rule = this.getRule(code, options);
1054
+ if (rule) {
1055
+ return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
1056
+ }
1057
+ this.logger.warn(`no plural rule found for: ${code}`);
1058
+ return this.getSuffix('dev', count, options);
1059
+ }
1060
+ }
1061
+ const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {
1062
+ let path = getPathWithDefaults(data, defaultData, key);
1063
+ if (!path && ignoreJSONStructure && isString$1(key)) {
1064
+ path = deepFind(data, key, keySeparator);
1065
+ if (path === undefined) path = deepFind(defaultData, key, keySeparator);
1066
+ }
1067
+ return path;
1068
+ };
1069
+ const regexSafe = val => val.replace(/\$/g, '$$$$');
1070
+ class Interpolator {
1071
+ constructor(options = {}) {
1072
+ this.logger = baseLogger.create('interpolator');
1073
+ this.options = options;
1074
+ this.format = options?.interpolation?.format || (value => value);
1075
+ this.init(options);
1076
+ }
1077
+ init(options = {}) {
1078
+ if (!options.interpolation) options.interpolation = {
1079
+ escapeValue: true
1080
+ };
1081
+ const {
1082
+ escape: escape$1,
1083
+ escapeValue,
1084
+ useRawValueToEscape,
1085
+ prefix,
1086
+ prefixEscaped,
1087
+ suffix,
1088
+ suffixEscaped,
1089
+ formatSeparator,
1090
+ unescapeSuffix,
1091
+ unescapePrefix,
1092
+ nestingPrefix,
1093
+ nestingPrefixEscaped,
1094
+ nestingSuffix,
1095
+ nestingSuffixEscaped,
1096
+ nestingOptionsSeparator,
1097
+ maxReplaces,
1098
+ alwaysFormat
1099
+ } = options.interpolation;
1100
+ this.escape = escape$1 !== undefined ? escape$1 : escape;
1101
+ this.escapeValue = escapeValue !== undefined ? escapeValue : true;
1102
+ this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
1103
+ this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
1104
+ this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
1105
+ this.formatSeparator = formatSeparator || ',';
1106
+ this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
1107
+ this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
1108
+ this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
1109
+ this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
1110
+ this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
1111
+ this.maxReplaces = maxReplaces || 1000;
1112
+ this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
1113
+ this.resetRegExp();
1114
+ }
1115
+ reset() {
1116
+ if (this.options) this.init(this.options);
1117
+ }
1118
+ resetRegExp() {
1119
+ const getOrResetRegExp = (existingRegExp, pattern) => {
1120
+ if (existingRegExp?.source === pattern) {
1121
+ existingRegExp.lastIndex = 0;
1122
+ return existingRegExp;
1123
+ }
1124
+ return new RegExp(pattern, 'g');
1125
+ };
1126
+ this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1127
+ this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1128
+ this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1129
+ }
1130
+ interpolate(str, data, lng, options) {
1131
+ let match;
1132
+ let value;
1133
+ let replaces;
1134
+ const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1135
+ const handleFormat = key => {
1136
+ if (key.indexOf(this.formatSeparator) < 0) {
1137
+ const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1138
+ return this.alwaysFormat ? this.format(path, undefined, lng, {
1139
+ ...options,
1140
+ ...data,
1141
+ interpolationkey: key
1142
+ }) : path;
1143
+ }
1144
+ const p = key.split(this.formatSeparator);
1145
+ const k = p.shift().trim();
1146
+ const f = p.join(this.formatSeparator).trim();
1147
+ return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1148
+ ...options,
1149
+ ...data,
1150
+ interpolationkey: k
1151
+ });
1152
+ };
1153
+ this.resetRegExp();
1154
+ const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1155
+ const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1156
+ const todos = [{
1157
+ regex: this.regexpUnescape,
1158
+ safeValue: val => regexSafe(val)
1159
+ }, {
1160
+ regex: this.regexp,
1161
+ safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1162
+ }];
1163
+ todos.forEach(todo => {
1164
+ replaces = 0;
1165
+ while (match = todo.regex.exec(str)) {
1166
+ const matchedVar = match[1].trim();
1167
+ value = handleFormat(matchedVar);
1168
+ if (value === undefined) {
1169
+ if (typeof missingInterpolationHandler === 'function') {
1170
+ const temp = missingInterpolationHandler(str, match, options);
1171
+ value = isString$1(temp) ? temp : '';
1172
+ } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1173
+ value = '';
1174
+ } else if (skipOnVariables) {
1175
+ value = match[0];
1176
+ continue;
1177
+ } else {
1178
+ this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1179
+ value = '';
1180
+ }
1181
+ } else if (!isString$1(value) && !this.useRawValueToEscape) {
1182
+ value = makeString(value);
1183
+ }
1184
+ const safeValue = todo.safeValue(value);
1185
+ str = str.replace(match[0], safeValue);
1186
+ if (skipOnVariables) {
1187
+ todo.regex.lastIndex += value.length;
1188
+ todo.regex.lastIndex -= match[0].length;
1189
+ } else {
1190
+ todo.regex.lastIndex = 0;
1191
+ }
1192
+ replaces++;
1193
+ if (replaces >= this.maxReplaces) {
1194
+ break;
1195
+ }
1196
+ }
1197
+ });
1198
+ return str;
1199
+ }
1200
+ nest(str, fc, options = {}) {
1201
+ let match;
1202
+ let value;
1203
+ let clonedOptions;
1204
+ const handleHasOptions = (key, inheritedOptions) => {
1205
+ const sep = this.nestingOptionsSeparator;
1206
+ if (key.indexOf(sep) < 0) return key;
1207
+ const c = key.split(new RegExp(`${sep}[ ]*{`));
1208
+ let optionsString = `{${c[1]}`;
1209
+ key = c[0];
1210
+ optionsString = this.interpolate(optionsString, clonedOptions);
1211
+ const matchedSingleQuotes = optionsString.match(/'/g);
1212
+ const matchedDoubleQuotes = optionsString.match(/"/g);
1213
+ if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1214
+ optionsString = optionsString.replace(/'/g, '"');
1215
+ }
1216
+ try {
1217
+ clonedOptions = JSON.parse(optionsString);
1218
+ if (inheritedOptions) clonedOptions = {
1219
+ ...inheritedOptions,
1220
+ ...clonedOptions
1221
+ };
1222
+ } catch (e) {
1223
+ this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1224
+ return `${key}${sep}${optionsString}`;
1225
+ }
1226
+ if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1227
+ return key;
1228
+ };
1229
+ while (match = this.nestingRegexp.exec(str)) {
1230
+ let formatters = [];
1231
+ clonedOptions = {
1232
+ ...options
1233
+ };
1234
+ clonedOptions = clonedOptions.replace && !isString$1(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1235
+ clonedOptions.applyPostProcessor = false;
1236
+ delete clonedOptions.defaultValue;
1237
+ const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);
1238
+ if (keyEndIndex !== -1) {
1239
+ formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);
1240
+ match[1] = match[1].slice(0, keyEndIndex);
1241
+ }
1242
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1243
+ if (value && match[0] === str && !isString$1(value)) return value;
1244
+ if (!isString$1(value)) value = makeString(value);
1245
+ if (!value) {
1246
+ this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1247
+ value = '';
1248
+ }
1249
+ if (formatters.length) {
1250
+ value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1251
+ ...options,
1252
+ interpolationkey: match[1].trim()
1253
+ }), value.trim());
1254
+ }
1255
+ str = str.replace(match[0], value);
1256
+ this.regexp.lastIndex = 0;
1257
+ }
1258
+ return str;
1259
+ }
1260
+ }
1261
+ const parseFormatStr = formatStr => {
1262
+ let formatName = formatStr.toLowerCase().trim();
1263
+ const formatOptions = {};
1264
+ if (formatStr.indexOf('(') > -1) {
1265
+ const p = formatStr.split('(');
1266
+ formatName = p[0].toLowerCase().trim();
1267
+ const optStr = p[1].substring(0, p[1].length - 1);
1268
+ if (formatName === 'currency' && optStr.indexOf(':') < 0) {
1269
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1270
+ } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
1271
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
1272
+ } else {
1273
+ const opts = optStr.split(';');
1274
+ opts.forEach(opt => {
1275
+ if (opt) {
1276
+ const [key, ...rest] = opt.split(':');
1277
+ const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
1278
+ const trimmedKey = key.trim();
1279
+ if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1280
+ if (val === 'false') formatOptions[trimmedKey] = false;
1281
+ if (val === 'true') formatOptions[trimmedKey] = true;
1282
+ if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1283
+ }
1284
+ });
1285
+ }
1286
+ }
1287
+ return {
1288
+ formatName,
1289
+ formatOptions
1290
+ };
1291
+ };
1292
+ const createCachedFormatter = fn => {
1293
+ const cache = {};
1294
+ return (v, l, o) => {
1295
+ let optForCache = o;
1296
+ if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
1297
+ optForCache = {
1298
+ ...optForCache,
1299
+ [o.interpolationkey]: undefined
1300
+ };
1301
+ }
1302
+ const key = l + JSON.stringify(optForCache);
1303
+ let frm = cache[key];
1304
+ if (!frm) {
1305
+ frm = fn(getCleanedCode(l), o);
1306
+ cache[key] = frm;
1307
+ }
1308
+ return frm(v);
1309
+ };
1310
+ };
1311
+ const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);
1312
+ class Formatter {
1313
+ constructor(options = {}) {
1314
+ this.logger = baseLogger.create('formatter');
1315
+ this.options = options;
1316
+ this.init(options);
1317
+ }
1318
+ init(services, options = {
1319
+ interpolation: {}
1320
+ }) {
1321
+ this.formatSeparator = options.interpolation.formatSeparator || ',';
1322
+ const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1323
+ this.formats = {
1324
+ number: cf((lng, opt) => {
1325
+ const formatter = new Intl.NumberFormat(lng, {
1326
+ ...opt
1327
+ });
1328
+ return val => formatter.format(val);
1329
+ }),
1330
+ currency: cf((lng, opt) => {
1331
+ const formatter = new Intl.NumberFormat(lng, {
1332
+ ...opt,
1333
+ style: 'currency'
1334
+ });
1335
+ return val => formatter.format(val);
1336
+ }),
1337
+ datetime: cf((lng, opt) => {
1338
+ const formatter = new Intl.DateTimeFormat(lng, {
1339
+ ...opt
1340
+ });
1341
+ return val => formatter.format(val);
1342
+ }),
1343
+ relativetime: cf((lng, opt) => {
1344
+ const formatter = new Intl.RelativeTimeFormat(lng, {
1345
+ ...opt
1346
+ });
1347
+ return val => formatter.format(val, opt.range || 'day');
1348
+ }),
1349
+ list: cf((lng, opt) => {
1350
+ const formatter = new Intl.ListFormat(lng, {
1351
+ ...opt
1352
+ });
1353
+ return val => formatter.format(val);
1354
+ })
1355
+ };
1356
+ }
1357
+ add(name, fc) {
1358
+ this.formats[name.toLowerCase().trim()] = fc;
1359
+ }
1360
+ addCached(name, fc) {
1361
+ this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1362
+ }
1363
+ format(value, format, lng, options = {}) {
1364
+ const formats = format.split(this.formatSeparator);
1365
+ if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
1366
+ const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
1367
+ formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1368
+ }
1369
+ const result = formats.reduce((mem, f) => {
1370
+ const {
1371
+ formatName,
1372
+ formatOptions
1373
+ } = parseFormatStr(f);
1374
+ if (this.formats[formatName]) {
1375
+ let formatted = mem;
1376
+ try {
1377
+ const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1378
+ const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1379
+ formatted = this.formats[formatName](mem, l, {
1380
+ ...formatOptions,
1381
+ ...options,
1382
+ ...valOptions
1383
+ });
1384
+ } catch (error) {
1385
+ this.logger.warn(error);
1386
+ }
1387
+ return formatted;
1388
+ } else {
1389
+ this.logger.warn(`there was no format function for ${formatName}`);
1390
+ }
1391
+ return mem;
1392
+ }, value);
1393
+ return result;
1394
+ }
1395
+ }
1396
+ const removePending = (q, name) => {
1397
+ if (q.pending[name] !== undefined) {
1398
+ delete q.pending[name];
1399
+ q.pendingCount--;
1400
+ }
1401
+ };
1402
+ class Connector extends EventEmitter {
1403
+ constructor(backend, store, services, options = {}) {
1404
+ super();
1405
+ this.backend = backend;
1406
+ this.store = store;
1407
+ this.services = services;
1408
+ this.languageUtils = services.languageUtils;
1409
+ this.options = options;
1410
+ this.logger = baseLogger.create('backendConnector');
1411
+ this.waitingReads = [];
1412
+ this.maxParallelReads = options.maxParallelReads || 10;
1413
+ this.readingCalls = 0;
1414
+ this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1415
+ this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1416
+ this.state = {};
1417
+ this.queue = [];
1418
+ this.backend?.init?.(services, options.backend, options);
1419
+ }
1420
+ queueLoad(languages, namespaces, options, callback) {
1421
+ const toLoad = {};
1422
+ const pending = {};
1423
+ const toLoadLanguages = {};
1424
+ const toLoadNamespaces = {};
1425
+ languages.forEach(lng => {
1426
+ let hasAllNamespaces = true;
1427
+ namespaces.forEach(ns => {
1428
+ const name = `${lng}|${ns}`;
1429
+ if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1430
+ this.state[name] = 2;
1431
+ } else if (this.state[name] < 0) ;else if (this.state[name] === 1) {
1432
+ if (pending[name] === undefined) pending[name] = true;
1433
+ } else {
1434
+ this.state[name] = 1;
1435
+ hasAllNamespaces = false;
1436
+ if (pending[name] === undefined) pending[name] = true;
1437
+ if (toLoad[name] === undefined) toLoad[name] = true;
1438
+ if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
1439
+ }
1440
+ });
1441
+ if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1442
+ });
1443
+ if (Object.keys(toLoad).length || Object.keys(pending).length) {
1444
+ this.queue.push({
1445
+ pending,
1446
+ pendingCount: Object.keys(pending).length,
1447
+ loaded: {},
1448
+ errors: [],
1449
+ callback
1450
+ });
1451
+ }
1452
+ return {
1453
+ toLoad: Object.keys(toLoad),
1454
+ pending: Object.keys(pending),
1455
+ toLoadLanguages: Object.keys(toLoadLanguages),
1456
+ toLoadNamespaces: Object.keys(toLoadNamespaces)
1457
+ };
1458
+ }
1459
+ loaded(name, err, data) {
1460
+ const s = name.split('|');
1461
+ const lng = s[0];
1462
+ const ns = s[1];
1463
+ if (err) this.emit('failedLoading', lng, ns, err);
1464
+ if (!err && data) {
1465
+ this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
1466
+ skipCopy: true
1467
+ });
1468
+ }
1469
+ this.state[name] = err ? -1 : 2;
1470
+ if (err && data) this.state[name] = 0;
1471
+ const loaded = {};
1472
+ this.queue.forEach(q => {
1473
+ pushPath(q.loaded, [lng], ns);
1474
+ removePending(q, name);
1475
+ if (err) q.errors.push(err);
1476
+ if (q.pendingCount === 0 && !q.done) {
1477
+ Object.keys(q.loaded).forEach(l => {
1478
+ if (!loaded[l]) loaded[l] = {};
1479
+ const loadedKeys = q.loaded[l];
1480
+ if (loadedKeys.length) {
1481
+ loadedKeys.forEach(n => {
1482
+ if (loaded[l][n] === undefined) loaded[l][n] = true;
1483
+ });
1484
+ }
1485
+ });
1486
+ q.done = true;
1487
+ if (q.errors.length) {
1488
+ q.callback(q.errors);
1489
+ } else {
1490
+ q.callback();
1491
+ }
1492
+ }
1493
+ });
1494
+ this.emit('loaded', loaded);
1495
+ this.queue = this.queue.filter(q => !q.done);
1496
+ }
1497
+ read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1498
+ if (!lng.length) return callback(null, {});
1499
+ if (this.readingCalls >= this.maxParallelReads) {
1500
+ this.waitingReads.push({
1501
+ lng,
1502
+ ns,
1503
+ fcName,
1504
+ tried,
1505
+ wait,
1506
+ callback
1507
+ });
1508
+ return;
1509
+ }
1510
+ this.readingCalls++;
1511
+ const resolver = (err, data) => {
1512
+ this.readingCalls--;
1513
+ if (this.waitingReads.length > 0) {
1514
+ const next = this.waitingReads.shift();
1515
+ this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1516
+ }
1517
+ if (err && data && tried < this.maxRetries) {
1518
+ setTimeout(() => {
1519
+ this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1520
+ }, wait);
1521
+ return;
1522
+ }
1523
+ callback(err, data);
1524
+ };
1525
+ const fc = this.backend[fcName].bind(this.backend);
1526
+ if (fc.length === 2) {
1527
+ try {
1528
+ const r = fc(lng, ns);
1529
+ if (r && typeof r.then === 'function') {
1530
+ r.then(data => resolver(null, data)).catch(resolver);
1531
+ } else {
1532
+ resolver(null, r);
1533
+ }
1534
+ } catch (err) {
1535
+ resolver(err);
1536
+ }
1537
+ return;
1538
+ }
1539
+ return fc(lng, ns, resolver);
1540
+ }
1541
+ prepareLoading(languages, namespaces, options = {}, callback) {
1542
+ if (!this.backend) {
1543
+ this.logger.warn('No backend was added via i18next.use. Will not load resources.');
1544
+ return callback && callback();
1545
+ }
1546
+ if (isString$1(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1547
+ if (isString$1(namespaces)) namespaces = [namespaces];
1548
+ const toLoad = this.queueLoad(languages, namespaces, options, callback);
1549
+ if (!toLoad.toLoad.length) {
1550
+ if (!toLoad.pending.length) callback();
1551
+ return null;
1552
+ }
1553
+ toLoad.toLoad.forEach(name => {
1554
+ this.loadOne(name);
1555
+ });
1556
+ }
1557
+ load(languages, namespaces, callback) {
1558
+ this.prepareLoading(languages, namespaces, {}, callback);
1559
+ }
1560
+ reload(languages, namespaces, callback) {
1561
+ this.prepareLoading(languages, namespaces, {
1562
+ reload: true
1563
+ }, callback);
1564
+ }
1565
+ loadOne(name, prefix = '') {
1566
+ const s = name.split('|');
1567
+ const lng = s[0];
1568
+ const ns = s[1];
1569
+ this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
1570
+ if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1571
+ if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1572
+ this.loaded(name, err, data);
1573
+ });
1574
+ }
1575
+ saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
1576
+ if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1577
+ 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!!!');
1578
+ return;
1579
+ }
1580
+ if (key === undefined || key === null || key === '') return;
1581
+ if (this.backend?.create) {
1582
+ const opts = {
1583
+ ...options,
1584
+ isUpdate
1585
+ };
1586
+ const fc = this.backend.create.bind(this.backend);
1587
+ if (fc.length < 6) {
1588
+ try {
1589
+ let r;
1590
+ if (fc.length === 5) {
1591
+ r = fc(languages, namespace, key, fallbackValue, opts);
1592
+ } else {
1593
+ r = fc(languages, namespace, key, fallbackValue);
1594
+ }
1595
+ if (r && typeof r.then === 'function') {
1596
+ r.then(data => clb(null, data)).catch(clb);
1597
+ } else {
1598
+ clb(null, r);
1599
+ }
1600
+ } catch (err) {
1601
+ clb(err);
1602
+ }
1603
+ } else {
1604
+ fc(languages, namespace, key, fallbackValue, clb, opts);
1605
+ }
1606
+ }
1607
+ if (!languages || !languages[0]) return;
1608
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
1609
+ }
1610
+ }
1611
+ const get = () => ({
1612
+ debug: false,
1613
+ initAsync: true,
1614
+ ns: ['translation'],
1615
+ defaultNS: ['translation'],
1616
+ fallbackLng: ['dev'],
1617
+ fallbackNS: false,
1618
+ supportedLngs: false,
1619
+ nonExplicitSupportedLngs: false,
1620
+ load: 'all',
1621
+ preload: false,
1622
+ simplifyPluralSuffix: true,
1623
+ keySeparator: '.',
1624
+ nsSeparator: ':',
1625
+ pluralSeparator: '_',
1626
+ contextSeparator: '_',
1627
+ partialBundledLanguages: false,
1628
+ saveMissing: false,
1629
+ updateMissing: false,
1630
+ saveMissingTo: 'fallback',
1631
+ saveMissingPlurals: true,
1632
+ missingKeyHandler: false,
1633
+ missingInterpolationHandler: false,
1634
+ postProcess: false,
1635
+ postProcessPassResolved: false,
1636
+ returnNull: false,
1637
+ returnEmptyString: true,
1638
+ returnObjects: false,
1639
+ joinArrays: false,
1640
+ returnedObjectHandler: false,
1641
+ parseMissingKeyHandler: false,
1642
+ appendNamespaceToMissingKey: false,
1643
+ appendNamespaceToCIMode: false,
1644
+ overloadTranslationOptionHandler: args => {
1645
+ let ret = {};
1646
+ if (typeof args[1] === 'object') ret = args[1];
1647
+ if (isString$1(args[1])) ret.defaultValue = args[1];
1648
+ if (isString$1(args[2])) ret.tDescription = args[2];
1649
+ if (typeof args[2] === 'object' || typeof args[3] === 'object') {
1650
+ const options = args[3] || args[2];
1651
+ Object.keys(options).forEach(key => {
1652
+ ret[key] = options[key];
1653
+ });
1654
+ }
1655
+ return ret;
1656
+ },
1657
+ interpolation: {
1658
+ escapeValue: true,
1659
+ format: value => value,
1660
+ prefix: '{{',
1661
+ suffix: '}}',
1662
+ formatSeparator: ',',
1663
+ unescapePrefix: '-',
1664
+ nestingPrefix: '$t(',
1665
+ nestingSuffix: ')',
1666
+ nestingOptionsSeparator: ',',
1667
+ maxReplaces: 1000,
1668
+ skipOnVariables: true
1669
+ },
1670
+ cacheInBuiltFormats: true
1671
+ });
1672
+ const transformOptions = options => {
1673
+ if (isString$1(options.ns)) options.ns = [options.ns];
1674
+ if (isString$1(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1675
+ if (isString$1(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1676
+ if (options.supportedLngs?.indexOf?.('cimode') < 0) {
1677
+ options.supportedLngs = options.supportedLngs.concat(['cimode']);
1678
+ }
1679
+ if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;
1680
+ return options;
1681
+ };
1682
+ const noop = () => {};
1683
+ const bindMemberFunctions = inst => {
1684
+ const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1685
+ mems.forEach(mem => {
1686
+ if (typeof inst[mem] === 'function') {
1687
+ inst[mem] = inst[mem].bind(inst);
1688
+ }
1689
+ });
1690
+ };
1691
+ class I18n extends EventEmitter {
1692
+ constructor(options = {}, callback) {
1693
+ super();
1694
+ this.options = transformOptions(options);
1695
+ this.services = {};
1696
+ this.logger = baseLogger;
1697
+ this.modules = {
1698
+ external: []
1699
+ };
1700
+ bindMemberFunctions(this);
1701
+ if (callback && !this.isInitialized && !options.isClone) {
1702
+ if (!this.options.initAsync) {
1703
+ this.init(options, callback);
1704
+ return this;
1705
+ }
1706
+ setTimeout(() => {
1707
+ this.init(options, callback);
1708
+ }, 0);
1709
+ }
1710
+ }
1711
+ init(options = {}, callback) {
1712
+ this.isInitializing = true;
1713
+ if (typeof options === 'function') {
1714
+ callback = options;
1715
+ options = {};
1716
+ }
1717
+ if (options.defaultNS == null && options.ns) {
1718
+ if (isString$1(options.ns)) {
1719
+ options.defaultNS = options.ns;
1720
+ } else if (options.ns.indexOf('translation') < 0) {
1721
+ options.defaultNS = options.ns[0];
1722
+ }
1723
+ }
1724
+ const defOpts = get();
1725
+ this.options = {
1726
+ ...defOpts,
1727
+ ...this.options,
1728
+ ...transformOptions(options)
1729
+ };
1730
+ this.options.interpolation = {
1731
+ ...defOpts.interpolation,
1732
+ ...this.options.interpolation
1733
+ };
1734
+ if (options.keySeparator !== undefined) {
1735
+ this.options.userDefinedKeySeparator = options.keySeparator;
1736
+ }
1737
+ if (options.nsSeparator !== undefined) {
1738
+ this.options.userDefinedNsSeparator = options.nsSeparator;
1739
+ }
1740
+ const createClassOnDemand = ClassOrObject => {
1741
+ if (!ClassOrObject) return null;
1742
+ if (typeof ClassOrObject === 'function') return new ClassOrObject();
1743
+ return ClassOrObject;
1744
+ };
1745
+ if (!this.options.isClone) {
1746
+ if (this.modules.logger) {
1747
+ baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1748
+ } else {
1749
+ baseLogger.init(null, this.options);
1750
+ }
1751
+ let formatter;
1752
+ if (this.modules.formatter) {
1753
+ formatter = this.modules.formatter;
1754
+ } else {
1755
+ formatter = Formatter;
1756
+ }
1757
+ const lu = new LanguageUtil(this.options);
1758
+ this.store = new ResourceStore(this.options.resources, this.options);
1759
+ const s = this.services;
1760
+ s.logger = baseLogger;
1761
+ s.resourceStore = this.store;
1762
+ s.languageUtils = lu;
1763
+ s.pluralResolver = new PluralResolver(lu, {
1764
+ prepend: this.options.pluralSeparator,
1765
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
1766
+ });
1767
+ const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
1768
+ if (usingLegacyFormatFunction) {
1769
+ this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1770
+ }
1771
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1772
+ s.formatter = createClassOnDemand(formatter);
1773
+ if (s.formatter.init) s.formatter.init(s, this.options);
1774
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1775
+ }
1776
+ s.interpolator = new Interpolator(this.options);
1777
+ s.utils = {
1778
+ hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1779
+ };
1780
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1781
+ s.backendConnector.on('*', (event, ...args) => {
1782
+ this.emit(event, ...args);
1783
+ });
1784
+ if (this.modules.languageDetector) {
1785
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1786
+ if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1787
+ }
1788
+ if (this.modules.i18nFormat) {
1789
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1790
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
1791
+ }
1792
+ this.translator = new Translator(this.services, this.options);
1793
+ this.translator.on('*', (event, ...args) => {
1794
+ this.emit(event, ...args);
1795
+ });
1796
+ this.modules.external.forEach(m => {
1797
+ if (m.init) m.init(this);
1798
+ });
1799
+ }
1800
+ this.format = this.options.interpolation.format;
1801
+ if (!callback) callback = noop;
1802
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1803
+ const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1804
+ if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
1805
+ }
1806
+ if (!this.services.languageDetector && !this.options.lng) {
1807
+ this.logger.warn('init: no languageDetector is used and no lng is defined');
1808
+ }
1809
+ const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
1810
+ storeApi.forEach(fcName => {
1811
+ this[fcName] = (...args) => this.store[fcName](...args);
1812
+ });
1813
+ const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
1814
+ storeApiChained.forEach(fcName => {
1815
+ this[fcName] = (...args) => {
1816
+ this.store[fcName](...args);
1817
+ return this;
1818
+ };
1819
+ });
1820
+ const deferred = defer();
1821
+ const load = () => {
1822
+ const finish = (err, t) => {
1823
+ this.isInitializing = false;
1824
+ if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
1825
+ this.isInitialized = true;
1826
+ if (!this.options.isClone) this.logger.log('initialized', this.options);
1827
+ this.emit('initialized', this.options);
1828
+ deferred.resolve(t);
1829
+ callback(err, t);
1830
+ };
1831
+ if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1832
+ this.changeLanguage(this.options.lng, finish);
1833
+ };
1834
+ if (this.options.resources || !this.options.initAsync) {
1835
+ load();
1836
+ } else {
1837
+ setTimeout(load, 0);
1838
+ }
1839
+ return deferred;
1840
+ }
1841
+ loadResources(language, callback = noop) {
1842
+ let usedCallback = callback;
1843
+ const usedLng = isString$1(language) ? language : this.language;
1844
+ if (typeof language === 'function') usedCallback = language;
1845
+ if (!this.options.resources || this.options.partialBundledLanguages) {
1846
+ if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1847
+ const toLoad = [];
1848
+ const append = lng => {
1849
+ if (!lng) return;
1850
+ if (lng === 'cimode') return;
1851
+ const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1852
+ lngs.forEach(l => {
1853
+ if (l === 'cimode') return;
1854
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
1855
+ });
1856
+ };
1857
+ if (!usedLng) {
1858
+ const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1859
+ fallbacks.forEach(l => append(l));
1860
+ } else {
1861
+ append(usedLng);
1862
+ }
1863
+ this.options.preload?.forEach?.(l => append(l));
1864
+ this.services.backendConnector.load(toLoad, this.options.ns, e => {
1865
+ if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1866
+ usedCallback(e);
1867
+ });
1868
+ } else {
1869
+ usedCallback(null);
1870
+ }
1871
+ }
1872
+ reloadResources(lngs, ns, callback) {
1873
+ const deferred = defer();
1874
+ if (typeof lngs === 'function') {
1875
+ callback = lngs;
1876
+ lngs = undefined;
1877
+ }
1878
+ if (typeof ns === 'function') {
1879
+ callback = ns;
1880
+ ns = undefined;
1881
+ }
1882
+ if (!lngs) lngs = this.languages;
1883
+ if (!ns) ns = this.options.ns;
1884
+ if (!callback) callback = noop;
1885
+ this.services.backendConnector.reload(lngs, ns, err => {
1886
+ deferred.resolve();
1887
+ callback(err);
1888
+ });
1889
+ return deferred;
1890
+ }
1891
+ use(module) {
1892
+ if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
1893
+ if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
1894
+ if (module.type === 'backend') {
1895
+ this.modules.backend = module;
1896
+ }
1897
+ if (module.type === 'logger' || module.log && module.warn && module.error) {
1898
+ this.modules.logger = module;
1899
+ }
1900
+ if (module.type === 'languageDetector') {
1901
+ this.modules.languageDetector = module;
1902
+ }
1903
+ if (module.type === 'i18nFormat') {
1904
+ this.modules.i18nFormat = module;
1905
+ }
1906
+ if (module.type === 'postProcessor') {
1907
+ postProcessor.addPostProcessor(module);
1908
+ }
1909
+ if (module.type === 'formatter') {
1910
+ this.modules.formatter = module;
1911
+ }
1912
+ if (module.type === '3rdParty') {
1913
+ this.modules.external.push(module);
1914
+ }
1915
+ return this;
1916
+ }
1917
+ setResolvedLanguage(l) {
1918
+ if (!l || !this.languages) return;
1919
+ if (['cimode', 'dev'].indexOf(l) > -1) return;
1920
+ for (let li = 0; li < this.languages.length; li++) {
1921
+ const lngInLngs = this.languages[li];
1922
+ if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
1923
+ if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
1924
+ this.resolvedLanguage = lngInLngs;
1925
+ break;
1926
+ }
1927
+ }
1928
+ if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
1929
+ this.resolvedLanguage = l;
1930
+ this.languages.unshift(l);
1931
+ }
1932
+ }
1933
+ changeLanguage(lng, callback) {
1934
+ this.isLanguageChangingTo = lng;
1935
+ const deferred = defer();
1936
+ this.emit('languageChanging', lng);
1937
+ const setLngProps = l => {
1938
+ this.language = l;
1939
+ this.languages = this.services.languageUtils.toResolveHierarchy(l);
1940
+ this.resolvedLanguage = undefined;
1941
+ this.setResolvedLanguage(l);
1942
+ };
1943
+ const done = (err, l) => {
1944
+ if (l) {
1945
+ if (this.isLanguageChangingTo === lng) {
1946
+ setLngProps(l);
1947
+ this.translator.changeLanguage(l);
1948
+ this.isLanguageChangingTo = undefined;
1949
+ this.emit('languageChanged', l);
1950
+ this.logger.log('languageChanged', l);
1951
+ }
1952
+ } else {
1953
+ this.isLanguageChangingTo = undefined;
1954
+ }
1955
+ deferred.resolve((...args) => this.t(...args));
1956
+ if (callback) callback(err, (...args) => this.t(...args));
1957
+ };
1958
+ const setLng = lngs => {
1959
+ if (!lng && !lngs && this.services.languageDetector) lngs = [];
1960
+ const fl = isString$1(lngs) ? lngs : lngs && lngs[0];
1961
+ const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString$1(lngs) ? [lngs] : lngs);
1962
+ if (l) {
1963
+ if (!this.language) {
1964
+ setLngProps(l);
1965
+ }
1966
+ if (!this.translator.language) this.translator.changeLanguage(l);
1967
+ this.services.languageDetector?.cacheUserLanguage?.(l);
1968
+ }
1969
+ this.loadResources(l, err => {
1970
+ done(err, l);
1971
+ });
1972
+ };
1973
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
1974
+ setLng(this.services.languageDetector.detect());
1975
+ } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
1976
+ if (this.services.languageDetector.detect.length === 0) {
1977
+ this.services.languageDetector.detect().then(setLng);
1978
+ } else {
1979
+ this.services.languageDetector.detect(setLng);
1980
+ }
1981
+ } else {
1982
+ setLng(lng);
1983
+ }
1984
+ return deferred;
1985
+ }
1986
+ getFixedT(lng, ns, keyPrefix) {
1987
+ const fixedT = (key, opts, ...rest) => {
1988
+ let o;
1989
+ if (typeof opts !== 'object') {
1990
+ o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
1991
+ } else {
1992
+ o = {
1993
+ ...opts
1994
+ };
1995
+ }
1996
+ o.lng = o.lng || fixedT.lng;
1997
+ o.lngs = o.lngs || fixedT.lngs;
1998
+ o.ns = o.ns || fixedT.ns;
1999
+ if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2000
+ const keySeparator = this.options.keySeparator || '.';
2001
+ let resultKey;
2002
+ if (o.keyPrefix && Array.isArray(key)) {
2003
+ resultKey = key.map(k => {
2004
+ if (typeof k === 'function') k = keysFromSelector(k, {
2005
+ ...this.options,
2006
+ ...opts
2007
+ });
2008
+ return `${o.keyPrefix}${keySeparator}${k}`;
2009
+ });
2010
+ } else {
2011
+ if (typeof key === 'function') key = keysFromSelector(key, {
2012
+ ...this.options,
2013
+ ...opts
2014
+ });
2015
+ resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2016
+ }
2017
+ return this.t(resultKey, o);
2018
+ };
2019
+ if (isString$1(lng)) {
2020
+ fixedT.lng = lng;
2021
+ } else {
2022
+ fixedT.lngs = lng;
2023
+ }
2024
+ fixedT.ns = ns;
2025
+ fixedT.keyPrefix = keyPrefix;
2026
+ return fixedT;
2027
+ }
2028
+ t(...args) {
2029
+ return this.translator?.translate(...args);
2030
+ }
2031
+ exists(...args) {
2032
+ return this.translator?.exists(...args);
2033
+ }
2034
+ setDefaultNamespace(ns) {
2035
+ this.options.defaultNS = ns;
2036
+ }
2037
+ hasLoadedNamespace(ns, options = {}) {
2038
+ if (!this.isInitialized) {
2039
+ this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
2040
+ return false;
2041
+ }
2042
+ if (!this.languages || !this.languages.length) {
2043
+ this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
2044
+ return false;
2045
+ }
2046
+ const lng = options.lng || this.resolvedLanguage || this.languages[0];
2047
+ const fallbackLng = this.options ? this.options.fallbackLng : false;
2048
+ const lastLng = this.languages[this.languages.length - 1];
2049
+ if (lng.toLowerCase() === 'cimode') return true;
2050
+ const loadNotPending = (l, n) => {
2051
+ const loadState = this.services.backendConnector.state[`${l}|${n}`];
2052
+ return loadState === -1 || loadState === 0 || loadState === 2;
2053
+ };
2054
+ if (options.precheck) {
2055
+ const preResult = options.precheck(this, loadNotPending);
2056
+ if (preResult !== undefined) return preResult;
2057
+ }
2058
+ if (this.hasResourceBundle(lng, ns)) return true;
2059
+ if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2060
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2061
+ return false;
2062
+ }
2063
+ loadNamespaces(ns, callback) {
2064
+ const deferred = defer();
2065
+ if (!this.options.ns) {
2066
+ if (callback) callback();
2067
+ return Promise.resolve();
2068
+ }
2069
+ if (isString$1(ns)) ns = [ns];
2070
+ ns.forEach(n => {
2071
+ if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2072
+ });
2073
+ this.loadResources(err => {
2074
+ deferred.resolve();
2075
+ if (callback) callback(err);
2076
+ });
2077
+ return deferred;
2078
+ }
2079
+ loadLanguages(lngs, callback) {
2080
+ const deferred = defer();
2081
+ if (isString$1(lngs)) lngs = [lngs];
2082
+ const preloaded = this.options.preload || [];
2083
+ const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2084
+ if (!newLngs.length) {
2085
+ if (callback) callback();
2086
+ return Promise.resolve();
2087
+ }
2088
+ this.options.preload = preloaded.concat(newLngs);
2089
+ this.loadResources(err => {
2090
+ deferred.resolve();
2091
+ if (callback) callback(err);
2092
+ });
2093
+ return deferred;
2094
+ }
2095
+ dir(lng) {
2096
+ if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2097
+ if (!lng) return 'rtl';
2098
+ try {
2099
+ const l = new Intl.Locale(lng);
2100
+ if (l && l.getTextInfo) {
2101
+ const ti = l.getTextInfo();
2102
+ if (ti && ti.direction) return ti.direction;
2103
+ }
2104
+ } catch (e) {}
2105
+ 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'];
2106
+ const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2107
+ if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';
2108
+ return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
2109
+ }
2110
+ static createInstance(options = {}, callback) {
2111
+ return new I18n(options, callback);
2112
+ }
2113
+ cloneInstance(options = {}, callback = noop) {
2114
+ const forkResourceStore = options.forkResourceStore;
2115
+ if (forkResourceStore) delete options.forkResourceStore;
2116
+ const mergedOptions = {
2117
+ ...this.options,
2118
+ ...options,
2119
+ ...{
2120
+ isClone: true
2121
+ }
2122
+ };
2123
+ const clone = new I18n(mergedOptions);
2124
+ if (options.debug !== undefined || options.prefix !== undefined) {
2125
+ clone.logger = clone.logger.clone(options);
2126
+ }
2127
+ const membersToCopy = ['store', 'services', 'language'];
2128
+ membersToCopy.forEach(m => {
2129
+ clone[m] = this[m];
2130
+ });
2131
+ clone.services = {
2132
+ ...this.services
2133
+ };
2134
+ clone.services.utils = {
2135
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2136
+ };
2137
+ if (forkResourceStore) {
2138
+ const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2139
+ prev[l] = {
2140
+ ...this.store.data[l]
2141
+ };
2142
+ prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2143
+ acc[n] = {
2144
+ ...prev[l][n]
2145
+ };
2146
+ return acc;
2147
+ }, prev[l]);
2148
+ return prev;
2149
+ }, {});
2150
+ clone.store = new ResourceStore(clonedData, mergedOptions);
2151
+ clone.services.resourceStore = clone.store;
2152
+ }
2153
+ clone.translator = new Translator(clone.services, mergedOptions);
2154
+ clone.translator.on('*', (event, ...args) => {
2155
+ clone.emit(event, ...args);
2156
+ });
2157
+ clone.init(mergedOptions, callback);
2158
+ clone.translator.options = mergedOptions;
2159
+ clone.translator.backendConnector.services.utils = {
2160
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2161
+ };
2162
+ return clone;
2163
+ }
2164
+ toJSON() {
2165
+ return {
2166
+ options: this.options,
2167
+ store: this.store,
2168
+ language: this.language,
2169
+ languages: this.languages,
2170
+ resolvedLanguage: this.resolvedLanguage
2171
+ };
2172
+ }
2173
+ }
2174
+ const instance = I18n.createInstance();
2175
+ instance.createInstance = I18n.createInstance;
2176
+ instance.createInstance;
2177
+ instance.dir;
2178
+ instance.init;
2179
+ instance.loadResources;
2180
+ instance.reloadResources;
2181
+ instance.use;
2182
+ instance.changeLanguage;
2183
+ instance.getFixedT;
2184
+ instance.t;
2185
+ instance.exists;
2186
+ instance.setDefaultNamespace;
2187
+ instance.hasLoadedNamespace;
2188
+ instance.loadNamespaces;
2189
+ instance.loadLanguages;
10
2190
 
11
- var voidElements = {
12
- "area": true,
13
- "base": true,
14
- "br": true,
15
- "col": true,
16
- "embed": true,
17
- "hr": true,
18
- "img": true,
19
- "input": true,
20
- "link": true,
21
- "meta": true,
22
- "param": true,
23
- "source": true,
24
- "track": true,
25
- "wbr": true
26
- };
2191
+ function getDefaultExportFromCjs (x) {
2192
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2193
+ }
27
2194
 
28
- var e = /*@__PURE__*/getDefaultExportFromCjs(voidElements);
2195
+ var voidElements = {
2196
+ "area": true,
2197
+ "base": true,
2198
+ "br": true,
2199
+ "col": true,
2200
+ "embed": true,
2201
+ "hr": true,
2202
+ "img": true,
2203
+ "input": true,
2204
+ "link": true,
2205
+ "meta": true,
2206
+ "param": true,
2207
+ "source": true,
2208
+ "track": true,
2209
+ "wbr": true
2210
+ };
29
2211
 
30
- var t = /\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;
31
- function n(n) {
32
- var r = {
33
- type: "tag",
34
- name: "",
35
- voidElement: false,
36
- attrs: {},
37
- children: []
38
- },
39
- i = n.match(/<\/?([^\s]+?)[/\s>]/);
40
- if (i && (r.name = i[1], (e[i[1]] || "/" === n.charAt(n.length - 2)) && (r.voidElement = true), r.name.startsWith("!--"))) {
41
- var s = n.indexOf("--\x3e");
42
- return {
43
- type: "comment",
44
- comment: -1 !== s ? n.slice(4, s) : ""
45
- };
46
- }
47
- for (var a = new RegExp(t), c = null; null !== (c = a.exec(n));) if (c[0].trim()) if (c[1]) {
48
- var o = c[1].trim(),
49
- l = [o, ""];
50
- o.indexOf("=") > -1 && (l = o.split("=")), r.attrs[l[0]] = l[1], a.lastIndex--;
51
- } else c[2] && (r.attrs[c[2]] = c[3].trim().substring(1, c[3].length - 1));
52
- return r;
53
- }
54
- var r = /<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,
55
- i = /^\s*$/,
56
- s = Object.create(null);
57
- function a(e, t) {
58
- switch (t.type) {
59
- case "text":
60
- return e + t.content;
61
- case "tag":
62
- return e += "<" + t.name + (t.attrs ? function (e) {
63
- var t = [];
64
- for (var n in e) t.push(n + '="' + e[n] + '"');
65
- return t.length ? " " + t.join(" ") : "";
66
- }(t.attrs) : "") + (t.voidElement ? "/>" : ">"), t.voidElement ? e : e + t.children.reduce(a, "") + "</" + t.name + ">";
67
- case "comment":
68
- return e + "\x3c!--" + t.comment + "--\x3e";
69
- }
70
- }
71
- var c = {
72
- parse: function (e, t) {
73
- t || (t = {}), t.components || (t.components = s);
74
- var a,
75
- c = [],
76
- o = [],
77
- l = -1,
78
- m = false;
79
- if (0 !== e.indexOf("<")) {
80
- var u = e.indexOf("<");
81
- c.push({
82
- type: "text",
83
- content: -1 === u ? e : e.substring(0, u)
84
- });
85
- }
86
- return e.replace(r, function (r, s) {
87
- if (m) {
88
- if (r !== "</" + a.name + ">") return;
89
- m = false;
90
- }
91
- var u,
92
- f = "/" !== r.charAt(1),
93
- h = r.startsWith("\x3c!--"),
94
- p = s + r.length,
95
- d = e.charAt(p);
96
- if (h) {
97
- var v = n(r);
98
- return l < 0 ? (c.push(v), c) : ((u = o[l]).children.push(v), c);
99
- }
100
- if (f && (l++, "tag" === (a = n(r)).type && t.components[a.name] && (a.type = "component", m = true), a.voidElement || m || !d || "<" === d || a.children.push({
101
- type: "text",
102
- content: e.slice(p, e.indexOf("<", p))
103
- }), 0 === l && c.push(a), (u = o[l - 1]) && u.children.push(a), o[l] = a), (!f || a.voidElement) && (l > -1 && (a.voidElement || a.name === r.slice(2, -1)) && (l--, a = -1 === l ? c : o[l]), !m && "<" !== d && d)) {
104
- u = -1 === l ? c : o[l].children;
105
- var x = e.indexOf("<", p),
106
- g = e.slice(p, -1 === x ? void 0 : x);
107
- i.test(g) && (g = " "), (x > -1 && l + u.length >= 0 || " " !== g) && u.push({
108
- type: "text",
109
- content: g
110
- });
111
- }
112
- }), c;
113
- },
114
- stringify: function (e) {
115
- return e.reduce(function (e, t) {
116
- return e + a("", t);
117
- }, "");
118
- }
119
- };
2212
+ var e = /*@__PURE__*/getDefaultExportFromCjs(voidElements);
120
2213
 
121
- const warn = (i18n, code, msg, rest) => {
122
- const args = [msg, {
123
- code,
124
- ...(rest || {})
125
- }];
126
- if (i18n?.services?.logger?.forward) {
127
- return i18n.services.logger.forward(args, 'warn', 'react-i18next::', true);
128
- }
129
- if (isString(args[0])) args[0] = `react-i18next:: ${args[0]}`;
130
- if (i18n?.services?.logger?.warn) {
131
- i18n.services.logger.warn(...args);
132
- } else if (console?.warn) {
133
- console.warn(...args);
134
- }
135
- };
136
- const alreadyWarned = {};
137
- const warnOnce = (i18n, code, msg, rest) => {
138
- if (isString(msg) && alreadyWarned[msg]) return;
139
- if (isString(msg)) alreadyWarned[msg] = new Date();
140
- warn(i18n, code, msg, rest);
141
- };
142
- const loadedClb = (i18n, cb) => () => {
143
- if (i18n.isInitialized) {
144
- cb();
145
- } else {
146
- const initialized = () => {
147
- setTimeout(() => {
148
- i18n.off('initialized', initialized);
149
- }, 0);
150
- cb();
151
- };
152
- i18n.on('initialized', initialized);
153
- }
154
- };
155
- const loadNamespaces = (i18n, ns, cb) => {
156
- i18n.loadNamespaces(ns, loadedClb(i18n, cb));
157
- };
158
- const loadLanguages = (i18n, lng, ns, cb) => {
159
- if (isString(ns)) ns = [ns];
160
- if (i18n.options.preload && i18n.options.preload.indexOf(lng) > -1) return loadNamespaces(i18n, ns, cb);
161
- ns.forEach(n => {
162
- if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);
163
- });
164
- i18n.loadLanguages(lng, loadedClb(i18n, cb));
165
- };
166
- const hasLoadedNamespace = (ns, i18n, options = {}) => {
167
- if (!i18n.languages || !i18n.languages.length) {
168
- warnOnce(i18n, 'NO_LANGUAGES', 'i18n.languages were undefined or empty', {
169
- languages: i18n.languages
170
- });
171
- return true;
172
- }
173
- return i18n.hasLoadedNamespace(ns, {
174
- lng: options.lng,
175
- precheck: (i18nInstance, loadNotPending) => {
176
- if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;
177
- }
178
- });
179
- };
180
- const getDisplayName = Component => Component.displayName || Component.name || (isString(Component) && Component.length > 0 ? Component : 'Unknown');
181
- const isString = obj => typeof obj === 'string';
182
- const isObject = obj => typeof obj === 'object' && obj !== null;
2214
+ var t = /\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;
2215
+ function n(n) {
2216
+ var r = {
2217
+ type: "tag",
2218
+ name: "",
2219
+ voidElement: false,
2220
+ attrs: {},
2221
+ children: []
2222
+ },
2223
+ i = n.match(/<\/?([^\s]+?)[/\s>]/);
2224
+ if (i && (r.name = i[1], (e[i[1]] || "/" === n.charAt(n.length - 2)) && (r.voidElement = true), r.name.startsWith("!--"))) {
2225
+ var s = n.indexOf("--\x3e");
2226
+ return {
2227
+ type: "comment",
2228
+ comment: -1 !== s ? n.slice(4, s) : ""
2229
+ };
2230
+ }
2231
+ for (var a = new RegExp(t), c = null; null !== (c = a.exec(n));) if (c[0].trim()) if (c[1]) {
2232
+ var o = c[1].trim(),
2233
+ l = [o, ""];
2234
+ o.indexOf("=") > -1 && (l = o.split("=")), r.attrs[l[0]] = l[1], a.lastIndex--;
2235
+ } else c[2] && (r.attrs[c[2]] = c[3].trim().substring(1, c[3].length - 1));
2236
+ return r;
2237
+ }
2238
+ var r = /<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,
2239
+ i = /^\s*$/,
2240
+ s = Object.create(null);
2241
+ function a(e, t) {
2242
+ switch (t.type) {
2243
+ case "text":
2244
+ return e + t.content;
2245
+ case "tag":
2246
+ return e += "<" + t.name + (t.attrs ? function (e) {
2247
+ var t = [];
2248
+ for (var n in e) t.push(n + '="' + e[n] + '"');
2249
+ return t.length ? " " + t.join(" ") : "";
2250
+ }(t.attrs) : "") + (t.voidElement ? "/>" : ">"), t.voidElement ? e : e + t.children.reduce(a, "") + "</" + t.name + ">";
2251
+ case "comment":
2252
+ return e + "\x3c!--" + t.comment + "--\x3e";
2253
+ }
2254
+ }
2255
+ var c = {
2256
+ parse: function (e, t) {
2257
+ t || (t = {}), t.components || (t.components = s);
2258
+ var a,
2259
+ c = [],
2260
+ o = [],
2261
+ l = -1,
2262
+ m = false;
2263
+ if (0 !== e.indexOf("<")) {
2264
+ var u = e.indexOf("<");
2265
+ c.push({
2266
+ type: "text",
2267
+ content: -1 === u ? e : e.substring(0, u)
2268
+ });
2269
+ }
2270
+ return e.replace(r, function (r, s) {
2271
+ if (m) {
2272
+ if (r !== "</" + a.name + ">") return;
2273
+ m = false;
2274
+ }
2275
+ var u,
2276
+ f = "/" !== r.charAt(1),
2277
+ h = r.startsWith("\x3c!--"),
2278
+ p = s + r.length,
2279
+ d = e.charAt(p);
2280
+ if (h) {
2281
+ var v = n(r);
2282
+ return l < 0 ? (c.push(v), c) : ((u = o[l]).children.push(v), c);
2283
+ }
2284
+ if (f && (l++, "tag" === (a = n(r)).type && t.components[a.name] && (a.type = "component", m = true), a.voidElement || m || !d || "<" === d || a.children.push({
2285
+ type: "text",
2286
+ content: e.slice(p, e.indexOf("<", p))
2287
+ }), 0 === l && c.push(a), (u = o[l - 1]) && u.children.push(a), o[l] = a), (!f || a.voidElement) && (l > -1 && (a.voidElement || a.name === r.slice(2, -1)) && (l--, a = -1 === l ? c : o[l]), !m && "<" !== d && d)) {
2288
+ u = -1 === l ? c : o[l].children;
2289
+ var x = e.indexOf("<", p),
2290
+ g = e.slice(p, -1 === x ? void 0 : x);
2291
+ i.test(g) && (g = " "), (x > -1 && l + u.length >= 0 || " " !== g) && u.push({
2292
+ type: "text",
2293
+ content: g
2294
+ });
2295
+ }
2296
+ }), c;
2297
+ },
2298
+ stringify: function (e) {
2299
+ return e.reduce(function (e, t) {
2300
+ return e + a("", t);
2301
+ }, "");
2302
+ }
2303
+ };
183
2304
 
184
- const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
185
- const htmlEntities = {
186
- '&amp;': '&',
187
- '&#38;': '&',
188
- '&lt;': '<',
189
- '&#60;': '<',
190
- '&gt;': '>',
191
- '&#62;': '>',
192
- '&apos;': "'",
193
- '&#39;': "'",
194
- '&quot;': '"',
195
- '&#34;': '"',
196
- '&nbsp;': ' ',
197
- '&#160;': ' ',
198
- '&copy;': '©',
199
- '&#169;': '©',
200
- '&reg;': '®',
201
- '&#174;': '®',
202
- '&hellip;': '…',
203
- '&#8230;': '…',
204
- '&#x2F;': '/',
205
- '&#47;': '/'
206
- };
207
- const unescapeHtmlEntity = m => htmlEntities[m];
208
- const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);
2305
+ const warn = (i18n, code, msg, rest) => {
2306
+ const args = [msg, {
2307
+ code,
2308
+ ...(rest || {})
2309
+ }];
2310
+ if (i18n?.services?.logger?.forward) {
2311
+ return i18n.services.logger.forward(args, 'warn', 'react-i18next::', true);
2312
+ }
2313
+ if (isString(args[0])) args[0] = `react-i18next:: ${args[0]}`;
2314
+ if (i18n?.services?.logger?.warn) {
2315
+ i18n.services.logger.warn(...args);
2316
+ } else if (console?.warn) {
2317
+ console.warn(...args);
2318
+ }
2319
+ };
2320
+ const alreadyWarned = {};
2321
+ const warnOnce = (i18n, code, msg, rest) => {
2322
+ if (isString(msg) && alreadyWarned[msg]) return;
2323
+ if (isString(msg)) alreadyWarned[msg] = new Date();
2324
+ warn(i18n, code, msg, rest);
2325
+ };
2326
+ const loadedClb = (i18n, cb) => () => {
2327
+ if (i18n.isInitialized) {
2328
+ cb();
2329
+ } else {
2330
+ const initialized = () => {
2331
+ setTimeout(() => {
2332
+ i18n.off('initialized', initialized);
2333
+ }, 0);
2334
+ cb();
2335
+ };
2336
+ i18n.on('initialized', initialized);
2337
+ }
2338
+ };
2339
+ const loadNamespaces = (i18n, ns, cb) => {
2340
+ i18n.loadNamespaces(ns, loadedClb(i18n, cb));
2341
+ };
2342
+ const loadLanguages = (i18n, lng, ns, cb) => {
2343
+ if (isString(ns)) ns = [ns];
2344
+ if (i18n.options.preload && i18n.options.preload.indexOf(lng) > -1) return loadNamespaces(i18n, ns, cb);
2345
+ ns.forEach(n => {
2346
+ if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);
2347
+ });
2348
+ i18n.loadLanguages(lng, loadedClb(i18n, cb));
2349
+ };
2350
+ const hasLoadedNamespace = (ns, i18n, options = {}) => {
2351
+ if (!i18n.languages || !i18n.languages.length) {
2352
+ warnOnce(i18n, 'NO_LANGUAGES', 'i18n.languages were undefined or empty', {
2353
+ languages: i18n.languages
2354
+ });
2355
+ return true;
2356
+ }
2357
+ return i18n.hasLoadedNamespace(ns, {
2358
+ lng: options.lng,
2359
+ precheck: (i18nInstance, loadNotPending) => {
2360
+ if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;
2361
+ }
2362
+ });
2363
+ };
2364
+ const getDisplayName = Component => Component.displayName || Component.name || (isString(Component) && Component.length > 0 ? Component : 'Unknown');
2365
+ const isString = obj => typeof obj === 'string';
2366
+ const isObject = obj => typeof obj === 'object' && obj !== null;
209
2367
 
210
- let defaultOptions = {
211
- bindI18n: 'languageChanged',
212
- bindI18nStore: '',
213
- transEmptyNodeValue: '',
214
- transSupportBasicHtmlNodes: true,
215
- transWrapTextNodes: '',
216
- transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
217
- useSuspense: true,
218
- unescape
219
- };
220
- const setDefaults = (options = {}) => {
221
- defaultOptions = {
222
- ...defaultOptions,
223
- ...options
224
- };
225
- };
226
- const getDefaults = () => defaultOptions;
2368
+ const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
2369
+ const htmlEntities = {
2370
+ '&amp;': '&',
2371
+ '&#38;': '&',
2372
+ '&lt;': '<',
2373
+ '&#60;': '<',
2374
+ '&gt;': '>',
2375
+ '&#62;': '>',
2376
+ '&apos;': "'",
2377
+ '&#39;': "'",
2378
+ '&quot;': '"',
2379
+ '&#34;': '"',
2380
+ '&nbsp;': ' ',
2381
+ '&#160;': ' ',
2382
+ '&copy;': '©',
2383
+ '&#169;': '©',
2384
+ '&reg;': '®',
2385
+ '&#174;': '®',
2386
+ '&hellip;': '…',
2387
+ '&#8230;': '…',
2388
+ '&#x2F;': '/',
2389
+ '&#47;': '/'
2390
+ };
2391
+ const unescapeHtmlEntity = m => htmlEntities[m];
2392
+ const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);
227
2393
 
228
- let i18nInstance;
229
- const setI18n = instance => {
230
- i18nInstance = instance;
231
- };
232
- const getI18n = () => i18nInstance;
2394
+ let defaultOptions = {
2395
+ bindI18n: 'languageChanged',
2396
+ bindI18nStore: '',
2397
+ transEmptyNodeValue: '',
2398
+ transSupportBasicHtmlNodes: true,
2399
+ transWrapTextNodes: '',
2400
+ transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
2401
+ useSuspense: true,
2402
+ unescape
2403
+ };
2404
+ const setDefaults = (options = {}) => {
2405
+ defaultOptions = {
2406
+ ...defaultOptions,
2407
+ ...options
2408
+ };
2409
+ };
2410
+ const getDefaults = () => defaultOptions;
233
2411
 
234
- const hasChildren = (node, checkLength) => {
235
- if (!node) return false;
236
- const base = node.props?.children ?? node.children;
237
- if (checkLength) return base.length > 0;
238
- return !!base;
239
- };
240
- const getChildren = node => {
241
- if (!node) return [];
242
- const children = node.props?.children ?? node.children;
243
- return node.props?.i18nIsDynamicList ? getAsArray(children) : children;
244
- };
245
- const hasValidReactChildren = children => Array.isArray(children) && children.every(react.isValidElement);
246
- const getAsArray = data => Array.isArray(data) ? data : [data];
247
- const mergeProps = (source, target) => {
248
- const newTarget = {
249
- ...target
250
- };
251
- newTarget.props = Object.assign(source.props, target.props);
252
- return newTarget;
253
- };
254
- const nodesToString = (children, i18nOptions, i18n, i18nKey) => {
255
- if (!children) return '';
256
- let stringNode = '';
257
- const childrenArray = getAsArray(children);
258
- const keepArray = i18nOptions?.transSupportBasicHtmlNodes ? i18nOptions.transKeepBasicHtmlNodesFor ?? [] : [];
259
- childrenArray.forEach((child, childIndex) => {
260
- if (isString(child)) {
261
- stringNode += `${child}`;
262
- return;
263
- }
264
- if (react.isValidElement(child)) {
265
- const {
266
- props,
267
- type
268
- } = child;
269
- const childPropsCount = Object.keys(props).length;
270
- const shouldKeepChild = keepArray.indexOf(type) > -1;
271
- const childChildren = props.children;
272
- if (!childChildren && shouldKeepChild && !childPropsCount) {
273
- stringNode += `<${type}/>`;
274
- return;
275
- }
276
- if (!childChildren && (!shouldKeepChild || childPropsCount) || props.i18nIsDynamicList) {
277
- stringNode += `<${childIndex}></${childIndex}>`;
278
- return;
279
- }
280
- if (shouldKeepChild && childPropsCount === 1 && isString(childChildren)) {
281
- stringNode += `<${type}>${childChildren}</${type}>`;
282
- return;
283
- }
284
- const content = nodesToString(childChildren, i18nOptions, i18n, i18nKey);
285
- stringNode += `<${childIndex}>${content}</${childIndex}>`;
286
- return;
287
- }
288
- if (child === null) {
289
- warn(i18n, 'TRANS_NULL_VALUE', `Passed in a null value as child`, {
290
- i18nKey
291
- });
292
- return;
293
- }
294
- if (isObject(child)) {
295
- const {
296
- format,
297
- ...clone
298
- } = child;
299
- const keys = Object.keys(clone);
300
- if (keys.length === 1) {
301
- const value = format ? `${keys[0]}, ${format}` : keys[0];
302
- stringNode += `{{${value}}}`;
303
- return;
304
- }
305
- warn(i18n, 'TRANS_INVALID_OBJ', `Invalid child - Object should only have keys {{ value, format }} (format is optional).`, {
306
- i18nKey,
307
- child
308
- });
309
- return;
310
- }
311
- warn(i18n, 'TRANS_INVALID_VAR', `Passed in a variable like {number} - pass variables for interpolation as full objects like {{number}}.`, {
312
- i18nKey,
313
- child
314
- });
315
- });
316
- return stringNode;
317
- };
318
- const renderNodes = (children, knownComponentsMap, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) => {
319
- if (targetString === '') return [];
320
- const keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
321
- const emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.map(keep => `<${keep}`).join('|')).test(targetString);
322
- if (!children && !knownComponentsMap && !emptyChildrenButNeedsHandling && !shouldUnescape) return [targetString];
323
- const data = knownComponentsMap ?? {};
324
- const getData = childs => {
325
- const childrenArray = getAsArray(childs);
326
- childrenArray.forEach(child => {
327
- if (isString(child)) return;
328
- if (hasChildren(child)) getData(getChildren(child));else if (isObject(child) && !react.isValidElement(child)) Object.assign(data, child);
329
- });
330
- };
331
- getData(children);
332
- const ast = c.parse(`<0>${targetString}</0>`);
333
- const opts = {
334
- ...data,
335
- ...combinedTOpts
336
- };
337
- const renderInner = (child, node, rootReactNode) => {
338
- const childs = getChildren(child);
339
- const mappedChildren = mapAST(childs, node.children, rootReactNode);
340
- return hasValidReactChildren(childs) && mappedChildren.length === 0 || child.props?.i18nIsDynamicList ? childs : mappedChildren;
341
- };
342
- const pushTranslatedJSX = (child, inner, mem, i, isVoid) => {
343
- if (child.dummy) {
344
- child.children = inner;
345
- mem.push(react.cloneElement(child, {
346
- key: i
347
- }, isVoid ? undefined : inner));
348
- } else {
349
- mem.push(...react.Children.map([child], c => {
350
- const props = {
351
- ...c.props
352
- };
353
- delete props.i18nIsDynamicList;
354
- return react.createElement(c.type, {
355
- ...props,
356
- key: i,
357
- ref: c.props.ref ?? c.ref
358
- }, isVoid ? null : inner);
359
- }));
360
- }
361
- };
362
- const mapAST = (reactNode, astNode, rootReactNode) => {
363
- const reactNodes = getAsArray(reactNode);
364
- const astNodes = getAsArray(astNode);
365
- return astNodes.reduce((mem, node, i) => {
366
- const translationContent = node.children?.[0]?.content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);
367
- if (node.type === 'tag') {
368
- let tmp = reactNodes[parseInt(node.name, 10)];
369
- if (!tmp && knownComponentsMap) tmp = knownComponentsMap[node.name];
370
- if (rootReactNode.length === 1 && !tmp) tmp = rootReactNode[0][node.name];
371
- if (!tmp) tmp = {};
372
- const child = Object.keys(node.attrs).length !== 0 ? mergeProps({
373
- props: node.attrs
374
- }, tmp) : tmp;
375
- const isElement = react.isValidElement(child);
376
- const isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;
377
- const isEmptyTransWithHTML = emptyChildrenButNeedsHandling && isObject(child) && child.dummy && !isElement;
378
- const isKnownComponent = isObject(knownComponentsMap) && Object.hasOwnProperty.call(knownComponentsMap, node.name);
379
- if (isString(child)) {
380
- const value = i18n.services.interpolator.interpolate(child, opts, i18n.language);
381
- mem.push(value);
382
- } else if (hasChildren(child) || isValidTranslationWithChildren) {
383
- const inner = renderInner(child, node, rootReactNode);
384
- pushTranslatedJSX(child, inner, mem, i);
385
- } else if (isEmptyTransWithHTML) {
386
- const inner = mapAST(reactNodes, node.children, rootReactNode);
387
- pushTranslatedJSX(child, inner, mem, i);
388
- } else if (Number.isNaN(parseFloat(node.name))) {
389
- if (isKnownComponent) {
390
- const inner = renderInner(child, node, rootReactNode);
391
- pushTranslatedJSX(child, inner, mem, i, node.voidElement);
392
- } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
393
- if (node.voidElement) {
394
- mem.push(react.createElement(node.name, {
395
- key: `${node.name}-${i}`
396
- }));
397
- } else {
398
- const inner = mapAST(reactNodes, node.children, rootReactNode);
399
- mem.push(react.createElement(node.name, {
400
- key: `${node.name}-${i}`
401
- }, inner));
402
- }
403
- } else if (node.voidElement) {
404
- mem.push(`<${node.name} />`);
405
- } else {
406
- const inner = mapAST(reactNodes, node.children, rootReactNode);
407
- mem.push(`<${node.name}>${inner}</${node.name}>`);
408
- }
409
- } else if (isObject(child) && !isElement) {
410
- const content = node.children[0] ? translationContent : null;
411
- if (content) mem.push(content);
412
- } else {
413
- pushTranslatedJSX(child, translationContent, mem, i, node.children.length !== 1 || !translationContent);
414
- }
415
- } else if (node.type === 'text') {
416
- const wrapTextNodes = i18nOptions.transWrapTextNodes;
417
- const content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);
418
- if (wrapTextNodes) {
419
- mem.push(react.createElement(wrapTextNodes, {
420
- key: `${node.name}-${i}`
421
- }, content));
422
- } else {
423
- mem.push(content);
424
- }
425
- }
426
- return mem;
427
- }, []);
428
- };
429
- const result = mapAST([{
430
- dummy: true,
431
- children: children || []
432
- }], ast, getAsArray(children || []));
433
- return getChildren(result[0]);
434
- };
435
- const fixComponentProps = (component, index, translation) => {
436
- const componentKey = component.key || index;
437
- const comp = react.cloneElement(component, {
438
- key: componentKey
439
- });
440
- if (!comp.props || !comp.props.children || translation.indexOf(`${index}/>`) < 0 && translation.indexOf(`${index} />`) < 0) {
441
- return comp;
442
- }
443
- function Componentized() {
444
- return react.createElement(react.Fragment, null, comp);
445
- }
446
- return react.createElement(Componentized, {
447
- key: componentKey
448
- });
449
- };
450
- const generateArrayComponents = (components, translation) => components.map((c, index) => fixComponentProps(c, index, translation));
451
- const generateObjectComponents = (components, translation) => {
452
- const componentMap = {};
453
- Object.keys(components).forEach(c => {
454
- Object.assign(componentMap, {
455
- [c]: fixComponentProps(components[c], c, translation)
456
- });
457
- });
458
- return componentMap;
459
- };
460
- const generateComponents = (components, translation, i18n, i18nKey) => {
461
- if (!components) return null;
462
- if (Array.isArray(components)) {
463
- return generateArrayComponents(components, translation);
464
- }
465
- if (isObject(components)) {
466
- return generateObjectComponents(components, translation);
467
- }
468
- warnOnce(i18n, 'TRANS_INVALID_COMPONENTS', `<Trans /> "components" prop expects an object or array`, {
469
- i18nKey
470
- });
471
- return null;
472
- };
473
- const isComponentsMap = object => {
474
- if (!isObject(object)) return false;
475
- if (Array.isArray(object)) return false;
476
- return Object.keys(object).reduce((acc, key) => acc && Number.isNaN(Number.parseFloat(key)), true);
477
- };
478
- function Trans$1({
479
- children,
480
- count,
481
- parent,
482
- i18nKey,
483
- context,
484
- tOptions = {},
485
- values,
486
- defaults,
487
- components,
488
- ns,
489
- i18n: i18nFromProps,
490
- t: tFromProps,
491
- shouldUnescape,
492
- ...additionalProps
493
- }) {
494
- const i18n = i18nFromProps || getI18n();
495
- if (!i18n) {
496
- warnOnce(i18n, 'NO_I18NEXT_INSTANCE', `Trans: You need to pass in an i18next instance using i18nextReactModule`, {
497
- i18nKey
498
- });
499
- return children;
500
- }
501
- const t = tFromProps || i18n.t.bind(i18n) || (k => k);
502
- const reactI18nextOptions = {
503
- ...getDefaults(),
504
- ...i18n.options?.react
505
- };
506
- let namespaces = ns || t.ns || i18n.options?.defaultNS;
507
- namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];
508
- const nodeAsString = nodesToString(children, reactI18nextOptions, i18n, i18nKey);
509
- const defaultValue = defaults || nodeAsString || reactI18nextOptions.transEmptyNodeValue || i18nKey;
510
- const {
511
- hashTransKey
512
- } = reactI18nextOptions;
513
- const key = i18nKey || (hashTransKey ? hashTransKey(nodeAsString || defaultValue) : nodeAsString || defaultValue);
514
- if (i18n.options?.interpolation?.defaultVariables) {
515
- values = values && Object.keys(values).length > 0 ? {
516
- ...values,
517
- ...i18n.options.interpolation.defaultVariables
518
- } : {
519
- ...i18n.options.interpolation.defaultVariables
520
- };
521
- }
522
- const interpolationOverride = values || count !== undefined && !i18n.options?.interpolation?.alwaysFormat || !children ? tOptions.interpolation : {
523
- interpolation: {
524
- ...tOptions.interpolation,
525
- prefix: '#$?',
526
- suffix: '?$#'
527
- }
528
- };
529
- const combinedTOpts = {
530
- ...tOptions,
531
- context: context || tOptions.context,
532
- count,
533
- ...values,
534
- ...interpolationOverride,
535
- defaultValue,
536
- ns: namespaces
537
- };
538
- const translation = key ? t(key, combinedTOpts) : defaultValue;
539
- const generatedComponents = generateComponents(components, translation, i18n, i18nKey);
540
- let indexedChildren = generatedComponents || children;
541
- let componentsMap = null;
542
- if (isComponentsMap(generatedComponents)) {
543
- componentsMap = generatedComponents;
544
- indexedChildren = children;
545
- }
546
- const content = renderNodes(indexedChildren, componentsMap, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);
547
- const useAsParent = parent ?? reactI18nextOptions.defaultTransParent;
548
- return useAsParent ? react.createElement(useAsParent, additionalProps, content) : content;
549
- }
2412
+ let i18nInstance;
2413
+ const setI18n = instance => {
2414
+ i18nInstance = instance;
2415
+ };
2416
+ const getI18n = () => i18nInstance;
550
2417
 
551
- const initReactI18next = {
552
- type: '3rdParty',
553
- init(instance) {
554
- setDefaults(instance.options.react);
555
- setI18n(instance);
556
- }
557
- };
2418
+ const hasChildren = (node, checkLength) => {
2419
+ if (!node) return false;
2420
+ const base = node.props?.children ?? node.children;
2421
+ if (checkLength) return base.length > 0;
2422
+ return !!base;
2423
+ };
2424
+ const getChildren = node => {
2425
+ if (!node) return [];
2426
+ const children = node.props?.children ?? node.children;
2427
+ return node.props?.i18nIsDynamicList ? getAsArray(children) : children;
2428
+ };
2429
+ const hasValidReactChildren = children => Array.isArray(children) && children.every(react.isValidElement);
2430
+ const getAsArray = data => Array.isArray(data) ? data : [data];
2431
+ const mergeProps = (source, target) => {
2432
+ const newTarget = {
2433
+ ...target
2434
+ };
2435
+ newTarget.props = Object.assign(source.props, target.props);
2436
+ return newTarget;
2437
+ };
2438
+ const nodesToString = (children, i18nOptions, i18n, i18nKey) => {
2439
+ if (!children) return '';
2440
+ let stringNode = '';
2441
+ const childrenArray = getAsArray(children);
2442
+ const keepArray = i18nOptions?.transSupportBasicHtmlNodes ? i18nOptions.transKeepBasicHtmlNodesFor ?? [] : [];
2443
+ childrenArray.forEach((child, childIndex) => {
2444
+ if (isString(child)) {
2445
+ stringNode += `${child}`;
2446
+ return;
2447
+ }
2448
+ if (react.isValidElement(child)) {
2449
+ const {
2450
+ props,
2451
+ type
2452
+ } = child;
2453
+ const childPropsCount = Object.keys(props).length;
2454
+ const shouldKeepChild = keepArray.indexOf(type) > -1;
2455
+ const childChildren = props.children;
2456
+ if (!childChildren && shouldKeepChild && !childPropsCount) {
2457
+ stringNode += `<${type}/>`;
2458
+ return;
2459
+ }
2460
+ if (!childChildren && (!shouldKeepChild || childPropsCount) || props.i18nIsDynamicList) {
2461
+ stringNode += `<${childIndex}></${childIndex}>`;
2462
+ return;
2463
+ }
2464
+ if (shouldKeepChild && childPropsCount === 1 && isString(childChildren)) {
2465
+ stringNode += `<${type}>${childChildren}</${type}>`;
2466
+ return;
2467
+ }
2468
+ const content = nodesToString(childChildren, i18nOptions, i18n, i18nKey);
2469
+ stringNode += `<${childIndex}>${content}</${childIndex}>`;
2470
+ return;
2471
+ }
2472
+ if (child === null) {
2473
+ warn(i18n, 'TRANS_NULL_VALUE', `Passed in a null value as child`, {
2474
+ i18nKey
2475
+ });
2476
+ return;
2477
+ }
2478
+ if (isObject(child)) {
2479
+ const {
2480
+ format,
2481
+ ...clone
2482
+ } = child;
2483
+ const keys = Object.keys(clone);
2484
+ if (keys.length === 1) {
2485
+ const value = format ? `${keys[0]}, ${format}` : keys[0];
2486
+ stringNode += `{{${value}}}`;
2487
+ return;
2488
+ }
2489
+ warn(i18n, 'TRANS_INVALID_OBJ', `Invalid child - Object should only have keys {{ value, format }} (format is optional).`, {
2490
+ i18nKey,
2491
+ child
2492
+ });
2493
+ return;
2494
+ }
2495
+ warn(i18n, 'TRANS_INVALID_VAR', `Passed in a variable like {number} - pass variables for interpolation as full objects like {{number}}.`, {
2496
+ i18nKey,
2497
+ child
2498
+ });
2499
+ });
2500
+ return stringNode;
2501
+ };
2502
+ const renderNodes = (children, knownComponentsMap, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) => {
2503
+ if (targetString === '') return [];
2504
+ const keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
2505
+ const emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.map(keep => `<${keep}`).join('|')).test(targetString);
2506
+ if (!children && !knownComponentsMap && !emptyChildrenButNeedsHandling && !shouldUnescape) return [targetString];
2507
+ const data = knownComponentsMap ?? {};
2508
+ const getData = childs => {
2509
+ const childrenArray = getAsArray(childs);
2510
+ childrenArray.forEach(child => {
2511
+ if (isString(child)) return;
2512
+ if (hasChildren(child)) getData(getChildren(child));else if (isObject(child) && !react.isValidElement(child)) Object.assign(data, child);
2513
+ });
2514
+ };
2515
+ getData(children);
2516
+ const ast = c.parse(`<0>${targetString}</0>`);
2517
+ const opts = {
2518
+ ...data,
2519
+ ...combinedTOpts
2520
+ };
2521
+ const renderInner = (child, node, rootReactNode) => {
2522
+ const childs = getChildren(child);
2523
+ const mappedChildren = mapAST(childs, node.children, rootReactNode);
2524
+ return hasValidReactChildren(childs) && mappedChildren.length === 0 || child.props?.i18nIsDynamicList ? childs : mappedChildren;
2525
+ };
2526
+ const pushTranslatedJSX = (child, inner, mem, i, isVoid) => {
2527
+ if (child.dummy) {
2528
+ child.children = inner;
2529
+ mem.push(react.cloneElement(child, {
2530
+ key: i
2531
+ }, isVoid ? undefined : inner));
2532
+ } else {
2533
+ mem.push(...react.Children.map([child], c => {
2534
+ const props = {
2535
+ ...c.props
2536
+ };
2537
+ delete props.i18nIsDynamicList;
2538
+ return react.createElement(c.type, {
2539
+ ...props,
2540
+ key: i,
2541
+ ref: c.props.ref ?? c.ref
2542
+ }, isVoid ? null : inner);
2543
+ }));
2544
+ }
2545
+ };
2546
+ const mapAST = (reactNode, astNode, rootReactNode) => {
2547
+ const reactNodes = getAsArray(reactNode);
2548
+ const astNodes = getAsArray(astNode);
2549
+ return astNodes.reduce((mem, node, i) => {
2550
+ const translationContent = node.children?.[0]?.content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);
2551
+ if (node.type === 'tag') {
2552
+ let tmp = reactNodes[parseInt(node.name, 10)];
2553
+ if (!tmp && knownComponentsMap) tmp = knownComponentsMap[node.name];
2554
+ if (rootReactNode.length === 1 && !tmp) tmp = rootReactNode[0][node.name];
2555
+ if (!tmp) tmp = {};
2556
+ const child = Object.keys(node.attrs).length !== 0 ? mergeProps({
2557
+ props: node.attrs
2558
+ }, tmp) : tmp;
2559
+ const isElement = react.isValidElement(child);
2560
+ const isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;
2561
+ const isEmptyTransWithHTML = emptyChildrenButNeedsHandling && isObject(child) && child.dummy && !isElement;
2562
+ const isKnownComponent = isObject(knownComponentsMap) && Object.hasOwnProperty.call(knownComponentsMap, node.name);
2563
+ if (isString(child)) {
2564
+ const value = i18n.services.interpolator.interpolate(child, opts, i18n.language);
2565
+ mem.push(value);
2566
+ } else if (hasChildren(child) || isValidTranslationWithChildren) {
2567
+ const inner = renderInner(child, node, rootReactNode);
2568
+ pushTranslatedJSX(child, inner, mem, i);
2569
+ } else if (isEmptyTransWithHTML) {
2570
+ const inner = mapAST(reactNodes, node.children, rootReactNode);
2571
+ pushTranslatedJSX(child, inner, mem, i);
2572
+ } else if (Number.isNaN(parseFloat(node.name))) {
2573
+ if (isKnownComponent) {
2574
+ const inner = renderInner(child, node, rootReactNode);
2575
+ pushTranslatedJSX(child, inner, mem, i, node.voidElement);
2576
+ } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
2577
+ if (node.voidElement) {
2578
+ mem.push(react.createElement(node.name, {
2579
+ key: `${node.name}-${i}`
2580
+ }));
2581
+ } else {
2582
+ const inner = mapAST(reactNodes, node.children, rootReactNode);
2583
+ mem.push(react.createElement(node.name, {
2584
+ key: `${node.name}-${i}`
2585
+ }, inner));
2586
+ }
2587
+ } else if (node.voidElement) {
2588
+ mem.push(`<${node.name} />`);
2589
+ } else {
2590
+ const inner = mapAST(reactNodes, node.children, rootReactNode);
2591
+ mem.push(`<${node.name}>${inner}</${node.name}>`);
2592
+ }
2593
+ } else if (isObject(child) && !isElement) {
2594
+ const content = node.children[0] ? translationContent : null;
2595
+ if (content) mem.push(content);
2596
+ } else {
2597
+ pushTranslatedJSX(child, translationContent, mem, i, node.children.length !== 1 || !translationContent);
2598
+ }
2599
+ } else if (node.type === 'text') {
2600
+ const wrapTextNodes = i18nOptions.transWrapTextNodes;
2601
+ const content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);
2602
+ if (wrapTextNodes) {
2603
+ mem.push(react.createElement(wrapTextNodes, {
2604
+ key: `${node.name}-${i}`
2605
+ }, content));
2606
+ } else {
2607
+ mem.push(content);
2608
+ }
2609
+ }
2610
+ return mem;
2611
+ }, []);
2612
+ };
2613
+ const result = mapAST([{
2614
+ dummy: true,
2615
+ children: children || []
2616
+ }], ast, getAsArray(children || []));
2617
+ return getChildren(result[0]);
2618
+ };
2619
+ const fixComponentProps = (component, index, translation) => {
2620
+ const componentKey = component.key || index;
2621
+ const comp = react.cloneElement(component, {
2622
+ key: componentKey
2623
+ });
2624
+ if (!comp.props || !comp.props.children || translation.indexOf(`${index}/>`) < 0 && translation.indexOf(`${index} />`) < 0) {
2625
+ return comp;
2626
+ }
2627
+ function Componentized() {
2628
+ return react.createElement(react.Fragment, null, comp);
2629
+ }
2630
+ return react.createElement(Componentized, {
2631
+ key: componentKey
2632
+ });
2633
+ };
2634
+ const generateArrayComponents = (components, translation) => components.map((c, index) => fixComponentProps(c, index, translation));
2635
+ const generateObjectComponents = (components, translation) => {
2636
+ const componentMap = {};
2637
+ Object.keys(components).forEach(c => {
2638
+ Object.assign(componentMap, {
2639
+ [c]: fixComponentProps(components[c], c, translation)
2640
+ });
2641
+ });
2642
+ return componentMap;
2643
+ };
2644
+ const generateComponents = (components, translation, i18n, i18nKey) => {
2645
+ if (!components) return null;
2646
+ if (Array.isArray(components)) {
2647
+ return generateArrayComponents(components, translation);
2648
+ }
2649
+ if (isObject(components)) {
2650
+ return generateObjectComponents(components, translation);
2651
+ }
2652
+ warnOnce(i18n, 'TRANS_INVALID_COMPONENTS', `<Trans /> "components" prop expects an object or array`, {
2653
+ i18nKey
2654
+ });
2655
+ return null;
2656
+ };
2657
+ const isComponentsMap = object => {
2658
+ if (!isObject(object)) return false;
2659
+ if (Array.isArray(object)) return false;
2660
+ return Object.keys(object).reduce((acc, key) => acc && Number.isNaN(Number.parseFloat(key)), true);
2661
+ };
2662
+ function Trans$1({
2663
+ children,
2664
+ count,
2665
+ parent,
2666
+ i18nKey,
2667
+ context,
2668
+ tOptions = {},
2669
+ values,
2670
+ defaults,
2671
+ components,
2672
+ ns,
2673
+ i18n: i18nFromProps,
2674
+ t: tFromProps,
2675
+ shouldUnescape,
2676
+ ...additionalProps
2677
+ }) {
2678
+ const i18n = i18nFromProps || getI18n();
2679
+ if (!i18n) {
2680
+ warnOnce(i18n, 'NO_I18NEXT_INSTANCE', `Trans: You need to pass in an i18next instance using i18nextReactModule`, {
2681
+ i18nKey
2682
+ });
2683
+ return children;
2684
+ }
2685
+ const t = tFromProps || i18n.t.bind(i18n) || (k => k);
2686
+ const reactI18nextOptions = {
2687
+ ...getDefaults(),
2688
+ ...i18n.options?.react
2689
+ };
2690
+ let namespaces = ns || t.ns || i18n.options?.defaultNS;
2691
+ namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];
2692
+ const nodeAsString = nodesToString(children, reactI18nextOptions, i18n, i18nKey);
2693
+ const defaultValue = defaults || nodeAsString || reactI18nextOptions.transEmptyNodeValue || (typeof i18nKey === 'function' ? keysFromSelector(i18nKey) : i18nKey);
2694
+ const {
2695
+ hashTransKey
2696
+ } = reactI18nextOptions;
2697
+ const key = i18nKey || (hashTransKey ? hashTransKey(nodeAsString || defaultValue) : nodeAsString || defaultValue);
2698
+ if (i18n.options?.interpolation?.defaultVariables) {
2699
+ values = values && Object.keys(values).length > 0 ? {
2700
+ ...values,
2701
+ ...i18n.options.interpolation.defaultVariables
2702
+ } : {
2703
+ ...i18n.options.interpolation.defaultVariables
2704
+ };
2705
+ }
2706
+ const interpolationOverride = values || count !== undefined && !i18n.options?.interpolation?.alwaysFormat || !children ? tOptions.interpolation : {
2707
+ interpolation: {
2708
+ ...tOptions.interpolation,
2709
+ prefix: '#$?',
2710
+ suffix: '?$#'
2711
+ }
2712
+ };
2713
+ const combinedTOpts = {
2714
+ ...tOptions,
2715
+ context: context || tOptions.context,
2716
+ count,
2717
+ ...values,
2718
+ ...interpolationOverride,
2719
+ defaultValue,
2720
+ ns: namespaces
2721
+ };
2722
+ const translation = key ? t(key, combinedTOpts) : defaultValue;
2723
+ const generatedComponents = generateComponents(components, translation, i18n, i18nKey);
2724
+ let indexedChildren = generatedComponents || children;
2725
+ let componentsMap = null;
2726
+ if (isComponentsMap(generatedComponents)) {
2727
+ componentsMap = generatedComponents;
2728
+ indexedChildren = children;
2729
+ }
2730
+ const content = renderNodes(indexedChildren, componentsMap, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);
2731
+ const useAsParent = parent ?? reactI18nextOptions.defaultTransParent;
2732
+ return useAsParent ? react.createElement(useAsParent, additionalProps, content) : content;
2733
+ }
558
2734
 
559
- const I18nContext = react.createContext();
560
- class ReportNamespaces {
561
- constructor() {
562
- this.usedNamespaces = {};
563
- }
564
- addUsedNamespaces(namespaces) {
565
- namespaces.forEach(ns => {
566
- if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;
567
- });
568
- }
569
- getUsedNamespaces() {
570
- return Object.keys(this.usedNamespaces);
571
- }
572
- }
573
- const composeInitialProps = ForComponent => async ctx => {
574
- const componentsInitialProps = (await ForComponent.getInitialProps?.(ctx)) ?? {};
575
- const i18nInitialProps = getInitialProps();
576
- return {
577
- ...componentsInitialProps,
578
- ...i18nInitialProps
579
- };
580
- };
581
- const getInitialProps = () => {
582
- const i18n = getI18n();
583
- const namespaces = i18n.reportNamespaces?.getUsedNamespaces() ?? [];
584
- const ret = {};
585
- const initialI18nStore = {};
586
- i18n.languages.forEach(l => {
587
- initialI18nStore[l] = {};
588
- namespaces.forEach(ns => {
589
- initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};
590
- });
591
- });
592
- ret.initialI18nStore = initialI18nStore;
593
- ret.initialLanguage = i18n.language;
594
- return ret;
595
- };
2735
+ const initReactI18next = {
2736
+ type: '3rdParty',
2737
+ init(instance) {
2738
+ setDefaults(instance.options.react);
2739
+ setI18n(instance);
2740
+ }
2741
+ };
596
2742
 
597
- function Trans({
598
- children,
599
- count,
600
- parent,
601
- i18nKey,
602
- context,
603
- tOptions = {},
604
- values,
605
- defaults,
606
- components,
607
- ns,
608
- i18n: i18nFromProps,
609
- t: tFromProps,
610
- shouldUnescape,
611
- ...additionalProps
612
- }) {
613
- const {
614
- i18n: i18nFromContext,
615
- defaultNS: defaultNSFromContext
616
- } = react.useContext(I18nContext) || {};
617
- const i18n = i18nFromProps || i18nFromContext || getI18n();
618
- const t = tFromProps || i18n?.t.bind(i18n);
619
- return Trans$1({
620
- children,
621
- count,
622
- parent,
623
- i18nKey,
624
- context,
625
- tOptions,
626
- values,
627
- defaults,
628
- components,
629
- ns: ns || t?.ns || defaultNSFromContext || i18n?.options?.defaultNS,
630
- i18n,
631
- t: tFromProps,
632
- shouldUnescape,
633
- ...additionalProps
634
- });
635
- }
2743
+ const I18nContext = react.createContext();
2744
+ class ReportNamespaces {
2745
+ constructor() {
2746
+ this.usedNamespaces = {};
2747
+ }
2748
+ addUsedNamespaces(namespaces) {
2749
+ namespaces.forEach(ns => {
2750
+ if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;
2751
+ });
2752
+ }
2753
+ getUsedNamespaces() {
2754
+ return Object.keys(this.usedNamespaces);
2755
+ }
2756
+ }
2757
+ const composeInitialProps = ForComponent => async ctx => {
2758
+ const componentsInitialProps = (await ForComponent.getInitialProps?.(ctx)) ?? {};
2759
+ const i18nInitialProps = getInitialProps();
2760
+ return {
2761
+ ...componentsInitialProps,
2762
+ ...i18nInitialProps
2763
+ };
2764
+ };
2765
+ const getInitialProps = () => {
2766
+ const i18n = getI18n();
2767
+ const namespaces = i18n.reportNamespaces?.getUsedNamespaces() ?? [];
2768
+ const ret = {};
2769
+ const initialI18nStore = {};
2770
+ i18n.languages.forEach(l => {
2771
+ initialI18nStore[l] = {};
2772
+ namespaces.forEach(ns => {
2773
+ initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};
2774
+ });
2775
+ });
2776
+ ret.initialI18nStore = initialI18nStore;
2777
+ ret.initialLanguage = i18n.language;
2778
+ return ret;
2779
+ };
636
2780
 
637
- const usePrevious = (value, ignore) => {
638
- const ref = react.useRef();
639
- react.useEffect(() => {
640
- ref.current = value;
641
- }, [value, ignore]);
642
- return ref.current;
643
- };
644
- const alwaysNewT = (i18n, language, namespace, keyPrefix) => i18n.getFixedT(language, namespace, keyPrefix);
645
- const useMemoizedT = (i18n, language, namespace, keyPrefix) => react.useCallback(alwaysNewT(i18n, language, namespace, keyPrefix), [i18n, language, namespace, keyPrefix]);
646
- const useTranslation = (ns, props = {}) => {
647
- const {
648
- i18n: i18nFromProps
649
- } = props;
650
- const {
651
- i18n: i18nFromContext,
652
- defaultNS: defaultNSFromContext
653
- } = react.useContext(I18nContext) || {};
654
- const i18n = i18nFromProps || i18nFromContext || getI18n();
655
- if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
656
- if (!i18n) {
657
- warnOnce(i18n, 'NO_I18NEXT_INSTANCE', 'useTranslation: You will need to pass in an i18next instance by using initReactI18next');
658
- const notReadyT = (k, optsOrDefaultValue) => {
659
- if (isString(optsOrDefaultValue)) return optsOrDefaultValue;
660
- if (isObject(optsOrDefaultValue) && isString(optsOrDefaultValue.defaultValue)) return optsOrDefaultValue.defaultValue;
661
- return Array.isArray(k) ? k[k.length - 1] : k;
662
- };
663
- const retNotReady = [notReadyT, {}, false];
664
- retNotReady.t = notReadyT;
665
- retNotReady.i18n = {};
666
- retNotReady.ready = false;
667
- return retNotReady;
668
- }
669
- if (i18n.options.react?.wait) warnOnce(i18n, 'DEPRECATED_OPTION', 'useTranslation: It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');
670
- const i18nOptions = {
671
- ...getDefaults(),
672
- ...i18n.options.react,
673
- ...props
674
- };
675
- const {
676
- useSuspense,
677
- keyPrefix
678
- } = i18nOptions;
679
- let namespaces = ns || defaultNSFromContext || i18n.options?.defaultNS;
680
- namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];
681
- i18n.reportNamespaces.addUsedNamespaces?.(namespaces);
682
- const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));
683
- const memoGetT = useMemoizedT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
684
- const getT = () => memoGetT;
685
- const getNewT = () => alwaysNewT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
686
- const [t, setT] = react.useState(getT);
687
- let joinedNS = namespaces.join();
688
- if (props.lng) joinedNS = `${props.lng}${joinedNS}`;
689
- const previousJoinedNS = usePrevious(joinedNS);
690
- const isMounted = react.useRef(true);
691
- react.useEffect(() => {
692
- const {
693
- bindI18n,
694
- bindI18nStore
695
- } = i18nOptions;
696
- isMounted.current = true;
697
- if (!ready && !useSuspense) {
698
- if (props.lng) {
699
- loadLanguages(i18n, props.lng, namespaces, () => {
700
- if (isMounted.current) setT(getNewT);
701
- });
702
- } else {
703
- loadNamespaces(i18n, namespaces, () => {
704
- if (isMounted.current) setT(getNewT);
705
- });
706
- }
707
- }
708
- if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
709
- setT(getNewT);
710
- }
711
- const boundReset = () => {
712
- if (isMounted.current) setT(getNewT);
713
- };
714
- if (bindI18n) i18n?.on(bindI18n, boundReset);
715
- if (bindI18nStore) i18n?.store.on(bindI18nStore, boundReset);
716
- return () => {
717
- isMounted.current = false;
718
- if (i18n && bindI18n) bindI18n?.split(' ').forEach(e => i18n.off(e, boundReset));
719
- if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));
720
- };
721
- }, [i18n, joinedNS]);
722
- react.useEffect(() => {
723
- if (isMounted.current && ready) {
724
- setT(getT);
725
- }
726
- }, [i18n, keyPrefix, ready]);
727
- const ret = [t, i18n, ready];
728
- ret.t = t;
729
- ret.i18n = i18n;
730
- ret.ready = ready;
731
- if (ready) return ret;
732
- if (!ready && !useSuspense) return ret;
733
- throw new Promise(resolve => {
734
- if (props.lng) {
735
- loadLanguages(i18n, props.lng, namespaces, () => resolve());
736
- } else {
737
- loadNamespaces(i18n, namespaces, () => resolve());
738
- }
739
- });
740
- };
2781
+ function Trans({
2782
+ children,
2783
+ count,
2784
+ parent,
2785
+ i18nKey,
2786
+ context,
2787
+ tOptions = {},
2788
+ values,
2789
+ defaults,
2790
+ components,
2791
+ ns,
2792
+ i18n: i18nFromProps,
2793
+ t: tFromProps,
2794
+ shouldUnescape,
2795
+ ...additionalProps
2796
+ }) {
2797
+ const {
2798
+ i18n: i18nFromContext,
2799
+ defaultNS: defaultNSFromContext
2800
+ } = react.useContext(I18nContext) || {};
2801
+ const i18n = i18nFromProps || i18nFromContext || getI18n();
2802
+ const t = tFromProps || i18n?.t.bind(i18n);
2803
+ return Trans$1({
2804
+ children,
2805
+ count,
2806
+ parent,
2807
+ i18nKey,
2808
+ context,
2809
+ tOptions,
2810
+ values,
2811
+ defaults,
2812
+ components,
2813
+ ns: ns || t?.ns || defaultNSFromContext || i18n?.options?.defaultNS,
2814
+ i18n,
2815
+ t: tFromProps,
2816
+ shouldUnescape,
2817
+ ...additionalProps
2818
+ });
2819
+ }
741
2820
 
742
- const withTranslation = (ns, options = {}) => function Extend(WrappedComponent) {
743
- function I18nextWithTranslation({
744
- forwardedRef,
745
- ...rest
746
- }) {
747
- const [t, i18n, ready] = useTranslation(ns, {
748
- ...rest,
749
- keyPrefix: options.keyPrefix
750
- });
751
- const passDownProps = {
752
- ...rest,
753
- t,
754
- i18n,
755
- tReady: ready
756
- };
757
- if (options.withRef && forwardedRef) {
758
- passDownProps.ref = forwardedRef;
759
- } else if (!options.withRef && forwardedRef) {
760
- passDownProps.forwardedRef = forwardedRef;
761
- }
762
- return react.createElement(WrappedComponent, passDownProps);
763
- }
764
- I18nextWithTranslation.displayName = `withI18nextTranslation(${getDisplayName(WrappedComponent)})`;
765
- I18nextWithTranslation.WrappedComponent = WrappedComponent;
766
- const forwardRef = (props, ref) => react.createElement(I18nextWithTranslation, Object.assign({}, props, {
767
- forwardedRef: ref
768
- }));
769
- return options.withRef ? react.forwardRef(forwardRef) : I18nextWithTranslation;
770
- };
2821
+ const usePrevious = (value, ignore) => {
2822
+ const ref = react.useRef();
2823
+ react.useEffect(() => {
2824
+ ref.current = value;
2825
+ }, [value, ignore]);
2826
+ return ref.current;
2827
+ };
2828
+ const alwaysNewT = (i18n, language, namespace, keyPrefix) => i18n.getFixedT(language, namespace, keyPrefix);
2829
+ const useMemoizedT = (i18n, language, namespace, keyPrefix) => react.useCallback(alwaysNewT(i18n, language, namespace, keyPrefix), [i18n, language, namespace, keyPrefix]);
2830
+ const useTranslation = (ns, props = {}) => {
2831
+ const {
2832
+ i18n: i18nFromProps
2833
+ } = props;
2834
+ const {
2835
+ i18n: i18nFromContext,
2836
+ defaultNS: defaultNSFromContext
2837
+ } = react.useContext(I18nContext) || {};
2838
+ const i18n = i18nFromProps || i18nFromContext || getI18n();
2839
+ if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
2840
+ if (!i18n) {
2841
+ warnOnce(i18n, 'NO_I18NEXT_INSTANCE', 'useTranslation: You will need to pass in an i18next instance by using initReactI18next');
2842
+ const notReadyT = (k, optsOrDefaultValue) => {
2843
+ if (isString(optsOrDefaultValue)) return optsOrDefaultValue;
2844
+ if (isObject(optsOrDefaultValue) && isString(optsOrDefaultValue.defaultValue)) return optsOrDefaultValue.defaultValue;
2845
+ return Array.isArray(k) ? k[k.length - 1] : k;
2846
+ };
2847
+ const retNotReady = [notReadyT, {}, false];
2848
+ retNotReady.t = notReadyT;
2849
+ retNotReady.i18n = {};
2850
+ retNotReady.ready = false;
2851
+ return retNotReady;
2852
+ }
2853
+ if (i18n.options.react?.wait) warnOnce(i18n, 'DEPRECATED_OPTION', 'useTranslation: It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');
2854
+ const i18nOptions = {
2855
+ ...getDefaults(),
2856
+ ...i18n.options.react,
2857
+ ...props
2858
+ };
2859
+ const {
2860
+ useSuspense,
2861
+ keyPrefix
2862
+ } = i18nOptions;
2863
+ let namespaces = ns || defaultNSFromContext || i18n.options?.defaultNS;
2864
+ namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];
2865
+ i18n.reportNamespaces.addUsedNamespaces?.(namespaces);
2866
+ const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));
2867
+ const memoGetT = useMemoizedT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
2868
+ const getT = () => memoGetT;
2869
+ const getNewT = () => alwaysNewT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
2870
+ const [t, setT] = react.useState(getT);
2871
+ let joinedNS = namespaces.join();
2872
+ if (props.lng) joinedNS = `${props.lng}${joinedNS}`;
2873
+ const previousJoinedNS = usePrevious(joinedNS);
2874
+ const isMounted = react.useRef(true);
2875
+ react.useEffect(() => {
2876
+ const {
2877
+ bindI18n,
2878
+ bindI18nStore
2879
+ } = i18nOptions;
2880
+ isMounted.current = true;
2881
+ if (!ready && !useSuspense) {
2882
+ if (props.lng) {
2883
+ loadLanguages(i18n, props.lng, namespaces, () => {
2884
+ if (isMounted.current) setT(getNewT);
2885
+ });
2886
+ } else {
2887
+ loadNamespaces(i18n, namespaces, () => {
2888
+ if (isMounted.current) setT(getNewT);
2889
+ });
2890
+ }
2891
+ }
2892
+ if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
2893
+ setT(getNewT);
2894
+ }
2895
+ const boundReset = () => {
2896
+ if (isMounted.current) setT(getNewT);
2897
+ };
2898
+ if (bindI18n) i18n?.on(bindI18n, boundReset);
2899
+ if (bindI18nStore) i18n?.store.on(bindI18nStore, boundReset);
2900
+ return () => {
2901
+ isMounted.current = false;
2902
+ if (i18n && bindI18n) bindI18n?.split(' ').forEach(e => i18n.off(e, boundReset));
2903
+ if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));
2904
+ };
2905
+ }, [i18n, joinedNS]);
2906
+ react.useEffect(() => {
2907
+ if (isMounted.current && ready) {
2908
+ setT(getT);
2909
+ }
2910
+ }, [i18n, keyPrefix, ready]);
2911
+ const ret = [t, i18n, ready];
2912
+ ret.t = t;
2913
+ ret.i18n = i18n;
2914
+ ret.ready = ready;
2915
+ if (ready) return ret;
2916
+ if (!ready && !useSuspense) return ret;
2917
+ throw new Promise(resolve => {
2918
+ if (props.lng) {
2919
+ loadLanguages(i18n, props.lng, namespaces, () => resolve());
2920
+ } else {
2921
+ loadNamespaces(i18n, namespaces, () => resolve());
2922
+ }
2923
+ });
2924
+ };
771
2925
 
772
- const Translation = ({
773
- ns,
774
- children,
775
- ...options
776
- }) => {
777
- const [t, i18n, ready] = useTranslation(ns, options);
778
- return children(t, {
779
- i18n,
780
- lng: i18n.language
781
- }, ready);
782
- };
2926
+ const withTranslation = (ns, options = {}) => function Extend(WrappedComponent) {
2927
+ function I18nextWithTranslation({
2928
+ forwardedRef,
2929
+ ...rest
2930
+ }) {
2931
+ const [t, i18n, ready] = useTranslation(ns, {
2932
+ ...rest,
2933
+ keyPrefix: options.keyPrefix
2934
+ });
2935
+ const passDownProps = {
2936
+ ...rest,
2937
+ t,
2938
+ i18n,
2939
+ tReady: ready
2940
+ };
2941
+ if (options.withRef && forwardedRef) {
2942
+ passDownProps.ref = forwardedRef;
2943
+ } else if (!options.withRef && forwardedRef) {
2944
+ passDownProps.forwardedRef = forwardedRef;
2945
+ }
2946
+ return react.createElement(WrappedComponent, passDownProps);
2947
+ }
2948
+ I18nextWithTranslation.displayName = `withI18nextTranslation(${getDisplayName(WrappedComponent)})`;
2949
+ I18nextWithTranslation.WrappedComponent = WrappedComponent;
2950
+ const forwardRef = (props, ref) => react.createElement(I18nextWithTranslation, Object.assign({}, props, {
2951
+ forwardedRef: ref
2952
+ }));
2953
+ return options.withRef ? react.forwardRef(forwardRef) : I18nextWithTranslation;
2954
+ };
783
2955
 
784
- function I18nextProvider({
785
- i18n,
786
- defaultNS,
787
- children
788
- }) {
789
- const value = react.useMemo(() => ({
790
- i18n,
791
- defaultNS
792
- }), [i18n, defaultNS]);
793
- return react.createElement(I18nContext.Provider, {
794
- value
795
- }, children);
796
- }
2956
+ const Translation = ({
2957
+ ns,
2958
+ children,
2959
+ ...options
2960
+ }) => {
2961
+ const [t, i18n, ready] = useTranslation(ns, options);
2962
+ return children(t, {
2963
+ i18n,
2964
+ lng: i18n.language
2965
+ }, ready);
2966
+ };
797
2967
 
798
- const useSSR = (initialI18nStore, initialLanguage, props = {}) => {
799
- const {
800
- i18n: i18nFromProps
801
- } = props;
802
- const {
803
- i18n: i18nFromContext
804
- } = react.useContext(I18nContext) || {};
805
- const i18n = i18nFromProps || i18nFromContext || getI18n();
806
- if (i18n.options?.isClone) return;
807
- if (initialI18nStore && !i18n.initializedStoreOnce) {
808
- i18n.services.resourceStore.data = initialI18nStore;
809
- i18n.options.ns = Object.values(initialI18nStore).reduce((mem, lngResources) => {
810
- Object.keys(lngResources).forEach(ns => {
811
- if (mem.indexOf(ns) < 0) mem.push(ns);
812
- });
813
- return mem;
814
- }, i18n.options.ns);
815
- i18n.initializedStoreOnce = true;
816
- i18n.isInitialized = true;
817
- }
818
- if (initialLanguage && !i18n.initializedLanguageOnce) {
819
- i18n.changeLanguage(initialLanguage);
820
- i18n.initializedLanguageOnce = true;
821
- }
822
- };
2968
+ function I18nextProvider({
2969
+ i18n,
2970
+ defaultNS,
2971
+ children
2972
+ }) {
2973
+ const value = react.useMemo(() => ({
2974
+ i18n,
2975
+ defaultNS
2976
+ }), [i18n, defaultNS]);
2977
+ return react.createElement(I18nContext.Provider, {
2978
+ value
2979
+ }, children);
2980
+ }
823
2981
 
824
- const withSSR = () => function Extend(WrappedComponent) {
825
- function I18nextWithSSR({
826
- initialI18nStore,
827
- initialLanguage,
828
- ...rest
829
- }) {
830
- useSSR(initialI18nStore, initialLanguage);
831
- return react.createElement(WrappedComponent, {
832
- ...rest
833
- });
834
- }
835
- I18nextWithSSR.getInitialProps = composeInitialProps(WrappedComponent);
836
- I18nextWithSSR.displayName = `withI18nextSSR(${getDisplayName(WrappedComponent)})`;
837
- I18nextWithSSR.WrappedComponent = WrappedComponent;
838
- return I18nextWithSSR;
839
- };
2982
+ const useSSR = (initialI18nStore, initialLanguage, props = {}) => {
2983
+ const {
2984
+ i18n: i18nFromProps
2985
+ } = props;
2986
+ const {
2987
+ i18n: i18nFromContext
2988
+ } = react.useContext(I18nContext) || {};
2989
+ const i18n = i18nFromProps || i18nFromContext || getI18n();
2990
+ if (i18n.options?.isClone) return;
2991
+ if (initialI18nStore && !i18n.initializedStoreOnce) {
2992
+ i18n.services.resourceStore.data = initialI18nStore;
2993
+ i18n.options.ns = Object.values(initialI18nStore).reduce((mem, lngResources) => {
2994
+ Object.keys(lngResources).forEach(ns => {
2995
+ if (mem.indexOf(ns) < 0) mem.push(ns);
2996
+ });
2997
+ return mem;
2998
+ }, i18n.options.ns);
2999
+ i18n.initializedStoreOnce = true;
3000
+ i18n.isInitialized = true;
3001
+ }
3002
+ if (initialLanguage && !i18n.initializedLanguageOnce) {
3003
+ i18n.changeLanguage(initialLanguage);
3004
+ i18n.initializedLanguageOnce = true;
3005
+ }
3006
+ };
840
3007
 
841
- const date = () => '';
842
- const time = () => '';
843
- const number = () => '';
844
- const select = () => '';
845
- const plural = () => '';
846
- const selectOrdinal = () => '';
3008
+ const withSSR = () => function Extend(WrappedComponent) {
3009
+ function I18nextWithSSR({
3010
+ initialI18nStore,
3011
+ initialLanguage,
3012
+ ...rest
3013
+ }) {
3014
+ useSSR(initialI18nStore, initialLanguage);
3015
+ return react.createElement(WrappedComponent, {
3016
+ ...rest
3017
+ });
3018
+ }
3019
+ I18nextWithSSR.getInitialProps = composeInitialProps(WrappedComponent);
3020
+ I18nextWithSSR.displayName = `withI18nextSSR(${getDisplayName(WrappedComponent)})`;
3021
+ I18nextWithSSR.WrappedComponent = WrappedComponent;
3022
+ return I18nextWithSSR;
3023
+ };
847
3024
 
848
- exports.I18nContext = I18nContext;
849
- exports.I18nextProvider = I18nextProvider;
850
- exports.Trans = Trans;
851
- exports.TransWithoutContext = Trans$1;
852
- exports.Translation = Translation;
853
- exports.composeInitialProps = composeInitialProps;
854
- exports.date = date;
855
- exports.getDefaults = getDefaults;
856
- exports.getI18n = getI18n;
857
- exports.getInitialProps = getInitialProps;
858
- exports.initReactI18next = initReactI18next;
859
- exports.number = number;
860
- exports.plural = plural;
861
- exports.select = select;
862
- exports.selectOrdinal = selectOrdinal;
863
- exports.setDefaults = setDefaults;
864
- exports.setI18n = setI18n;
865
- exports.time = time;
866
- exports.useSSR = useSSR;
867
- exports.useTranslation = useTranslation;
868
- exports.withSSR = withSSR;
869
- exports.withTranslation = withTranslation;
3025
+ const date = () => '';
3026
+ const time = () => '';
3027
+ const number = () => '';
3028
+ const select = () => '';
3029
+ const plural = () => '';
3030
+ const selectOrdinal = () => '';
3031
+
3032
+ exports.I18nContext = I18nContext;
3033
+ exports.I18nextProvider = I18nextProvider;
3034
+ exports.Trans = Trans;
3035
+ exports.TransWithoutContext = Trans$1;
3036
+ exports.Translation = Translation;
3037
+ exports.composeInitialProps = composeInitialProps;
3038
+ exports.date = date;
3039
+ exports.getDefaults = getDefaults;
3040
+ exports.getI18n = getI18n;
3041
+ exports.getInitialProps = getInitialProps;
3042
+ exports.initReactI18next = initReactI18next;
3043
+ exports.number = number;
3044
+ exports.plural = plural;
3045
+ exports.select = select;
3046
+ exports.selectOrdinal = selectOrdinal;
3047
+ exports.setDefaults = setDefaults;
3048
+ exports.setI18n = setI18n;
3049
+ exports.time = time;
3050
+ exports.useSSR = useSSR;
3051
+ exports.useTranslation = useTranslation;
3052
+ exports.withSSR = withSSR;
3053
+ exports.withTranslation = withTranslation;
870
3054
 
871
3055
  }));