@pie-element/math-templated 6.0.0-beta.1 → 6.0.0-next.42

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.
@@ -0,0 +1,5044 @@
1
+ import * as mv from '@pie-framework/math-validation';
2
+
3
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
4
+
5
+ /** Used for built-in method references. */
6
+
7
+ var objectProto$c = Object.prototype;
8
+
9
+ /**
10
+ * Checks if `value` is likely a prototype object.
11
+ *
12
+ * @private
13
+ * @param {*} value The value to check.
14
+ * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
15
+ */
16
+ function isPrototype$2(value) {
17
+ var Ctor = value && value.constructor,
18
+ proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$c;
19
+
20
+ return value === proto;
21
+ }
22
+
23
+ var _isPrototype = isPrototype$2;
24
+
25
+ /**
26
+ * Creates a unary function that invokes `func` with its argument transformed.
27
+ *
28
+ * @private
29
+ * @param {Function} func The function to wrap.
30
+ * @param {Function} transform The argument transform.
31
+ * @returns {Function} Returns the new function.
32
+ */
33
+
34
+ function overArg$1(func, transform) {
35
+ return function(arg) {
36
+ return func(transform(arg));
37
+ };
38
+ }
39
+
40
+ var _overArg = overArg$1;
41
+
42
+ var overArg = _overArg;
43
+
44
+ /* Built-in method references for those with the same name as other `lodash` methods. */
45
+ var nativeKeys$1 = overArg(Object.keys, Object);
46
+
47
+ var _nativeKeys = nativeKeys$1;
48
+
49
+ var isPrototype$1 = _isPrototype,
50
+ nativeKeys = _nativeKeys;
51
+
52
+ /** Used for built-in method references. */
53
+ var objectProto$b = Object.prototype;
54
+
55
+ /** Used to check objects for own properties. */
56
+ var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
57
+
58
+ /**
59
+ * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
60
+ *
61
+ * @private
62
+ * @param {Object} object The object to query.
63
+ * @returns {Array} Returns the array of property names.
64
+ */
65
+ function baseKeys$1(object) {
66
+ if (!isPrototype$1(object)) {
67
+ return nativeKeys(object);
68
+ }
69
+ var result = [];
70
+ for (var key in Object(object)) {
71
+ if (hasOwnProperty$9.call(object, key) && key != 'constructor') {
72
+ result.push(key);
73
+ }
74
+ }
75
+ return result;
76
+ }
77
+
78
+ var _baseKeys = baseKeys$1;
79
+
80
+ /** Detect free variable `global` from Node.js. */
81
+
82
+ var freeGlobal$3 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
83
+
84
+ var _freeGlobal$1 = freeGlobal$3;
85
+
86
+ var freeGlobal$2 = _freeGlobal$1;
87
+
88
+ /** Detect free variable `self`. */
89
+ var freeSelf$1 = typeof self == 'object' && self && self.Object === Object && self;
90
+
91
+ /** Used as a reference to the global object. */
92
+ var root$f = freeGlobal$2 || freeSelf$1 || Function('return this')();
93
+
94
+ var _root$1 = root$f;
95
+
96
+ var root$e = _root$1;
97
+
98
+ /** Built-in value references. */
99
+ var Symbol$7 = root$e.Symbol;
100
+
101
+ var _Symbol$1 = Symbol$7;
102
+
103
+ var Symbol$6 = _Symbol$1;
104
+
105
+ /** Used for built-in method references. */
106
+ var objectProto$a = Object.prototype;
107
+
108
+ /** Used to check objects for own properties. */
109
+ var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
110
+
111
+ /**
112
+ * Used to resolve the
113
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
114
+ * of values.
115
+ */
116
+ var nativeObjectToString$3 = objectProto$a.toString;
117
+
118
+ /** Built-in value references. */
119
+ var symToStringTag$3 = Symbol$6 ? Symbol$6.toStringTag : undefined;
120
+
121
+ /**
122
+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
123
+ *
124
+ * @private
125
+ * @param {*} value The value to query.
126
+ * @returns {string} Returns the raw `toStringTag`.
127
+ */
128
+ function getRawTag$3(value) {
129
+ var isOwn = hasOwnProperty$8.call(value, symToStringTag$3),
130
+ tag = value[symToStringTag$3];
131
+
132
+ try {
133
+ value[symToStringTag$3] = undefined;
134
+ var unmasked = true;
135
+ } catch (e) {}
136
+
137
+ var result = nativeObjectToString$3.call(value);
138
+ if (unmasked) {
139
+ if (isOwn) {
140
+ value[symToStringTag$3] = tag;
141
+ } else {
142
+ delete value[symToStringTag$3];
143
+ }
144
+ }
145
+ return result;
146
+ }
147
+
148
+ var _getRawTag$1 = getRawTag$3;
149
+
150
+ /** Used for built-in method references. */
151
+
152
+ var objectProto$9 = Object.prototype;
153
+
154
+ /**
155
+ * Used to resolve the
156
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
157
+ * of values.
158
+ */
159
+ var nativeObjectToString$2 = objectProto$9.toString;
160
+
161
+ /**
162
+ * Converts `value` to a string using `Object.prototype.toString`.
163
+ *
164
+ * @private
165
+ * @param {*} value The value to convert.
166
+ * @returns {string} Returns the converted string.
167
+ */
168
+ function objectToString$3(value) {
169
+ return nativeObjectToString$2.call(value);
170
+ }
171
+
172
+ var _objectToString$1 = objectToString$3;
173
+
174
+ var Symbol$5 = _Symbol$1,
175
+ getRawTag$2 = _getRawTag$1,
176
+ objectToString$2 = _objectToString$1;
177
+
178
+ /** `Object#toString` result references. */
179
+ var nullTag$1 = '[object Null]',
180
+ undefinedTag$1 = '[object Undefined]';
181
+
182
+ /** Built-in value references. */
183
+ var symToStringTag$2 = Symbol$5 ? Symbol$5.toStringTag : undefined;
184
+
185
+ /**
186
+ * The base implementation of `getTag` without fallbacks for buggy environments.
187
+ *
188
+ * @private
189
+ * @param {*} value The value to query.
190
+ * @returns {string} Returns the `toStringTag`.
191
+ */
192
+ function baseGetTag$8(value) {
193
+ if (value == null) {
194
+ return value === undefined ? undefinedTag$1 : nullTag$1;
195
+ }
196
+ return (symToStringTag$2 && symToStringTag$2 in Object(value))
197
+ ? getRawTag$2(value)
198
+ : objectToString$2(value);
199
+ }
200
+
201
+ var _baseGetTag$1 = baseGetTag$8;
202
+
203
+ /**
204
+ * Checks if `value` is the
205
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
206
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
207
+ *
208
+ * @static
209
+ * @memberOf _
210
+ * @since 0.1.0
211
+ * @category Lang
212
+ * @param {*} value The value to check.
213
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
214
+ * @example
215
+ *
216
+ * _.isObject({});
217
+ * // => true
218
+ *
219
+ * _.isObject([1, 2, 3]);
220
+ * // => true
221
+ *
222
+ * _.isObject(_.noop);
223
+ * // => true
224
+ *
225
+ * _.isObject(null);
226
+ * // => false
227
+ */
228
+
229
+ function isObject$5(value) {
230
+ var type = typeof value;
231
+ return value != null && (type == 'object' || type == 'function');
232
+ }
233
+
234
+ var isObject_1$1 = isObject$5;
235
+
236
+ var baseGetTag$7 = _baseGetTag$1,
237
+ isObject$4 = isObject_1$1;
238
+
239
+ /** `Object#toString` result references. */
240
+ var asyncTag$1 = '[object AsyncFunction]',
241
+ funcTag$2 = '[object Function]',
242
+ genTag$1 = '[object GeneratorFunction]',
243
+ proxyTag$1 = '[object Proxy]';
244
+
245
+ /**
246
+ * Checks if `value` is classified as a `Function` object.
247
+ *
248
+ * @static
249
+ * @memberOf _
250
+ * @since 0.1.0
251
+ * @category Lang
252
+ * @param {*} value The value to check.
253
+ * @returns {boolean} Returns `true` if `value` is a function, else `false`.
254
+ * @example
255
+ *
256
+ * _.isFunction(_);
257
+ * // => true
258
+ *
259
+ * _.isFunction(/abc/);
260
+ * // => false
261
+ */
262
+ function isFunction$4(value) {
263
+ if (!isObject$4(value)) {
264
+ return false;
265
+ }
266
+ // The use of `Object#toString` avoids issues with the `typeof` operator
267
+ // in Safari 9 which returns 'object' for typed arrays and other constructors.
268
+ var tag = baseGetTag$7(value);
269
+ return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag$1 || tag == proxyTag$1;
270
+ }
271
+
272
+ var isFunction_1$1 = isFunction$4;
273
+
274
+ var root$d = _root$1;
275
+
276
+ /** Used to detect overreaching core-js shims. */
277
+ var coreJsData$3 = root$d['__core-js_shared__'];
278
+
279
+ var _coreJsData$1 = coreJsData$3;
280
+
281
+ var coreJsData$2 = _coreJsData$1;
282
+
283
+ /** Used to detect methods masquerading as native. */
284
+ var maskSrcKey$1 = (function() {
285
+ var uid = /[^.]+$/.exec(coreJsData$2 && coreJsData$2.keys && coreJsData$2.keys.IE_PROTO || '');
286
+ return uid ? ('Symbol(src)_1.' + uid) : '';
287
+ }());
288
+
289
+ /**
290
+ * Checks if `func` has its source masked.
291
+ *
292
+ * @private
293
+ * @param {Function} func The function to check.
294
+ * @returns {boolean} Returns `true` if `func` is masked, else `false`.
295
+ */
296
+ function isMasked$3(func) {
297
+ return !!maskSrcKey$1 && (maskSrcKey$1 in func);
298
+ }
299
+
300
+ var _isMasked$1 = isMasked$3;
301
+
302
+ /** Used for built-in method references. */
303
+
304
+ var funcProto$3 = Function.prototype;
305
+
306
+ /** Used to resolve the decompiled source of functions. */
307
+ var funcToString$3 = funcProto$3.toString;
308
+
309
+ /**
310
+ * Converts `func` to its source code.
311
+ *
312
+ * @private
313
+ * @param {Function} func The function to convert.
314
+ * @returns {string} Returns the source code.
315
+ */
316
+ function toSource$5(func) {
317
+ if (func != null) {
318
+ try {
319
+ return funcToString$3.call(func);
320
+ } catch (e) {}
321
+ try {
322
+ return (func + '');
323
+ } catch (e) {}
324
+ }
325
+ return '';
326
+ }
327
+
328
+ var _toSource$1 = toSource$5;
329
+
330
+ var isFunction$3 = isFunction_1$1,
331
+ isMasked$2 = _isMasked$1,
332
+ isObject$3 = isObject_1$1,
333
+ toSource$4 = _toSource$1;
334
+
335
+ /**
336
+ * Used to match `RegExp`
337
+ * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
338
+ */
339
+ var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g;
340
+
341
+ /** Used to detect host constructors (Safari). */
342
+ var reIsHostCtor$1 = /^\[object .+?Constructor\]$/;
343
+
344
+ /** Used for built-in method references. */
345
+ var funcProto$2 = Function.prototype,
346
+ objectProto$8 = Object.prototype;
347
+
348
+ /** Used to resolve the decompiled source of functions. */
349
+ var funcToString$2 = funcProto$2.toString;
350
+
351
+ /** Used to check objects for own properties. */
352
+ var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
353
+
354
+ /** Used to detect if a method is native. */
355
+ var reIsNative$1 = RegExp('^' +
356
+ funcToString$2.call(hasOwnProperty$7).replace(reRegExpChar$1, '\\$&')
357
+ .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
358
+ );
359
+
360
+ /**
361
+ * The base implementation of `_.isNative` without bad shim checks.
362
+ *
363
+ * @private
364
+ * @param {*} value The value to check.
365
+ * @returns {boolean} Returns `true` if `value` is a native function,
366
+ * else `false`.
367
+ */
368
+ function baseIsNative$3(value) {
369
+ if (!isObject$3(value) || isMasked$2(value)) {
370
+ return false;
371
+ }
372
+ var pattern = isFunction$3(value) ? reIsNative$1 : reIsHostCtor$1;
373
+ return pattern.test(toSource$4(value));
374
+ }
375
+
376
+ var _baseIsNative$1 = baseIsNative$3;
377
+
378
+ /**
379
+ * Gets the value at `key` of `object`.
380
+ *
381
+ * @private
382
+ * @param {Object} [object] The object to query.
383
+ * @param {string} key The key of the property to get.
384
+ * @returns {*} Returns the property value.
385
+ */
386
+
387
+ function getValue$3(object, key) {
388
+ return object == null ? undefined : object[key];
389
+ }
390
+
391
+ var _getValue$1 = getValue$3;
392
+
393
+ var baseIsNative$2 = _baseIsNative$1,
394
+ getValue$2 = _getValue$1;
395
+
396
+ /**
397
+ * Gets the native function at `key` of `object`.
398
+ *
399
+ * @private
400
+ * @param {Object} object The object to query.
401
+ * @param {string} key The key of the method to get.
402
+ * @returns {*} Returns the function if it's native, else `undefined`.
403
+ */
404
+ function getNative$c(object, key) {
405
+ var value = getValue$2(object, key);
406
+ return baseIsNative$2(value) ? value : undefined;
407
+ }
408
+
409
+ var _getNative$1 = getNative$c;
410
+
411
+ var getNative$b = _getNative$1,
412
+ root$c = _root$1;
413
+
414
+ /* Built-in method references that are verified to be native. */
415
+ var DataView$3 = getNative$b(root$c, 'DataView');
416
+
417
+ var _DataView$1 = DataView$3;
418
+
419
+ var getNative$a = _getNative$1,
420
+ root$b = _root$1;
421
+
422
+ /* Built-in method references that are verified to be native. */
423
+ var Map$5 = getNative$a(root$b, 'Map');
424
+
425
+ var _Map$1 = Map$5;
426
+
427
+ var getNative$9 = _getNative$1,
428
+ root$a = _root$1;
429
+
430
+ /* Built-in method references that are verified to be native. */
431
+ var Promise$4 = getNative$9(root$a, 'Promise');
432
+
433
+ var _Promise$1 = Promise$4;
434
+
435
+ var getNative$8 = _getNative$1,
436
+ root$9 = _root$1;
437
+
438
+ /* Built-in method references that are verified to be native. */
439
+ var Set$3 = getNative$8(root$9, 'Set');
440
+
441
+ var _Set$1 = Set$3;
442
+
443
+ var getNative$7 = _getNative$1,
444
+ root$8 = _root$1;
445
+
446
+ /* Built-in method references that are verified to be native. */
447
+ var WeakMap$3 = getNative$7(root$8, 'WeakMap');
448
+
449
+ var _WeakMap$1 = WeakMap$3;
450
+
451
+ var DataView$2 = _DataView$1,
452
+ Map$4 = _Map$1,
453
+ Promise$3 = _Promise$1,
454
+ Set$2 = _Set$1,
455
+ WeakMap$2 = _WeakMap$1,
456
+ baseGetTag$6 = _baseGetTag$1,
457
+ toSource$3 = _toSource$1;
458
+
459
+ /** `Object#toString` result references. */
460
+ var mapTag$3 = '[object Map]',
461
+ objectTag$2 = '[object Object]',
462
+ promiseTag$1 = '[object Promise]',
463
+ setTag$3 = '[object Set]',
464
+ weakMapTag$2 = '[object WeakMap]';
465
+
466
+ var dataViewTag$2 = '[object DataView]';
467
+
468
+ /** Used to detect maps, sets, and weakmaps. */
469
+ var dataViewCtorString$1 = toSource$3(DataView$2),
470
+ mapCtorString$1 = toSource$3(Map$4),
471
+ promiseCtorString$1 = toSource$3(Promise$3),
472
+ setCtorString$1 = toSource$3(Set$2),
473
+ weakMapCtorString$1 = toSource$3(WeakMap$2);
474
+
475
+ /**
476
+ * Gets the `toStringTag` of `value`.
477
+ *
478
+ * @private
479
+ * @param {*} value The value to query.
480
+ * @returns {string} Returns the `toStringTag`.
481
+ */
482
+ var getTag$2 = baseGetTag$6;
483
+
484
+ // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
485
+ if ((DataView$2 && getTag$2(new DataView$2(new ArrayBuffer(1))) != dataViewTag$2) ||
486
+ (Map$4 && getTag$2(new Map$4) != mapTag$3) ||
487
+ (Promise$3 && getTag$2(Promise$3.resolve()) != promiseTag$1) ||
488
+ (Set$2 && getTag$2(new Set$2) != setTag$3) ||
489
+ (WeakMap$2 && getTag$2(new WeakMap$2) != weakMapTag$2)) {
490
+ getTag$2 = function(value) {
491
+ var result = baseGetTag$6(value),
492
+ Ctor = result == objectTag$2 ? value.constructor : undefined,
493
+ ctorString = Ctor ? toSource$3(Ctor) : '';
494
+
495
+ if (ctorString) {
496
+ switch (ctorString) {
497
+ case dataViewCtorString$1: return dataViewTag$2;
498
+ case mapCtorString$1: return mapTag$3;
499
+ case promiseCtorString$1: return promiseTag$1;
500
+ case setCtorString$1: return setTag$3;
501
+ case weakMapCtorString$1: return weakMapTag$2;
502
+ }
503
+ }
504
+ return result;
505
+ };
506
+ }
507
+
508
+ var _getTag = getTag$2;
509
+
510
+ /**
511
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
512
+ * and has a `typeof` result of "object".
513
+ *
514
+ * @static
515
+ * @memberOf _
516
+ * @since 4.0.0
517
+ * @category Lang
518
+ * @param {*} value The value to check.
519
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
520
+ * @example
521
+ *
522
+ * _.isObjectLike({});
523
+ * // => true
524
+ *
525
+ * _.isObjectLike([1, 2, 3]);
526
+ * // => true
527
+ *
528
+ * _.isObjectLike(_.noop);
529
+ * // => false
530
+ *
531
+ * _.isObjectLike(null);
532
+ * // => false
533
+ */
534
+
535
+ function isObjectLike$6(value) {
536
+ return value != null && typeof value == 'object';
537
+ }
538
+
539
+ var isObjectLike_1$1 = isObjectLike$6;
540
+
541
+ var baseGetTag$5 = _baseGetTag$1,
542
+ isObjectLike$5 = isObjectLike_1$1;
543
+
544
+ /** `Object#toString` result references. */
545
+ var argsTag$2 = '[object Arguments]';
546
+
547
+ /**
548
+ * The base implementation of `_.isArguments`.
549
+ *
550
+ * @private
551
+ * @param {*} value The value to check.
552
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
553
+ */
554
+ function baseIsArguments$3(value) {
555
+ return isObjectLike$5(value) && baseGetTag$5(value) == argsTag$2;
556
+ }
557
+
558
+ var _baseIsArguments$1 = baseIsArguments$3;
559
+
560
+ var baseIsArguments$2 = _baseIsArguments$1,
561
+ isObjectLike$4 = isObjectLike_1$1;
562
+
563
+ /** Used for built-in method references. */
564
+ var objectProto$7 = Object.prototype;
565
+
566
+ /** Used to check objects for own properties. */
567
+ var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
568
+
569
+ /** Built-in value references. */
570
+ var propertyIsEnumerable$1 = objectProto$7.propertyIsEnumerable;
571
+
572
+ /**
573
+ * Checks if `value` is likely an `arguments` object.
574
+ *
575
+ * @static
576
+ * @memberOf _
577
+ * @since 0.1.0
578
+ * @category Lang
579
+ * @param {*} value The value to check.
580
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
581
+ * else `false`.
582
+ * @example
583
+ *
584
+ * _.isArguments(function() { return arguments; }());
585
+ * // => true
586
+ *
587
+ * _.isArguments([1, 2, 3]);
588
+ * // => false
589
+ */
590
+ var isArguments$1 = baseIsArguments$2(function() { return arguments; }()) ? baseIsArguments$2 : function(value) {
591
+ return isObjectLike$4(value) && hasOwnProperty$6.call(value, 'callee') &&
592
+ !propertyIsEnumerable$1.call(value, 'callee');
593
+ };
594
+
595
+ var isArguments_1 = isArguments$1;
596
+
597
+ /**
598
+ * Checks if `value` is classified as an `Array` object.
599
+ *
600
+ * @static
601
+ * @memberOf _
602
+ * @since 0.1.0
603
+ * @category Lang
604
+ * @param {*} value The value to check.
605
+ * @returns {boolean} Returns `true` if `value` is an array, else `false`.
606
+ * @example
607
+ *
608
+ * _.isArray([1, 2, 3]);
609
+ * // => true
610
+ *
611
+ * _.isArray(document.body.children);
612
+ * // => false
613
+ *
614
+ * _.isArray('abc');
615
+ * // => false
616
+ *
617
+ * _.isArray(_.noop);
618
+ * // => false
619
+ */
620
+
621
+ var isArray$1 = Array.isArray;
622
+
623
+ var isArray_1 = isArray$1;
624
+
625
+ /** Used as references for various `Number` constants. */
626
+
627
+ var MAX_SAFE_INTEGER = 9007199254740991;
628
+
629
+ /**
630
+ * Checks if `value` is a valid array-like length.
631
+ *
632
+ * **Note:** This method is loosely based on
633
+ * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
634
+ *
635
+ * @static
636
+ * @memberOf _
637
+ * @since 4.0.0
638
+ * @category Lang
639
+ * @param {*} value The value to check.
640
+ * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
641
+ * @example
642
+ *
643
+ * _.isLength(3);
644
+ * // => true
645
+ *
646
+ * _.isLength(Number.MIN_VALUE);
647
+ * // => false
648
+ *
649
+ * _.isLength(Infinity);
650
+ * // => false
651
+ *
652
+ * _.isLength('3');
653
+ * // => false
654
+ */
655
+ function isLength$2(value) {
656
+ return typeof value == 'number' &&
657
+ value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
658
+ }
659
+
660
+ var isLength_1 = isLength$2;
661
+
662
+ var isFunction$2 = isFunction_1$1,
663
+ isLength$1 = isLength_1;
664
+
665
+ /**
666
+ * Checks if `value` is array-like. A value is considered array-like if it's
667
+ * not a function and has a `value.length` that's an integer greater than or
668
+ * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
669
+ *
670
+ * @static
671
+ * @memberOf _
672
+ * @since 4.0.0
673
+ * @category Lang
674
+ * @param {*} value The value to check.
675
+ * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
676
+ * @example
677
+ *
678
+ * _.isArrayLike([1, 2, 3]);
679
+ * // => true
680
+ *
681
+ * _.isArrayLike(document.body.children);
682
+ * // => true
683
+ *
684
+ * _.isArrayLike('abc');
685
+ * // => true
686
+ *
687
+ * _.isArrayLike(_.noop);
688
+ * // => false
689
+ */
690
+ function isArrayLike$1(value) {
691
+ return value != null && isLength$1(value.length) && !isFunction$2(value);
692
+ }
693
+
694
+ var isArrayLike_1 = isArrayLike$1;
695
+
696
+ var isBuffer$2 = {exports: {}};
697
+
698
+ /**
699
+ * This method returns `false`.
700
+ *
701
+ * @static
702
+ * @memberOf _
703
+ * @since 4.13.0
704
+ * @category Util
705
+ * @returns {boolean} Returns `false`.
706
+ * @example
707
+ *
708
+ * _.times(2, _.stubFalse);
709
+ * // => [false, false]
710
+ */
711
+
712
+ function stubFalse$1() {
713
+ return false;
714
+ }
715
+
716
+ var stubFalse_1$1 = stubFalse$1;
717
+
718
+ (function (module, exports) {
719
+ var root = _root$1,
720
+ stubFalse = stubFalse_1$1;
721
+
722
+ /** Detect free variable `exports`. */
723
+ var freeExports = exports && !exports.nodeType && exports;
724
+
725
+ /** Detect free variable `module`. */
726
+ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
727
+
728
+ /** Detect the popular CommonJS extension `module.exports`. */
729
+ var moduleExports = freeModule && freeModule.exports === freeExports;
730
+
731
+ /** Built-in value references. */
732
+ var Buffer = moduleExports ? root.Buffer : undefined;
733
+
734
+ /* Built-in method references for those with the same name as other `lodash` methods. */
735
+ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
736
+
737
+ /**
738
+ * Checks if `value` is a buffer.
739
+ *
740
+ * @static
741
+ * @memberOf _
742
+ * @since 4.3.0
743
+ * @category Lang
744
+ * @param {*} value The value to check.
745
+ * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
746
+ * @example
747
+ *
748
+ * _.isBuffer(new Buffer(2));
749
+ * // => true
750
+ *
751
+ * _.isBuffer(new Uint8Array(2));
752
+ * // => false
753
+ */
754
+ var isBuffer = nativeIsBuffer || stubFalse;
755
+
756
+ module.exports = isBuffer;
757
+ }(isBuffer$2, isBuffer$2.exports));
758
+
759
+ var baseGetTag$4 = _baseGetTag$1,
760
+ isLength = isLength_1,
761
+ isObjectLike$3 = isObjectLike_1$1;
762
+
763
+ /** `Object#toString` result references. */
764
+ var argsTag$1 = '[object Arguments]',
765
+ arrayTag = '[object Array]',
766
+ boolTag = '[object Boolean]',
767
+ dateTag = '[object Date]',
768
+ errorTag = '[object Error]',
769
+ funcTag$1 = '[object Function]',
770
+ mapTag$2 = '[object Map]',
771
+ numberTag = '[object Number]',
772
+ objectTag$1 = '[object Object]',
773
+ regexpTag = '[object RegExp]',
774
+ setTag$2 = '[object Set]',
775
+ stringTag = '[object String]',
776
+ weakMapTag$1 = '[object WeakMap]';
777
+
778
+ var arrayBufferTag = '[object ArrayBuffer]',
779
+ dataViewTag$1 = '[object DataView]',
780
+ float32Tag = '[object Float32Array]',
781
+ float64Tag = '[object Float64Array]',
782
+ int8Tag = '[object Int8Array]',
783
+ int16Tag = '[object Int16Array]',
784
+ int32Tag = '[object Int32Array]',
785
+ uint8Tag = '[object Uint8Array]',
786
+ uint8ClampedTag = '[object Uint8ClampedArray]',
787
+ uint16Tag = '[object Uint16Array]',
788
+ uint32Tag = '[object Uint32Array]';
789
+
790
+ /** Used to identify `toStringTag` values of typed arrays. */
791
+ var typedArrayTags = {};
792
+ typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
793
+ typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
794
+ typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
795
+ typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
796
+ typedArrayTags[uint32Tag] = true;
797
+ typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
798
+ typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
799
+ typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] =
800
+ typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
801
+ typedArrayTags[mapTag$2] = typedArrayTags[numberTag] =
802
+ typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] =
803
+ typedArrayTags[setTag$2] = typedArrayTags[stringTag] =
804
+ typedArrayTags[weakMapTag$1] = false;
805
+
806
+ /**
807
+ * The base implementation of `_.isTypedArray` without Node.js optimizations.
808
+ *
809
+ * @private
810
+ * @param {*} value The value to check.
811
+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
812
+ */
813
+ function baseIsTypedArray$1(value) {
814
+ return isObjectLike$3(value) &&
815
+ isLength(value.length) && !!typedArrayTags[baseGetTag$4(value)];
816
+ }
817
+
818
+ var _baseIsTypedArray = baseIsTypedArray$1;
819
+
820
+ /**
821
+ * The base implementation of `_.unary` without support for storing metadata.
822
+ *
823
+ * @private
824
+ * @param {Function} func The function to cap arguments for.
825
+ * @returns {Function} Returns the new capped function.
826
+ */
827
+
828
+ function baseUnary$1(func) {
829
+ return function(value) {
830
+ return func(value);
831
+ };
832
+ }
833
+
834
+ var _baseUnary = baseUnary$1;
835
+
836
+ var _nodeUtil$1 = {exports: {}};
837
+
838
+ (function (module, exports) {
839
+ var freeGlobal = _freeGlobal$1;
840
+
841
+ /** Detect free variable `exports`. */
842
+ var freeExports = exports && !exports.nodeType && exports;
843
+
844
+ /** Detect free variable `module`. */
845
+ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
846
+
847
+ /** Detect the popular CommonJS extension `module.exports`. */
848
+ var moduleExports = freeModule && freeModule.exports === freeExports;
849
+
850
+ /** Detect free variable `process` from Node.js. */
851
+ var freeProcess = moduleExports && freeGlobal.process;
852
+
853
+ /** Used to access faster Node.js helpers. */
854
+ var nodeUtil = (function() {
855
+ try {
856
+ // Use `util.types` for Node.js 10+.
857
+ var types = freeModule && freeModule.require && freeModule.require('util').types;
858
+
859
+ if (types) {
860
+ return types;
861
+ }
862
+
863
+ // Legacy `process.binding('util')` for Node.js < 10.
864
+ return freeProcess && freeProcess.binding && freeProcess.binding('util');
865
+ } catch (e) {}
866
+ }());
867
+
868
+ module.exports = nodeUtil;
869
+ }(_nodeUtil$1, _nodeUtil$1.exports));
870
+
871
+ var baseIsTypedArray = _baseIsTypedArray,
872
+ baseUnary = _baseUnary,
873
+ nodeUtil$1 = _nodeUtil$1.exports;
874
+
875
+ /* Node.js helper references. */
876
+ var nodeIsTypedArray = nodeUtil$1 && nodeUtil$1.isTypedArray;
877
+
878
+ /**
879
+ * Checks if `value` is classified as a typed array.
880
+ *
881
+ * @static
882
+ * @memberOf _
883
+ * @since 3.0.0
884
+ * @category Lang
885
+ * @param {*} value The value to check.
886
+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
887
+ * @example
888
+ *
889
+ * _.isTypedArray(new Uint8Array);
890
+ * // => true
891
+ *
892
+ * _.isTypedArray([]);
893
+ * // => false
894
+ */
895
+ var isTypedArray$1 = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
896
+
897
+ var isTypedArray_1 = isTypedArray$1;
898
+
899
+ var baseKeys = _baseKeys,
900
+ getTag$1 = _getTag,
901
+ isArguments = isArguments_1,
902
+ isArray = isArray_1,
903
+ isArrayLike = isArrayLike_1,
904
+ isBuffer$1 = isBuffer$2.exports,
905
+ isPrototype = _isPrototype,
906
+ isTypedArray = isTypedArray_1;
907
+
908
+ /** `Object#toString` result references. */
909
+ var mapTag$1 = '[object Map]',
910
+ setTag$1 = '[object Set]';
911
+
912
+ /** Used for built-in method references. */
913
+ var objectProto$6 = Object.prototype;
914
+
915
+ /** Used to check objects for own properties. */
916
+ var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
917
+
918
+ /**
919
+ * Checks if `value` is an empty object, collection, map, or set.
920
+ *
921
+ * Objects are considered empty if they have no own enumerable string keyed
922
+ * properties.
923
+ *
924
+ * Array-like values such as `arguments` objects, arrays, buffers, strings, or
925
+ * jQuery-like collections are considered empty if they have a `length` of `0`.
926
+ * Similarly, maps and sets are considered empty if they have a `size` of `0`.
927
+ *
928
+ * @static
929
+ * @memberOf _
930
+ * @since 0.1.0
931
+ * @category Lang
932
+ * @param {*} value The value to check.
933
+ * @returns {boolean} Returns `true` if `value` is empty, else `false`.
934
+ * @example
935
+ *
936
+ * _.isEmpty(null);
937
+ * // => true
938
+ *
939
+ * _.isEmpty(true);
940
+ * // => true
941
+ *
942
+ * _.isEmpty(1);
943
+ * // => true
944
+ *
945
+ * _.isEmpty([1, 2, 3]);
946
+ * // => false
947
+ *
948
+ * _.isEmpty({ 'a': 1 });
949
+ * // => false
950
+ */
951
+ function isEmpty(value) {
952
+ if (value == null) {
953
+ return true;
954
+ }
955
+ if (isArrayLike(value) &&
956
+ (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
957
+ isBuffer$1(value) || isTypedArray(value) || isArguments(value))) {
958
+ return !value.length;
959
+ }
960
+ var tag = getTag$1(value);
961
+ if (tag == mapTag$1 || tag == setTag$1) {
962
+ return !value.size;
963
+ }
964
+ if (isPrototype(value)) {
965
+ return !baseKeys(value).length;
966
+ }
967
+ for (var key in value) {
968
+ if (hasOwnProperty$5.call(value, key)) {
969
+ return false;
970
+ }
971
+ }
972
+ return true;
973
+ }
974
+
975
+ var isEmpty_1 = isEmpty;
976
+
977
+ const isString = obj => typeof obj === 'string';
978
+ const defer = () => {
979
+ let res;
980
+ let rej;
981
+ const promise = new Promise((resolve, reject) => {
982
+ res = resolve;
983
+ rej = reject;
984
+ });
985
+ promise.resolve = res;
986
+ promise.reject = rej;
987
+ return promise;
988
+ };
989
+ const makeString = object => {
990
+ if (object == null) return '';
991
+ return '' + object;
992
+ };
993
+ const copy = (a, s, t) => {
994
+ a.forEach(m => {
995
+ if (s[m]) t[m] = s[m];
996
+ });
997
+ };
998
+ const lastOfPathSeparatorRegExp = /###/g;
999
+ const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
1000
+ const canNotTraverseDeeper = object => !object || isString(object);
1001
+ const getLastOfPath = (object, path, Empty) => {
1002
+ const stack = !isString(path) ? path : path.split('.');
1003
+ let stackIndex = 0;
1004
+ while (stackIndex < stack.length - 1) {
1005
+ if (canNotTraverseDeeper(object)) return {};
1006
+ const key = cleanKey(stack[stackIndex]);
1007
+ if (!object[key] && Empty) object[key] = new Empty();
1008
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
1009
+ object = object[key];
1010
+ } else {
1011
+ object = {};
1012
+ }
1013
+ ++stackIndex;
1014
+ }
1015
+ if (canNotTraverseDeeper(object)) return {};
1016
+ return {
1017
+ obj: object,
1018
+ k: cleanKey(stack[stackIndex])
1019
+ };
1020
+ };
1021
+ const setPath = (object, path, newValue) => {
1022
+ const {
1023
+ obj,
1024
+ k
1025
+ } = getLastOfPath(object, path, Object);
1026
+ if (obj !== undefined || path.length === 1) {
1027
+ obj[k] = newValue;
1028
+ return;
1029
+ }
1030
+ let e = path[path.length - 1];
1031
+ let p = path.slice(0, path.length - 1);
1032
+ let last = getLastOfPath(object, p, Object);
1033
+ while (last.obj === undefined && p.length) {
1034
+ e = `${p[p.length - 1]}.${e}`;
1035
+ p = p.slice(0, p.length - 1);
1036
+ last = getLastOfPath(object, p, Object);
1037
+ if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
1038
+ last.obj = undefined;
1039
+ }
1040
+ }
1041
+ last.obj[`${last.k}.${e}`] = newValue;
1042
+ };
1043
+ const pushPath = (object, path, newValue, concat) => {
1044
+ const {
1045
+ obj,
1046
+ k
1047
+ } = getLastOfPath(object, path, Object);
1048
+ obj[k] = obj[k] || [];
1049
+ obj[k].push(newValue);
1050
+ };
1051
+ const getPath = (object, path) => {
1052
+ const {
1053
+ obj,
1054
+ k
1055
+ } = getLastOfPath(object, path);
1056
+ if (!obj) return undefined;
1057
+ if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;
1058
+ return obj[k];
1059
+ };
1060
+ const getPathWithDefaults = (data, defaultData, key) => {
1061
+ const value = getPath(data, key);
1062
+ if (value !== undefined) {
1063
+ return value;
1064
+ }
1065
+ return getPath(defaultData, key);
1066
+ };
1067
+ const deepExtend = (target, source, overwrite) => {
1068
+ for (const prop in source) {
1069
+ if (prop !== '__proto__' && prop !== 'constructor') {
1070
+ if (prop in target) {
1071
+ if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
1072
+ if (overwrite) target[prop] = source[prop];
1073
+ } else {
1074
+ deepExtend(target[prop], source[prop], overwrite);
1075
+ }
1076
+ } else {
1077
+ target[prop] = source[prop];
1078
+ }
1079
+ }
1080
+ }
1081
+ return target;
1082
+ };
1083
+ const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
1084
+ var _entityMap = {
1085
+ '&': '&amp;',
1086
+ '<': '&lt;',
1087
+ '>': '&gt;',
1088
+ '"': '&quot;',
1089
+ "'": '&#39;',
1090
+ '/': '&#x2F;'
1091
+ };
1092
+ const escape = data => {
1093
+ if (isString(data)) {
1094
+ return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
1095
+ }
1096
+ return data;
1097
+ };
1098
+ class RegExpCache {
1099
+ constructor(capacity) {
1100
+ this.capacity = capacity;
1101
+ this.regExpMap = new Map();
1102
+ this.regExpQueue = [];
1103
+ }
1104
+ getRegExp(pattern) {
1105
+ const regExpFromCache = this.regExpMap.get(pattern);
1106
+ if (regExpFromCache !== undefined) {
1107
+ return regExpFromCache;
1108
+ }
1109
+ const regExpNew = new RegExp(pattern);
1110
+ if (this.regExpQueue.length === this.capacity) {
1111
+ this.regExpMap.delete(this.regExpQueue.shift());
1112
+ }
1113
+ this.regExpMap.set(pattern, regExpNew);
1114
+ this.regExpQueue.push(pattern);
1115
+ return regExpNew;
1116
+ }
1117
+ }
1118
+ const chars = [' ', ',', '?', '!', ';'];
1119
+ const looksLikeObjectPathRegExpCache = new RegExpCache(20);
1120
+ const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
1121
+ nsSeparator = nsSeparator || '';
1122
+ keySeparator = keySeparator || '';
1123
+ const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
1124
+ if (possibleChars.length === 0) return true;
1125
+ const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
1126
+ let matched = !r.test(key);
1127
+ if (!matched) {
1128
+ const ki = key.indexOf(keySeparator);
1129
+ if (ki > 0 && !r.test(key.substring(0, ki))) {
1130
+ matched = true;
1131
+ }
1132
+ }
1133
+ return matched;
1134
+ };
1135
+ const deepFind = (obj, path, keySeparator = '.') => {
1136
+ if (!obj) return undefined;
1137
+ if (obj[path]) {
1138
+ if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;
1139
+ return obj[path];
1140
+ }
1141
+ const tokens = path.split(keySeparator);
1142
+ let current = obj;
1143
+ for (let i = 0; i < tokens.length;) {
1144
+ if (!current || typeof current !== 'object') {
1145
+ return undefined;
1146
+ }
1147
+ let next;
1148
+ let nextPath = '';
1149
+ for (let j = i; j < tokens.length; ++j) {
1150
+ if (j !== i) {
1151
+ nextPath += keySeparator;
1152
+ }
1153
+ nextPath += tokens[j];
1154
+ next = current[nextPath];
1155
+ if (next !== undefined) {
1156
+ if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
1157
+ continue;
1158
+ }
1159
+ i += j - i + 1;
1160
+ break;
1161
+ }
1162
+ }
1163
+ current = next;
1164
+ }
1165
+ return current;
1166
+ };
1167
+ const getCleanedCode = code => code?.replace('_', '-');
1168
+
1169
+ const consoleLogger = {
1170
+ type: 'logger',
1171
+ log(args) {
1172
+ this.output('log', args);
1173
+ },
1174
+ warn(args) {
1175
+ this.output('warn', args);
1176
+ },
1177
+ error(args) {
1178
+ this.output('error', args);
1179
+ },
1180
+ output(type, args) {
1181
+ console?.[type]?.apply?.(console, args);
1182
+ }
1183
+ };
1184
+ class Logger {
1185
+ constructor(concreteLogger, options = {}) {
1186
+ this.init(concreteLogger, options);
1187
+ }
1188
+ init(concreteLogger, options = {}) {
1189
+ this.prefix = options.prefix || 'i18next:';
1190
+ this.logger = concreteLogger || consoleLogger;
1191
+ this.options = options;
1192
+ this.debug = options.debug;
1193
+ }
1194
+ log(...args) {
1195
+ return this.forward(args, 'log', '', true);
1196
+ }
1197
+ warn(...args) {
1198
+ return this.forward(args, 'warn', '', true);
1199
+ }
1200
+ error(...args) {
1201
+ return this.forward(args, 'error', '');
1202
+ }
1203
+ deprecate(...args) {
1204
+ return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
1205
+ }
1206
+ forward(args, lvl, prefix, debugOnly) {
1207
+ if (debugOnly && !this.debug) return null;
1208
+ if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
1209
+ return this.logger[lvl](args);
1210
+ }
1211
+ create(moduleName) {
1212
+ return new Logger(this.logger, {
1213
+ ...{
1214
+ prefix: `${this.prefix}:${moduleName}:`
1215
+ },
1216
+ ...this.options
1217
+ });
1218
+ }
1219
+ clone(options) {
1220
+ options = options || this.options;
1221
+ options.prefix = options.prefix || this.prefix;
1222
+ return new Logger(this.logger, options);
1223
+ }
1224
+ }
1225
+ var baseLogger = new Logger();
1226
+
1227
+ class EventEmitter {
1228
+ constructor() {
1229
+ this.observers = {};
1230
+ }
1231
+ on(events, listener) {
1232
+ events.split(' ').forEach(event => {
1233
+ if (!this.observers[event]) this.observers[event] = new Map();
1234
+ const numListeners = this.observers[event].get(listener) || 0;
1235
+ this.observers[event].set(listener, numListeners + 1);
1236
+ });
1237
+ return this;
1238
+ }
1239
+ off(event, listener) {
1240
+ if (!this.observers[event]) return;
1241
+ if (!listener) {
1242
+ delete this.observers[event];
1243
+ return;
1244
+ }
1245
+ this.observers[event].delete(listener);
1246
+ }
1247
+ emit(event, ...args) {
1248
+ if (this.observers[event]) {
1249
+ const cloned = Array.from(this.observers[event].entries());
1250
+ cloned.forEach(([observer, numTimesAdded]) => {
1251
+ for (let i = 0; i < numTimesAdded; i++) {
1252
+ observer(...args);
1253
+ }
1254
+ });
1255
+ }
1256
+ if (this.observers['*']) {
1257
+ const cloned = Array.from(this.observers['*'].entries());
1258
+ cloned.forEach(([observer, numTimesAdded]) => {
1259
+ for (let i = 0; i < numTimesAdded; i++) {
1260
+ observer.apply(observer, [event, ...args]);
1261
+ }
1262
+ });
1263
+ }
1264
+ }
1265
+ }
1266
+
1267
+ class ResourceStore extends EventEmitter {
1268
+ constructor(data, options = {
1269
+ ns: ['translation'],
1270
+ defaultNS: 'translation'
1271
+ }) {
1272
+ super();
1273
+ this.data = data || {};
1274
+ this.options = options;
1275
+ if (this.options.keySeparator === undefined) {
1276
+ this.options.keySeparator = '.';
1277
+ }
1278
+ if (this.options.ignoreJSONStructure === undefined) {
1279
+ this.options.ignoreJSONStructure = true;
1280
+ }
1281
+ }
1282
+ addNamespaces(ns) {
1283
+ if (this.options.ns.indexOf(ns) < 0) {
1284
+ this.options.ns.push(ns);
1285
+ }
1286
+ }
1287
+ removeNamespaces(ns) {
1288
+ const index = this.options.ns.indexOf(ns);
1289
+ if (index > -1) {
1290
+ this.options.ns.splice(index, 1);
1291
+ }
1292
+ }
1293
+ getResource(lng, ns, key, options = {}) {
1294
+ const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
1295
+ const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
1296
+ let path;
1297
+ if (lng.indexOf('.') > -1) {
1298
+ path = lng.split('.');
1299
+ } else {
1300
+ path = [lng, ns];
1301
+ if (key) {
1302
+ if (Array.isArray(key)) {
1303
+ path.push(...key);
1304
+ } else if (isString(key) && keySeparator) {
1305
+ path.push(...key.split(keySeparator));
1306
+ } else {
1307
+ path.push(key);
1308
+ }
1309
+ }
1310
+ }
1311
+ const result = getPath(this.data, path);
1312
+ if (!result && !ns && !key && lng.indexOf('.') > -1) {
1313
+ lng = path[0];
1314
+ ns = path[1];
1315
+ key = path.slice(2).join('.');
1316
+ }
1317
+ if (result || !ignoreJSONStructure || !isString(key)) return result;
1318
+ return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
1319
+ }
1320
+ addResource(lng, ns, key, value, options = {
1321
+ silent: false
1322
+ }) {
1323
+ const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
1324
+ let path = [lng, ns];
1325
+ if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
1326
+ if (lng.indexOf('.') > -1) {
1327
+ path = lng.split('.');
1328
+ value = ns;
1329
+ ns = path[1];
1330
+ }
1331
+ this.addNamespaces(ns);
1332
+ setPath(this.data, path, value);
1333
+ if (!options.silent) this.emit('added', lng, ns, key, value);
1334
+ }
1335
+ addResources(lng, ns, resources, options = {
1336
+ silent: false
1337
+ }) {
1338
+ for (const m in resources) {
1339
+ if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
1340
+ silent: true
1341
+ });
1342
+ }
1343
+ if (!options.silent) this.emit('added', lng, ns, resources);
1344
+ }
1345
+ addResourceBundle(lng, ns, resources, deep, overwrite, options = {
1346
+ silent: false,
1347
+ skipCopy: false
1348
+ }) {
1349
+ let path = [lng, ns];
1350
+ if (lng.indexOf('.') > -1) {
1351
+ path = lng.split('.');
1352
+ deep = resources;
1353
+ resources = ns;
1354
+ ns = path[1];
1355
+ }
1356
+ this.addNamespaces(ns);
1357
+ let pack = getPath(this.data, path) || {};
1358
+ if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
1359
+ if (deep) {
1360
+ deepExtend(pack, resources, overwrite);
1361
+ } else {
1362
+ pack = {
1363
+ ...pack,
1364
+ ...resources
1365
+ };
1366
+ }
1367
+ setPath(this.data, path, pack);
1368
+ if (!options.silent) this.emit('added', lng, ns, resources);
1369
+ }
1370
+ removeResourceBundle(lng, ns) {
1371
+ if (this.hasResourceBundle(lng, ns)) {
1372
+ delete this.data[lng][ns];
1373
+ }
1374
+ this.removeNamespaces(ns);
1375
+ this.emit('removed', lng, ns);
1376
+ }
1377
+ hasResourceBundle(lng, ns) {
1378
+ return this.getResource(lng, ns) !== undefined;
1379
+ }
1380
+ getResourceBundle(lng, ns) {
1381
+ if (!ns) ns = this.options.defaultNS;
1382
+ return this.getResource(lng, ns);
1383
+ }
1384
+ getDataByLanguage(lng) {
1385
+ return this.data[lng];
1386
+ }
1387
+ hasLanguageSomeTranslations(lng) {
1388
+ const data = this.getDataByLanguage(lng);
1389
+ const n = data && Object.keys(data) || [];
1390
+ return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
1391
+ }
1392
+ toJSON() {
1393
+ return this.data;
1394
+ }
1395
+ }
1396
+
1397
+ var postProcessor = {
1398
+ processors: {},
1399
+ addPostProcessor(module) {
1400
+ this.processors[module.name] = module;
1401
+ },
1402
+ handle(processors, value, key, options, translator) {
1403
+ processors.forEach(processor => {
1404
+ value = this.processors[processor]?.process(value, key, options, translator) ?? value;
1405
+ });
1406
+ return value;
1407
+ }
1408
+ };
1409
+
1410
+ const PATH_KEY = Symbol('i18next/PATH_KEY');
1411
+ function createProxy() {
1412
+ const state = [];
1413
+ const handler = Object.create(null);
1414
+ let proxy;
1415
+ handler.get = (target, key) => {
1416
+ proxy?.revoke?.();
1417
+ if (key === PATH_KEY) return state;
1418
+ state.push(key);
1419
+ proxy = Proxy.revocable(target, handler);
1420
+ return proxy.proxy;
1421
+ };
1422
+ return Proxy.revocable(Object.create(null), handler).proxy;
1423
+ }
1424
+ function keysFromSelector(selector, opts) {
1425
+ const {
1426
+ [PATH_KEY]: path
1427
+ } = selector(createProxy());
1428
+ return path.join(opts?.keySeparator ?? '.');
1429
+ }
1430
+
1431
+ const checkedLoadedFor = {};
1432
+ const shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';
1433
+ class Translator$1 extends EventEmitter {
1434
+ constructor(services, options = {}) {
1435
+ super();
1436
+ copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
1437
+ this.options = options;
1438
+ if (this.options.keySeparator === undefined) {
1439
+ this.options.keySeparator = '.';
1440
+ }
1441
+ this.logger = baseLogger.create('translator');
1442
+ }
1443
+ changeLanguage(lng) {
1444
+ if (lng) this.language = lng;
1445
+ }
1446
+ exists(key, o = {
1447
+ interpolation: {}
1448
+ }) {
1449
+ const opt = {
1450
+ ...o
1451
+ };
1452
+ if (key == null) return false;
1453
+ const resolved = this.resolve(key, opt);
1454
+ if (resolved?.res === undefined) return false;
1455
+ const isObject = shouldHandleAsObject(resolved.res);
1456
+ if (opt.returnObjects === false && isObject) {
1457
+ return false;
1458
+ }
1459
+ return true;
1460
+ }
1461
+ extractFromKey(key, opt) {
1462
+ let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
1463
+ if (nsSeparator === undefined) nsSeparator = ':';
1464
+ const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
1465
+ let namespaces = opt.ns || this.options.defaultNS || [];
1466
+ const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
1467
+ const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
1468
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
1469
+ const m = key.match(this.interpolator.nestingRegexp);
1470
+ if (m && m.length > 0) {
1471
+ return {
1472
+ key,
1473
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
1474
+ };
1475
+ }
1476
+ const parts = key.split(nsSeparator);
1477
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
1478
+ key = parts.join(keySeparator);
1479
+ }
1480
+ return {
1481
+ key,
1482
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
1483
+ };
1484
+ }
1485
+ translate(keys, o, lastKey) {
1486
+ let opt = typeof o === 'object' ? {
1487
+ ...o
1488
+ } : o;
1489
+ if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {
1490
+ opt = this.options.overloadTranslationOptionHandler(arguments);
1491
+ }
1492
+ if (typeof opt === 'object') opt = {
1493
+ ...opt
1494
+ };
1495
+ if (!opt) opt = {};
1496
+ if (keys == null) return '';
1497
+ if (typeof keys === 'function') keys = keysFromSelector(keys, {
1498
+ ...this.options,
1499
+ ...opt
1500
+ });
1501
+ if (!Array.isArray(keys)) keys = [String(keys)];
1502
+ const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
1503
+ const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
1504
+ const {
1505
+ key,
1506
+ namespaces
1507
+ } = this.extractFromKey(keys[keys.length - 1], opt);
1508
+ const namespace = namespaces[namespaces.length - 1];
1509
+ let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
1510
+ if (nsSeparator === undefined) nsSeparator = ':';
1511
+ const lng = opt.lng || this.language;
1512
+ const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
1513
+ if (lng?.toLowerCase() === 'cimode') {
1514
+ if (appendNamespaceToCIMode) {
1515
+ if (returnDetails) {
1516
+ return {
1517
+ res: `${namespace}${nsSeparator}${key}`,
1518
+ usedKey: key,
1519
+ exactUsedKey: key,
1520
+ usedLng: lng,
1521
+ usedNS: namespace,
1522
+ usedParams: this.getUsedParamsDetails(opt)
1523
+ };
1524
+ }
1525
+ return `${namespace}${nsSeparator}${key}`;
1526
+ }
1527
+ if (returnDetails) {
1528
+ return {
1529
+ res: key,
1530
+ usedKey: key,
1531
+ exactUsedKey: key,
1532
+ usedLng: lng,
1533
+ usedNS: namespace,
1534
+ usedParams: this.getUsedParamsDetails(opt)
1535
+ };
1536
+ }
1537
+ return key;
1538
+ }
1539
+ const resolved = this.resolve(keys, opt);
1540
+ let res = resolved?.res;
1541
+ const resUsedKey = resolved?.usedKey || key;
1542
+ const resExactUsedKey = resolved?.exactUsedKey || key;
1543
+ const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
1544
+ const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
1545
+ const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
1546
+ const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
1547
+ const hasDefaultValue = Translator$1.hasDefaultValue(opt);
1548
+ const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';
1549
+ const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
1550
+ ordinal: false
1551
+ }) : '';
1552
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
1553
+ const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
1554
+ let resForObjHndl = res;
1555
+ if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
1556
+ resForObjHndl = defaultValue;
1557
+ }
1558
+ const handleAsObject = shouldHandleAsObject(resForObjHndl);
1559
+ const resType = Object.prototype.toString.apply(resForObjHndl);
1560
+ if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
1561
+ if (!opt.returnObjects && !this.options.returnObjects) {
1562
+ if (!this.options.returnedObjectHandler) {
1563
+ this.logger.warn('accessing an object - but returnObjects options is not enabled!');
1564
+ }
1565
+ const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
1566
+ ...opt,
1567
+ ns: namespaces
1568
+ }) : `key '${key} (${this.language})' returned an object instead of string.`;
1569
+ if (returnDetails) {
1570
+ resolved.res = r;
1571
+ resolved.usedParams = this.getUsedParamsDetails(opt);
1572
+ return resolved;
1573
+ }
1574
+ return r;
1575
+ }
1576
+ if (keySeparator) {
1577
+ const resTypeIsArray = Array.isArray(resForObjHndl);
1578
+ const copy = resTypeIsArray ? [] : {};
1579
+ const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
1580
+ for (const m in resForObjHndl) {
1581
+ if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
1582
+ const deepKey = `${newKeyToUse}${keySeparator}${m}`;
1583
+ if (hasDefaultValue && !res) {
1584
+ copy[m] = this.translate(deepKey, {
1585
+ ...opt,
1586
+ defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
1587
+ ...{
1588
+ joinArrays: false,
1589
+ ns: namespaces
1590
+ }
1591
+ });
1592
+ } else {
1593
+ copy[m] = this.translate(deepKey, {
1594
+ ...opt,
1595
+ ...{
1596
+ joinArrays: false,
1597
+ ns: namespaces
1598
+ }
1599
+ });
1600
+ }
1601
+ if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
1602
+ }
1603
+ }
1604
+ res = copy;
1605
+ }
1606
+ } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
1607
+ res = res.join(joinArrays);
1608
+ if (res) res = this.extendTranslation(res, keys, opt, lastKey);
1609
+ } else {
1610
+ let usedDefault = false;
1611
+ let usedKey = false;
1612
+ if (!this.isValidLookup(res) && hasDefaultValue) {
1613
+ usedDefault = true;
1614
+ res = defaultValue;
1615
+ }
1616
+ if (!this.isValidLookup(res)) {
1617
+ usedKey = true;
1618
+ res = key;
1619
+ }
1620
+ const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
1621
+ const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
1622
+ const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
1623
+ if (usedKey || usedDefault || updateMissing) {
1624
+ this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
1625
+ if (keySeparator) {
1626
+ const fk = this.resolve(key, {
1627
+ ...opt,
1628
+ keySeparator: false
1629
+ });
1630
+ 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.');
1631
+ }
1632
+ let lngs = [];
1633
+ const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
1634
+ if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
1635
+ for (let i = 0; i < fallbackLngs.length; i++) {
1636
+ lngs.push(fallbackLngs[i]);
1637
+ }
1638
+ } else if (this.options.saveMissingTo === 'all') {
1639
+ lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
1640
+ } else {
1641
+ lngs.push(opt.lng || this.language);
1642
+ }
1643
+ const send = (l, k, specificDefaultValue) => {
1644
+ const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
1645
+ if (this.options.missingKeyHandler) {
1646
+ this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
1647
+ } else if (this.backendConnector?.saveMissing) {
1648
+ this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
1649
+ }
1650
+ this.emit('missingKey', l, namespace, k, res);
1651
+ };
1652
+ if (this.options.saveMissing) {
1653
+ if (this.options.saveMissingPlurals && needsPluralHandling) {
1654
+ lngs.forEach(language => {
1655
+ const suffixes = this.pluralResolver.getSuffixes(language, opt);
1656
+ if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
1657
+ suffixes.push(`${this.options.pluralSeparator}zero`);
1658
+ }
1659
+ suffixes.forEach(suffix => {
1660
+ send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
1661
+ });
1662
+ });
1663
+ } else {
1664
+ send(lngs, key, defaultValue);
1665
+ }
1666
+ }
1667
+ }
1668
+ res = this.extendTranslation(res, keys, opt, resolved, lastKey);
1669
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
1670
+ res = `${namespace}${nsSeparator}${key}`;
1671
+ }
1672
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
1673
+ res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
1674
+ }
1675
+ }
1676
+ if (returnDetails) {
1677
+ resolved.res = res;
1678
+ resolved.usedParams = this.getUsedParamsDetails(opt);
1679
+ return resolved;
1680
+ }
1681
+ return res;
1682
+ }
1683
+ extendTranslation(res, key, opt, resolved, lastKey) {
1684
+ if (this.i18nFormat?.parse) {
1685
+ res = this.i18nFormat.parse(res, {
1686
+ ...this.options.interpolation.defaultVariables,
1687
+ ...opt
1688
+ }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
1689
+ resolved
1690
+ });
1691
+ } else if (!opt.skipInterpolation) {
1692
+ if (opt.interpolation) this.interpolator.init({
1693
+ ...opt,
1694
+ ...{
1695
+ interpolation: {
1696
+ ...this.options.interpolation,
1697
+ ...opt.interpolation
1698
+ }
1699
+ }
1700
+ });
1701
+ const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
1702
+ let nestBef;
1703
+ if (skipOnVariables) {
1704
+ const nb = res.match(this.interpolator.nestingRegexp);
1705
+ nestBef = nb && nb.length;
1706
+ }
1707
+ let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
1708
+ if (this.options.interpolation.defaultVariables) data = {
1709
+ ...this.options.interpolation.defaultVariables,
1710
+ ...data
1711
+ };
1712
+ res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
1713
+ if (skipOnVariables) {
1714
+ const na = res.match(this.interpolator.nestingRegexp);
1715
+ const nestAft = na && na.length;
1716
+ if (nestBef < nestAft) opt.nest = false;
1717
+ }
1718
+ if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
1719
+ if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
1720
+ if (lastKey?.[0] === args[0] && !opt.context) {
1721
+ this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
1722
+ return null;
1723
+ }
1724
+ return this.translate(...args, key);
1725
+ }, opt);
1726
+ if (opt.interpolation) this.interpolator.reset();
1727
+ }
1728
+ const postProcess = opt.postProcess || this.options.postProcess;
1729
+ const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
1730
+ if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
1731
+ res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
1732
+ i18nResolved: {
1733
+ ...resolved,
1734
+ usedParams: this.getUsedParamsDetails(opt)
1735
+ },
1736
+ ...opt
1737
+ } : opt, this);
1738
+ }
1739
+ return res;
1740
+ }
1741
+ resolve(keys, opt = {}) {
1742
+ let found;
1743
+ let usedKey;
1744
+ let exactUsedKey;
1745
+ let usedLng;
1746
+ let usedNS;
1747
+ if (isString(keys)) keys = [keys];
1748
+ keys.forEach(k => {
1749
+ if (this.isValidLookup(found)) return;
1750
+ const extracted = this.extractFromKey(k, opt);
1751
+ const key = extracted.key;
1752
+ usedKey = key;
1753
+ let namespaces = extracted.namespaces;
1754
+ if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
1755
+ const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
1756
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
1757
+ const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';
1758
+ const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
1759
+ namespaces.forEach(ns => {
1760
+ if (this.isValidLookup(found)) return;
1761
+ usedNS = ns;
1762
+ if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
1763
+ checkedLoadedFor[`${codes[0]}-${ns}`] = true;
1764
+ 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!!!');
1765
+ }
1766
+ codes.forEach(code => {
1767
+ if (this.isValidLookup(found)) return;
1768
+ usedLng = code;
1769
+ const finalKeys = [key];
1770
+ if (this.i18nFormat?.addLookupKeys) {
1771
+ this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
1772
+ } else {
1773
+ let pluralSuffix;
1774
+ if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
1775
+ const zeroSuffix = `${this.options.pluralSeparator}zero`;
1776
+ const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
1777
+ if (needsPluralHandling) {
1778
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
1779
+ finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
1780
+ }
1781
+ finalKeys.push(key + pluralSuffix);
1782
+ if (needsZeroSuffixLookup) {
1783
+ finalKeys.push(key + zeroSuffix);
1784
+ }
1785
+ }
1786
+ if (needsContextHandling) {
1787
+ const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;
1788
+ finalKeys.push(contextKey);
1789
+ if (needsPluralHandling) {
1790
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
1791
+ finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
1792
+ }
1793
+ finalKeys.push(contextKey + pluralSuffix);
1794
+ if (needsZeroSuffixLookup) {
1795
+ finalKeys.push(contextKey + zeroSuffix);
1796
+ }
1797
+ }
1798
+ }
1799
+ }
1800
+ let possibleKey;
1801
+ while (possibleKey = finalKeys.pop()) {
1802
+ if (!this.isValidLookup(found)) {
1803
+ exactUsedKey = possibleKey;
1804
+ found = this.getResource(code, ns, possibleKey, opt);
1805
+ }
1806
+ }
1807
+ });
1808
+ });
1809
+ });
1810
+ return {
1811
+ res: found,
1812
+ usedKey,
1813
+ exactUsedKey,
1814
+ usedLng,
1815
+ usedNS
1816
+ };
1817
+ }
1818
+ isValidLookup(res) {
1819
+ return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
1820
+ }
1821
+ getResource(code, ns, key, options = {}) {
1822
+ if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
1823
+ return this.resourceStore.getResource(code, ns, key, options);
1824
+ }
1825
+ getUsedParamsDetails(options = {}) {
1826
+ const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
1827
+ const useOptionsReplaceForData = options.replace && !isString(options.replace);
1828
+ let data = useOptionsReplaceForData ? options.replace : options;
1829
+ if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
1830
+ data.count = options.count;
1831
+ }
1832
+ if (this.options.interpolation.defaultVariables) {
1833
+ data = {
1834
+ ...this.options.interpolation.defaultVariables,
1835
+ ...data
1836
+ };
1837
+ }
1838
+ if (!useOptionsReplaceForData) {
1839
+ data = {
1840
+ ...data
1841
+ };
1842
+ for (const key of optionsKeys) {
1843
+ delete data[key];
1844
+ }
1845
+ }
1846
+ return data;
1847
+ }
1848
+ static hasDefaultValue(options) {
1849
+ const prefix = 'defaultValue';
1850
+ for (const option in options) {
1851
+ if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
1852
+ return true;
1853
+ }
1854
+ }
1855
+ return false;
1856
+ }
1857
+ }
1858
+
1859
+ class LanguageUtil {
1860
+ constructor(options) {
1861
+ this.options = options;
1862
+ this.supportedLngs = this.options.supportedLngs || false;
1863
+ this.logger = baseLogger.create('languageUtils');
1864
+ }
1865
+ getScriptPartFromCode(code) {
1866
+ code = getCleanedCode(code);
1867
+ if (!code || code.indexOf('-') < 0) return null;
1868
+ const p = code.split('-');
1869
+ if (p.length === 2) return null;
1870
+ p.pop();
1871
+ if (p[p.length - 1].toLowerCase() === 'x') return null;
1872
+ return this.formatLanguageCode(p.join('-'));
1873
+ }
1874
+ getLanguagePartFromCode(code) {
1875
+ code = getCleanedCode(code);
1876
+ if (!code || code.indexOf('-') < 0) return code;
1877
+ const p = code.split('-');
1878
+ return this.formatLanguageCode(p[0]);
1879
+ }
1880
+ formatLanguageCode(code) {
1881
+ if (isString(code) && code.indexOf('-') > -1) {
1882
+ let formattedCode;
1883
+ try {
1884
+ formattedCode = Intl.getCanonicalLocales(code)[0];
1885
+ } catch (e) {}
1886
+ if (formattedCode && this.options.lowerCaseLng) {
1887
+ formattedCode = formattedCode.toLowerCase();
1888
+ }
1889
+ if (formattedCode) return formattedCode;
1890
+ if (this.options.lowerCaseLng) {
1891
+ return code.toLowerCase();
1892
+ }
1893
+ return code;
1894
+ }
1895
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1896
+ }
1897
+ isSupportedCode(code) {
1898
+ if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
1899
+ code = this.getLanguagePartFromCode(code);
1900
+ }
1901
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1902
+ }
1903
+ getBestMatchFromCodes(codes) {
1904
+ if (!codes) return null;
1905
+ let found;
1906
+ codes.forEach(code => {
1907
+ if (found) return;
1908
+ const cleanedLng = this.formatLanguageCode(code);
1909
+ if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
1910
+ });
1911
+ if (!found && this.options.supportedLngs) {
1912
+ codes.forEach(code => {
1913
+ if (found) return;
1914
+ const lngScOnly = this.getScriptPartFromCode(code);
1915
+ if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
1916
+ const lngOnly = this.getLanguagePartFromCode(code);
1917
+ if (this.isSupportedCode(lngOnly)) return found = lngOnly;
1918
+ found = this.options.supportedLngs.find(supportedLng => {
1919
+ if (supportedLng === lngOnly) return supportedLng;
1920
+ if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
1921
+ if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
1922
+ if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
1923
+ });
1924
+ });
1925
+ }
1926
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1927
+ return found;
1928
+ }
1929
+ getFallbackCodes(fallbacks, code) {
1930
+ if (!fallbacks) return [];
1931
+ if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
1932
+ if (isString(fallbacks)) fallbacks = [fallbacks];
1933
+ if (Array.isArray(fallbacks)) return fallbacks;
1934
+ if (!code) return fallbacks.default || [];
1935
+ let found = fallbacks[code];
1936
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1937
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
1938
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1939
+ if (!found) found = fallbacks.default;
1940
+ return found || [];
1941
+ }
1942
+ toResolveHierarchy(code, fallbackCode) {
1943
+ const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1944
+ const codes = [];
1945
+ const addCode = c => {
1946
+ if (!c) return;
1947
+ if (this.isSupportedCode(c)) {
1948
+ codes.push(c);
1949
+ } else {
1950
+ this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1951
+ }
1952
+ };
1953
+ if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
1954
+ if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
1955
+ if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
1956
+ if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
1957
+ } else if (isString(code)) {
1958
+ addCode(this.formatLanguageCode(code));
1959
+ }
1960
+ fallbackCodes.forEach(fc => {
1961
+ if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
1962
+ });
1963
+ return codes;
1964
+ }
1965
+ }
1966
+
1967
+ const suffixesOrder = {
1968
+ zero: 0,
1969
+ one: 1,
1970
+ two: 2,
1971
+ few: 3,
1972
+ many: 4,
1973
+ other: 5
1974
+ };
1975
+ const dummyRule = {
1976
+ select: count => count === 1 ? 'one' : 'other',
1977
+ resolvedOptions: () => ({
1978
+ pluralCategories: ['one', 'other']
1979
+ })
1980
+ };
1981
+ class PluralResolver {
1982
+ constructor(languageUtils, options = {}) {
1983
+ this.languageUtils = languageUtils;
1984
+ this.options = options;
1985
+ this.logger = baseLogger.create('pluralResolver');
1986
+ this.pluralRulesCache = {};
1987
+ }
1988
+ clearCache() {
1989
+ this.pluralRulesCache = {};
1990
+ }
1991
+ getRule(code, options = {}) {
1992
+ const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
1993
+ const type = options.ordinal ? 'ordinal' : 'cardinal';
1994
+ const cacheKey = JSON.stringify({
1995
+ cleanedCode,
1996
+ type
1997
+ });
1998
+ if (cacheKey in this.pluralRulesCache) {
1999
+ return this.pluralRulesCache[cacheKey];
2000
+ }
2001
+ let rule;
2002
+ try {
2003
+ rule = new Intl.PluralRules(cleanedCode, {
2004
+ type
2005
+ });
2006
+ } catch (err) {
2007
+ if (!Intl) {
2008
+ this.logger.error('No Intl support, please use an Intl polyfill!');
2009
+ return dummyRule;
2010
+ }
2011
+ if (!code.match(/-|_/)) return dummyRule;
2012
+ const lngPart = this.languageUtils.getLanguagePartFromCode(code);
2013
+ rule = this.getRule(lngPart, options);
2014
+ }
2015
+ this.pluralRulesCache[cacheKey] = rule;
2016
+ return rule;
2017
+ }
2018
+ needsPlural(code, options = {}) {
2019
+ let rule = this.getRule(code, options);
2020
+ if (!rule) rule = this.getRule('dev', options);
2021
+ return rule?.resolvedOptions().pluralCategories.length > 1;
2022
+ }
2023
+ getPluralFormsOfKey(code, key, options = {}) {
2024
+ return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
2025
+ }
2026
+ getSuffixes(code, options = {}) {
2027
+ let rule = this.getRule(code, options);
2028
+ if (!rule) rule = this.getRule('dev', options);
2029
+ if (!rule) return [];
2030
+ return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
2031
+ }
2032
+ getSuffix(code, count, options = {}) {
2033
+ const rule = this.getRule(code, options);
2034
+ if (rule) {
2035
+ return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
2036
+ }
2037
+ this.logger.warn(`no plural rule found for: ${code}`);
2038
+ return this.getSuffix('dev', count, options);
2039
+ }
2040
+ }
2041
+
2042
+ const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {
2043
+ let path = getPathWithDefaults(data, defaultData, key);
2044
+ if (!path && ignoreJSONStructure && isString(key)) {
2045
+ path = deepFind(data, key, keySeparator);
2046
+ if (path === undefined) path = deepFind(defaultData, key, keySeparator);
2047
+ }
2048
+ return path;
2049
+ };
2050
+ const regexSafe = val => val.replace(/\$/g, '$$$$');
2051
+ class Interpolator {
2052
+ constructor(options = {}) {
2053
+ this.logger = baseLogger.create('interpolator');
2054
+ this.options = options;
2055
+ this.format = options?.interpolation?.format || (value => value);
2056
+ this.init(options);
2057
+ }
2058
+ init(options = {}) {
2059
+ if (!options.interpolation) options.interpolation = {
2060
+ escapeValue: true
2061
+ };
2062
+ const {
2063
+ escape: escape$1,
2064
+ escapeValue,
2065
+ useRawValueToEscape,
2066
+ prefix,
2067
+ prefixEscaped,
2068
+ suffix,
2069
+ suffixEscaped,
2070
+ formatSeparator,
2071
+ unescapeSuffix,
2072
+ unescapePrefix,
2073
+ nestingPrefix,
2074
+ nestingPrefixEscaped,
2075
+ nestingSuffix,
2076
+ nestingSuffixEscaped,
2077
+ nestingOptionsSeparator,
2078
+ maxReplaces,
2079
+ alwaysFormat
2080
+ } = options.interpolation;
2081
+ this.escape = escape$1 !== undefined ? escape$1 : escape;
2082
+ this.escapeValue = escapeValue !== undefined ? escapeValue : true;
2083
+ this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
2084
+ this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
2085
+ this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
2086
+ this.formatSeparator = formatSeparator || ',';
2087
+ this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
2088
+ this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
2089
+ this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
2090
+ this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
2091
+ this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
2092
+ this.maxReplaces = maxReplaces || 1000;
2093
+ this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
2094
+ this.resetRegExp();
2095
+ }
2096
+ reset() {
2097
+ if (this.options) this.init(this.options);
2098
+ }
2099
+ resetRegExp() {
2100
+ const getOrResetRegExp = (existingRegExp, pattern) => {
2101
+ if (existingRegExp?.source === pattern) {
2102
+ existingRegExp.lastIndex = 0;
2103
+ return existingRegExp;
2104
+ }
2105
+ return new RegExp(pattern, 'g');
2106
+ };
2107
+ this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
2108
+ this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
2109
+ this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
2110
+ }
2111
+ interpolate(str, data, lng, options) {
2112
+ let match;
2113
+ let value;
2114
+ let replaces;
2115
+ const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
2116
+ const handleFormat = key => {
2117
+ if (key.indexOf(this.formatSeparator) < 0) {
2118
+ const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
2119
+ return this.alwaysFormat ? this.format(path, undefined, lng, {
2120
+ ...options,
2121
+ ...data,
2122
+ interpolationkey: key
2123
+ }) : path;
2124
+ }
2125
+ const p = key.split(this.formatSeparator);
2126
+ const k = p.shift().trim();
2127
+ const f = p.join(this.formatSeparator).trim();
2128
+ return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
2129
+ ...options,
2130
+ ...data,
2131
+ interpolationkey: k
2132
+ });
2133
+ };
2134
+ this.resetRegExp();
2135
+ const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
2136
+ const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
2137
+ const todos = [{
2138
+ regex: this.regexpUnescape,
2139
+ safeValue: val => regexSafe(val)
2140
+ }, {
2141
+ regex: this.regexp,
2142
+ safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
2143
+ }];
2144
+ todos.forEach(todo => {
2145
+ replaces = 0;
2146
+ while (match = todo.regex.exec(str)) {
2147
+ const matchedVar = match[1].trim();
2148
+ value = handleFormat(matchedVar);
2149
+ if (value === undefined) {
2150
+ if (typeof missingInterpolationHandler === 'function') {
2151
+ const temp = missingInterpolationHandler(str, match, options);
2152
+ value = isString(temp) ? temp : '';
2153
+ } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
2154
+ value = '';
2155
+ } else if (skipOnVariables) {
2156
+ value = match[0];
2157
+ continue;
2158
+ } else {
2159
+ this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
2160
+ value = '';
2161
+ }
2162
+ } else if (!isString(value) && !this.useRawValueToEscape) {
2163
+ value = makeString(value);
2164
+ }
2165
+ const safeValue = todo.safeValue(value);
2166
+ str = str.replace(match[0], safeValue);
2167
+ if (skipOnVariables) {
2168
+ todo.regex.lastIndex += value.length;
2169
+ todo.regex.lastIndex -= match[0].length;
2170
+ } else {
2171
+ todo.regex.lastIndex = 0;
2172
+ }
2173
+ replaces++;
2174
+ if (replaces >= this.maxReplaces) {
2175
+ break;
2176
+ }
2177
+ }
2178
+ });
2179
+ return str;
2180
+ }
2181
+ nest(str, fc, options = {}) {
2182
+ let match;
2183
+ let value;
2184
+ let clonedOptions;
2185
+ const handleHasOptions = (key, inheritedOptions) => {
2186
+ const sep = this.nestingOptionsSeparator;
2187
+ if (key.indexOf(sep) < 0) return key;
2188
+ const c = key.split(new RegExp(`${sep}[ ]*{`));
2189
+ let optionsString = `{${c[1]}`;
2190
+ key = c[0];
2191
+ optionsString = this.interpolate(optionsString, clonedOptions);
2192
+ const matchedSingleQuotes = optionsString.match(/'/g);
2193
+ const matchedDoubleQuotes = optionsString.match(/"/g);
2194
+ if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
2195
+ optionsString = optionsString.replace(/'/g, '"');
2196
+ }
2197
+ try {
2198
+ clonedOptions = JSON.parse(optionsString);
2199
+ if (inheritedOptions) clonedOptions = {
2200
+ ...inheritedOptions,
2201
+ ...clonedOptions
2202
+ };
2203
+ } catch (e) {
2204
+ this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
2205
+ return `${key}${sep}${optionsString}`;
2206
+ }
2207
+ if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
2208
+ return key;
2209
+ };
2210
+ while (match = this.nestingRegexp.exec(str)) {
2211
+ let formatters = [];
2212
+ clonedOptions = {
2213
+ ...options
2214
+ };
2215
+ clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
2216
+ clonedOptions.applyPostProcessor = false;
2217
+ delete clonedOptions.defaultValue;
2218
+ const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);
2219
+ if (keyEndIndex !== -1) {
2220
+ formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);
2221
+ match[1] = match[1].slice(0, keyEndIndex);
2222
+ }
2223
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
2224
+ if (value && match[0] === str && !isString(value)) return value;
2225
+ if (!isString(value)) value = makeString(value);
2226
+ if (!value) {
2227
+ this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
2228
+ value = '';
2229
+ }
2230
+ if (formatters.length) {
2231
+ value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
2232
+ ...options,
2233
+ interpolationkey: match[1].trim()
2234
+ }), value.trim());
2235
+ }
2236
+ str = str.replace(match[0], value);
2237
+ this.regexp.lastIndex = 0;
2238
+ }
2239
+ return str;
2240
+ }
2241
+ }
2242
+
2243
+ const parseFormatStr = formatStr => {
2244
+ let formatName = formatStr.toLowerCase().trim();
2245
+ const formatOptions = {};
2246
+ if (formatStr.indexOf('(') > -1) {
2247
+ const p = formatStr.split('(');
2248
+ formatName = p[0].toLowerCase().trim();
2249
+ const optStr = p[1].substring(0, p[1].length - 1);
2250
+ if (formatName === 'currency' && optStr.indexOf(':') < 0) {
2251
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
2252
+ } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
2253
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
2254
+ } else {
2255
+ const opts = optStr.split(';');
2256
+ opts.forEach(opt => {
2257
+ if (opt) {
2258
+ const [key, ...rest] = opt.split(':');
2259
+ const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
2260
+ const trimmedKey = key.trim();
2261
+ if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
2262
+ if (val === 'false') formatOptions[trimmedKey] = false;
2263
+ if (val === 'true') formatOptions[trimmedKey] = true;
2264
+ if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
2265
+ }
2266
+ });
2267
+ }
2268
+ }
2269
+ return {
2270
+ formatName,
2271
+ formatOptions
2272
+ };
2273
+ };
2274
+ const createCachedFormatter = fn => {
2275
+ const cache = {};
2276
+ return (v, l, o) => {
2277
+ let optForCache = o;
2278
+ if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
2279
+ optForCache = {
2280
+ ...optForCache,
2281
+ [o.interpolationkey]: undefined
2282
+ };
2283
+ }
2284
+ const key = l + JSON.stringify(optForCache);
2285
+ let frm = cache[key];
2286
+ if (!frm) {
2287
+ frm = fn(getCleanedCode(l), o);
2288
+ cache[key] = frm;
2289
+ }
2290
+ return frm(v);
2291
+ };
2292
+ };
2293
+ const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);
2294
+ class Formatter {
2295
+ constructor(options = {}) {
2296
+ this.logger = baseLogger.create('formatter');
2297
+ this.options = options;
2298
+ this.init(options);
2299
+ }
2300
+ init(services, options = {
2301
+ interpolation: {}
2302
+ }) {
2303
+ this.formatSeparator = options.interpolation.formatSeparator || ',';
2304
+ const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
2305
+ this.formats = {
2306
+ number: cf((lng, opt) => {
2307
+ const formatter = new Intl.NumberFormat(lng, {
2308
+ ...opt
2309
+ });
2310
+ return val => formatter.format(val);
2311
+ }),
2312
+ currency: cf((lng, opt) => {
2313
+ const formatter = new Intl.NumberFormat(lng, {
2314
+ ...opt,
2315
+ style: 'currency'
2316
+ });
2317
+ return val => formatter.format(val);
2318
+ }),
2319
+ datetime: cf((lng, opt) => {
2320
+ const formatter = new Intl.DateTimeFormat(lng, {
2321
+ ...opt
2322
+ });
2323
+ return val => formatter.format(val);
2324
+ }),
2325
+ relativetime: cf((lng, opt) => {
2326
+ const formatter = new Intl.RelativeTimeFormat(lng, {
2327
+ ...opt
2328
+ });
2329
+ return val => formatter.format(val, opt.range || 'day');
2330
+ }),
2331
+ list: cf((lng, opt) => {
2332
+ const formatter = new Intl.ListFormat(lng, {
2333
+ ...opt
2334
+ });
2335
+ return val => formatter.format(val);
2336
+ })
2337
+ };
2338
+ }
2339
+ add(name, fc) {
2340
+ this.formats[name.toLowerCase().trim()] = fc;
2341
+ }
2342
+ addCached(name, fc) {
2343
+ this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
2344
+ }
2345
+ format(value, format, lng, options = {}) {
2346
+ const formats = format.split(this.formatSeparator);
2347
+ if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
2348
+ const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
2349
+ formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
2350
+ }
2351
+ const result = formats.reduce((mem, f) => {
2352
+ const {
2353
+ formatName,
2354
+ formatOptions
2355
+ } = parseFormatStr(f);
2356
+ if (this.formats[formatName]) {
2357
+ let formatted = mem;
2358
+ try {
2359
+ const valOptions = options?.formatParams?.[options.interpolationkey] || {};
2360
+ const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
2361
+ formatted = this.formats[formatName](mem, l, {
2362
+ ...formatOptions,
2363
+ ...options,
2364
+ ...valOptions
2365
+ });
2366
+ } catch (error) {
2367
+ this.logger.warn(error);
2368
+ }
2369
+ return formatted;
2370
+ } else {
2371
+ this.logger.warn(`there was no format function for ${formatName}`);
2372
+ }
2373
+ return mem;
2374
+ }, value);
2375
+ return result;
2376
+ }
2377
+ }
2378
+
2379
+ const removePending = (q, name) => {
2380
+ if (q.pending[name] !== undefined) {
2381
+ delete q.pending[name];
2382
+ q.pendingCount--;
2383
+ }
2384
+ };
2385
+ class Connector extends EventEmitter {
2386
+ constructor(backend, store, services, options = {}) {
2387
+ super();
2388
+ this.backend = backend;
2389
+ this.store = store;
2390
+ this.services = services;
2391
+ this.languageUtils = services.languageUtils;
2392
+ this.options = options;
2393
+ this.logger = baseLogger.create('backendConnector');
2394
+ this.waitingReads = [];
2395
+ this.maxParallelReads = options.maxParallelReads || 10;
2396
+ this.readingCalls = 0;
2397
+ this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
2398
+ this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
2399
+ this.state = {};
2400
+ this.queue = [];
2401
+ this.backend?.init?.(services, options.backend, options);
2402
+ }
2403
+ queueLoad(languages, namespaces, options, callback) {
2404
+ const toLoad = {};
2405
+ const pending = {};
2406
+ const toLoadLanguages = {};
2407
+ const toLoadNamespaces = {};
2408
+ languages.forEach(lng => {
2409
+ let hasAllNamespaces = true;
2410
+ namespaces.forEach(ns => {
2411
+ const name = `${lng}|${ns}`;
2412
+ if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
2413
+ this.state[name] = 2;
2414
+ } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
2415
+ if (pending[name] === undefined) pending[name] = true;
2416
+ } else {
2417
+ this.state[name] = 1;
2418
+ hasAllNamespaces = false;
2419
+ if (pending[name] === undefined) pending[name] = true;
2420
+ if (toLoad[name] === undefined) toLoad[name] = true;
2421
+ if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
2422
+ }
2423
+ });
2424
+ if (!hasAllNamespaces) toLoadLanguages[lng] = true;
2425
+ });
2426
+ if (Object.keys(toLoad).length || Object.keys(pending).length) {
2427
+ this.queue.push({
2428
+ pending,
2429
+ pendingCount: Object.keys(pending).length,
2430
+ loaded: {},
2431
+ errors: [],
2432
+ callback
2433
+ });
2434
+ }
2435
+ return {
2436
+ toLoad: Object.keys(toLoad),
2437
+ pending: Object.keys(pending),
2438
+ toLoadLanguages: Object.keys(toLoadLanguages),
2439
+ toLoadNamespaces: Object.keys(toLoadNamespaces)
2440
+ };
2441
+ }
2442
+ loaded(name, err, data) {
2443
+ const s = name.split('|');
2444
+ const lng = s[0];
2445
+ const ns = s[1];
2446
+ if (err) this.emit('failedLoading', lng, ns, err);
2447
+ if (!err && data) {
2448
+ this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
2449
+ skipCopy: true
2450
+ });
2451
+ }
2452
+ this.state[name] = err ? -1 : 2;
2453
+ if (err && data) this.state[name] = 0;
2454
+ const loaded = {};
2455
+ this.queue.forEach(q => {
2456
+ pushPath(q.loaded, [lng], ns);
2457
+ removePending(q, name);
2458
+ if (err) q.errors.push(err);
2459
+ if (q.pendingCount === 0 && !q.done) {
2460
+ Object.keys(q.loaded).forEach(l => {
2461
+ if (!loaded[l]) loaded[l] = {};
2462
+ const loadedKeys = q.loaded[l];
2463
+ if (loadedKeys.length) {
2464
+ loadedKeys.forEach(n => {
2465
+ if (loaded[l][n] === undefined) loaded[l][n] = true;
2466
+ });
2467
+ }
2468
+ });
2469
+ q.done = true;
2470
+ if (q.errors.length) {
2471
+ q.callback(q.errors);
2472
+ } else {
2473
+ q.callback();
2474
+ }
2475
+ }
2476
+ });
2477
+ this.emit('loaded', loaded);
2478
+ this.queue = this.queue.filter(q => !q.done);
2479
+ }
2480
+ read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
2481
+ if (!lng.length) return callback(null, {});
2482
+ if (this.readingCalls >= this.maxParallelReads) {
2483
+ this.waitingReads.push({
2484
+ lng,
2485
+ ns,
2486
+ fcName,
2487
+ tried,
2488
+ wait,
2489
+ callback
2490
+ });
2491
+ return;
2492
+ }
2493
+ this.readingCalls++;
2494
+ const resolver = (err, data) => {
2495
+ this.readingCalls--;
2496
+ if (this.waitingReads.length > 0) {
2497
+ const next = this.waitingReads.shift();
2498
+ this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
2499
+ }
2500
+ if (err && data && tried < this.maxRetries) {
2501
+ setTimeout(() => {
2502
+ this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
2503
+ }, wait);
2504
+ return;
2505
+ }
2506
+ callback(err, data);
2507
+ };
2508
+ const fc = this.backend[fcName].bind(this.backend);
2509
+ if (fc.length === 2) {
2510
+ try {
2511
+ const r = fc(lng, ns);
2512
+ if (r && typeof r.then === 'function') {
2513
+ r.then(data => resolver(null, data)).catch(resolver);
2514
+ } else {
2515
+ resolver(null, r);
2516
+ }
2517
+ } catch (err) {
2518
+ resolver(err);
2519
+ }
2520
+ return;
2521
+ }
2522
+ return fc(lng, ns, resolver);
2523
+ }
2524
+ prepareLoading(languages, namespaces, options = {}, callback) {
2525
+ if (!this.backend) {
2526
+ this.logger.warn('No backend was added via i18next.use. Will not load resources.');
2527
+ return callback && callback();
2528
+ }
2529
+ if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
2530
+ if (isString(namespaces)) namespaces = [namespaces];
2531
+ const toLoad = this.queueLoad(languages, namespaces, options, callback);
2532
+ if (!toLoad.toLoad.length) {
2533
+ if (!toLoad.pending.length) callback();
2534
+ return null;
2535
+ }
2536
+ toLoad.toLoad.forEach(name => {
2537
+ this.loadOne(name);
2538
+ });
2539
+ }
2540
+ load(languages, namespaces, callback) {
2541
+ this.prepareLoading(languages, namespaces, {}, callback);
2542
+ }
2543
+ reload(languages, namespaces, callback) {
2544
+ this.prepareLoading(languages, namespaces, {
2545
+ reload: true
2546
+ }, callback);
2547
+ }
2548
+ loadOne(name, prefix = '') {
2549
+ const s = name.split('|');
2550
+ const lng = s[0];
2551
+ const ns = s[1];
2552
+ this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
2553
+ if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
2554
+ if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
2555
+ this.loaded(name, err, data);
2556
+ });
2557
+ }
2558
+ saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
2559
+ if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
2560
+ 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!!!');
2561
+ return;
2562
+ }
2563
+ if (key === undefined || key === null || key === '') return;
2564
+ if (this.backend?.create) {
2565
+ const opts = {
2566
+ ...options,
2567
+ isUpdate
2568
+ };
2569
+ const fc = this.backend.create.bind(this.backend);
2570
+ if (fc.length < 6) {
2571
+ try {
2572
+ let r;
2573
+ if (fc.length === 5) {
2574
+ r = fc(languages, namespace, key, fallbackValue, opts);
2575
+ } else {
2576
+ r = fc(languages, namespace, key, fallbackValue);
2577
+ }
2578
+ if (r && typeof r.then === 'function') {
2579
+ r.then(data => clb(null, data)).catch(clb);
2580
+ } else {
2581
+ clb(null, r);
2582
+ }
2583
+ } catch (err) {
2584
+ clb(err);
2585
+ }
2586
+ } else {
2587
+ fc(languages, namespace, key, fallbackValue, clb, opts);
2588
+ }
2589
+ }
2590
+ if (!languages || !languages[0]) return;
2591
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
2592
+ }
2593
+ }
2594
+
2595
+ const get = () => ({
2596
+ debug: false,
2597
+ initAsync: true,
2598
+ ns: ['translation'],
2599
+ defaultNS: ['translation'],
2600
+ fallbackLng: ['dev'],
2601
+ fallbackNS: false,
2602
+ supportedLngs: false,
2603
+ nonExplicitSupportedLngs: false,
2604
+ load: 'all',
2605
+ preload: false,
2606
+ simplifyPluralSuffix: true,
2607
+ keySeparator: '.',
2608
+ nsSeparator: ':',
2609
+ pluralSeparator: '_',
2610
+ contextSeparator: '_',
2611
+ partialBundledLanguages: false,
2612
+ saveMissing: false,
2613
+ updateMissing: false,
2614
+ saveMissingTo: 'fallback',
2615
+ saveMissingPlurals: true,
2616
+ missingKeyHandler: false,
2617
+ missingInterpolationHandler: false,
2618
+ postProcess: false,
2619
+ postProcessPassResolved: false,
2620
+ returnNull: false,
2621
+ returnEmptyString: true,
2622
+ returnObjects: false,
2623
+ joinArrays: false,
2624
+ returnedObjectHandler: false,
2625
+ parseMissingKeyHandler: false,
2626
+ appendNamespaceToMissingKey: false,
2627
+ appendNamespaceToCIMode: false,
2628
+ overloadTranslationOptionHandler: args => {
2629
+ let ret = {};
2630
+ if (typeof args[1] === 'object') ret = args[1];
2631
+ if (isString(args[1])) ret.defaultValue = args[1];
2632
+ if (isString(args[2])) ret.tDescription = args[2];
2633
+ if (typeof args[2] === 'object' || typeof args[3] === 'object') {
2634
+ const options = args[3] || args[2];
2635
+ Object.keys(options).forEach(key => {
2636
+ ret[key] = options[key];
2637
+ });
2638
+ }
2639
+ return ret;
2640
+ },
2641
+ interpolation: {
2642
+ escapeValue: true,
2643
+ format: value => value,
2644
+ prefix: '{{',
2645
+ suffix: '}}',
2646
+ formatSeparator: ',',
2647
+ unescapePrefix: '-',
2648
+ nestingPrefix: '$t(',
2649
+ nestingSuffix: ')',
2650
+ nestingOptionsSeparator: ',',
2651
+ maxReplaces: 1000,
2652
+ skipOnVariables: true
2653
+ },
2654
+ cacheInBuiltFormats: true
2655
+ });
2656
+ const transformOptions = options => {
2657
+ if (isString(options.ns)) options.ns = [options.ns];
2658
+ if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
2659
+ if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
2660
+ if (options.supportedLngs?.indexOf?.('cimode') < 0) {
2661
+ options.supportedLngs = options.supportedLngs.concat(['cimode']);
2662
+ }
2663
+ if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;
2664
+ return options;
2665
+ };
2666
+
2667
+ const noop = () => {};
2668
+ const bindMemberFunctions = inst => {
2669
+ const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
2670
+ mems.forEach(mem => {
2671
+ if (typeof inst[mem] === 'function') {
2672
+ inst[mem] = inst[mem].bind(inst);
2673
+ }
2674
+ });
2675
+ };
2676
+ const usesLocize = inst => {
2677
+ if (inst?.modules?.backend?.name?.indexOf('Locize') > 0) return true;
2678
+ if (inst?.modules?.backend?.constructor?.name?.indexOf('Locize') > 0) return true;
2679
+ if (inst?.options?.backend?.backends) {
2680
+ if (inst.options.backend.backends.some(b => b?.name.indexOf('Locize') > 0 || b?.constructor?.name.indexOf('Locize') > 0)) return true;
2681
+ }
2682
+ return false;
2683
+ };
2684
+ class I18n extends EventEmitter {
2685
+ constructor(options = {}, callback) {
2686
+ super();
2687
+ this.options = transformOptions(options);
2688
+ this.services = {};
2689
+ this.logger = baseLogger;
2690
+ this.modules = {
2691
+ external: []
2692
+ };
2693
+ bindMemberFunctions(this);
2694
+ if (callback && !this.isInitialized && !options.isClone) {
2695
+ if (!this.options.initAsync) {
2696
+ this.init(options, callback);
2697
+ return this;
2698
+ }
2699
+ setTimeout(() => {
2700
+ this.init(options, callback);
2701
+ }, 0);
2702
+ }
2703
+ }
2704
+ init(options = {}, callback) {
2705
+ this.isInitializing = true;
2706
+ if (typeof options === 'function') {
2707
+ callback = options;
2708
+ options = {};
2709
+ }
2710
+ if (options.defaultNS == null && options.ns) {
2711
+ if (isString(options.ns)) {
2712
+ options.defaultNS = options.ns;
2713
+ } else if (options.ns.indexOf('translation') < 0) {
2714
+ options.defaultNS = options.ns[0];
2715
+ }
2716
+ }
2717
+ const defOpts = get();
2718
+ this.options = {
2719
+ ...defOpts,
2720
+ ...this.options,
2721
+ ...transformOptions(options)
2722
+ };
2723
+ this.options.interpolation = {
2724
+ ...defOpts.interpolation,
2725
+ ...this.options.interpolation
2726
+ };
2727
+ if (options.keySeparator !== undefined) {
2728
+ this.options.userDefinedKeySeparator = options.keySeparator;
2729
+ }
2730
+ if (options.nsSeparator !== undefined) {
2731
+ this.options.userDefinedNsSeparator = options.nsSeparator;
2732
+ }
2733
+ if (typeof this.options.overloadTranslationOptionHandler !== 'function') {
2734
+ this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;
2735
+ }
2736
+ if (this.options.showSupportNotice !== false && !usesLocize(this)) {
2737
+ if (typeof console !== 'undefined' && typeof console.info !== 'undefined') console.info('🌐 i18next is maintained with support from locize.com — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙');
2738
+ }
2739
+ const createClassOnDemand = ClassOrObject => {
2740
+ if (!ClassOrObject) return null;
2741
+ if (typeof ClassOrObject === 'function') return new ClassOrObject();
2742
+ return ClassOrObject;
2743
+ };
2744
+ if (!this.options.isClone) {
2745
+ if (this.modules.logger) {
2746
+ baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
2747
+ } else {
2748
+ baseLogger.init(null, this.options);
2749
+ }
2750
+ let formatter;
2751
+ if (this.modules.formatter) {
2752
+ formatter = this.modules.formatter;
2753
+ } else {
2754
+ formatter = Formatter;
2755
+ }
2756
+ const lu = new LanguageUtil(this.options);
2757
+ this.store = new ResourceStore(this.options.resources, this.options);
2758
+ const s = this.services;
2759
+ s.logger = baseLogger;
2760
+ s.resourceStore = this.store;
2761
+ s.languageUtils = lu;
2762
+ s.pluralResolver = new PluralResolver(lu, {
2763
+ prepend: this.options.pluralSeparator,
2764
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
2765
+ });
2766
+ const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
2767
+ if (usingLegacyFormatFunction) {
2768
+ this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
2769
+ }
2770
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
2771
+ s.formatter = createClassOnDemand(formatter);
2772
+ if (s.formatter.init) s.formatter.init(s, this.options);
2773
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
2774
+ }
2775
+ s.interpolator = new Interpolator(this.options);
2776
+ s.utils = {
2777
+ hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
2778
+ };
2779
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
2780
+ s.backendConnector.on('*', (event, ...args) => {
2781
+ this.emit(event, ...args);
2782
+ });
2783
+ if (this.modules.languageDetector) {
2784
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
2785
+ if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
2786
+ }
2787
+ if (this.modules.i18nFormat) {
2788
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
2789
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
2790
+ }
2791
+ this.translator = new Translator$1(this.services, this.options);
2792
+ this.translator.on('*', (event, ...args) => {
2793
+ this.emit(event, ...args);
2794
+ });
2795
+ this.modules.external.forEach(m => {
2796
+ if (m.init) m.init(this);
2797
+ });
2798
+ }
2799
+ this.format = this.options.interpolation.format;
2800
+ if (!callback) callback = noop;
2801
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
2802
+ const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2803
+ if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
2804
+ }
2805
+ if (!this.services.languageDetector && !this.options.lng) {
2806
+ this.logger.warn('init: no languageDetector is used and no lng is defined');
2807
+ }
2808
+ const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
2809
+ storeApi.forEach(fcName => {
2810
+ this[fcName] = (...args) => this.store[fcName](...args);
2811
+ });
2812
+ const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
2813
+ storeApiChained.forEach(fcName => {
2814
+ this[fcName] = (...args) => {
2815
+ this.store[fcName](...args);
2816
+ return this;
2817
+ };
2818
+ });
2819
+ const deferred = defer();
2820
+ const load = () => {
2821
+ const finish = (err, t) => {
2822
+ this.isInitializing = false;
2823
+ if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
2824
+ this.isInitialized = true;
2825
+ if (!this.options.isClone) this.logger.log('initialized', this.options);
2826
+ this.emit('initialized', this.options);
2827
+ deferred.resolve(t);
2828
+ callback(err, t);
2829
+ };
2830
+ if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
2831
+ this.changeLanguage(this.options.lng, finish);
2832
+ };
2833
+ if (this.options.resources || !this.options.initAsync) {
2834
+ load();
2835
+ } else {
2836
+ setTimeout(load, 0);
2837
+ }
2838
+ return deferred;
2839
+ }
2840
+ loadResources(language, callback = noop) {
2841
+ let usedCallback = callback;
2842
+ const usedLng = isString(language) ? language : this.language;
2843
+ if (typeof language === 'function') usedCallback = language;
2844
+ if (!this.options.resources || this.options.partialBundledLanguages) {
2845
+ if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
2846
+ const toLoad = [];
2847
+ const append = lng => {
2848
+ if (!lng) return;
2849
+ if (lng === 'cimode') return;
2850
+ const lngs = this.services.languageUtils.toResolveHierarchy(lng);
2851
+ lngs.forEach(l => {
2852
+ if (l === 'cimode') return;
2853
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
2854
+ });
2855
+ };
2856
+ if (!usedLng) {
2857
+ const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2858
+ fallbacks.forEach(l => append(l));
2859
+ } else {
2860
+ append(usedLng);
2861
+ }
2862
+ this.options.preload?.forEach?.(l => append(l));
2863
+ this.services.backendConnector.load(toLoad, this.options.ns, e => {
2864
+ if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
2865
+ usedCallback(e);
2866
+ });
2867
+ } else {
2868
+ usedCallback(null);
2869
+ }
2870
+ }
2871
+ reloadResources(lngs, ns, callback) {
2872
+ const deferred = defer();
2873
+ if (typeof lngs === 'function') {
2874
+ callback = lngs;
2875
+ lngs = undefined;
2876
+ }
2877
+ if (typeof ns === 'function') {
2878
+ callback = ns;
2879
+ ns = undefined;
2880
+ }
2881
+ if (!lngs) lngs = this.languages;
2882
+ if (!ns) ns = this.options.ns;
2883
+ if (!callback) callback = noop;
2884
+ this.services.backendConnector.reload(lngs, ns, err => {
2885
+ deferred.resolve();
2886
+ callback(err);
2887
+ });
2888
+ return deferred;
2889
+ }
2890
+ use(module) {
2891
+ if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
2892
+ if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
2893
+ if (module.type === 'backend') {
2894
+ this.modules.backend = module;
2895
+ }
2896
+ if (module.type === 'logger' || module.log && module.warn && module.error) {
2897
+ this.modules.logger = module;
2898
+ }
2899
+ if (module.type === 'languageDetector') {
2900
+ this.modules.languageDetector = module;
2901
+ }
2902
+ if (module.type === 'i18nFormat') {
2903
+ this.modules.i18nFormat = module;
2904
+ }
2905
+ if (module.type === 'postProcessor') {
2906
+ postProcessor.addPostProcessor(module);
2907
+ }
2908
+ if (module.type === 'formatter') {
2909
+ this.modules.formatter = module;
2910
+ }
2911
+ if (module.type === '3rdParty') {
2912
+ this.modules.external.push(module);
2913
+ }
2914
+ return this;
2915
+ }
2916
+ setResolvedLanguage(l) {
2917
+ if (!l || !this.languages) return;
2918
+ if (['cimode', 'dev'].indexOf(l) > -1) return;
2919
+ for (let li = 0; li < this.languages.length; li++) {
2920
+ const lngInLngs = this.languages[li];
2921
+ if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
2922
+ if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2923
+ this.resolvedLanguage = lngInLngs;
2924
+ break;
2925
+ }
2926
+ }
2927
+ if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
2928
+ this.resolvedLanguage = l;
2929
+ this.languages.unshift(l);
2930
+ }
2931
+ }
2932
+ changeLanguage(lng, callback) {
2933
+ this.isLanguageChangingTo = lng;
2934
+ const deferred = defer();
2935
+ this.emit('languageChanging', lng);
2936
+ const setLngProps = l => {
2937
+ this.language = l;
2938
+ this.languages = this.services.languageUtils.toResolveHierarchy(l);
2939
+ this.resolvedLanguage = undefined;
2940
+ this.setResolvedLanguage(l);
2941
+ };
2942
+ const done = (err, l) => {
2943
+ if (l) {
2944
+ if (this.isLanguageChangingTo === lng) {
2945
+ setLngProps(l);
2946
+ this.translator.changeLanguage(l);
2947
+ this.isLanguageChangingTo = undefined;
2948
+ this.emit('languageChanged', l);
2949
+ this.logger.log('languageChanged', l);
2950
+ }
2951
+ } else {
2952
+ this.isLanguageChangingTo = undefined;
2953
+ }
2954
+ deferred.resolve((...args) => this.t(...args));
2955
+ if (callback) callback(err, (...args) => this.t(...args));
2956
+ };
2957
+ const setLng = lngs => {
2958
+ if (!lng && !lngs && this.services.languageDetector) lngs = [];
2959
+ const fl = isString(lngs) ? lngs : lngs && lngs[0];
2960
+ const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
2961
+ if (l) {
2962
+ if (!this.language) {
2963
+ setLngProps(l);
2964
+ }
2965
+ if (!this.translator.language) this.translator.changeLanguage(l);
2966
+ this.services.languageDetector?.cacheUserLanguage?.(l);
2967
+ }
2968
+ this.loadResources(l, err => {
2969
+ done(err, l);
2970
+ });
2971
+ };
2972
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2973
+ setLng(this.services.languageDetector.detect());
2974
+ } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2975
+ if (this.services.languageDetector.detect.length === 0) {
2976
+ this.services.languageDetector.detect().then(setLng);
2977
+ } else {
2978
+ this.services.languageDetector.detect(setLng);
2979
+ }
2980
+ } else {
2981
+ setLng(lng);
2982
+ }
2983
+ return deferred;
2984
+ }
2985
+ getFixedT(lng, ns, keyPrefix) {
2986
+ const fixedT = (key, opts, ...rest) => {
2987
+ let o;
2988
+ if (typeof opts !== 'object') {
2989
+ o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2990
+ } else {
2991
+ o = {
2992
+ ...opts
2993
+ };
2994
+ }
2995
+ o.lng = o.lng || fixedT.lng;
2996
+ o.lngs = o.lngs || fixedT.lngs;
2997
+ o.ns = o.ns || fixedT.ns;
2998
+ if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2999
+ const keySeparator = this.options.keySeparator || '.';
3000
+ let resultKey;
3001
+ if (o.keyPrefix && Array.isArray(key)) {
3002
+ resultKey = key.map(k => {
3003
+ if (typeof k === 'function') k = keysFromSelector(k, {
3004
+ ...this.options,
3005
+ ...opts
3006
+ });
3007
+ return `${o.keyPrefix}${keySeparator}${k}`;
3008
+ });
3009
+ } else {
3010
+ if (typeof key === 'function') key = keysFromSelector(key, {
3011
+ ...this.options,
3012
+ ...opts
3013
+ });
3014
+ resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
3015
+ }
3016
+ return this.t(resultKey, o);
3017
+ };
3018
+ if (isString(lng)) {
3019
+ fixedT.lng = lng;
3020
+ } else {
3021
+ fixedT.lngs = lng;
3022
+ }
3023
+ fixedT.ns = ns;
3024
+ fixedT.keyPrefix = keyPrefix;
3025
+ return fixedT;
3026
+ }
3027
+ t(...args) {
3028
+ return this.translator?.translate(...args);
3029
+ }
3030
+ exists(...args) {
3031
+ return this.translator?.exists(...args);
3032
+ }
3033
+ setDefaultNamespace(ns) {
3034
+ this.options.defaultNS = ns;
3035
+ }
3036
+ hasLoadedNamespace(ns, options = {}) {
3037
+ if (!this.isInitialized) {
3038
+ this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
3039
+ return false;
3040
+ }
3041
+ if (!this.languages || !this.languages.length) {
3042
+ this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
3043
+ return false;
3044
+ }
3045
+ const lng = options.lng || this.resolvedLanguage || this.languages[0];
3046
+ const fallbackLng = this.options ? this.options.fallbackLng : false;
3047
+ const lastLng = this.languages[this.languages.length - 1];
3048
+ if (lng.toLowerCase() === 'cimode') return true;
3049
+ const loadNotPending = (l, n) => {
3050
+ const loadState = this.services.backendConnector.state[`${l}|${n}`];
3051
+ return loadState === -1 || loadState === 0 || loadState === 2;
3052
+ };
3053
+ if (options.precheck) {
3054
+ const preResult = options.precheck(this, loadNotPending);
3055
+ if (preResult !== undefined) return preResult;
3056
+ }
3057
+ if (this.hasResourceBundle(lng, ns)) return true;
3058
+ if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
3059
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
3060
+ return false;
3061
+ }
3062
+ loadNamespaces(ns, callback) {
3063
+ const deferred = defer();
3064
+ if (!this.options.ns) {
3065
+ if (callback) callback();
3066
+ return Promise.resolve();
3067
+ }
3068
+ if (isString(ns)) ns = [ns];
3069
+ ns.forEach(n => {
3070
+ if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
3071
+ });
3072
+ this.loadResources(err => {
3073
+ deferred.resolve();
3074
+ if (callback) callback(err);
3075
+ });
3076
+ return deferred;
3077
+ }
3078
+ loadLanguages(lngs, callback) {
3079
+ const deferred = defer();
3080
+ if (isString(lngs)) lngs = [lngs];
3081
+ const preloaded = this.options.preload || [];
3082
+ const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
3083
+ if (!newLngs.length) {
3084
+ if (callback) callback();
3085
+ return Promise.resolve();
3086
+ }
3087
+ this.options.preload = preloaded.concat(newLngs);
3088
+ this.loadResources(err => {
3089
+ deferred.resolve();
3090
+ if (callback) callback(err);
3091
+ });
3092
+ return deferred;
3093
+ }
3094
+ dir(lng) {
3095
+ if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
3096
+ if (!lng) return 'rtl';
3097
+ try {
3098
+ const l = new Intl.Locale(lng);
3099
+ if (l && l.getTextInfo) {
3100
+ const ti = l.getTextInfo();
3101
+ if (ti && ti.direction) return ti.direction;
3102
+ }
3103
+ } catch (e) {}
3104
+ 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'];
3105
+ const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
3106
+ if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';
3107
+ return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
3108
+ }
3109
+ static createInstance(options = {}, callback) {
3110
+ const instance = new I18n(options, callback);
3111
+ instance.createInstance = I18n.createInstance;
3112
+ return instance;
3113
+ }
3114
+ cloneInstance(options = {}, callback = noop) {
3115
+ const forkResourceStore = options.forkResourceStore;
3116
+ if (forkResourceStore) delete options.forkResourceStore;
3117
+ const mergedOptions = {
3118
+ ...this.options,
3119
+ ...options,
3120
+ ...{
3121
+ isClone: true
3122
+ }
3123
+ };
3124
+ const clone = new I18n(mergedOptions);
3125
+ if (options.debug !== undefined || options.prefix !== undefined) {
3126
+ clone.logger = clone.logger.clone(options);
3127
+ }
3128
+ const membersToCopy = ['store', 'services', 'language'];
3129
+ membersToCopy.forEach(m => {
3130
+ clone[m] = this[m];
3131
+ });
3132
+ clone.services = {
3133
+ ...this.services
3134
+ };
3135
+ clone.services.utils = {
3136
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
3137
+ };
3138
+ if (forkResourceStore) {
3139
+ const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
3140
+ prev[l] = {
3141
+ ...this.store.data[l]
3142
+ };
3143
+ prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
3144
+ acc[n] = {
3145
+ ...prev[l][n]
3146
+ };
3147
+ return acc;
3148
+ }, prev[l]);
3149
+ return prev;
3150
+ }, {});
3151
+ clone.store = new ResourceStore(clonedData, mergedOptions);
3152
+ clone.services.resourceStore = clone.store;
3153
+ }
3154
+ if (options.interpolation) {
3155
+ const defOpts = get();
3156
+ const mergedInterpolation = {
3157
+ ...defOpts.interpolation,
3158
+ ...this.options.interpolation,
3159
+ ...options.interpolation
3160
+ };
3161
+ const mergedForInterpolator = {
3162
+ ...mergedOptions,
3163
+ interpolation: mergedInterpolation
3164
+ };
3165
+ clone.services.interpolator = new Interpolator(mergedForInterpolator);
3166
+ }
3167
+ clone.translator = new Translator$1(clone.services, mergedOptions);
3168
+ clone.translator.on('*', (event, ...args) => {
3169
+ clone.emit(event, ...args);
3170
+ });
3171
+ clone.init(mergedOptions, callback);
3172
+ clone.translator.options = mergedOptions;
3173
+ clone.translator.backendConnector.services.utils = {
3174
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
3175
+ };
3176
+ return clone;
3177
+ }
3178
+ toJSON() {
3179
+ return {
3180
+ options: this.options,
3181
+ store: this.store,
3182
+ language: this.language,
3183
+ languages: this.languages,
3184
+ resolvedLanguage: this.resolvedLanguage
3185
+ };
3186
+ }
3187
+ }
3188
+ const instance = I18n.createInstance();
3189
+
3190
+ instance.createInstance;
3191
+ instance.dir;
3192
+ instance.init;
3193
+ instance.loadResources;
3194
+ instance.reloadResources;
3195
+ instance.use;
3196
+ instance.changeLanguage;
3197
+ instance.getFixedT;
3198
+ instance.t;
3199
+ instance.exists;
3200
+ instance.setDefaultNamespace;
3201
+ instance.hasLoadedNamespace;
3202
+ instance.loadNamespaces;
3203
+ instance.loadLanguages;
3204
+
3205
+ var en = {
3206
+ translation: {
3207
+ categorize: {
3208
+ limitMaxChoicesPerCategory:
3209
+ 'You\'ve reached the limit of {{maxChoicesPerCategory}} responses per area. To add another response, one must first be removed.',
3210
+ maxChoicesPerCategoryRestriction:
3211
+ 'To change this value to {{maxChoicesPerCategory}}, each category must have {{maxChoicesPerCategory}} or fewer answer choice[s].',
3212
+ },
3213
+ ebsr: {
3214
+ part: 'Part {{index}}',
3215
+ },
3216
+ numberLine: {
3217
+ addElementLimit_one: 'You can only add {{count}} element',
3218
+ addElementLimit_other: 'You can only add {{count}} elements',
3219
+ clearAll: 'Clear all',
3220
+ },
3221
+ imageClozeAssociation: {
3222
+ reachedLimit_one:
3223
+ 'You’ve reached the limit of {{count}} response per area. To add another response, one must first be removed.',
3224
+ reachedLimit_other: 'Full',
3225
+ },
3226
+ drawingResponse: {
3227
+ fillColor: 'Fill color',
3228
+ outlineColor: 'Outline color',
3229
+ noFill: 'No fill',
3230
+ lightblue: 'Light blue',
3231
+ lightyellow: 'Light yellow',
3232
+ red: 'Red',
3233
+ orange: 'Orange',
3234
+ yellow: 'Yellow',
3235
+ violet: 'Violet',
3236
+ blue: 'Blue',
3237
+ green: 'Green',
3238
+ white: 'White',
3239
+ black: 'Black',
3240
+ onDoubleClick: 'Double click to edit this text. Press Enter to submit.',
3241
+ },
3242
+ charting: {
3243
+ addCategory: 'Add category',
3244
+ actions: 'Actions',
3245
+ add: 'Add',
3246
+ delete: 'Delete',
3247
+ newLabel: 'New label',
3248
+ reachedLimit_other: "There can't be more than {{count}} categories.",
3249
+ keyLegend: {
3250
+ incorrectAnswer: 'Student incorrect answer',
3251
+ correctAnswer: 'Student correct answer',
3252
+ correctKeyAnswer: 'Answer key correct',
3253
+ },
3254
+ },
3255
+ graphing: {
3256
+ point: 'Point',
3257
+ circle: 'Circle',
3258
+ line: 'Line',
3259
+ parabola: 'Parabola',
3260
+ absolute: 'Absolute Value',
3261
+ exponential: 'Exponential',
3262
+ polygon: 'Polygon',
3263
+ ray: 'Ray',
3264
+ segment: 'Segment',
3265
+ sine: 'Sine',
3266
+ vector: 'Vector',
3267
+ label: 'Label',
3268
+ redo: 'Redo',
3269
+ reset: 'Reset',
3270
+ },
3271
+ mathInline: {
3272
+ primaryCorrectWithAlternates:
3273
+ 'Note: The answer shown above is the primary correct answer specified by the author for this item, but other answers may also be recognized as correct.',
3274
+ },
3275
+ multipleChoice: {
3276
+ minSelections: 'Select at least {{minSelections}}.',
3277
+ maxSelections_one: 'Only {{maxSelections}} answer is allowed.',
3278
+ maxSelections_other: 'Only {{maxSelections}} answers are allowed.',
3279
+ minmaxSelections_equal: 'Select {{minSelections}}.',
3280
+ minmaxSelections_range: 'Select between {{minSelections}} and {{maxSelections}}.',
3281
+ },
3282
+ selectText: {
3283
+ correctAnswerSelected: 'Correct',
3284
+ correctAnswerNotSelected: 'Correct Answer Not Selected',
3285
+ incorrectSelection: 'Incorrect Selection',
3286
+ key: 'Key',
3287
+ },
3288
+ },
3289
+ common: {
3290
+ undo: 'Undo',
3291
+ clearAll: 'Clear all',
3292
+ correct: 'Correct',
3293
+ incorrect: 'Incorrect',
3294
+ showCorrectAnswer: 'Show correct answer',
3295
+ hideCorrectAnswer: 'Hide correct answer',
3296
+ commonCorrectAnswerWithAlternates:
3297
+ 'Note: The answer shown above is the most common correct answer for this item. One or more additional correct answers are also defined, and will also be recognized as correct.',
3298
+ warning: 'Warning',
3299
+ showNote: 'Show Note',
3300
+ hideNote: 'Hide Note',
3301
+ cancel: 'Cancel',
3302
+ },
3303
+ };
3304
+
3305
+ var es = {
3306
+ translation: {
3307
+ categorize: {
3308
+ limitMaxChoicesPerCategory:
3309
+ 'Has alcanzado el límite de {{maxChoicesPerCategory}} respuestas por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.',
3310
+ maxChoicesPerCategoryRestriction:
3311
+ 'Para cambiar este valor a {{maxChoicesPerCategory}}, cada categoría debe tener {{maxChoicesPerCategory}} o menos opciones de respuesta',
3312
+ },
3313
+ ebsr: {
3314
+ part: 'Parte {{index}}',
3315
+ },
3316
+ numberLine: {
3317
+ addElementLimit_one: 'Solo puedes agregar {{count}} elemento',
3318
+ addElementLimit_other: 'Solo puedes agregar {{count}} elementos',
3319
+ clearAll: 'Borrar todo',
3320
+ },
3321
+ imageClozeAssociation: {
3322
+ reachedLimit_one:
3323
+ 'Has alcanzado el límite de {{count}} respuesta por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.',
3324
+ reachedLimit_other: 'Lleno',
3325
+ },
3326
+ drawingResponse: {
3327
+ fillColor: 'Color de relleno',
3328
+ outlineColor: 'Color del contorno',
3329
+ noFill: 'Sin relleno',
3330
+ lightblue: 'Azul claro',
3331
+ lightyellow: 'Amarillo claro',
3332
+ red: 'Rojo',
3333
+ orange: 'Naranja',
3334
+ yellow: 'Amarillo',
3335
+ violet: 'Violeta',
3336
+ blue: 'Azul',
3337
+ green: 'Verde',
3338
+ white: 'Blanco',
3339
+ black: 'Negro',
3340
+ onDoubleClick: 'Haz doble clic para revisar este texto. Presiona el botón de ingreso para enviar',
3341
+ },
3342
+ charting: {
3343
+ addCategory: 'Añadir categoría',
3344
+ actions: 'Acciones',
3345
+ add: 'Añadir',
3346
+ delete: 'Eliminar',
3347
+ newLabel: 'Nueva etiqueta',
3348
+ reachedLimit_other: 'No puede haber más de {{count}} categorías.',
3349
+ keyLegend: {
3350
+ incorrectAnswer: 'Respuesta incorrecta del estudiante',
3351
+ correctAnswer: 'Respuesta correcta del estudiante',
3352
+ correctKeyAnswer: 'Clave de respuesta correcta',
3353
+ },
3354
+ },
3355
+ graphing: {
3356
+ point: 'Punto',
3357
+ circle: 'Circulo',
3358
+ line: 'Línea',
3359
+ parabola: 'Parábola',
3360
+ absolute: 'Valor absoluto',
3361
+ exponential: 'Exponencial',
3362
+ polygon: 'Polígono',
3363
+ ray: 'Semirrecta',
3364
+ segment: 'Segmento ',
3365
+ sine: 'Seno',
3366
+ vector: 'Vector',
3367
+ label: 'Etiqueta',
3368
+ redo: 'Rehacer',
3369
+ reset: 'Reiniciar',
3370
+ },
3371
+ mathInline: {
3372
+ primaryCorrectWithAlternates:
3373
+ 'Nota: La respuesta que se muestra arriba es la respuesta correcta principal especificada por el autor para esta pregunta, pero también se pueden reconocer otras respuestas como correctas.',
3374
+ },
3375
+ multipleChoice: {
3376
+ minSelections: 'Seleccione al menos {{minSelections}}.',
3377
+ maxSelections_one: 'Sólo se permite {{maxSelections}} respuesta.',
3378
+ maxSelections_other: 'Sólo se permiten {{maxSelections}} respuestas.',
3379
+ minmaxSelections_equal: 'Seleccione {{minSelections}}.',
3380
+ minmaxSelections_range: 'Seleccione entre {{minSelections}} y {{maxSelections}}.',
3381
+ },
3382
+ selectText: {
3383
+ correctAnswerSelected: 'Respuesta Correcta',
3384
+ correctAnswerNotSelected: 'Respuesta Correcta No Seleccionada',
3385
+ incorrectSelection: 'Selección Incorrecta',
3386
+ key: 'Clave',
3387
+ },
3388
+ },
3389
+ common: {
3390
+ undo: 'Deshacer',
3391
+ clearAll: 'Borrar todo',
3392
+ correct: 'Correct',
3393
+ incorrect: 'Incorrect',
3394
+ showCorrectAnswer: 'Mostrar respuesta correcta',
3395
+ hideCorrectAnswer: 'Ocultar respuesta correcta',
3396
+ commonCorrectAnswerWithAlternates:
3397
+ 'Nota: La respuesta que se muestra arriba es la respuesta correcta más común para esta pregunta. También se definen una o más respuestas correctas adicionales, y también se reconocerán como correctas.',
3398
+ warning: 'Advertencia',
3399
+ showNote: 'Mostrar Nota',
3400
+ hideNote: 'Ocultar Nota',
3401
+ cancel: 'Cancelar',
3402
+ },
3403
+ };
3404
+
3405
+ instance.init({
3406
+ fallbackLng: 'en',
3407
+ lng: 'en',
3408
+ debug: true,
3409
+ resources: {
3410
+ en: en,
3411
+ es: es,
3412
+ },
3413
+ });
3414
+
3415
+ var Translator = {
3416
+ translator: {
3417
+ ...instance,
3418
+ t: (key, options) => {
3419
+ const { lng } = options;
3420
+
3421
+ switch (lng) {
3422
+ // these keys don't work with plurals, don't know why, so I added a workaround to convert them to the correct lng
3423
+ case 'en_US':
3424
+ case 'en-US':
3425
+ options.lng = 'en';
3426
+ break;
3427
+ case 'es_ES':
3428
+ case 'es-ES':
3429
+ case 'es_MX':
3430
+ case 'es-MX':
3431
+ options.lng = 'es';
3432
+ break;
3433
+ }
3434
+ return instance.t(key, { lng, ...options });
3435
+ },
3436
+ },
3437
+ languageOptions: [
3438
+ { value: 'en_US', label: 'English (US)' },
3439
+ { value: 'es_ES', label: 'Spanish' },
3440
+ ],
3441
+ };
3442
+
3443
+ // Should be exactly the same as configure/defaults.js
3444
+ var defaults = {
3445
+ model: {
3446
+ allowTrailingZerosDefault: false,
3447
+ equationEditor: '8',
3448
+ ignoreOrderDefault: false,
3449
+ markup: '',
3450
+ playerSpellCheckEnabled: true,
3451
+ prompt: '',
3452
+ promptEnabled: true,
3453
+ rationale: '',
3454
+ rationaleEnabled: true,
3455
+ responses: {},
3456
+ spellCheckEnabled: true,
3457
+ teacherInstructions: '',
3458
+ teacherInstructionsEnabled: true,
3459
+ toolbarEditorPosition: 'bottom',
3460
+ validationDefault: 'literal',
3461
+ },
3462
+ configuration: {},
3463
+ };
3464
+
3465
+ const enabled = (config, env, defaultValue) => {
3466
+ // if model.partialScoring = false
3467
+ // - if env.partialScoring = false || env.partialScoring = true => use dichotomous scoring
3468
+ // else if model.partialScoring = true || undefined
3469
+ // - if env.partialScoring = false, use dichotomous scoring
3470
+ // - else if env.partialScoring = true, use partial scoring
3471
+ config = config || {};
3472
+ env = env || {};
3473
+
3474
+ if (config.partialScoring === false) {
3475
+ return false;
3476
+ }
3477
+
3478
+ if (env.partialScoring === false) {
3479
+ return false;
3480
+ }
3481
+
3482
+ return typeof defaultValue === 'boolean' ? defaultValue : true;
3483
+ };
3484
+
3485
+ /** Detect free variable `global` from Node.js. */
3486
+
3487
+ var freeGlobal$1 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
3488
+
3489
+ var _freeGlobal = freeGlobal$1;
3490
+
3491
+ var freeGlobal = _freeGlobal;
3492
+
3493
+ /** Detect free variable `self`. */
3494
+ var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
3495
+
3496
+ /** Used as a reference to the global object. */
3497
+ var root$7 = freeGlobal || freeSelf || Function('return this')();
3498
+
3499
+ var _root = root$7;
3500
+
3501
+ var root$6 = _root;
3502
+
3503
+ /** Built-in value references. */
3504
+ var Symbol$4 = root$6.Symbol;
3505
+
3506
+ var _Symbol = Symbol$4;
3507
+
3508
+ var Symbol$3 = _Symbol;
3509
+
3510
+ /** Used for built-in method references. */
3511
+ var objectProto$5 = Object.prototype;
3512
+
3513
+ /** Used to check objects for own properties. */
3514
+ var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
3515
+
3516
+ /**
3517
+ * Used to resolve the
3518
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
3519
+ * of values.
3520
+ */
3521
+ var nativeObjectToString$1 = objectProto$5.toString;
3522
+
3523
+ /** Built-in value references. */
3524
+ var symToStringTag$1 = Symbol$3 ? Symbol$3.toStringTag : undefined;
3525
+
3526
+ /**
3527
+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
3528
+ *
3529
+ * @private
3530
+ * @param {*} value The value to query.
3531
+ * @returns {string} Returns the raw `toStringTag`.
3532
+ */
3533
+ function getRawTag$1(value) {
3534
+ var isOwn = hasOwnProperty$4.call(value, symToStringTag$1),
3535
+ tag = value[symToStringTag$1];
3536
+
3537
+ try {
3538
+ value[symToStringTag$1] = undefined;
3539
+ var unmasked = true;
3540
+ } catch (e) {}
3541
+
3542
+ var result = nativeObjectToString$1.call(value);
3543
+ if (unmasked) {
3544
+ if (isOwn) {
3545
+ value[symToStringTag$1] = tag;
3546
+ } else {
3547
+ delete value[symToStringTag$1];
3548
+ }
3549
+ }
3550
+ return result;
3551
+ }
3552
+
3553
+ var _getRawTag = getRawTag$1;
3554
+
3555
+ /** Used for built-in method references. */
3556
+
3557
+ var objectProto$4 = Object.prototype;
3558
+
3559
+ /**
3560
+ * Used to resolve the
3561
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
3562
+ * of values.
3563
+ */
3564
+ var nativeObjectToString = objectProto$4.toString;
3565
+
3566
+ /**
3567
+ * Converts `value` to a string using `Object.prototype.toString`.
3568
+ *
3569
+ * @private
3570
+ * @param {*} value The value to convert.
3571
+ * @returns {string} Returns the converted string.
3572
+ */
3573
+ function objectToString$1(value) {
3574
+ return nativeObjectToString.call(value);
3575
+ }
3576
+
3577
+ var _objectToString = objectToString$1;
3578
+
3579
+ var Symbol$2 = _Symbol,
3580
+ getRawTag = _getRawTag,
3581
+ objectToString = _objectToString;
3582
+
3583
+ /** `Object#toString` result references. */
3584
+ var nullTag = '[object Null]',
3585
+ undefinedTag = '[object Undefined]';
3586
+
3587
+ /** Built-in value references. */
3588
+ var symToStringTag = Symbol$2 ? Symbol$2.toStringTag : undefined;
3589
+
3590
+ /**
3591
+ * The base implementation of `getTag` without fallbacks for buggy environments.
3592
+ *
3593
+ * @private
3594
+ * @param {*} value The value to query.
3595
+ * @returns {string} Returns the `toStringTag`.
3596
+ */
3597
+ function baseGetTag$3(value) {
3598
+ if (value == null) {
3599
+ return value === undefined ? undefinedTag : nullTag;
3600
+ }
3601
+ return (symToStringTag && symToStringTag in Object(value))
3602
+ ? getRawTag(value)
3603
+ : objectToString(value);
3604
+ }
3605
+
3606
+ var _baseGetTag = baseGetTag$3;
3607
+
3608
+ /**
3609
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
3610
+ * and has a `typeof` result of "object".
3611
+ *
3612
+ * @static
3613
+ * @memberOf _
3614
+ * @since 4.0.0
3615
+ * @category Lang
3616
+ * @param {*} value The value to check.
3617
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
3618
+ * @example
3619
+ *
3620
+ * _.isObjectLike({});
3621
+ * // => true
3622
+ *
3623
+ * _.isObjectLike([1, 2, 3]);
3624
+ * // => true
3625
+ *
3626
+ * _.isObjectLike(_.noop);
3627
+ * // => false
3628
+ *
3629
+ * _.isObjectLike(null);
3630
+ * // => false
3631
+ */
3632
+
3633
+ function isObjectLike$2(value) {
3634
+ return value != null && typeof value == 'object';
3635
+ }
3636
+
3637
+ var isObjectLike_1 = isObjectLike$2;
3638
+
3639
+ /**
3640
+ * Checks if `value` is the
3641
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
3642
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
3643
+ *
3644
+ * @static
3645
+ * @memberOf _
3646
+ * @since 0.1.0
3647
+ * @category Lang
3648
+ * @param {*} value The value to check.
3649
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
3650
+ * @example
3651
+ *
3652
+ * _.isObject({});
3653
+ * // => true
3654
+ *
3655
+ * _.isObject([1, 2, 3]);
3656
+ * // => true
3657
+ *
3658
+ * _.isObject(_.noop);
3659
+ * // => true
3660
+ *
3661
+ * _.isObject(null);
3662
+ * // => false
3663
+ */
3664
+
3665
+ function isObject$2(value) {
3666
+ var type = typeof value;
3667
+ return value != null && (type == 'object' || type == 'function');
3668
+ }
3669
+
3670
+ var isObject_1 = isObject$2;
3671
+
3672
+ var baseGetTag$2 = _baseGetTag,
3673
+ isObject$1 = isObject_1;
3674
+
3675
+ /** `Object#toString` result references. */
3676
+ var asyncTag = '[object AsyncFunction]',
3677
+ funcTag = '[object Function]',
3678
+ genTag = '[object GeneratorFunction]',
3679
+ proxyTag = '[object Proxy]';
3680
+
3681
+ /**
3682
+ * Checks if `value` is classified as a `Function` object.
3683
+ *
3684
+ * @static
3685
+ * @memberOf _
3686
+ * @since 0.1.0
3687
+ * @category Lang
3688
+ * @param {*} value The value to check.
3689
+ * @returns {boolean} Returns `true` if `value` is a function, else `false`.
3690
+ * @example
3691
+ *
3692
+ * _.isFunction(_);
3693
+ * // => true
3694
+ *
3695
+ * _.isFunction(/abc/);
3696
+ * // => false
3697
+ */
3698
+ function isFunction$1(value) {
3699
+ if (!isObject$1(value)) {
3700
+ return false;
3701
+ }
3702
+ // The use of `Object#toString` avoids issues with the `typeof` operator
3703
+ // in Safari 9 which returns 'object' for typed arrays and other constructors.
3704
+ var tag = baseGetTag$2(value);
3705
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
3706
+ }
3707
+
3708
+ var isFunction_1 = isFunction$1;
3709
+
3710
+ var root$5 = _root;
3711
+
3712
+ /** Used to detect overreaching core-js shims. */
3713
+ var coreJsData$1 = root$5['__core-js_shared__'];
3714
+
3715
+ var _coreJsData = coreJsData$1;
3716
+
3717
+ var coreJsData = _coreJsData;
3718
+
3719
+ /** Used to detect methods masquerading as native. */
3720
+ var maskSrcKey = (function() {
3721
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
3722
+ return uid ? ('Symbol(src)_1.' + uid) : '';
3723
+ }());
3724
+
3725
+ /**
3726
+ * Checks if `func` has its source masked.
3727
+ *
3728
+ * @private
3729
+ * @param {Function} func The function to check.
3730
+ * @returns {boolean} Returns `true` if `func` is masked, else `false`.
3731
+ */
3732
+ function isMasked$1(func) {
3733
+ return !!maskSrcKey && (maskSrcKey in func);
3734
+ }
3735
+
3736
+ var _isMasked = isMasked$1;
3737
+
3738
+ /** Used for built-in method references. */
3739
+
3740
+ var funcProto$1 = Function.prototype;
3741
+
3742
+ /** Used to resolve the decompiled source of functions. */
3743
+ var funcToString$1 = funcProto$1.toString;
3744
+
3745
+ /**
3746
+ * Converts `func` to its source code.
3747
+ *
3748
+ * @private
3749
+ * @param {Function} func The function to convert.
3750
+ * @returns {string} Returns the source code.
3751
+ */
3752
+ function toSource$2(func) {
3753
+ if (func != null) {
3754
+ try {
3755
+ return funcToString$1.call(func);
3756
+ } catch (e) {}
3757
+ try {
3758
+ return (func + '');
3759
+ } catch (e) {}
3760
+ }
3761
+ return '';
3762
+ }
3763
+
3764
+ var _toSource = toSource$2;
3765
+
3766
+ var isFunction = isFunction_1,
3767
+ isMasked = _isMasked,
3768
+ isObject = isObject_1,
3769
+ toSource$1 = _toSource;
3770
+
3771
+ /**
3772
+ * Used to match `RegExp`
3773
+ * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
3774
+ */
3775
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
3776
+
3777
+ /** Used to detect host constructors (Safari). */
3778
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
3779
+
3780
+ /** Used for built-in method references. */
3781
+ var funcProto = Function.prototype,
3782
+ objectProto$3 = Object.prototype;
3783
+
3784
+ /** Used to resolve the decompiled source of functions. */
3785
+ var funcToString = funcProto.toString;
3786
+
3787
+ /** Used to check objects for own properties. */
3788
+ var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
3789
+
3790
+ /** Used to detect if a method is native. */
3791
+ var reIsNative = RegExp('^' +
3792
+ funcToString.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&')
3793
+ .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
3794
+ );
3795
+
3796
+ /**
3797
+ * The base implementation of `_.isNative` without bad shim checks.
3798
+ *
3799
+ * @private
3800
+ * @param {*} value The value to check.
3801
+ * @returns {boolean} Returns `true` if `value` is a native function,
3802
+ * else `false`.
3803
+ */
3804
+ function baseIsNative$1(value) {
3805
+ if (!isObject(value) || isMasked(value)) {
3806
+ return false;
3807
+ }
3808
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
3809
+ return pattern.test(toSource$1(value));
3810
+ }
3811
+
3812
+ var _baseIsNative = baseIsNative$1;
3813
+
3814
+ /**
3815
+ * Gets the value at `key` of `object`.
3816
+ *
3817
+ * @private
3818
+ * @param {Object} [object] The object to query.
3819
+ * @param {string} key The key of the property to get.
3820
+ * @returns {*} Returns the property value.
3821
+ */
3822
+
3823
+ function getValue$1(object, key) {
3824
+ return object == null ? undefined : object[key];
3825
+ }
3826
+
3827
+ var _getValue = getValue$1;
3828
+
3829
+ var baseIsNative = _baseIsNative,
3830
+ getValue = _getValue;
3831
+
3832
+ /**
3833
+ * Gets the native function at `key` of `object`.
3834
+ *
3835
+ * @private
3836
+ * @param {Object} object The object to query.
3837
+ * @param {string} key The key of the method to get.
3838
+ * @returns {*} Returns the function if it's native, else `undefined`.
3839
+ */
3840
+ function getNative$6(object, key) {
3841
+ var value = getValue(object, key);
3842
+ return baseIsNative(value) ? value : undefined;
3843
+ }
3844
+
3845
+ var _getNative = getNative$6;
3846
+
3847
+ var getNative$5 = _getNative;
3848
+
3849
+ /* Built-in method references that are verified to be native. */
3850
+ var nativeCreate$4 = getNative$5(Object, 'create');
3851
+
3852
+ var _nativeCreate = nativeCreate$4;
3853
+
3854
+ var nativeCreate$3 = _nativeCreate;
3855
+
3856
+ /**
3857
+ * Removes all key-value entries from the hash.
3858
+ *
3859
+ * @private
3860
+ * @name clear
3861
+ * @memberOf Hash
3862
+ */
3863
+ function hashClear$1() {
3864
+ this.__data__ = nativeCreate$3 ? nativeCreate$3(null) : {};
3865
+ this.size = 0;
3866
+ }
3867
+
3868
+ var _hashClear = hashClear$1;
3869
+
3870
+ /**
3871
+ * Removes `key` and its value from the hash.
3872
+ *
3873
+ * @private
3874
+ * @name delete
3875
+ * @memberOf Hash
3876
+ * @param {Object} hash The hash to modify.
3877
+ * @param {string} key The key of the value to remove.
3878
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
3879
+ */
3880
+
3881
+ function hashDelete$1(key) {
3882
+ var result = this.has(key) && delete this.__data__[key];
3883
+ this.size -= result ? 1 : 0;
3884
+ return result;
3885
+ }
3886
+
3887
+ var _hashDelete = hashDelete$1;
3888
+
3889
+ var nativeCreate$2 = _nativeCreate;
3890
+
3891
+ /** Used to stand-in for `undefined` hash values. */
3892
+ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
3893
+
3894
+ /** Used for built-in method references. */
3895
+ var objectProto$2 = Object.prototype;
3896
+
3897
+ /** Used to check objects for own properties. */
3898
+ var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
3899
+
3900
+ /**
3901
+ * Gets the hash value for `key`.
3902
+ *
3903
+ * @private
3904
+ * @name get
3905
+ * @memberOf Hash
3906
+ * @param {string} key The key of the value to get.
3907
+ * @returns {*} Returns the entry value.
3908
+ */
3909
+ function hashGet$1(key) {
3910
+ var data = this.__data__;
3911
+ if (nativeCreate$2) {
3912
+ var result = data[key];
3913
+ return result === HASH_UNDEFINED$1 ? undefined : result;
3914
+ }
3915
+ return hasOwnProperty$2.call(data, key) ? data[key] : undefined;
3916
+ }
3917
+
3918
+ var _hashGet = hashGet$1;
3919
+
3920
+ var nativeCreate$1 = _nativeCreate;
3921
+
3922
+ /** Used for built-in method references. */
3923
+ var objectProto$1 = Object.prototype;
3924
+
3925
+ /** Used to check objects for own properties. */
3926
+ var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
3927
+
3928
+ /**
3929
+ * Checks if a hash value for `key` exists.
3930
+ *
3931
+ * @private
3932
+ * @name has
3933
+ * @memberOf Hash
3934
+ * @param {string} key The key of the entry to check.
3935
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3936
+ */
3937
+ function hashHas$1(key) {
3938
+ var data = this.__data__;
3939
+ return nativeCreate$1 ? (data[key] !== undefined) : hasOwnProperty$1.call(data, key);
3940
+ }
3941
+
3942
+ var _hashHas = hashHas$1;
3943
+
3944
+ var nativeCreate = _nativeCreate;
3945
+
3946
+ /** Used to stand-in for `undefined` hash values. */
3947
+ var HASH_UNDEFINED = '__lodash_hash_undefined__';
3948
+
3949
+ /**
3950
+ * Sets the hash `key` to `value`.
3951
+ *
3952
+ * @private
3953
+ * @name set
3954
+ * @memberOf Hash
3955
+ * @param {string} key The key of the value to set.
3956
+ * @param {*} value The value to set.
3957
+ * @returns {Object} Returns the hash instance.
3958
+ */
3959
+ function hashSet$1(key, value) {
3960
+ var data = this.__data__;
3961
+ this.size += this.has(key) ? 0 : 1;
3962
+ data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
3963
+ return this;
3964
+ }
3965
+
3966
+ var _hashSet = hashSet$1;
3967
+
3968
+ var hashClear = _hashClear,
3969
+ hashDelete = _hashDelete,
3970
+ hashGet = _hashGet,
3971
+ hashHas = _hashHas,
3972
+ hashSet = _hashSet;
3973
+
3974
+ /**
3975
+ * Creates a hash object.
3976
+ *
3977
+ * @private
3978
+ * @constructor
3979
+ * @param {Array} [entries] The key-value pairs to cache.
3980
+ */
3981
+ function Hash$1(entries) {
3982
+ var index = -1,
3983
+ length = entries == null ? 0 : entries.length;
3984
+
3985
+ this.clear();
3986
+ while (++index < length) {
3987
+ var entry = entries[index];
3988
+ this.set(entry[0], entry[1]);
3989
+ }
3990
+ }
3991
+
3992
+ // Add methods to `Hash`.
3993
+ Hash$1.prototype.clear = hashClear;
3994
+ Hash$1.prototype['delete'] = hashDelete;
3995
+ Hash$1.prototype.get = hashGet;
3996
+ Hash$1.prototype.has = hashHas;
3997
+ Hash$1.prototype.set = hashSet;
3998
+
3999
+ var _Hash = Hash$1;
4000
+
4001
+ /**
4002
+ * Removes all key-value entries from the list cache.
4003
+ *
4004
+ * @private
4005
+ * @name clear
4006
+ * @memberOf ListCache
4007
+ */
4008
+
4009
+ function listCacheClear$1() {
4010
+ this.__data__ = [];
4011
+ this.size = 0;
4012
+ }
4013
+
4014
+ var _listCacheClear = listCacheClear$1;
4015
+
4016
+ /**
4017
+ * Performs a
4018
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
4019
+ * comparison between two values to determine if they are equivalent.
4020
+ *
4021
+ * @static
4022
+ * @memberOf _
4023
+ * @since 4.0.0
4024
+ * @category Lang
4025
+ * @param {*} value The value to compare.
4026
+ * @param {*} other The other value to compare.
4027
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
4028
+ * @example
4029
+ *
4030
+ * var object = { 'a': 1 };
4031
+ * var other = { 'a': 1 };
4032
+ *
4033
+ * _.eq(object, object);
4034
+ * // => true
4035
+ *
4036
+ * _.eq(object, other);
4037
+ * // => false
4038
+ *
4039
+ * _.eq('a', 'a');
4040
+ * // => true
4041
+ *
4042
+ * _.eq('a', Object('a'));
4043
+ * // => false
4044
+ *
4045
+ * _.eq(NaN, NaN);
4046
+ * // => true
4047
+ */
4048
+
4049
+ function eq$1(value, other) {
4050
+ return value === other || (value !== value && other !== other);
4051
+ }
4052
+
4053
+ var eq_1 = eq$1;
4054
+
4055
+ var eq = eq_1;
4056
+
4057
+ /**
4058
+ * Gets the index at which the `key` is found in `array` of key-value pairs.
4059
+ *
4060
+ * @private
4061
+ * @param {Array} array The array to inspect.
4062
+ * @param {*} key The key to search for.
4063
+ * @returns {number} Returns the index of the matched value, else `-1`.
4064
+ */
4065
+ function assocIndexOf$4(array, key) {
4066
+ var length = array.length;
4067
+ while (length--) {
4068
+ if (eq(array[length][0], key)) {
4069
+ return length;
4070
+ }
4071
+ }
4072
+ return -1;
4073
+ }
4074
+
4075
+ var _assocIndexOf = assocIndexOf$4;
4076
+
4077
+ var assocIndexOf$3 = _assocIndexOf;
4078
+
4079
+ /** Used for built-in method references. */
4080
+ var arrayProto = Array.prototype;
4081
+
4082
+ /** Built-in value references. */
4083
+ var splice = arrayProto.splice;
4084
+
4085
+ /**
4086
+ * Removes `key` and its value from the list cache.
4087
+ *
4088
+ * @private
4089
+ * @name delete
4090
+ * @memberOf ListCache
4091
+ * @param {string} key The key of the value to remove.
4092
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4093
+ */
4094
+ function listCacheDelete$1(key) {
4095
+ var data = this.__data__,
4096
+ index = assocIndexOf$3(data, key);
4097
+
4098
+ if (index < 0) {
4099
+ return false;
4100
+ }
4101
+ var lastIndex = data.length - 1;
4102
+ if (index == lastIndex) {
4103
+ data.pop();
4104
+ } else {
4105
+ splice.call(data, index, 1);
4106
+ }
4107
+ --this.size;
4108
+ return true;
4109
+ }
4110
+
4111
+ var _listCacheDelete = listCacheDelete$1;
4112
+
4113
+ var assocIndexOf$2 = _assocIndexOf;
4114
+
4115
+ /**
4116
+ * Gets the list cache value for `key`.
4117
+ *
4118
+ * @private
4119
+ * @name get
4120
+ * @memberOf ListCache
4121
+ * @param {string} key The key of the value to get.
4122
+ * @returns {*} Returns the entry value.
4123
+ */
4124
+ function listCacheGet$1(key) {
4125
+ var data = this.__data__,
4126
+ index = assocIndexOf$2(data, key);
4127
+
4128
+ return index < 0 ? undefined : data[index][1];
4129
+ }
4130
+
4131
+ var _listCacheGet = listCacheGet$1;
4132
+
4133
+ var assocIndexOf$1 = _assocIndexOf;
4134
+
4135
+ /**
4136
+ * Checks if a list cache value for `key` exists.
4137
+ *
4138
+ * @private
4139
+ * @name has
4140
+ * @memberOf ListCache
4141
+ * @param {string} key The key of the entry to check.
4142
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4143
+ */
4144
+ function listCacheHas$1(key) {
4145
+ return assocIndexOf$1(this.__data__, key) > -1;
4146
+ }
4147
+
4148
+ var _listCacheHas = listCacheHas$1;
4149
+
4150
+ var assocIndexOf = _assocIndexOf;
4151
+
4152
+ /**
4153
+ * Sets the list cache `key` to `value`.
4154
+ *
4155
+ * @private
4156
+ * @name set
4157
+ * @memberOf ListCache
4158
+ * @param {string} key The key of the value to set.
4159
+ * @param {*} value The value to set.
4160
+ * @returns {Object} Returns the list cache instance.
4161
+ */
4162
+ function listCacheSet$1(key, value) {
4163
+ var data = this.__data__,
4164
+ index = assocIndexOf(data, key);
4165
+
4166
+ if (index < 0) {
4167
+ ++this.size;
4168
+ data.push([key, value]);
4169
+ } else {
4170
+ data[index][1] = value;
4171
+ }
4172
+ return this;
4173
+ }
4174
+
4175
+ var _listCacheSet = listCacheSet$1;
4176
+
4177
+ var listCacheClear = _listCacheClear,
4178
+ listCacheDelete = _listCacheDelete,
4179
+ listCacheGet = _listCacheGet,
4180
+ listCacheHas = _listCacheHas,
4181
+ listCacheSet = _listCacheSet;
4182
+
4183
+ /**
4184
+ * Creates an list cache object.
4185
+ *
4186
+ * @private
4187
+ * @constructor
4188
+ * @param {Array} [entries] The key-value pairs to cache.
4189
+ */
4190
+ function ListCache$1(entries) {
4191
+ var index = -1,
4192
+ length = entries == null ? 0 : entries.length;
4193
+
4194
+ this.clear();
4195
+ while (++index < length) {
4196
+ var entry = entries[index];
4197
+ this.set(entry[0], entry[1]);
4198
+ }
4199
+ }
4200
+
4201
+ // Add methods to `ListCache`.
4202
+ ListCache$1.prototype.clear = listCacheClear;
4203
+ ListCache$1.prototype['delete'] = listCacheDelete;
4204
+ ListCache$1.prototype.get = listCacheGet;
4205
+ ListCache$1.prototype.has = listCacheHas;
4206
+ ListCache$1.prototype.set = listCacheSet;
4207
+
4208
+ var _ListCache = ListCache$1;
4209
+
4210
+ var getNative$4 = _getNative,
4211
+ root$4 = _root;
4212
+
4213
+ /* Built-in method references that are verified to be native. */
4214
+ var Map$3 = getNative$4(root$4, 'Map');
4215
+
4216
+ var _Map = Map$3;
4217
+
4218
+ var Hash = _Hash,
4219
+ ListCache = _ListCache,
4220
+ Map$2 = _Map;
4221
+
4222
+ /**
4223
+ * Removes all key-value entries from the map.
4224
+ *
4225
+ * @private
4226
+ * @name clear
4227
+ * @memberOf MapCache
4228
+ */
4229
+ function mapCacheClear$1() {
4230
+ this.size = 0;
4231
+ this.__data__ = {
4232
+ 'hash': new Hash,
4233
+ 'map': new (Map$2 || ListCache),
4234
+ 'string': new Hash
4235
+ };
4236
+ }
4237
+
4238
+ var _mapCacheClear = mapCacheClear$1;
4239
+
4240
+ /**
4241
+ * Checks if `value` is suitable for use as unique object key.
4242
+ *
4243
+ * @private
4244
+ * @param {*} value The value to check.
4245
+ * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
4246
+ */
4247
+
4248
+ function isKeyable$1(value) {
4249
+ var type = typeof value;
4250
+ return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
4251
+ ? (value !== '__proto__')
4252
+ : (value === null);
4253
+ }
4254
+
4255
+ var _isKeyable = isKeyable$1;
4256
+
4257
+ var isKeyable = _isKeyable;
4258
+
4259
+ /**
4260
+ * Gets the data for `map`.
4261
+ *
4262
+ * @private
4263
+ * @param {Object} map The map to query.
4264
+ * @param {string} key The reference key.
4265
+ * @returns {*} Returns the map data.
4266
+ */
4267
+ function getMapData$4(map, key) {
4268
+ var data = map.__data__;
4269
+ return isKeyable(key)
4270
+ ? data[typeof key == 'string' ? 'string' : 'hash']
4271
+ : data.map;
4272
+ }
4273
+
4274
+ var _getMapData = getMapData$4;
4275
+
4276
+ var getMapData$3 = _getMapData;
4277
+
4278
+ /**
4279
+ * Removes `key` and its value from the map.
4280
+ *
4281
+ * @private
4282
+ * @name delete
4283
+ * @memberOf MapCache
4284
+ * @param {string} key The key of the value to remove.
4285
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4286
+ */
4287
+ function mapCacheDelete$1(key) {
4288
+ var result = getMapData$3(this, key)['delete'](key);
4289
+ this.size -= result ? 1 : 0;
4290
+ return result;
4291
+ }
4292
+
4293
+ var _mapCacheDelete = mapCacheDelete$1;
4294
+
4295
+ var getMapData$2 = _getMapData;
4296
+
4297
+ /**
4298
+ * Gets the map value for `key`.
4299
+ *
4300
+ * @private
4301
+ * @name get
4302
+ * @memberOf MapCache
4303
+ * @param {string} key The key of the value to get.
4304
+ * @returns {*} Returns the entry value.
4305
+ */
4306
+ function mapCacheGet$1(key) {
4307
+ return getMapData$2(this, key).get(key);
4308
+ }
4309
+
4310
+ var _mapCacheGet = mapCacheGet$1;
4311
+
4312
+ var getMapData$1 = _getMapData;
4313
+
4314
+ /**
4315
+ * Checks if a map value for `key` exists.
4316
+ *
4317
+ * @private
4318
+ * @name has
4319
+ * @memberOf MapCache
4320
+ * @param {string} key The key of the entry to check.
4321
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4322
+ */
4323
+ function mapCacheHas$1(key) {
4324
+ return getMapData$1(this, key).has(key);
4325
+ }
4326
+
4327
+ var _mapCacheHas = mapCacheHas$1;
4328
+
4329
+ var getMapData = _getMapData;
4330
+
4331
+ /**
4332
+ * Sets the map `key` to `value`.
4333
+ *
4334
+ * @private
4335
+ * @name set
4336
+ * @memberOf MapCache
4337
+ * @param {string} key The key of the value to set.
4338
+ * @param {*} value The value to set.
4339
+ * @returns {Object} Returns the map cache instance.
4340
+ */
4341
+ function mapCacheSet$1(key, value) {
4342
+ var data = getMapData(this, key),
4343
+ size = data.size;
4344
+
4345
+ data.set(key, value);
4346
+ this.size += data.size == size ? 0 : 1;
4347
+ return this;
4348
+ }
4349
+
4350
+ var _mapCacheSet = mapCacheSet$1;
4351
+
4352
+ var mapCacheClear = _mapCacheClear,
4353
+ mapCacheDelete = _mapCacheDelete,
4354
+ mapCacheGet = _mapCacheGet,
4355
+ mapCacheHas = _mapCacheHas,
4356
+ mapCacheSet = _mapCacheSet;
4357
+
4358
+ /**
4359
+ * Creates a map cache object to store key-value pairs.
4360
+ *
4361
+ * @private
4362
+ * @constructor
4363
+ * @param {Array} [entries] The key-value pairs to cache.
4364
+ */
4365
+ function MapCache$1(entries) {
4366
+ var index = -1,
4367
+ length = entries == null ? 0 : entries.length;
4368
+
4369
+ this.clear();
4370
+ while (++index < length) {
4371
+ var entry = entries[index];
4372
+ this.set(entry[0], entry[1]);
4373
+ }
4374
+ }
4375
+
4376
+ // Add methods to `MapCache`.
4377
+ MapCache$1.prototype.clear = mapCacheClear;
4378
+ MapCache$1.prototype['delete'] = mapCacheDelete;
4379
+ MapCache$1.prototype.get = mapCacheGet;
4380
+ MapCache$1.prototype.has = mapCacheHas;
4381
+ MapCache$1.prototype.set = mapCacheSet;
4382
+
4383
+ var _MapCache = MapCache$1;
4384
+
4385
+ var MapCache = _MapCache;
4386
+
4387
+ /** Error message constants. */
4388
+ var FUNC_ERROR_TEXT = 'Expected a function';
4389
+
4390
+ /**
4391
+ * Creates a function that memoizes the result of `func`. If `resolver` is
4392
+ * provided, it determines the cache key for storing the result based on the
4393
+ * arguments provided to the memoized function. By default, the first argument
4394
+ * provided to the memoized function is used as the map cache key. The `func`
4395
+ * is invoked with the `this` binding of the memoized function.
4396
+ *
4397
+ * **Note:** The cache is exposed as the `cache` property on the memoized
4398
+ * function. Its creation may be customized by replacing the `_.memoize.Cache`
4399
+ * constructor with one whose instances implement the
4400
+ * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
4401
+ * method interface of `clear`, `delete`, `get`, `has`, and `set`.
4402
+ *
4403
+ * @static
4404
+ * @memberOf _
4405
+ * @since 0.1.0
4406
+ * @category Function
4407
+ * @param {Function} func The function to have its output memoized.
4408
+ * @param {Function} [resolver] The function to resolve the cache key.
4409
+ * @returns {Function} Returns the new memoized function.
4410
+ * @example
4411
+ *
4412
+ * var object = { 'a': 1, 'b': 2 };
4413
+ * var other = { 'c': 3, 'd': 4 };
4414
+ *
4415
+ * var values = _.memoize(_.values);
4416
+ * values(object);
4417
+ * // => [1, 2]
4418
+ *
4419
+ * values(other);
4420
+ * // => [3, 4]
4421
+ *
4422
+ * object.a = 2;
4423
+ * values(object);
4424
+ * // => [1, 2]
4425
+ *
4426
+ * // Modify the result cache.
4427
+ * values.cache.set(object, ['a', 'b']);
4428
+ * values(object);
4429
+ * // => ['a', 'b']
4430
+ *
4431
+ * // Replace `_.memoize.Cache`.
4432
+ * _.memoize.Cache = WeakMap;
4433
+ */
4434
+ function memoize$1(func, resolver) {
4435
+ if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
4436
+ throw new TypeError(FUNC_ERROR_TEXT);
4437
+ }
4438
+ var memoized = function() {
4439
+ var args = arguments,
4440
+ key = resolver ? resolver.apply(this, args) : args[0],
4441
+ cache = memoized.cache;
4442
+
4443
+ if (cache.has(key)) {
4444
+ return cache.get(key);
4445
+ }
4446
+ var result = func.apply(this, args);
4447
+ memoized.cache = cache.set(key, result) || cache;
4448
+ return result;
4449
+ };
4450
+ memoized.cache = new (memoize$1.Cache || MapCache);
4451
+ return memoized;
4452
+ }
4453
+
4454
+ // Expose `MapCache`.
4455
+ memoize$1.Cache = MapCache;
4456
+
4457
+ var memoize_1 = memoize$1;
4458
+
4459
+ var memoize = memoize_1;
4460
+
4461
+ /** Used as the maximum memoize cache size. */
4462
+ var MAX_MEMOIZE_SIZE = 500;
4463
+
4464
+ /**
4465
+ * A specialized version of `_.memoize` which clears the memoized function's
4466
+ * cache when it exceeds `MAX_MEMOIZE_SIZE`.
4467
+ *
4468
+ * @private
4469
+ * @param {Function} func The function to have its output memoized.
4470
+ * @returns {Function} Returns the new memoized function.
4471
+ */
4472
+ function memoizeCapped$1(func) {
4473
+ var result = memoize(func, function(key) {
4474
+ if (cache.size === MAX_MEMOIZE_SIZE) {
4475
+ cache.clear();
4476
+ }
4477
+ return key;
4478
+ });
4479
+
4480
+ var cache = result.cache;
4481
+ return result;
4482
+ }
4483
+
4484
+ var _memoizeCapped = memoizeCapped$1;
4485
+
4486
+ var memoizeCapped = _memoizeCapped;
4487
+
4488
+ /** Used to match property names within property paths. */
4489
+ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
4490
+
4491
+ /** Used to match backslashes in property paths. */
4492
+ var reEscapeChar = /\\(\\)?/g;
4493
+
4494
+ /**
4495
+ * Converts `string` to a property path array.
4496
+ *
4497
+ * @private
4498
+ * @param {string} string The string to convert.
4499
+ * @returns {Array} Returns the property path array.
4500
+ */
4501
+ memoizeCapped(function(string) {
4502
+ var result = [];
4503
+ if (string.charCodeAt(0) === 46 /* . */) {
4504
+ result.push('');
4505
+ }
4506
+ string.replace(rePropName, function(match, number, quote, subString) {
4507
+ result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
4508
+ });
4509
+ return result;
4510
+ });
4511
+
4512
+ var Symbol$1 = _Symbol;
4513
+
4514
+ /** Used to convert symbols to primitives and strings. */
4515
+ var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined;
4516
+ symbolProto ? symbolProto.toString : undefined;
4517
+
4518
+ var baseGetTag$1 = _baseGetTag,
4519
+ isObjectLike$1 = isObjectLike_1;
4520
+
4521
+ /** `Object#toString` result references. */
4522
+ var argsTag = '[object Arguments]';
4523
+
4524
+ /**
4525
+ * The base implementation of `_.isArguments`.
4526
+ *
4527
+ * @private
4528
+ * @param {*} value The value to check.
4529
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
4530
+ */
4531
+ function baseIsArguments$1(value) {
4532
+ return isObjectLike$1(value) && baseGetTag$1(value) == argsTag;
4533
+ }
4534
+
4535
+ var _baseIsArguments = baseIsArguments$1;
4536
+
4537
+ var baseIsArguments = _baseIsArguments,
4538
+ isObjectLike = isObjectLike_1;
4539
+
4540
+ /** Used for built-in method references. */
4541
+ var objectProto = Object.prototype;
4542
+
4543
+ /** Used to check objects for own properties. */
4544
+ var hasOwnProperty = objectProto.hasOwnProperty;
4545
+
4546
+ /** Built-in value references. */
4547
+ var propertyIsEnumerable = objectProto.propertyIsEnumerable;
4548
+
4549
+ /**
4550
+ * Checks if `value` is likely an `arguments` object.
4551
+ *
4552
+ * @static
4553
+ * @memberOf _
4554
+ * @since 0.1.0
4555
+ * @category Lang
4556
+ * @param {*} value The value to check.
4557
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
4558
+ * else `false`.
4559
+ * @example
4560
+ *
4561
+ * _.isArguments(function() { return arguments; }());
4562
+ * // => true
4563
+ *
4564
+ * _.isArguments([1, 2, 3]);
4565
+ * // => false
4566
+ */
4567
+ baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
4568
+ return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
4569
+ !propertyIsEnumerable.call(value, 'callee');
4570
+ };
4571
+
4572
+ var isBuffer = {exports: {}};
4573
+
4574
+ /**
4575
+ * This method returns `false`.
4576
+ *
4577
+ * @static
4578
+ * @memberOf _
4579
+ * @since 4.13.0
4580
+ * @category Util
4581
+ * @returns {boolean} Returns `false`.
4582
+ * @example
4583
+ *
4584
+ * _.times(2, _.stubFalse);
4585
+ * // => [false, false]
4586
+ */
4587
+
4588
+ function stubFalse() {
4589
+ return false;
4590
+ }
4591
+
4592
+ var stubFalse_1 = stubFalse;
4593
+
4594
+ (function (module, exports) {
4595
+ var root = _root,
4596
+ stubFalse = stubFalse_1;
4597
+
4598
+ /** Detect free variable `exports`. */
4599
+ var freeExports = exports && !exports.nodeType && exports;
4600
+
4601
+ /** Detect free variable `module`. */
4602
+ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
4603
+
4604
+ /** Detect the popular CommonJS extension `module.exports`. */
4605
+ var moduleExports = freeModule && freeModule.exports === freeExports;
4606
+
4607
+ /** Built-in value references. */
4608
+ var Buffer = moduleExports ? root.Buffer : undefined;
4609
+
4610
+ /* Built-in method references for those with the same name as other `lodash` methods. */
4611
+ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
4612
+
4613
+ /**
4614
+ * Checks if `value` is a buffer.
4615
+ *
4616
+ * @static
4617
+ * @memberOf _
4618
+ * @since 4.3.0
4619
+ * @category Lang
4620
+ * @param {*} value The value to check.
4621
+ * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
4622
+ * @example
4623
+ *
4624
+ * _.isBuffer(new Buffer(2));
4625
+ * // => true
4626
+ *
4627
+ * _.isBuffer(new Uint8Array(2));
4628
+ * // => false
4629
+ */
4630
+ var isBuffer = nativeIsBuffer || stubFalse;
4631
+
4632
+ module.exports = isBuffer;
4633
+ }(isBuffer, isBuffer.exports));
4634
+
4635
+ var _nodeUtil = {exports: {}};
4636
+
4637
+ (function (module, exports) {
4638
+ var freeGlobal = _freeGlobal;
4639
+
4640
+ /** Detect free variable `exports`. */
4641
+ var freeExports = exports && !exports.nodeType && exports;
4642
+
4643
+ /** Detect free variable `module`. */
4644
+ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
4645
+
4646
+ /** Detect the popular CommonJS extension `module.exports`. */
4647
+ var moduleExports = freeModule && freeModule.exports === freeExports;
4648
+
4649
+ /** Detect free variable `process` from Node.js. */
4650
+ var freeProcess = moduleExports && freeGlobal.process;
4651
+
4652
+ /** Used to access faster Node.js helpers. */
4653
+ var nodeUtil = (function() {
4654
+ try {
4655
+ // Use `util.types` for Node.js 10+.
4656
+ var types = freeModule && freeModule.require && freeModule.require('util').types;
4657
+
4658
+ if (types) {
4659
+ return types;
4660
+ }
4661
+
4662
+ // Legacy `process.binding('util')` for Node.js < 10.
4663
+ return freeProcess && freeProcess.binding && freeProcess.binding('util');
4664
+ } catch (e) {}
4665
+ }());
4666
+
4667
+ module.exports = nodeUtil;
4668
+ }(_nodeUtil, _nodeUtil.exports));
4669
+
4670
+ var nodeUtil = _nodeUtil.exports;
4671
+
4672
+ /* Node.js helper references. */
4673
+ nodeUtil && nodeUtil.isTypedArray;
4674
+
4675
+ var getNative$3 = _getNative,
4676
+ root$3 = _root;
4677
+
4678
+ /* Built-in method references that are verified to be native. */
4679
+ var DataView$1 = getNative$3(root$3, 'DataView');
4680
+
4681
+ var _DataView = DataView$1;
4682
+
4683
+ var getNative$2 = _getNative,
4684
+ root$2 = _root;
4685
+
4686
+ /* Built-in method references that are verified to be native. */
4687
+ var Promise$2 = getNative$2(root$2, 'Promise');
4688
+
4689
+ var _Promise = Promise$2;
4690
+
4691
+ var getNative$1 = _getNative,
4692
+ root$1 = _root;
4693
+
4694
+ /* Built-in method references that are verified to be native. */
4695
+ var Set$1 = getNative$1(root$1, 'Set');
4696
+
4697
+ var _Set = Set$1;
4698
+
4699
+ var getNative = _getNative,
4700
+ root = _root;
4701
+
4702
+ /* Built-in method references that are verified to be native. */
4703
+ var WeakMap$1 = getNative(root, 'WeakMap');
4704
+
4705
+ var _WeakMap = WeakMap$1;
4706
+
4707
+ var DataView = _DataView,
4708
+ Map$1 = _Map,
4709
+ Promise$1 = _Promise,
4710
+ Set = _Set,
4711
+ WeakMap = _WeakMap,
4712
+ baseGetTag = _baseGetTag,
4713
+ toSource = _toSource;
4714
+
4715
+ /** `Object#toString` result references. */
4716
+ var mapTag = '[object Map]',
4717
+ objectTag = '[object Object]',
4718
+ promiseTag = '[object Promise]',
4719
+ setTag = '[object Set]',
4720
+ weakMapTag = '[object WeakMap]';
4721
+
4722
+ var dataViewTag = '[object DataView]';
4723
+
4724
+ /** Used to detect maps, sets, and weakmaps. */
4725
+ var dataViewCtorString = toSource(DataView),
4726
+ mapCtorString = toSource(Map$1),
4727
+ promiseCtorString = toSource(Promise$1),
4728
+ setCtorString = toSource(Set),
4729
+ weakMapCtorString = toSource(WeakMap);
4730
+
4731
+ /**
4732
+ * Gets the `toStringTag` of `value`.
4733
+ *
4734
+ * @private
4735
+ * @param {*} value The value to query.
4736
+ * @returns {string} Returns the `toStringTag`.
4737
+ */
4738
+ var getTag = baseGetTag;
4739
+
4740
+ // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
4741
+ if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
4742
+ (Map$1 && getTag(new Map$1) != mapTag) ||
4743
+ (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) ||
4744
+ (Set && getTag(new Set) != setTag) ||
4745
+ (WeakMap && getTag(new WeakMap) != weakMapTag)) {
4746
+ getTag = function(value) {
4747
+ var result = baseGetTag(value),
4748
+ Ctor = result == objectTag ? value.constructor : undefined,
4749
+ ctorString = Ctor ? toSource(Ctor) : '';
4750
+
4751
+ if (ctorString) {
4752
+ switch (ctorString) {
4753
+ case dataViewCtorString: return dataViewTag;
4754
+ case mapCtorString: return mapTag;
4755
+ case promiseCtorString: return promiseTag;
4756
+ case setCtorString: return setTag;
4757
+ case weakMapCtorString: return weakMapTag;
4758
+ }
4759
+ }
4760
+ return result;
4761
+ };
4762
+ }
4763
+
4764
+ // eslint-disable-next-line no-console
4765
+ const lg = (n) => console[n].bind(console, 'controller-utils:');
4766
+ lg('debug');
4767
+ lg('log');
4768
+ lg('warn');
4769
+ lg('error');
4770
+
4771
+ const { translator } = Translator;
4772
+
4773
+ const getFeedback = (value) => (value ? 'correct' : 'incorrect');
4774
+ const getContent = (html) => (html || '').replace(/(<(?!img|iframe|source)([^>]+)>)/gi, '');
4775
+
4776
+ const getIsAnswerCorrect = (correctResponse, answerItem) => {
4777
+ let answerCorrect = false;
4778
+
4779
+ const opts = {
4780
+ mode: correctResponse.validation || defaults.validationDefault,
4781
+ ...(correctResponse.validation === 'literal' && {
4782
+ literal: {
4783
+ allowTrailingZeros: correctResponse.allowTrailingZeros || false,
4784
+ ignoreOrder: correctResponse.ignoreOrder || false,
4785
+ },
4786
+ }),
4787
+ };
4788
+
4789
+ if (!answerCorrect) {
4790
+ const acceptedValues = [correctResponse.answer, ...Object.values(correctResponse.alternates || {})];
4791
+
4792
+ try {
4793
+ for (const value of acceptedValues) {
4794
+ answerCorrect = mv.latexEqual(answerItem.value, value, opts);
4795
+ if (answerCorrect) break;
4796
+ }
4797
+ } catch (e) {
4798
+ answerCorrect = false;
4799
+ }
4800
+ }
4801
+
4802
+ return answerCorrect;
4803
+ };
4804
+
4805
+ const getResponseCorrectness = (question, sessionResponse) => {
4806
+ const correctResponses = question.responses;
4807
+
4808
+ if (!sessionResponse) {
4809
+ return {
4810
+ correctness: 'unanswered',
4811
+ score: 0,
4812
+ correct: false,
4813
+ };
4814
+ } else {
4815
+ let correctAnswers = 0;
4816
+ let score = 0;
4817
+ const correctResponsesCount = Object.keys(correctResponses || {}).length;
4818
+
4819
+ Object.keys(correctResponses).forEach((responseId) => {
4820
+ const answerItem = sessionResponse['r' + responseId];
4821
+ const correctResponse = correctResponses[responseId] || {};
4822
+
4823
+ const answerCorrect = getIsAnswerCorrect(correctResponse, answerItem);
4824
+ if (answerCorrect) {
4825
+ correctAnswers++;
4826
+ }
4827
+ });
4828
+
4829
+ const fullyCorrect = correctAnswers === correctResponsesCount;
4830
+
4831
+ // partial credit scoring: each correct answer is worth 1 / total answers point
4832
+ // dichotomous scoring: for credit to be awarded, a correct answer must be entered for every response area
4833
+ score = Number((correctAnswers / Object.keys(correctResponses).length).toFixed(2));
4834
+
4835
+ return {
4836
+ correctness: getFeedback(fullyCorrect),
4837
+ score: correctAnswers > 0 ? score : 0,
4838
+ correct: fullyCorrect,
4839
+ };
4840
+ }
4841
+ };
4842
+
4843
+ const getCorrectness = (question, env, session) => {
4844
+ if (env.mode === 'evaluate') {
4845
+ return getResponseCorrectness(question, session && session.answers);
4846
+ }
4847
+ };
4848
+
4849
+ const getPartialScore = (question, session) => {
4850
+ if (!session || isEmpty_1(session)) {
4851
+ return 0;
4852
+ }
4853
+
4854
+ return 1;
4855
+ };
4856
+
4857
+ const outcome = (question, session, env) =>
4858
+ new Promise((resolve) => {
4859
+ if (!session || isEmpty_1(session)) {
4860
+ resolve({ score: 0, empty: true });
4861
+ }
4862
+ const partialScoringEnabled = enabled(question, env);
4863
+ session = normalizeSession(session);
4864
+
4865
+ if (env.mode !== 'evaluate') {
4866
+ resolve({ score: undefined, completed: undefined });
4867
+ } else {
4868
+ const correctness = getCorrectness(question, env, session);
4869
+ const score = correctness.score;
4870
+
4871
+ resolve({ score: partialScoringEnabled ? score : score === 1 ? 1 : 0 });
4872
+ }
4873
+ });
4874
+
4875
+ const createDefaultModel = (model = {}) => {
4876
+ const { validationDefault, allowTrailingZerosDefault, ignoreOrderDefault, responses = {} } = model;
4877
+
4878
+ const updatedResponses = Object.keys(responses).reduce((acc, responseId) => {
4879
+ const correctResponse = responses[responseId];
4880
+
4881
+ acc[responseId] = {
4882
+ ...correctResponse,
4883
+ validation: correctResponse.validation || validationDefault,
4884
+ allowTrailingZeros: correctResponse.allowTrailingZeros || allowTrailingZerosDefault,
4885
+ ignoreOrder: correctResponse.ignoreOrder || ignoreOrderDefault,
4886
+ };
4887
+
4888
+ return acc;
4889
+ }, {});
4890
+
4891
+ return {
4892
+ ...defaults.model,
4893
+ ...model,
4894
+ responses: updatedResponses,
4895
+ };
4896
+ };
4897
+
4898
+ const normalizeSession = (s) => ({ ...s });
4899
+
4900
+ const getTextFromHTML = (html) => (html || '').replace(/<\/?[^>]+(>|$)/g, '');
4901
+
4902
+ const prepareVal = (html) => getTextFromHTML(html).trim();
4903
+
4904
+ const model = (question, session, env) => {
4905
+ return new Promise((resolve) => {
4906
+ session = session || {};
4907
+ const normalizedQuestion = createDefaultModel(question);
4908
+ const correctness = getCorrectness(normalizedQuestion, env, session);
4909
+ const { responses, language } = normalizedQuestion;
4910
+ let { note } = normalizedQuestion;
4911
+ let showNote = false;
4912
+
4913
+ // check if there is at least one alternate response or if the validation for at least one response is not literal
4914
+ Object.keys(responses).forEach((responseId) => {
4915
+ const correctResponse = responses[responseId] || {};
4916
+ if (correctResponse.alternates && Object.keys(correctResponse.alternates).length > 0) {
4917
+ showNote = true;
4918
+ } else if (correctResponse.validation !== 'literal') {
4919
+ showNote = true;
4920
+ }
4921
+ });
4922
+
4923
+ if (!note) {
4924
+ note = translator.t('mathInline.primaryCorrectWithAlternates', { lng: language });
4925
+ }
4926
+
4927
+ const out = {
4928
+ prompt: normalizedQuestion.promptEnabled ? normalizedQuestion.prompt : null,
4929
+ markup: normalizedQuestion.markup,
4930
+ responses: env.mode === 'gather' ? null : normalizedQuestion.responses,
4931
+ language: normalizedQuestion.language,
4932
+ equationEditor: normalizedQuestion.equationEditor,
4933
+ customKeys: normalizedQuestion.customKeys,
4934
+ disabled: env.mode !== 'gather',
4935
+ view: env.mode === 'view',
4936
+ correctness,
4937
+ env,
4938
+ extraCSSRules: normalizedQuestion.extraCSSRules,
4939
+ };
4940
+
4941
+ const { answers = {} } = session || {};
4942
+ let feedback = {};
4943
+
4944
+ if (env.mode === 'evaluate') {
4945
+ Object.keys(responses).forEach((responseId) => {
4946
+ const answerItem = answers['r' + responseId];
4947
+ const correctResponse = responses[responseId];
4948
+ feedback[responseId] = getIsAnswerCorrect(correctResponse, answerItem);
4949
+ });
4950
+ }
4951
+
4952
+ if (env.mode === 'evaluate') {
4953
+ out.correctResponse = {};
4954
+ out.showNote = showNote;
4955
+ out.note = note;
4956
+ out.feedback = feedback;
4957
+ } else {
4958
+ out.responses = {};
4959
+ out.showNote = false;
4960
+ }
4961
+
4962
+ if (env.role === 'instructor' && (env.mode === 'view' || env.mode === 'evaluate')) {
4963
+ out.rationale = normalizedQuestion.rationaleEnabled ? normalizedQuestion.rationale : null;
4964
+ out.teacherInstructions = normalizedQuestion.teacherInstructionsEnabled
4965
+ ? normalizedQuestion.teacherInstructions
4966
+ : null;
4967
+ } else {
4968
+ out.rationale = null;
4969
+ out.teacherInstructions = null;
4970
+ }
4971
+ resolve(out);
4972
+ });
4973
+ };
4974
+
4975
+ const createCorrectResponseSession = (question, env) =>
4976
+ new Promise((resolve) => {
4977
+ if (env.mode !== 'evaluate' && env.role === 'instructor') {
4978
+ const correctResponse = Object.keys(question.responses).reduce((acc, responseId) => {
4979
+ acc['r' + responseId] = { value: question.responses[responseId].answer };
4980
+ return acc;
4981
+ }, {});
4982
+
4983
+ resolve({ id: '1', answers: correctResponse });
4984
+ } else {
4985
+ resolve(null);
4986
+ }
4987
+ });
4988
+
4989
+ const validate = (model = {}, config = {}) => {
4990
+ const { responses, markup } = model;
4991
+ const { maxResponseAreas } = config;
4992
+ const responsesErrors = {};
4993
+ const errors = {};
4994
+
4995
+ ['teacherInstructions', 'prompt', 'rationale'].forEach((field) => {
4996
+ if (config[field]?.required && !getContent(model[field])) {
4997
+ errors[field] = 'This field is required.';
4998
+ }
4999
+ });
5000
+
5001
+ Object.entries(responses || {}).forEach(([key, response], index) => {
5002
+ const { answer } = response;
5003
+ const reversedAlternates = [...Object.entries(response.alternates || {})].reverse();
5004
+ const alternatesErrors = {};
5005
+ const responseError = {};
5006
+
5007
+ if (answer === '') {
5008
+ responseError.answer = 'Content should not be empty.';
5009
+ }
5010
+
5011
+ reversedAlternates.forEach(([key, value], index) => {
5012
+ if (value === '') {
5013
+ alternatesErrors[key] = 'Content should not be empty.';
5014
+ } else {
5015
+ const identicalAnswer =
5016
+ answer === value || reversedAlternates.slice(index + 1).some(([, val]) => val === value);
5017
+
5018
+ if (identicalAnswer) {
5019
+ alternatesErrors[key] = 'Content should be unique.';
5020
+ }
5021
+ }
5022
+ });
5023
+
5024
+ if (!isEmpty_1(responseError) || !isEmpty_1(alternatesErrors)) {
5025
+ responsesErrors[index] = { ...responseError, ...alternatesErrors };
5026
+ }
5027
+ });
5028
+
5029
+ const nbOfResponseAreas = (markup.match(/\{\{(\d+)\}\}/g) || []).length;
5030
+
5031
+ if (nbOfResponseAreas > maxResponseAreas) {
5032
+ errors.responseAreas = `No more than ${maxResponseAreas} response areas should be defined.`;
5033
+ } else if (nbOfResponseAreas < 1) {
5034
+ errors.responseAreas = 'There should be at least 1 response area defined.';
5035
+ }
5036
+
5037
+ if (!isEmpty_1(responsesErrors)) {
5038
+ errors.responses = responsesErrors;
5039
+ }
5040
+
5041
+ return errors;
5042
+ };
5043
+
5044
+ export { createCorrectResponseSession, createDefaultModel, getCorrectness, getPartialScore, model, normalizeSession, outcome, prepareVal, validate };