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