@fctc/sme-widget-ui 4.1.10-beta.0 → 4.1.10-beta.11

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.
package/dist/utils.mjs CHANGED
@@ -1 +1,3576 @@
1
- export{x as ACCEPT_TYPES,w as ALLOWED_EXTS,v as ALLOWED_MIME_TYPES,z as COLORS,A as DOTS,B as SearchType,p as checkIsImageLink,n as convertFloatToTime,r as convertTimeToFloat,q as formatFileSize,s as formatFloatNumber,j as formatNumberOnly,t as generateTagColors,u as getFileLabel,h as getPasswordMessage,o as isBase64Image,m as isObjectEmpty,k as parseFormattedNumber,i as range,y as uppercaseFirstLetter,f as useFormatDate,l as validateAndParseDate,g as validateInput}from'./chunk-QH3T7FI4.mjs';import'./chunk-YEKQJ4YC.mjs';
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // node_modules/void-elements/index.js
28
+ var require_void_elements = __commonJS({
29
+ "node_modules/void-elements/index.js"(exports, module) {
30
+ "use strict";
31
+ module.exports = {
32
+ "area": true,
33
+ "base": true,
34
+ "br": true,
35
+ "col": true,
36
+ "embed": true,
37
+ "hr": true,
38
+ "img": true,
39
+ "input": true,
40
+ "link": true,
41
+ "meta": true,
42
+ "param": true,
43
+ "source": true,
44
+ "track": true,
45
+ "wbr": true
46
+ };
47
+ }
48
+ });
49
+
50
+ // src/utils/file.ts
51
+ var isBase64Image = (str) => {
52
+ const base64Regex = /^data:image\/(png|jpeg|jpg|gif|webp);base64,/;
53
+ if (!base64Regex.test(str)) {
54
+ return false;
55
+ }
56
+ try {
57
+ const base64Data = str.split(",")[1];
58
+ return !!base64Data && atob(base64Data).length > 0;
59
+ } catch (error) {
60
+ return false;
61
+ }
62
+ };
63
+ var checkIsImageLink = (url) => {
64
+ const imageExtensions = /\.(jpg|jpeg|png|gif|bmp|webp|svg|tiff|ico)$/i;
65
+ return imageExtensions.test(url) || isBase64Image(url);
66
+ };
67
+ var formatFileSize = (size) => {
68
+ if (size < 1024) return `${size} B`;
69
+ const i = Math.floor(Math.log(size) / Math.log(1024));
70
+ const sizes = ["B", "KB", "MB", "GB", "TB"];
71
+ return `${(size / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
72
+ };
73
+ var getFileLabel = (name) => {
74
+ const ext = (name?.split(".").pop() || "").toLowerCase();
75
+ if (ext === "pdf") return "PDF";
76
+ if (ext === "json") return "JSON";
77
+ if (ext === "zip") return "ZIP";
78
+ if (ext === "mp4") return "MP4";
79
+ if (ext === "xls" || ext === "xlsx") return "XLS";
80
+ if (ext === "png" || ext === "jpg" || ext === "jpeg") return "IMG";
81
+ return "FILE";
82
+ };
83
+ var ALLOWED_MIME_TYPES = /* @__PURE__ */ new Set([
84
+ "image/jpeg",
85
+ "image/png",
86
+ "application/pdf",
87
+ "video/mp4",
88
+ "application/zip",
89
+ "application/x-zip-compressed",
90
+ "application/vnd.ms-excel",
91
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
92
+ "application/json"
93
+ ]);
94
+ var ALLOWED_EXTS = [
95
+ ".pdf",
96
+ ".json",
97
+ ".mp4",
98
+ ".zip",
99
+ ".xls",
100
+ ".xlsx",
101
+ ".jpeg",
102
+ ".jpg",
103
+ ".png"
104
+ ];
105
+ var ACCEPT_TYPES = [
106
+ ...ALLOWED_EXTS,
107
+ ...Array.from(ALLOWED_MIME_TYPES)
108
+ ].join(",");
109
+
110
+ // src/utils/number.ts
111
+ var formatNumberOnly = (num) => {
112
+ if (isNaN(num)) return "";
113
+ return num?.toString()?.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
114
+ };
115
+ var parseFormattedNumber = (val) => {
116
+ if (!val) return "0";
117
+ const raw = val.replace(/[^\d]/g, "");
118
+ return raw ? parseFloat(raw) : "";
119
+ };
120
+ var convertFloatToTime = (floatValue) => {
121
+ const hours = Math.floor(floatValue);
122
+ const minutes = Math.round((floatValue - hours) * 60);
123
+ const formattedHours = String(hours).padStart(2, "0");
124
+ const formattedMinutes = String(minutes).padStart(2, "0");
125
+ return `${formattedHours}:${formattedMinutes}`;
126
+ };
127
+ var convertTimeToFloat = (timeString) => {
128
+ const [hours, minutes] = timeString.split(":").map(Number);
129
+ return hours + minutes / 60;
130
+ };
131
+ var formatFloatNumber = (value) => {
132
+ if (value === void 0 || value === null || value === "") return "";
133
+ const numValue = typeof value === "string" ? parseFloat(value.replace(/,/g, "")) : value;
134
+ if (isNaN(numValue)) return "";
135
+ return numValue.toLocaleString("en-US", {
136
+ minimumFractionDigits: numValue % 1 === 0 ? 0 : 1,
137
+ maximumFractionDigits: 20
138
+ });
139
+ };
140
+
141
+ // src/utils/string.ts
142
+ function validateInput(value, type) {
143
+ if (type === "text") {
144
+ return /^[\p{L}\s]+$/u.test(value);
145
+ }
146
+ if (type === "number") {
147
+ return /^[0-9]+$/.test(value);
148
+ }
149
+ if (type === "email") {
150
+ return /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value);
151
+ }
152
+ if (type === "phone") {
153
+ return /^(0|\+?84)[0-9]{9}$/.test(value);
154
+ }
155
+ return false;
156
+ }
157
+ function getPasswordMessage(min, max, upcase, digit, special) {
158
+ let message = `M?t kh?u ph?i c\uFFFD t? ${min} d?n ${max} k\uFFFD t?`;
159
+ if (upcase || upcase === "0") {
160
+ message += `, ${upcase} ch? in hoa`;
161
+ }
162
+ if (digit || digit === "0") {
163
+ message += `, ${digit} s?`;
164
+ }
165
+ if (special || special === "0") {
166
+ message += `, ${special} k\uFFFD t? d?c bi?t`;
167
+ }
168
+ return message;
169
+ }
170
+ var uppercaseFirstLetter = (str) => {
171
+ const strLowerCase = str?.toLowerCase();
172
+ return strLowerCase.charAt(0).toUpperCase() + strLowerCase.slice(1);
173
+ };
174
+
175
+ // src/utils/array.ts
176
+ var range = (start, end) => {
177
+ let length = end - start + 1;
178
+ return Array.from({ length }, (_, idx) => idx + start);
179
+ };
180
+
181
+ // src/utils/date.ts
182
+ import moment from "moment";
183
+
184
+ // src/provider/index.tsx
185
+ import { useEffect as useEffect2, createContext as createContext2, useContext as useContext4 } from "react";
186
+
187
+ // node_modules/react-i18next/dist/es/Trans.js
188
+ import { useContext } from "react";
189
+
190
+ // node_modules/react-i18next/dist/es/TransWithoutContext.js
191
+ import { Fragment, isValidElement, cloneElement, createElement, Children } from "react";
192
+
193
+ // node_modules/html-parse-stringify/dist/html-parse-stringify.module.js
194
+ var import_void_elements = __toESM(require_void_elements());
195
+
196
+ // node_modules/react-i18next/dist/es/unescape.js
197
+ var matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
198
+ var htmlEntities = {
199
+ "&amp;": "&",
200
+ "&#38;": "&",
201
+ "&lt;": "<",
202
+ "&#60;": "<",
203
+ "&gt;": ">",
204
+ "&#62;": ">",
205
+ "&apos;": "'",
206
+ "&#39;": "'",
207
+ "&quot;": '"',
208
+ "&#34;": '"',
209
+ "&nbsp;": " ",
210
+ "&#160;": " ",
211
+ "&copy;": "\xA9",
212
+ "&#169;": "\xA9",
213
+ "&reg;": "\xAE",
214
+ "&#174;": "\xAE",
215
+ "&hellip;": "\u2026",
216
+ "&#8230;": "\u2026",
217
+ "&#x2F;": "/",
218
+ "&#47;": "/"
219
+ };
220
+ var unescapeHtmlEntity = (m) => htmlEntities[m];
221
+ var unescape = (text) => text.replace(matchHtmlEntity, unescapeHtmlEntity);
222
+
223
+ // node_modules/react-i18next/dist/es/defaults.js
224
+ var defaultOptions = {
225
+ bindI18n: "languageChanged",
226
+ bindI18nStore: "",
227
+ transEmptyNodeValue: "",
228
+ transSupportBasicHtmlNodes: true,
229
+ transWrapTextNodes: "",
230
+ transKeepBasicHtmlNodesFor: ["br", "strong", "i", "p"],
231
+ useSuspense: true,
232
+ unescape
233
+ };
234
+ var setDefaults = (options = {}) => {
235
+ defaultOptions = {
236
+ ...defaultOptions,
237
+ ...options
238
+ };
239
+ };
240
+
241
+ // node_modules/react-i18next/dist/es/i18nInstance.js
242
+ var i18nInstance;
243
+ var setI18n = (instance2) => {
244
+ i18nInstance = instance2;
245
+ };
246
+
247
+ // node_modules/react-i18next/dist/es/context.js
248
+ import { createContext } from "react";
249
+
250
+ // node_modules/react-i18next/dist/es/initReactI18next.js
251
+ var initReactI18next = {
252
+ type: "3rdParty",
253
+ init(instance2) {
254
+ setDefaults(instance2.options.react);
255
+ setI18n(instance2);
256
+ }
257
+ };
258
+
259
+ // node_modules/react-i18next/dist/es/context.js
260
+ var I18nContext = createContext();
261
+
262
+ // node_modules/react-i18next/dist/es/useTranslation.js
263
+ import { useState, useEffect, useContext as useContext2, useRef, useCallback } from "react";
264
+
265
+ // node_modules/react-i18next/dist/es/withTranslation.js
266
+ import { createElement as createElement2, forwardRef as forwardRefReact } from "react";
267
+
268
+ // node_modules/react-i18next/dist/es/I18nextProvider.js
269
+ import { createElement as createElement3, useMemo } from "react";
270
+
271
+ // node_modules/react-i18next/dist/es/withSSR.js
272
+ import { createElement as createElement4 } from "react";
273
+
274
+ // node_modules/react-i18next/dist/es/useSSR.js
275
+ import { useContext as useContext3 } from "react";
276
+
277
+ // node_modules/i18next/dist/esm/i18next.js
278
+ var isString2 = (obj) => typeof obj === "string";
279
+ var defer = () => {
280
+ let res;
281
+ let rej;
282
+ const promise = new Promise((resolve, reject) => {
283
+ res = resolve;
284
+ rej = reject;
285
+ });
286
+ promise.resolve = res;
287
+ promise.reject = rej;
288
+ return promise;
289
+ };
290
+ var makeString = (object) => {
291
+ if (object == null) return "";
292
+ return "" + object;
293
+ };
294
+ var copy = (a, s, t2) => {
295
+ a.forEach((m) => {
296
+ if (s[m]) t2[m] = s[m];
297
+ });
298
+ };
299
+ var lastOfPathSeparatorRegExp = /###/g;
300
+ var cleanKey = (key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
301
+ var canNotTraverseDeeper = (object) => !object || isString2(object);
302
+ var getLastOfPath = (object, path2, Empty) => {
303
+ const stack = !isString2(path2) ? path2 : path2.split(".");
304
+ let stackIndex = 0;
305
+ while (stackIndex < stack.length - 1) {
306
+ if (canNotTraverseDeeper(object)) return {};
307
+ const key = cleanKey(stack[stackIndex]);
308
+ if (!object[key] && Empty) object[key] = new Empty();
309
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
310
+ object = object[key];
311
+ } else {
312
+ object = {};
313
+ }
314
+ ++stackIndex;
315
+ }
316
+ if (canNotTraverseDeeper(object)) return {};
317
+ return {
318
+ obj: object,
319
+ k: cleanKey(stack[stackIndex])
320
+ };
321
+ };
322
+ var setPath = (object, path2, newValue) => {
323
+ const {
324
+ obj,
325
+ k
326
+ } = getLastOfPath(object, path2, Object);
327
+ if (obj !== void 0 || path2.length === 1) {
328
+ obj[k] = newValue;
329
+ return;
330
+ }
331
+ let e2 = path2[path2.length - 1];
332
+ let p = path2.slice(0, path2.length - 1);
333
+ let last = getLastOfPath(object, p, Object);
334
+ while (last.obj === void 0 && p.length) {
335
+ e2 = `${p[p.length - 1]}.${e2}`;
336
+ p = p.slice(0, p.length - 1);
337
+ last = getLastOfPath(object, p, Object);
338
+ if (last?.obj && typeof last.obj[`${last.k}.${e2}`] !== "undefined") {
339
+ last.obj = void 0;
340
+ }
341
+ }
342
+ last.obj[`${last.k}.${e2}`] = newValue;
343
+ };
344
+ var pushPath = (object, path2, newValue, concat) => {
345
+ const {
346
+ obj,
347
+ k
348
+ } = getLastOfPath(object, path2, Object);
349
+ obj[k] = obj[k] || [];
350
+ obj[k].push(newValue);
351
+ };
352
+ var getPath = (object, path2) => {
353
+ const {
354
+ obj,
355
+ k
356
+ } = getLastOfPath(object, path2);
357
+ if (!obj) return void 0;
358
+ if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0;
359
+ return obj[k];
360
+ };
361
+ var getPathWithDefaults = (data, defaultData, key) => {
362
+ const value = getPath(data, key);
363
+ if (value !== void 0) {
364
+ return value;
365
+ }
366
+ return getPath(defaultData, key);
367
+ };
368
+ var deepExtend = (target, source, overwrite) => {
369
+ for (const prop in source) {
370
+ if (prop !== "__proto__" && prop !== "constructor") {
371
+ if (prop in target) {
372
+ if (isString2(target[prop]) || target[prop] instanceof String || isString2(source[prop]) || source[prop] instanceof String) {
373
+ if (overwrite) target[prop] = source[prop];
374
+ } else {
375
+ deepExtend(target[prop], source[prop], overwrite);
376
+ }
377
+ } else {
378
+ target[prop] = source[prop];
379
+ }
380
+ }
381
+ }
382
+ return target;
383
+ };
384
+ var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
385
+ var _entityMap = {
386
+ "&": "&amp;",
387
+ "<": "&lt;",
388
+ ">": "&gt;",
389
+ '"': "&quot;",
390
+ "'": "&#39;",
391
+ "/": "&#x2F;"
392
+ };
393
+ var escape = (data) => {
394
+ if (isString2(data)) {
395
+ return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
396
+ }
397
+ return data;
398
+ };
399
+ var RegExpCache = class {
400
+ constructor(capacity) {
401
+ this.capacity = capacity;
402
+ this.regExpMap = /* @__PURE__ */ new Map();
403
+ this.regExpQueue = [];
404
+ }
405
+ getRegExp(pattern) {
406
+ const regExpFromCache = this.regExpMap.get(pattern);
407
+ if (regExpFromCache !== void 0) {
408
+ return regExpFromCache;
409
+ }
410
+ const regExpNew = new RegExp(pattern);
411
+ if (this.regExpQueue.length === this.capacity) {
412
+ this.regExpMap.delete(this.regExpQueue.shift());
413
+ }
414
+ this.regExpMap.set(pattern, regExpNew);
415
+ this.regExpQueue.push(pattern);
416
+ return regExpNew;
417
+ }
418
+ };
419
+ var chars = [" ", ",", "?", "!", ";"];
420
+ var looksLikeObjectPathRegExpCache = new RegExpCache(20);
421
+ var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
422
+ nsSeparator = nsSeparator || "";
423
+ keySeparator = keySeparator || "";
424
+ const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
425
+ if (possibleChars.length === 0) return true;
426
+ const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
427
+ let matched = !r.test(key);
428
+ if (!matched) {
429
+ const ki = key.indexOf(keySeparator);
430
+ if (ki > 0 && !r.test(key.substring(0, ki))) {
431
+ matched = true;
432
+ }
433
+ }
434
+ return matched;
435
+ };
436
+ var deepFind = function(obj, path2) {
437
+ let keySeparator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ".";
438
+ if (!obj) return void 0;
439
+ if (obj[path2]) {
440
+ if (!Object.prototype.hasOwnProperty.call(obj, path2)) return void 0;
441
+ return obj[path2];
442
+ }
443
+ const tokens = path2.split(keySeparator);
444
+ let current = obj;
445
+ for (let i = 0; i < tokens.length; ) {
446
+ if (!current || typeof current !== "object") {
447
+ return void 0;
448
+ }
449
+ let next;
450
+ let nextPath = "";
451
+ for (let j = i; j < tokens.length; ++j) {
452
+ if (j !== i) {
453
+ nextPath += keySeparator;
454
+ }
455
+ nextPath += tokens[j];
456
+ next = current[nextPath];
457
+ if (next !== void 0) {
458
+ if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) {
459
+ continue;
460
+ }
461
+ i += j - i + 1;
462
+ break;
463
+ }
464
+ }
465
+ current = next;
466
+ }
467
+ return current;
468
+ };
469
+ var getCleanedCode = (code) => code?.replace("_", "-");
470
+ var consoleLogger = {
471
+ type: "logger",
472
+ log(args) {
473
+ this.output("log", args);
474
+ },
475
+ warn(args) {
476
+ this.output("warn", args);
477
+ },
478
+ error(args) {
479
+ this.output("error", args);
480
+ },
481
+ output(type, args) {
482
+ console?.[type]?.apply?.(console, args);
483
+ }
484
+ };
485
+ var Logger = class _Logger {
486
+ constructor(concreteLogger) {
487
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
488
+ this.init(concreteLogger, options);
489
+ }
490
+ init(concreteLogger) {
491
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
492
+ this.prefix = options.prefix || "i18next:";
493
+ this.logger = concreteLogger || consoleLogger;
494
+ this.options = options;
495
+ this.debug = options.debug;
496
+ }
497
+ log() {
498
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
499
+ args[_key] = arguments[_key];
500
+ }
501
+ return this.forward(args, "log", "", true);
502
+ }
503
+ warn() {
504
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
505
+ args[_key2] = arguments[_key2];
506
+ }
507
+ return this.forward(args, "warn", "", true);
508
+ }
509
+ error() {
510
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
511
+ args[_key3] = arguments[_key3];
512
+ }
513
+ return this.forward(args, "error", "");
514
+ }
515
+ deprecate() {
516
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
517
+ args[_key4] = arguments[_key4];
518
+ }
519
+ return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
520
+ }
521
+ forward(args, lvl, prefix, debugOnly) {
522
+ if (debugOnly && !this.debug) return null;
523
+ if (isString2(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
524
+ return this.logger[lvl](args);
525
+ }
526
+ create(moduleName) {
527
+ return new _Logger(this.logger, {
528
+ ...{
529
+ prefix: `${this.prefix}:${moduleName}:`
530
+ },
531
+ ...this.options
532
+ });
533
+ }
534
+ clone(options) {
535
+ options = options || this.options;
536
+ options.prefix = options.prefix || this.prefix;
537
+ return new _Logger(this.logger, options);
538
+ }
539
+ };
540
+ var baseLogger = new Logger();
541
+ var EventEmitter = class {
542
+ constructor() {
543
+ this.observers = {};
544
+ }
545
+ on(events, listener) {
546
+ events.split(" ").forEach((event) => {
547
+ if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
548
+ const numListeners = this.observers[event].get(listener) || 0;
549
+ this.observers[event].set(listener, numListeners + 1);
550
+ });
551
+ return this;
552
+ }
553
+ off(event, listener) {
554
+ if (!this.observers[event]) return;
555
+ if (!listener) {
556
+ delete this.observers[event];
557
+ return;
558
+ }
559
+ this.observers[event].delete(listener);
560
+ }
561
+ emit(event) {
562
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
563
+ args[_key - 1] = arguments[_key];
564
+ }
565
+ if (this.observers[event]) {
566
+ const cloned = Array.from(this.observers[event].entries());
567
+ cloned.forEach((_ref) => {
568
+ let [observer, numTimesAdded] = _ref;
569
+ for (let i = 0; i < numTimesAdded; i++) {
570
+ observer(...args);
571
+ }
572
+ });
573
+ }
574
+ if (this.observers["*"]) {
575
+ const cloned = Array.from(this.observers["*"].entries());
576
+ cloned.forEach((_ref2) => {
577
+ let [observer, numTimesAdded] = _ref2;
578
+ for (let i = 0; i < numTimesAdded; i++) {
579
+ observer.apply(observer, [event, ...args]);
580
+ }
581
+ });
582
+ }
583
+ }
584
+ };
585
+ var ResourceStore = class extends EventEmitter {
586
+ constructor(data) {
587
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
588
+ ns: ["translation"],
589
+ defaultNS: "translation"
590
+ };
591
+ super();
592
+ this.data = data || {};
593
+ this.options = options;
594
+ if (this.options.keySeparator === void 0) {
595
+ this.options.keySeparator = ".";
596
+ }
597
+ if (this.options.ignoreJSONStructure === void 0) {
598
+ this.options.ignoreJSONStructure = true;
599
+ }
600
+ }
601
+ addNamespaces(ns) {
602
+ if (this.options.ns.indexOf(ns) < 0) {
603
+ this.options.ns.push(ns);
604
+ }
605
+ }
606
+ removeNamespaces(ns) {
607
+ const index = this.options.ns.indexOf(ns);
608
+ if (index > -1) {
609
+ this.options.ns.splice(index, 1);
610
+ }
611
+ }
612
+ getResource(lng, ns, key) {
613
+ let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
614
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
615
+ const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
616
+ let path2;
617
+ if (lng.indexOf(".") > -1) {
618
+ path2 = lng.split(".");
619
+ } else {
620
+ path2 = [lng, ns];
621
+ if (key) {
622
+ if (Array.isArray(key)) {
623
+ path2.push(...key);
624
+ } else if (isString2(key) && keySeparator) {
625
+ path2.push(...key.split(keySeparator));
626
+ } else {
627
+ path2.push(key);
628
+ }
629
+ }
630
+ }
631
+ const result = getPath(this.data, path2);
632
+ if (!result && !ns && !key && lng.indexOf(".") > -1) {
633
+ lng = path2[0];
634
+ ns = path2[1];
635
+ key = path2.slice(2).join(".");
636
+ }
637
+ if (result || !ignoreJSONStructure || !isString2(key)) return result;
638
+ return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
639
+ }
640
+ addResource(lng, ns, key, value) {
641
+ let options = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : {
642
+ silent: false
643
+ };
644
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
645
+ let path2 = [lng, ns];
646
+ if (key) path2 = path2.concat(keySeparator ? key.split(keySeparator) : key);
647
+ if (lng.indexOf(".") > -1) {
648
+ path2 = lng.split(".");
649
+ value = ns;
650
+ ns = path2[1];
651
+ }
652
+ this.addNamespaces(ns);
653
+ setPath(this.data, path2, value);
654
+ if (!options.silent) this.emit("added", lng, ns, key, value);
655
+ }
656
+ addResources(lng, ns, resources) {
657
+ let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {
658
+ silent: false
659
+ };
660
+ for (const m in resources) {
661
+ if (isString2(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
662
+ silent: true
663
+ });
664
+ }
665
+ if (!options.silent) this.emit("added", lng, ns, resources);
666
+ }
667
+ addResourceBundle(lng, ns, resources, deep, overwrite) {
668
+ let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {
669
+ silent: false,
670
+ skipCopy: false
671
+ };
672
+ let path2 = [lng, ns];
673
+ if (lng.indexOf(".") > -1) {
674
+ path2 = lng.split(".");
675
+ deep = resources;
676
+ resources = ns;
677
+ ns = path2[1];
678
+ }
679
+ this.addNamespaces(ns);
680
+ let pack = getPath(this.data, path2) || {};
681
+ if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
682
+ if (deep) {
683
+ deepExtend(pack, resources, overwrite);
684
+ } else {
685
+ pack = {
686
+ ...pack,
687
+ ...resources
688
+ };
689
+ }
690
+ setPath(this.data, path2, pack);
691
+ if (!options.silent) this.emit("added", lng, ns, resources);
692
+ }
693
+ removeResourceBundle(lng, ns) {
694
+ if (this.hasResourceBundle(lng, ns)) {
695
+ delete this.data[lng][ns];
696
+ }
697
+ this.removeNamespaces(ns);
698
+ this.emit("removed", lng, ns);
699
+ }
700
+ hasResourceBundle(lng, ns) {
701
+ return this.getResource(lng, ns) !== void 0;
702
+ }
703
+ getResourceBundle(lng, ns) {
704
+ if (!ns) ns = this.options.defaultNS;
705
+ return this.getResource(lng, ns);
706
+ }
707
+ getDataByLanguage(lng) {
708
+ return this.data[lng];
709
+ }
710
+ hasLanguageSomeTranslations(lng) {
711
+ const data = this.getDataByLanguage(lng);
712
+ const n = data && Object.keys(data) || [];
713
+ return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
714
+ }
715
+ toJSON() {
716
+ return this.data;
717
+ }
718
+ };
719
+ var postProcessor = {
720
+ processors: {},
721
+ addPostProcessor(module) {
722
+ this.processors[module.name] = module;
723
+ },
724
+ handle(processors, value, key, options, translator) {
725
+ processors.forEach((processor) => {
726
+ value = this.processors[processor]?.process(value, key, options, translator) ?? value;
727
+ });
728
+ return value;
729
+ }
730
+ };
731
+ var checkedLoadedFor = {};
732
+ var shouldHandleAsObject = (res) => !isString2(res) && typeof res !== "boolean" && typeof res !== "number";
733
+ var Translator = class _Translator extends EventEmitter {
734
+ constructor(services) {
735
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
736
+ super();
737
+ copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
738
+ this.options = options;
739
+ if (this.options.keySeparator === void 0) {
740
+ this.options.keySeparator = ".";
741
+ }
742
+ this.logger = baseLogger.create("translator");
743
+ }
744
+ changeLanguage(lng) {
745
+ if (lng) this.language = lng;
746
+ }
747
+ exists(key) {
748
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
749
+ interpolation: {}
750
+ };
751
+ if (key == null) {
752
+ return false;
753
+ }
754
+ const resolved = this.resolve(key, options);
755
+ return resolved?.res !== void 0;
756
+ }
757
+ extractFromKey(key, options) {
758
+ let nsSeparator = options.nsSeparator !== void 0 ? options.nsSeparator : this.options.nsSeparator;
759
+ if (nsSeparator === void 0) nsSeparator = ":";
760
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
761
+ let namespaces = options.ns || this.options.defaultNS || [];
762
+ const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
763
+ const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
764
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
765
+ const m = key.match(this.interpolator.nestingRegexp);
766
+ if (m && m.length > 0) {
767
+ return {
768
+ key,
769
+ namespaces: isString2(namespaces) ? [namespaces] : namespaces
770
+ };
771
+ }
772
+ const parts = key.split(nsSeparator);
773
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
774
+ key = parts.join(keySeparator);
775
+ }
776
+ return {
777
+ key,
778
+ namespaces: isString2(namespaces) ? [namespaces] : namespaces
779
+ };
780
+ }
781
+ translate(keys, options, lastKey) {
782
+ if (typeof options !== "object" && this.options.overloadTranslationOptionHandler) {
783
+ options = this.options.overloadTranslationOptionHandler(arguments);
784
+ }
785
+ if (typeof options === "object") options = {
786
+ ...options
787
+ };
788
+ if (!options) options = {};
789
+ if (keys == null) return "";
790
+ if (!Array.isArray(keys)) keys = [String(keys)];
791
+ const returnDetails = options.returnDetails !== void 0 ? options.returnDetails : this.options.returnDetails;
792
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
793
+ const {
794
+ key,
795
+ namespaces
796
+ } = this.extractFromKey(keys[keys.length - 1], options);
797
+ const namespace = namespaces[namespaces.length - 1];
798
+ const lng = options.lng || this.language;
799
+ const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
800
+ if (lng?.toLowerCase() === "cimode") {
801
+ if (appendNamespaceToCIMode) {
802
+ const nsSeparator = options.nsSeparator || this.options.nsSeparator;
803
+ if (returnDetails) {
804
+ return {
805
+ res: `${namespace}${nsSeparator}${key}`,
806
+ usedKey: key,
807
+ exactUsedKey: key,
808
+ usedLng: lng,
809
+ usedNS: namespace,
810
+ usedParams: this.getUsedParamsDetails(options)
811
+ };
812
+ }
813
+ return `${namespace}${nsSeparator}${key}`;
814
+ }
815
+ if (returnDetails) {
816
+ return {
817
+ res: key,
818
+ usedKey: key,
819
+ exactUsedKey: key,
820
+ usedLng: lng,
821
+ usedNS: namespace,
822
+ usedParams: this.getUsedParamsDetails(options)
823
+ };
824
+ }
825
+ return key;
826
+ }
827
+ const resolved = this.resolve(keys, options);
828
+ let res = resolved?.res;
829
+ const resUsedKey = resolved?.usedKey || key;
830
+ const resExactUsedKey = resolved?.exactUsedKey || key;
831
+ const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
832
+ const joinArrays = options.joinArrays !== void 0 ? options.joinArrays : this.options.joinArrays;
833
+ const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
834
+ const needsPluralHandling = options.count !== void 0 && !isString2(options.count);
835
+ const hasDefaultValue = _Translator.hasDefaultValue(options);
836
+ const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : "";
837
+ const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
838
+ ordinal: false
839
+ }) : "";
840
+ const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0;
841
+ const defaultValue = needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] || options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
842
+ let resForObjHndl = res;
843
+ if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
844
+ resForObjHndl = defaultValue;
845
+ }
846
+ const handleAsObject = shouldHandleAsObject(resForObjHndl);
847
+ const resType = Object.prototype.toString.apply(resForObjHndl);
848
+ if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString2(joinArrays) && Array.isArray(resForObjHndl))) {
849
+ if (!options.returnObjects && !this.options.returnObjects) {
850
+ if (!this.options.returnedObjectHandler) {
851
+ this.logger.warn("accessing an object - but returnObjects options is not enabled!");
852
+ }
853
+ const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
854
+ ...options,
855
+ ns: namespaces
856
+ }) : `key '${key} (${this.language})' returned an object instead of string.`;
857
+ if (returnDetails) {
858
+ resolved.res = r;
859
+ resolved.usedParams = this.getUsedParamsDetails(options);
860
+ return resolved;
861
+ }
862
+ return r;
863
+ }
864
+ if (keySeparator) {
865
+ const resTypeIsArray = Array.isArray(resForObjHndl);
866
+ const copy2 = resTypeIsArray ? [] : {};
867
+ const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
868
+ for (const m in resForObjHndl) {
869
+ if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
870
+ const deepKey = `${newKeyToUse}${keySeparator}${m}`;
871
+ if (hasDefaultValue && !res) {
872
+ copy2[m] = this.translate(deepKey, {
873
+ ...options,
874
+ defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0,
875
+ ...{
876
+ joinArrays: false,
877
+ ns: namespaces
878
+ }
879
+ });
880
+ } else {
881
+ copy2[m] = this.translate(deepKey, {
882
+ ...options,
883
+ ...{
884
+ joinArrays: false,
885
+ ns: namespaces
886
+ }
887
+ });
888
+ }
889
+ if (copy2[m] === deepKey) copy2[m] = resForObjHndl[m];
890
+ }
891
+ }
892
+ res = copy2;
893
+ }
894
+ } else if (handleAsObjectInI18nFormat && isString2(joinArrays) && Array.isArray(res)) {
895
+ res = res.join(joinArrays);
896
+ if (res) res = this.extendTranslation(res, keys, options, lastKey);
897
+ } else {
898
+ let usedDefault = false;
899
+ let usedKey = false;
900
+ if (!this.isValidLookup(res) && hasDefaultValue) {
901
+ usedDefault = true;
902
+ res = defaultValue;
903
+ }
904
+ if (!this.isValidLookup(res)) {
905
+ usedKey = true;
906
+ res = key;
907
+ }
908
+ const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
909
+ const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
910
+ const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
911
+ if (usedKey || usedDefault || updateMissing) {
912
+ this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
913
+ if (keySeparator) {
914
+ const fk = this.resolve(key, {
915
+ ...options,
916
+ keySeparator: false
917
+ });
918
+ 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.");
919
+ }
920
+ let lngs = [];
921
+ const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
922
+ if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
923
+ for (let i = 0; i < fallbackLngs.length; i++) {
924
+ lngs.push(fallbackLngs[i]);
925
+ }
926
+ } else if (this.options.saveMissingTo === "all") {
927
+ lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
928
+ } else {
929
+ lngs.push(options.lng || this.language);
930
+ }
931
+ const send = (l, k, specificDefaultValue) => {
932
+ const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
933
+ if (this.options.missingKeyHandler) {
934
+ this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
935
+ } else if (this.backendConnector?.saveMissing) {
936
+ this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
937
+ }
938
+ this.emit("missingKey", l, namespace, k, res);
939
+ };
940
+ if (this.options.saveMissing) {
941
+ if (this.options.saveMissingPlurals && needsPluralHandling) {
942
+ lngs.forEach((language) => {
943
+ const suffixes = this.pluralResolver.getSuffixes(language, options);
944
+ if (needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
945
+ suffixes.push(`${this.options.pluralSeparator}zero`);
946
+ }
947
+ suffixes.forEach((suffix) => {
948
+ send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);
949
+ });
950
+ });
951
+ } else {
952
+ send(lngs, key, defaultValue);
953
+ }
954
+ }
955
+ }
956
+ res = this.extendTranslation(res, keys, options, resolved, lastKey);
957
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;
958
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
959
+ res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : void 0);
960
+ }
961
+ }
962
+ if (returnDetails) {
963
+ resolved.res = res;
964
+ resolved.usedParams = this.getUsedParamsDetails(options);
965
+ return resolved;
966
+ }
967
+ return res;
968
+ }
969
+ extendTranslation(res, key, options, resolved, lastKey) {
970
+ var _this = this;
971
+ if (this.i18nFormat?.parse) {
972
+ res = this.i18nFormat.parse(res, {
973
+ ...this.options.interpolation.defaultVariables,
974
+ ...options
975
+ }, options.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
976
+ resolved
977
+ });
978
+ } else if (!options.skipInterpolation) {
979
+ if (options.interpolation) this.interpolator.init({
980
+ ...options,
981
+ ...{
982
+ interpolation: {
983
+ ...this.options.interpolation,
984
+ ...options.interpolation
985
+ }
986
+ }
987
+ });
988
+ const skipOnVariables = isString2(res) && (options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
989
+ let nestBef;
990
+ if (skipOnVariables) {
991
+ const nb = res.match(this.interpolator.nestingRegexp);
992
+ nestBef = nb && nb.length;
993
+ }
994
+ let data = options.replace && !isString2(options.replace) ? options.replace : options;
995
+ if (this.options.interpolation.defaultVariables) data = {
996
+ ...this.options.interpolation.defaultVariables,
997
+ ...data
998
+ };
999
+ res = this.interpolator.interpolate(res, data, options.lng || this.language || resolved.usedLng, options);
1000
+ if (skipOnVariables) {
1001
+ const na = res.match(this.interpolator.nestingRegexp);
1002
+ const nestAft = na && na.length;
1003
+ if (nestBef < nestAft) options.nest = false;
1004
+ }
1005
+ if (!options.lng && resolved && resolved.res) options.lng = this.language || resolved.usedLng;
1006
+ if (options.nest !== false) res = this.interpolator.nest(res, function() {
1007
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1008
+ args[_key] = arguments[_key];
1009
+ }
1010
+ if (lastKey?.[0] === args[0] && !options.context) {
1011
+ _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
1012
+ return null;
1013
+ }
1014
+ return _this.translate(...args, key);
1015
+ }, options);
1016
+ if (options.interpolation) this.interpolator.reset();
1017
+ }
1018
+ const postProcess = options.postProcess || this.options.postProcess;
1019
+ const postProcessorNames = isString2(postProcess) ? [postProcess] : postProcess;
1020
+ if (res != null && postProcessorNames?.length && options.applyPostProcessor !== false) {
1021
+ res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
1022
+ i18nResolved: {
1023
+ ...resolved,
1024
+ usedParams: this.getUsedParamsDetails(options)
1025
+ },
1026
+ ...options
1027
+ } : options, this);
1028
+ }
1029
+ return res;
1030
+ }
1031
+ resolve(keys) {
1032
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1033
+ let found;
1034
+ let usedKey;
1035
+ let exactUsedKey;
1036
+ let usedLng;
1037
+ let usedNS;
1038
+ if (isString2(keys)) keys = [keys];
1039
+ keys.forEach((k) => {
1040
+ if (this.isValidLookup(found)) return;
1041
+ const extracted = this.extractFromKey(k, options);
1042
+ const key = extracted.key;
1043
+ usedKey = key;
1044
+ let namespaces = extracted.namespaces;
1045
+ if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
1046
+ const needsPluralHandling = options.count !== void 0 && !isString2(options.count);
1047
+ const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0;
1048
+ const needsContextHandling = options.context !== void 0 && (isString2(options.context) || typeof options.context === "number") && options.context !== "";
1049
+ const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
1050
+ namespaces.forEach((ns) => {
1051
+ if (this.isValidLookup(found)) return;
1052
+ usedNS = ns;
1053
+ if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
1054
+ checkedLoadedFor[`${codes[0]}-${ns}`] = true;
1055
+ 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!!!");
1056
+ }
1057
+ codes.forEach((code) => {
1058
+ if (this.isValidLookup(found)) return;
1059
+ usedLng = code;
1060
+ const finalKeys = [key];
1061
+ if (this.i18nFormat?.addLookupKeys) {
1062
+ this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
1063
+ } else {
1064
+ let pluralSuffix;
1065
+ if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
1066
+ const zeroSuffix = `${this.options.pluralSeparator}zero`;
1067
+ const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
1068
+ if (needsPluralHandling) {
1069
+ finalKeys.push(key + pluralSuffix);
1070
+ if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
1071
+ finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
1072
+ }
1073
+ if (needsZeroSuffixLookup) {
1074
+ finalKeys.push(key + zeroSuffix);
1075
+ }
1076
+ }
1077
+ if (needsContextHandling) {
1078
+ const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
1079
+ finalKeys.push(contextKey);
1080
+ if (needsPluralHandling) {
1081
+ finalKeys.push(contextKey + pluralSuffix);
1082
+ if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
1083
+ finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
1084
+ }
1085
+ if (needsZeroSuffixLookup) {
1086
+ finalKeys.push(contextKey + zeroSuffix);
1087
+ }
1088
+ }
1089
+ }
1090
+ }
1091
+ let possibleKey;
1092
+ while (possibleKey = finalKeys.pop()) {
1093
+ if (!this.isValidLookup(found)) {
1094
+ exactUsedKey = possibleKey;
1095
+ found = this.getResource(code, ns, possibleKey, options);
1096
+ }
1097
+ }
1098
+ });
1099
+ });
1100
+ });
1101
+ return {
1102
+ res: found,
1103
+ usedKey,
1104
+ exactUsedKey,
1105
+ usedLng,
1106
+ usedNS
1107
+ };
1108
+ }
1109
+ isValidLookup(res) {
1110
+ return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
1111
+ }
1112
+ getResource(code, ns, key) {
1113
+ let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1114
+ if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
1115
+ return this.resourceStore.getResource(code, ns, key, options);
1116
+ }
1117
+ getUsedParamsDetails() {
1118
+ let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1119
+ const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
1120
+ const useOptionsReplaceForData = options.replace && !isString2(options.replace);
1121
+ let data = useOptionsReplaceForData ? options.replace : options;
1122
+ if (useOptionsReplaceForData && typeof options.count !== "undefined") {
1123
+ data.count = options.count;
1124
+ }
1125
+ if (this.options.interpolation.defaultVariables) {
1126
+ data = {
1127
+ ...this.options.interpolation.defaultVariables,
1128
+ ...data
1129
+ };
1130
+ }
1131
+ if (!useOptionsReplaceForData) {
1132
+ data = {
1133
+ ...data
1134
+ };
1135
+ for (const key of optionsKeys) {
1136
+ delete data[key];
1137
+ }
1138
+ }
1139
+ return data;
1140
+ }
1141
+ static hasDefaultValue(options) {
1142
+ const prefix = "defaultValue";
1143
+ for (const option in options) {
1144
+ if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) {
1145
+ return true;
1146
+ }
1147
+ }
1148
+ return false;
1149
+ }
1150
+ };
1151
+ var LanguageUtil = class {
1152
+ constructor(options) {
1153
+ this.options = options;
1154
+ this.supportedLngs = this.options.supportedLngs || false;
1155
+ this.logger = baseLogger.create("languageUtils");
1156
+ }
1157
+ getScriptPartFromCode(code) {
1158
+ code = getCleanedCode(code);
1159
+ if (!code || code.indexOf("-") < 0) return null;
1160
+ const p = code.split("-");
1161
+ if (p.length === 2) return null;
1162
+ p.pop();
1163
+ if (p[p.length - 1].toLowerCase() === "x") return null;
1164
+ return this.formatLanguageCode(p.join("-"));
1165
+ }
1166
+ getLanguagePartFromCode(code) {
1167
+ code = getCleanedCode(code);
1168
+ if (!code || code.indexOf("-") < 0) return code;
1169
+ const p = code.split("-");
1170
+ return this.formatLanguageCode(p[0]);
1171
+ }
1172
+ formatLanguageCode(code) {
1173
+ if (isString2(code) && code.indexOf("-") > -1) {
1174
+ let formattedCode;
1175
+ try {
1176
+ formattedCode = Intl.getCanonicalLocales(code)[0];
1177
+ } catch (e2) {
1178
+ }
1179
+ if (formattedCode && this.options.lowerCaseLng) {
1180
+ formattedCode = formattedCode.toLowerCase();
1181
+ }
1182
+ if (formattedCode) return formattedCode;
1183
+ if (this.options.lowerCaseLng) {
1184
+ return code.toLowerCase();
1185
+ }
1186
+ return code;
1187
+ }
1188
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1189
+ }
1190
+ isSupportedCode(code) {
1191
+ if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
1192
+ code = this.getLanguagePartFromCode(code);
1193
+ }
1194
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1195
+ }
1196
+ getBestMatchFromCodes(codes) {
1197
+ if (!codes) return null;
1198
+ let found;
1199
+ codes.forEach((code) => {
1200
+ if (found) return;
1201
+ const cleanedLng = this.formatLanguageCode(code);
1202
+ if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
1203
+ });
1204
+ if (!found && this.options.supportedLngs) {
1205
+ codes.forEach((code) => {
1206
+ if (found) return;
1207
+ const lngOnly = this.getLanguagePartFromCode(code);
1208
+ if (this.isSupportedCode(lngOnly)) return found = lngOnly;
1209
+ found = this.options.supportedLngs.find((supportedLng) => {
1210
+ if (supportedLng === lngOnly) return supportedLng;
1211
+ if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
1212
+ if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
1213
+ if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
1214
+ });
1215
+ });
1216
+ }
1217
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1218
+ return found;
1219
+ }
1220
+ getFallbackCodes(fallbacks, code) {
1221
+ if (!fallbacks) return [];
1222
+ if (typeof fallbacks === "function") fallbacks = fallbacks(code);
1223
+ if (isString2(fallbacks)) fallbacks = [fallbacks];
1224
+ if (Array.isArray(fallbacks)) return fallbacks;
1225
+ if (!code) return fallbacks.default || [];
1226
+ let found = fallbacks[code];
1227
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1228
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
1229
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1230
+ if (!found) found = fallbacks.default;
1231
+ return found || [];
1232
+ }
1233
+ toResolveHierarchy(code, fallbackCode) {
1234
+ const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
1235
+ const codes = [];
1236
+ const addCode = (c) => {
1237
+ if (!c) return;
1238
+ if (this.isSupportedCode(c)) {
1239
+ codes.push(c);
1240
+ } else {
1241
+ this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1242
+ }
1243
+ };
1244
+ if (isString2(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
1245
+ if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
1246
+ if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
1247
+ if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
1248
+ } else if (isString2(code)) {
1249
+ addCode(this.formatLanguageCode(code));
1250
+ }
1251
+ fallbackCodes.forEach((fc) => {
1252
+ if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
1253
+ });
1254
+ return codes;
1255
+ }
1256
+ };
1257
+ var suffixesOrder = {
1258
+ zero: 0,
1259
+ one: 1,
1260
+ two: 2,
1261
+ few: 3,
1262
+ many: 4,
1263
+ other: 5
1264
+ };
1265
+ var dummyRule = {
1266
+ select: (count) => count === 1 ? "one" : "other",
1267
+ resolvedOptions: () => ({
1268
+ pluralCategories: ["one", "other"]
1269
+ })
1270
+ };
1271
+ var PluralResolver = class {
1272
+ constructor(languageUtils) {
1273
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1274
+ this.languageUtils = languageUtils;
1275
+ this.options = options;
1276
+ this.logger = baseLogger.create("pluralResolver");
1277
+ this.pluralRulesCache = {};
1278
+ }
1279
+ addRule(lng, obj) {
1280
+ this.rules[lng] = obj;
1281
+ }
1282
+ clearCache() {
1283
+ this.pluralRulesCache = {};
1284
+ }
1285
+ getRule(code) {
1286
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1287
+ const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
1288
+ const type = options.ordinal ? "ordinal" : "cardinal";
1289
+ const cacheKey = JSON.stringify({
1290
+ cleanedCode,
1291
+ type
1292
+ });
1293
+ if (cacheKey in this.pluralRulesCache) {
1294
+ return this.pluralRulesCache[cacheKey];
1295
+ }
1296
+ let rule;
1297
+ try {
1298
+ rule = new Intl.PluralRules(cleanedCode, {
1299
+ type
1300
+ });
1301
+ } catch (err) {
1302
+ if (!Intl) {
1303
+ this.logger.error("No Intl support, please use an Intl polyfill!");
1304
+ return dummyRule;
1305
+ }
1306
+ if (!code.match(/-|_/)) return dummyRule;
1307
+ const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1308
+ rule = this.getRule(lngPart, options);
1309
+ }
1310
+ this.pluralRulesCache[cacheKey] = rule;
1311
+ return rule;
1312
+ }
1313
+ needsPlural(code) {
1314
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1315
+ let rule = this.getRule(code, options);
1316
+ if (!rule) rule = this.getRule("dev", options);
1317
+ return rule?.resolvedOptions().pluralCategories.length > 1;
1318
+ }
1319
+ getPluralFormsOfKey(code, key) {
1320
+ let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1321
+ return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
1322
+ }
1323
+ getSuffixes(code) {
1324
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1325
+ let rule = this.getRule(code, options);
1326
+ if (!rule) rule = this.getRule("dev", options);
1327
+ if (!rule) return [];
1328
+ return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
1329
+ }
1330
+ getSuffix(code, count) {
1331
+ let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1332
+ const rule = this.getRule(code, options);
1333
+ if (rule) {
1334
+ return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
1335
+ }
1336
+ this.logger.warn(`no plural rule found for: ${code}`);
1337
+ return this.getSuffix("dev", count, options);
1338
+ }
1339
+ };
1340
+ var deepFindWithDefaults = function(data, defaultData, key) {
1341
+ let keySeparator = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ".";
1342
+ let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
1343
+ let path2 = getPathWithDefaults(data, defaultData, key);
1344
+ if (!path2 && ignoreJSONStructure && isString2(key)) {
1345
+ path2 = deepFind(data, key, keySeparator);
1346
+ if (path2 === void 0) path2 = deepFind(defaultData, key, keySeparator);
1347
+ }
1348
+ return path2;
1349
+ };
1350
+ var regexSafe = (val) => val.replace(/\$/g, "$$$$");
1351
+ var Interpolator = class {
1352
+ constructor() {
1353
+ let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1354
+ this.logger = baseLogger.create("interpolator");
1355
+ this.options = options;
1356
+ this.format = options?.interpolation?.format || ((value) => value);
1357
+ this.init(options);
1358
+ }
1359
+ init() {
1360
+ let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1361
+ if (!options.interpolation) options.interpolation = {
1362
+ escapeValue: true
1363
+ };
1364
+ const {
1365
+ escape: escape$1,
1366
+ escapeValue,
1367
+ useRawValueToEscape,
1368
+ prefix,
1369
+ prefixEscaped,
1370
+ suffix,
1371
+ suffixEscaped,
1372
+ formatSeparator,
1373
+ unescapeSuffix,
1374
+ unescapePrefix,
1375
+ nestingPrefix,
1376
+ nestingPrefixEscaped,
1377
+ nestingSuffix,
1378
+ nestingSuffixEscaped,
1379
+ nestingOptionsSeparator,
1380
+ maxReplaces,
1381
+ alwaysFormat
1382
+ } = options.interpolation;
1383
+ this.escape = escape$1 !== void 0 ? escape$1 : escape;
1384
+ this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
1385
+ this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
1386
+ this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
1387
+ this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
1388
+ this.formatSeparator = formatSeparator || ",";
1389
+ this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
1390
+ this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
1391
+ this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
1392
+ this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
1393
+ this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
1394
+ this.maxReplaces = maxReplaces || 1e3;
1395
+ this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
1396
+ this.resetRegExp();
1397
+ }
1398
+ reset() {
1399
+ if (this.options) this.init(this.options);
1400
+ }
1401
+ resetRegExp() {
1402
+ const getOrResetRegExp = (existingRegExp, pattern) => {
1403
+ if (existingRegExp?.source === pattern) {
1404
+ existingRegExp.lastIndex = 0;
1405
+ return existingRegExp;
1406
+ }
1407
+ return new RegExp(pattern, "g");
1408
+ };
1409
+ this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1410
+ this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1411
+ this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}(.+?)${this.nestingSuffix}`);
1412
+ }
1413
+ interpolate(str, data, lng, options) {
1414
+ let match;
1415
+ let value;
1416
+ let replaces;
1417
+ const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1418
+ const handleFormat = (key) => {
1419
+ if (key.indexOf(this.formatSeparator) < 0) {
1420
+ const path2 = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1421
+ return this.alwaysFormat ? this.format(path2, void 0, lng, {
1422
+ ...options,
1423
+ ...data,
1424
+ interpolationkey: key
1425
+ }) : path2;
1426
+ }
1427
+ const p = key.split(this.formatSeparator);
1428
+ const k = p.shift().trim();
1429
+ const f = p.join(this.formatSeparator).trim();
1430
+ return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1431
+ ...options,
1432
+ ...data,
1433
+ interpolationkey: k
1434
+ });
1435
+ };
1436
+ this.resetRegExp();
1437
+ const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1438
+ const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1439
+ const todos = [{
1440
+ regex: this.regexpUnescape,
1441
+ safeValue: (val) => regexSafe(val)
1442
+ }, {
1443
+ regex: this.regexp,
1444
+ safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1445
+ }];
1446
+ todos.forEach((todo) => {
1447
+ replaces = 0;
1448
+ while (match = todo.regex.exec(str)) {
1449
+ const matchedVar = match[1].trim();
1450
+ value = handleFormat(matchedVar);
1451
+ if (value === void 0) {
1452
+ if (typeof missingInterpolationHandler === "function") {
1453
+ const temp = missingInterpolationHandler(str, match, options);
1454
+ value = isString2(temp) ? temp : "";
1455
+ } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1456
+ value = "";
1457
+ } else if (skipOnVariables) {
1458
+ value = match[0];
1459
+ continue;
1460
+ } else {
1461
+ this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1462
+ value = "";
1463
+ }
1464
+ } else if (!isString2(value) && !this.useRawValueToEscape) {
1465
+ value = makeString(value);
1466
+ }
1467
+ const safeValue = todo.safeValue(value);
1468
+ str = str.replace(match[0], safeValue);
1469
+ if (skipOnVariables) {
1470
+ todo.regex.lastIndex += value.length;
1471
+ todo.regex.lastIndex -= match[0].length;
1472
+ } else {
1473
+ todo.regex.lastIndex = 0;
1474
+ }
1475
+ replaces++;
1476
+ if (replaces >= this.maxReplaces) {
1477
+ break;
1478
+ }
1479
+ }
1480
+ });
1481
+ return str;
1482
+ }
1483
+ nest(str, fc) {
1484
+ let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1485
+ let match;
1486
+ let value;
1487
+ let clonedOptions;
1488
+ const handleHasOptions = (key, inheritedOptions) => {
1489
+ const sep = this.nestingOptionsSeparator;
1490
+ if (key.indexOf(sep) < 0) return key;
1491
+ const c = key.split(new RegExp(`${sep}[ ]*{`));
1492
+ let optionsString = `{${c[1]}`;
1493
+ key = c[0];
1494
+ optionsString = this.interpolate(optionsString, clonedOptions);
1495
+ const matchedSingleQuotes = optionsString.match(/'/g);
1496
+ const matchedDoubleQuotes = optionsString.match(/"/g);
1497
+ if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1498
+ optionsString = optionsString.replace(/'/g, '"');
1499
+ }
1500
+ try {
1501
+ clonedOptions = JSON.parse(optionsString);
1502
+ if (inheritedOptions) clonedOptions = {
1503
+ ...inheritedOptions,
1504
+ ...clonedOptions
1505
+ };
1506
+ } catch (e2) {
1507
+ this.logger.warn(`failed parsing options string in nesting for key ${key}`, e2);
1508
+ return `${key}${sep}${optionsString}`;
1509
+ }
1510
+ if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1511
+ return key;
1512
+ };
1513
+ while (match = this.nestingRegexp.exec(str)) {
1514
+ let formatters = [];
1515
+ clonedOptions = {
1516
+ ...options
1517
+ };
1518
+ clonedOptions = clonedOptions.replace && !isString2(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1519
+ clonedOptions.applyPostProcessor = false;
1520
+ delete clonedOptions.defaultValue;
1521
+ let doReduce = false;
1522
+ if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
1523
+ const r = match[1].split(this.formatSeparator).map((elem) => elem.trim());
1524
+ match[1] = r.shift();
1525
+ formatters = r;
1526
+ doReduce = true;
1527
+ }
1528
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1529
+ if (value && match[0] === str && !isString2(value)) return value;
1530
+ if (!isString2(value)) value = makeString(value);
1531
+ if (!value) {
1532
+ this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1533
+ value = "";
1534
+ }
1535
+ if (doReduce) {
1536
+ value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1537
+ ...options,
1538
+ interpolationkey: match[1].trim()
1539
+ }), value.trim());
1540
+ }
1541
+ str = str.replace(match[0], value);
1542
+ this.regexp.lastIndex = 0;
1543
+ }
1544
+ return str;
1545
+ }
1546
+ };
1547
+ var parseFormatStr = (formatStr) => {
1548
+ let formatName = formatStr.toLowerCase().trim();
1549
+ const formatOptions = {};
1550
+ if (formatStr.indexOf("(") > -1) {
1551
+ const p = formatStr.split("(");
1552
+ formatName = p[0].toLowerCase().trim();
1553
+ const optStr = p[1].substring(0, p[1].length - 1);
1554
+ if (formatName === "currency" && optStr.indexOf(":") < 0) {
1555
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1556
+ } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
1557
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
1558
+ } else {
1559
+ const opts = optStr.split(";");
1560
+ opts.forEach((opt) => {
1561
+ if (opt) {
1562
+ const [key, ...rest] = opt.split(":");
1563
+ const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
1564
+ const trimmedKey = key.trim();
1565
+ if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1566
+ if (val === "false") formatOptions[trimmedKey] = false;
1567
+ if (val === "true") formatOptions[trimmedKey] = true;
1568
+ if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1569
+ }
1570
+ });
1571
+ }
1572
+ }
1573
+ return {
1574
+ formatName,
1575
+ formatOptions
1576
+ };
1577
+ };
1578
+ var createCachedFormatter = (fn) => {
1579
+ const cache = {};
1580
+ return (val, lng, options) => {
1581
+ let optForCache = options;
1582
+ if (options && options.interpolationkey && options.formatParams && options.formatParams[options.interpolationkey] && options[options.interpolationkey]) {
1583
+ optForCache = {
1584
+ ...optForCache,
1585
+ [options.interpolationkey]: void 0
1586
+ };
1587
+ }
1588
+ const key = lng + JSON.stringify(optForCache);
1589
+ let formatter = cache[key];
1590
+ if (!formatter) {
1591
+ formatter = fn(getCleanedCode(lng), options);
1592
+ cache[key] = formatter;
1593
+ }
1594
+ return formatter(val);
1595
+ };
1596
+ };
1597
+ var Formatter = class {
1598
+ constructor() {
1599
+ let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1600
+ this.logger = baseLogger.create("formatter");
1601
+ this.options = options;
1602
+ this.formats = {
1603
+ number: createCachedFormatter((lng, opt) => {
1604
+ const formatter = new Intl.NumberFormat(lng, {
1605
+ ...opt
1606
+ });
1607
+ return (val) => formatter.format(val);
1608
+ }),
1609
+ currency: createCachedFormatter((lng, opt) => {
1610
+ const formatter = new Intl.NumberFormat(lng, {
1611
+ ...opt,
1612
+ style: "currency"
1613
+ });
1614
+ return (val) => formatter.format(val);
1615
+ }),
1616
+ datetime: createCachedFormatter((lng, opt) => {
1617
+ const formatter = new Intl.DateTimeFormat(lng, {
1618
+ ...opt
1619
+ });
1620
+ return (val) => formatter.format(val);
1621
+ }),
1622
+ relativetime: createCachedFormatter((lng, opt) => {
1623
+ const formatter = new Intl.RelativeTimeFormat(lng, {
1624
+ ...opt
1625
+ });
1626
+ return (val) => formatter.format(val, opt.range || "day");
1627
+ }),
1628
+ list: createCachedFormatter((lng, opt) => {
1629
+ const formatter = new Intl.ListFormat(lng, {
1630
+ ...opt
1631
+ });
1632
+ return (val) => formatter.format(val);
1633
+ })
1634
+ };
1635
+ this.init(options);
1636
+ }
1637
+ init(services) {
1638
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
1639
+ interpolation: {}
1640
+ };
1641
+ this.formatSeparator = options.interpolation.formatSeparator || ",";
1642
+ }
1643
+ add(name, fc) {
1644
+ this.formats[name.toLowerCase().trim()] = fc;
1645
+ }
1646
+ addCached(name, fc) {
1647
+ this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1648
+ }
1649
+ format(value, format, lng) {
1650
+ let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1651
+ const formats = format.split(this.formatSeparator);
1652
+ if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) {
1653
+ const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1);
1654
+ formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1655
+ }
1656
+ const result = formats.reduce((mem, f) => {
1657
+ const {
1658
+ formatName,
1659
+ formatOptions
1660
+ } = parseFormatStr(f);
1661
+ if (this.formats[formatName]) {
1662
+ let formatted = mem;
1663
+ try {
1664
+ const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1665
+ const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1666
+ formatted = this.formats[formatName](mem, l, {
1667
+ ...formatOptions,
1668
+ ...options,
1669
+ ...valOptions
1670
+ });
1671
+ } catch (error) {
1672
+ this.logger.warn(error);
1673
+ }
1674
+ return formatted;
1675
+ } else {
1676
+ this.logger.warn(`there was no format function for ${formatName}`);
1677
+ }
1678
+ return mem;
1679
+ }, value);
1680
+ return result;
1681
+ }
1682
+ };
1683
+ var removePending = (q, name) => {
1684
+ if (q.pending[name] !== void 0) {
1685
+ delete q.pending[name];
1686
+ q.pendingCount--;
1687
+ }
1688
+ };
1689
+ var Connector = class extends EventEmitter {
1690
+ constructor(backend, store, services) {
1691
+ let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1692
+ super();
1693
+ this.backend = backend;
1694
+ this.store = store;
1695
+ this.services = services;
1696
+ this.languageUtils = services.languageUtils;
1697
+ this.options = options;
1698
+ this.logger = baseLogger.create("backendConnector");
1699
+ this.waitingReads = [];
1700
+ this.maxParallelReads = options.maxParallelReads || 10;
1701
+ this.readingCalls = 0;
1702
+ this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1703
+ this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1704
+ this.state = {};
1705
+ this.queue = [];
1706
+ this.backend?.init?.(services, options.backend, options);
1707
+ }
1708
+ queueLoad(languages, namespaces, options, callback) {
1709
+ const toLoad = {};
1710
+ const pending = {};
1711
+ const toLoadLanguages = {};
1712
+ const toLoadNamespaces = {};
1713
+ languages.forEach((lng) => {
1714
+ let hasAllNamespaces = true;
1715
+ namespaces.forEach((ns) => {
1716
+ const name = `${lng}|${ns}`;
1717
+ if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1718
+ this.state[name] = 2;
1719
+ } else if (this.state[name] < 0) ;
1720
+ else if (this.state[name] === 1) {
1721
+ if (pending[name] === void 0) pending[name] = true;
1722
+ } else {
1723
+ this.state[name] = 1;
1724
+ hasAllNamespaces = false;
1725
+ if (pending[name] === void 0) pending[name] = true;
1726
+ if (toLoad[name] === void 0) toLoad[name] = true;
1727
+ if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
1728
+ }
1729
+ });
1730
+ if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1731
+ });
1732
+ if (Object.keys(toLoad).length || Object.keys(pending).length) {
1733
+ this.queue.push({
1734
+ pending,
1735
+ pendingCount: Object.keys(pending).length,
1736
+ loaded: {},
1737
+ errors: [],
1738
+ callback
1739
+ });
1740
+ }
1741
+ return {
1742
+ toLoad: Object.keys(toLoad),
1743
+ pending: Object.keys(pending),
1744
+ toLoadLanguages: Object.keys(toLoadLanguages),
1745
+ toLoadNamespaces: Object.keys(toLoadNamespaces)
1746
+ };
1747
+ }
1748
+ loaded(name, err, data) {
1749
+ const s = name.split("|");
1750
+ const lng = s[0];
1751
+ const ns = s[1];
1752
+ if (err) this.emit("failedLoading", lng, ns, err);
1753
+ if (!err && data) {
1754
+ this.store.addResourceBundle(lng, ns, data, void 0, void 0, {
1755
+ skipCopy: true
1756
+ });
1757
+ }
1758
+ this.state[name] = err ? -1 : 2;
1759
+ if (err && data) this.state[name] = 0;
1760
+ const loaded = {};
1761
+ this.queue.forEach((q) => {
1762
+ pushPath(q.loaded, [lng], ns);
1763
+ removePending(q, name);
1764
+ if (err) q.errors.push(err);
1765
+ if (q.pendingCount === 0 && !q.done) {
1766
+ Object.keys(q.loaded).forEach((l) => {
1767
+ if (!loaded[l]) loaded[l] = {};
1768
+ const loadedKeys = q.loaded[l];
1769
+ if (loadedKeys.length) {
1770
+ loadedKeys.forEach((n) => {
1771
+ if (loaded[l][n] === void 0) loaded[l][n] = true;
1772
+ });
1773
+ }
1774
+ });
1775
+ q.done = true;
1776
+ if (q.errors.length) {
1777
+ q.callback(q.errors);
1778
+ } else {
1779
+ q.callback();
1780
+ }
1781
+ }
1782
+ });
1783
+ this.emit("loaded", loaded);
1784
+ this.queue = this.queue.filter((q) => !q.done);
1785
+ }
1786
+ read(lng, ns, fcName) {
1787
+ let tried = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
1788
+ let wait = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : this.retryTimeout;
1789
+ let callback = arguments.length > 5 ? arguments[5] : void 0;
1790
+ if (!lng.length) return callback(null, {});
1791
+ if (this.readingCalls >= this.maxParallelReads) {
1792
+ this.waitingReads.push({
1793
+ lng,
1794
+ ns,
1795
+ fcName,
1796
+ tried,
1797
+ wait,
1798
+ callback
1799
+ });
1800
+ return;
1801
+ }
1802
+ this.readingCalls++;
1803
+ const resolver = (err, data) => {
1804
+ this.readingCalls--;
1805
+ if (this.waitingReads.length > 0) {
1806
+ const next = this.waitingReads.shift();
1807
+ this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1808
+ }
1809
+ if (err && data && tried < this.maxRetries) {
1810
+ setTimeout(() => {
1811
+ this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1812
+ }, wait);
1813
+ return;
1814
+ }
1815
+ callback(err, data);
1816
+ };
1817
+ const fc = this.backend[fcName].bind(this.backend);
1818
+ if (fc.length === 2) {
1819
+ try {
1820
+ const r = fc(lng, ns);
1821
+ if (r && typeof r.then === "function") {
1822
+ r.then((data) => resolver(null, data)).catch(resolver);
1823
+ } else {
1824
+ resolver(null, r);
1825
+ }
1826
+ } catch (err) {
1827
+ resolver(err);
1828
+ }
1829
+ return;
1830
+ }
1831
+ return fc(lng, ns, resolver);
1832
+ }
1833
+ prepareLoading(languages, namespaces) {
1834
+ let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1835
+ let callback = arguments.length > 3 ? arguments[3] : void 0;
1836
+ if (!this.backend) {
1837
+ this.logger.warn("No backend was added via i18next.use. Will not load resources.");
1838
+ return callback && callback();
1839
+ }
1840
+ if (isString2(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1841
+ if (isString2(namespaces)) namespaces = [namespaces];
1842
+ const toLoad = this.queueLoad(languages, namespaces, options, callback);
1843
+ if (!toLoad.toLoad.length) {
1844
+ if (!toLoad.pending.length) callback();
1845
+ return null;
1846
+ }
1847
+ toLoad.toLoad.forEach((name) => {
1848
+ this.loadOne(name);
1849
+ });
1850
+ }
1851
+ load(languages, namespaces, callback) {
1852
+ this.prepareLoading(languages, namespaces, {}, callback);
1853
+ }
1854
+ reload(languages, namespaces, callback) {
1855
+ this.prepareLoading(languages, namespaces, {
1856
+ reload: true
1857
+ }, callback);
1858
+ }
1859
+ loadOne(name) {
1860
+ let prefix = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
1861
+ const s = name.split("|");
1862
+ const lng = s[0];
1863
+ const ns = s[1];
1864
+ this.read(lng, ns, "read", void 0, void 0, (err, data) => {
1865
+ if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1866
+ if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1867
+ this.loaded(name, err, data);
1868
+ });
1869
+ }
1870
+ saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
1871
+ let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {};
1872
+ let clb = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : () => {
1873
+ };
1874
+ if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1875
+ 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!!!");
1876
+ return;
1877
+ }
1878
+ if (key === void 0 || key === null || key === "") return;
1879
+ if (this.backend?.create) {
1880
+ const opts = {
1881
+ ...options,
1882
+ isUpdate
1883
+ };
1884
+ const fc = this.backend.create.bind(this.backend);
1885
+ if (fc.length < 6) {
1886
+ try {
1887
+ let r;
1888
+ if (fc.length === 5) {
1889
+ r = fc(languages, namespace, key, fallbackValue, opts);
1890
+ } else {
1891
+ r = fc(languages, namespace, key, fallbackValue);
1892
+ }
1893
+ if (r && typeof r.then === "function") {
1894
+ r.then((data) => clb(null, data)).catch(clb);
1895
+ } else {
1896
+ clb(null, r);
1897
+ }
1898
+ } catch (err) {
1899
+ clb(err);
1900
+ }
1901
+ } else {
1902
+ fc(languages, namespace, key, fallbackValue, clb, opts);
1903
+ }
1904
+ }
1905
+ if (!languages || !languages[0]) return;
1906
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
1907
+ }
1908
+ };
1909
+ var get = () => ({
1910
+ debug: false,
1911
+ initAsync: true,
1912
+ ns: ["translation"],
1913
+ defaultNS: ["translation"],
1914
+ fallbackLng: ["dev"],
1915
+ fallbackNS: false,
1916
+ supportedLngs: false,
1917
+ nonExplicitSupportedLngs: false,
1918
+ load: "all",
1919
+ preload: false,
1920
+ simplifyPluralSuffix: true,
1921
+ keySeparator: ".",
1922
+ nsSeparator: ":",
1923
+ pluralSeparator: "_",
1924
+ contextSeparator: "_",
1925
+ partialBundledLanguages: false,
1926
+ saveMissing: false,
1927
+ updateMissing: false,
1928
+ saveMissingTo: "fallback",
1929
+ saveMissingPlurals: true,
1930
+ missingKeyHandler: false,
1931
+ missingInterpolationHandler: false,
1932
+ postProcess: false,
1933
+ postProcessPassResolved: false,
1934
+ returnNull: false,
1935
+ returnEmptyString: true,
1936
+ returnObjects: false,
1937
+ joinArrays: false,
1938
+ returnedObjectHandler: false,
1939
+ parseMissingKeyHandler: false,
1940
+ appendNamespaceToMissingKey: false,
1941
+ appendNamespaceToCIMode: false,
1942
+ overloadTranslationOptionHandler: (args) => {
1943
+ let ret = {};
1944
+ if (typeof args[1] === "object") ret = args[1];
1945
+ if (isString2(args[1])) ret.defaultValue = args[1];
1946
+ if (isString2(args[2])) ret.tDescription = args[2];
1947
+ if (typeof args[2] === "object" || typeof args[3] === "object") {
1948
+ const options = args[3] || args[2];
1949
+ Object.keys(options).forEach((key) => {
1950
+ ret[key] = options[key];
1951
+ });
1952
+ }
1953
+ return ret;
1954
+ },
1955
+ interpolation: {
1956
+ escapeValue: true,
1957
+ format: (value) => value,
1958
+ prefix: "{{",
1959
+ suffix: "}}",
1960
+ formatSeparator: ",",
1961
+ unescapePrefix: "-",
1962
+ nestingPrefix: "$t(",
1963
+ nestingSuffix: ")",
1964
+ nestingOptionsSeparator: ",",
1965
+ maxReplaces: 1e3,
1966
+ skipOnVariables: true
1967
+ }
1968
+ });
1969
+ var transformOptions = (options) => {
1970
+ if (isString2(options.ns)) options.ns = [options.ns];
1971
+ if (isString2(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1972
+ if (isString2(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1973
+ if (options.supportedLngs?.indexOf?.("cimode") < 0) {
1974
+ options.supportedLngs = options.supportedLngs.concat(["cimode"]);
1975
+ }
1976
+ if (typeof options.initImmediate === "boolean") options.initAsync = options.initImmediate;
1977
+ return options;
1978
+ };
1979
+ var noop = () => {
1980
+ };
1981
+ var bindMemberFunctions = (inst) => {
1982
+ const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1983
+ mems.forEach((mem) => {
1984
+ if (typeof inst[mem] === "function") {
1985
+ inst[mem] = inst[mem].bind(inst);
1986
+ }
1987
+ });
1988
+ };
1989
+ var I18n = class _I18n extends EventEmitter {
1990
+ constructor() {
1991
+ let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1992
+ let callback = arguments.length > 1 ? arguments[1] : void 0;
1993
+ super();
1994
+ this.options = transformOptions(options);
1995
+ this.services = {};
1996
+ this.logger = baseLogger;
1997
+ this.modules = {
1998
+ external: []
1999
+ };
2000
+ bindMemberFunctions(this);
2001
+ if (callback && !this.isInitialized && !options.isClone) {
2002
+ if (!this.options.initAsync) {
2003
+ this.init(options, callback);
2004
+ return this;
2005
+ }
2006
+ setTimeout(() => {
2007
+ this.init(options, callback);
2008
+ }, 0);
2009
+ }
2010
+ }
2011
+ init() {
2012
+ var _this = this;
2013
+ let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2014
+ let callback = arguments.length > 1 ? arguments[1] : void 0;
2015
+ this.isInitializing = true;
2016
+ if (typeof options === "function") {
2017
+ callback = options;
2018
+ options = {};
2019
+ }
2020
+ if (options.defaultNS == null && options.ns) {
2021
+ if (isString2(options.ns)) {
2022
+ options.defaultNS = options.ns;
2023
+ } else if (options.ns.indexOf("translation") < 0) {
2024
+ options.defaultNS = options.ns[0];
2025
+ }
2026
+ }
2027
+ const defOpts = get();
2028
+ this.options = {
2029
+ ...defOpts,
2030
+ ...this.options,
2031
+ ...transformOptions(options)
2032
+ };
2033
+ this.options.interpolation = {
2034
+ ...defOpts.interpolation,
2035
+ ...this.options.interpolation
2036
+ };
2037
+ if (options.keySeparator !== void 0) {
2038
+ this.options.userDefinedKeySeparator = options.keySeparator;
2039
+ }
2040
+ if (options.nsSeparator !== void 0) {
2041
+ this.options.userDefinedNsSeparator = options.nsSeparator;
2042
+ }
2043
+ const createClassOnDemand = (ClassOrObject) => {
2044
+ if (!ClassOrObject) return null;
2045
+ if (typeof ClassOrObject === "function") return new ClassOrObject();
2046
+ return ClassOrObject;
2047
+ };
2048
+ if (!this.options.isClone) {
2049
+ if (this.modules.logger) {
2050
+ baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
2051
+ } else {
2052
+ baseLogger.init(null, this.options);
2053
+ }
2054
+ let formatter;
2055
+ if (this.modules.formatter) {
2056
+ formatter = this.modules.formatter;
2057
+ } else {
2058
+ formatter = Formatter;
2059
+ }
2060
+ const lu = new LanguageUtil(this.options);
2061
+ this.store = new ResourceStore(this.options.resources, this.options);
2062
+ const s = this.services;
2063
+ s.logger = baseLogger;
2064
+ s.resourceStore = this.store;
2065
+ s.languageUtils = lu;
2066
+ s.pluralResolver = new PluralResolver(lu, {
2067
+ prepend: this.options.pluralSeparator,
2068
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
2069
+ });
2070
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
2071
+ s.formatter = createClassOnDemand(formatter);
2072
+ s.formatter.init(s, this.options);
2073
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
2074
+ }
2075
+ s.interpolator = new Interpolator(this.options);
2076
+ s.utils = {
2077
+ hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
2078
+ };
2079
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
2080
+ s.backendConnector.on("*", function(event) {
2081
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2082
+ args[_key - 1] = arguments[_key];
2083
+ }
2084
+ _this.emit(event, ...args);
2085
+ });
2086
+ if (this.modules.languageDetector) {
2087
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
2088
+ if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
2089
+ }
2090
+ if (this.modules.i18nFormat) {
2091
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
2092
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
2093
+ }
2094
+ this.translator = new Translator(this.services, this.options);
2095
+ this.translator.on("*", function(event) {
2096
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
2097
+ args[_key2 - 1] = arguments[_key2];
2098
+ }
2099
+ _this.emit(event, ...args);
2100
+ });
2101
+ this.modules.external.forEach((m) => {
2102
+ if (m.init) m.init(this);
2103
+ });
2104
+ }
2105
+ this.format = this.options.interpolation.format;
2106
+ if (!callback) callback = noop;
2107
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
2108
+ const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2109
+ if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
2110
+ }
2111
+ if (!this.services.languageDetector && !this.options.lng) {
2112
+ this.logger.warn("init: no languageDetector is used and no lng is defined");
2113
+ }
2114
+ const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
2115
+ storeApi.forEach((fcName) => {
2116
+ this[fcName] = function() {
2117
+ return _this.store[fcName](...arguments);
2118
+ };
2119
+ });
2120
+ const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
2121
+ storeApiChained.forEach((fcName) => {
2122
+ this[fcName] = function() {
2123
+ _this.store[fcName](...arguments);
2124
+ return _this;
2125
+ };
2126
+ });
2127
+ const deferred = defer();
2128
+ const load = () => {
2129
+ const finish = (err, t2) => {
2130
+ this.isInitializing = false;
2131
+ if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
2132
+ this.isInitialized = true;
2133
+ if (!this.options.isClone) this.logger.log("initialized", this.options);
2134
+ this.emit("initialized", this.options);
2135
+ deferred.resolve(t2);
2136
+ callback(err, t2);
2137
+ };
2138
+ if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
2139
+ this.changeLanguage(this.options.lng, finish);
2140
+ };
2141
+ if (this.options.resources || !this.options.initAsync) {
2142
+ load();
2143
+ } else {
2144
+ setTimeout(load, 0);
2145
+ }
2146
+ return deferred;
2147
+ }
2148
+ loadResources(language) {
2149
+ let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
2150
+ let usedCallback = callback;
2151
+ const usedLng = isString2(language) ? language : this.language;
2152
+ if (typeof language === "function") usedCallback = language;
2153
+ if (!this.options.resources || this.options.partialBundledLanguages) {
2154
+ if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
2155
+ const toLoad = [];
2156
+ const append = (lng) => {
2157
+ if (!lng) return;
2158
+ if (lng === "cimode") return;
2159
+ const lngs = this.services.languageUtils.toResolveHierarchy(lng);
2160
+ lngs.forEach((l) => {
2161
+ if (l === "cimode") return;
2162
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
2163
+ });
2164
+ };
2165
+ if (!usedLng) {
2166
+ const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2167
+ fallbacks.forEach((l) => append(l));
2168
+ } else {
2169
+ append(usedLng);
2170
+ }
2171
+ this.options.preload?.forEach?.((l) => append(l));
2172
+ this.services.backendConnector.load(toLoad, this.options.ns, (e2) => {
2173
+ if (!e2 && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
2174
+ usedCallback(e2);
2175
+ });
2176
+ } else {
2177
+ usedCallback(null);
2178
+ }
2179
+ }
2180
+ reloadResources(lngs, ns, callback) {
2181
+ const deferred = defer();
2182
+ if (typeof lngs === "function") {
2183
+ callback = lngs;
2184
+ lngs = void 0;
2185
+ }
2186
+ if (typeof ns === "function") {
2187
+ callback = ns;
2188
+ ns = void 0;
2189
+ }
2190
+ if (!lngs) lngs = this.languages;
2191
+ if (!ns) ns = this.options.ns;
2192
+ if (!callback) callback = noop;
2193
+ this.services.backendConnector.reload(lngs, ns, (err) => {
2194
+ deferred.resolve();
2195
+ callback(err);
2196
+ });
2197
+ return deferred;
2198
+ }
2199
+ use(module) {
2200
+ if (!module) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
2201
+ if (!module.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
2202
+ if (module.type === "backend") {
2203
+ this.modules.backend = module;
2204
+ }
2205
+ if (module.type === "logger" || module.log && module.warn && module.error) {
2206
+ this.modules.logger = module;
2207
+ }
2208
+ if (module.type === "languageDetector") {
2209
+ this.modules.languageDetector = module;
2210
+ }
2211
+ if (module.type === "i18nFormat") {
2212
+ this.modules.i18nFormat = module;
2213
+ }
2214
+ if (module.type === "postProcessor") {
2215
+ postProcessor.addPostProcessor(module);
2216
+ }
2217
+ if (module.type === "formatter") {
2218
+ this.modules.formatter = module;
2219
+ }
2220
+ if (module.type === "3rdParty") {
2221
+ this.modules.external.push(module);
2222
+ }
2223
+ return this;
2224
+ }
2225
+ setResolvedLanguage(l) {
2226
+ if (!l || !this.languages) return;
2227
+ if (["cimode", "dev"].indexOf(l) > -1) return;
2228
+ for (let li = 0; li < this.languages.length; li++) {
2229
+ const lngInLngs = this.languages[li];
2230
+ if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue;
2231
+ if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2232
+ this.resolvedLanguage = lngInLngs;
2233
+ break;
2234
+ }
2235
+ }
2236
+ }
2237
+ changeLanguage(lng, callback) {
2238
+ var _this2 = this;
2239
+ this.isLanguageChangingTo = lng;
2240
+ const deferred = defer();
2241
+ this.emit("languageChanging", lng);
2242
+ const setLngProps = (l) => {
2243
+ this.language = l;
2244
+ this.languages = this.services.languageUtils.toResolveHierarchy(l);
2245
+ this.resolvedLanguage = void 0;
2246
+ this.setResolvedLanguage(l);
2247
+ };
2248
+ const done = (err, l) => {
2249
+ if (l) {
2250
+ setLngProps(l);
2251
+ this.translator.changeLanguage(l);
2252
+ this.isLanguageChangingTo = void 0;
2253
+ this.emit("languageChanged", l);
2254
+ this.logger.log("languageChanged", l);
2255
+ } else {
2256
+ this.isLanguageChangingTo = void 0;
2257
+ }
2258
+ deferred.resolve(function() {
2259
+ return _this2.t(...arguments);
2260
+ });
2261
+ if (callback) callback(err, function() {
2262
+ return _this2.t(...arguments);
2263
+ });
2264
+ };
2265
+ const setLng = (lngs) => {
2266
+ if (!lng && !lngs && this.services.languageDetector) lngs = [];
2267
+ const l = isString2(lngs) ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);
2268
+ if (l) {
2269
+ if (!this.language) {
2270
+ setLngProps(l);
2271
+ }
2272
+ if (!this.translator.language) this.translator.changeLanguage(l);
2273
+ this.services.languageDetector?.cacheUserLanguage?.(l);
2274
+ }
2275
+ this.loadResources(l, (err) => {
2276
+ done(err, l);
2277
+ });
2278
+ };
2279
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2280
+ setLng(this.services.languageDetector.detect());
2281
+ } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2282
+ if (this.services.languageDetector.detect.length === 0) {
2283
+ this.services.languageDetector.detect().then(setLng);
2284
+ } else {
2285
+ this.services.languageDetector.detect(setLng);
2286
+ }
2287
+ } else {
2288
+ setLng(lng);
2289
+ }
2290
+ return deferred;
2291
+ }
2292
+ getFixedT(lng, ns, keyPrefix) {
2293
+ var _this3 = this;
2294
+ const fixedT = function(key, opts) {
2295
+ let options;
2296
+ if (typeof opts !== "object") {
2297
+ for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
2298
+ rest[_key3 - 2] = arguments[_key3];
2299
+ }
2300
+ options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2301
+ } else {
2302
+ options = {
2303
+ ...opts
2304
+ };
2305
+ }
2306
+ options.lng = options.lng || fixedT.lng;
2307
+ options.lngs = options.lngs || fixedT.lngs;
2308
+ options.ns = options.ns || fixedT.ns;
2309
+ if (options.keyPrefix !== "") options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
2310
+ const keySeparator = _this3.options.keySeparator || ".";
2311
+ let resultKey;
2312
+ if (options.keyPrefix && Array.isArray(key)) {
2313
+ resultKey = key.map((k) => `${options.keyPrefix}${keySeparator}${k}`);
2314
+ } else {
2315
+ resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;
2316
+ }
2317
+ return _this3.t(resultKey, options);
2318
+ };
2319
+ if (isString2(lng)) {
2320
+ fixedT.lng = lng;
2321
+ } else {
2322
+ fixedT.lngs = lng;
2323
+ }
2324
+ fixedT.ns = ns;
2325
+ fixedT.keyPrefix = keyPrefix;
2326
+ return fixedT;
2327
+ }
2328
+ t() {
2329
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
2330
+ args[_key4] = arguments[_key4];
2331
+ }
2332
+ return this.translator?.translate(...args);
2333
+ }
2334
+ exists() {
2335
+ for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
2336
+ args[_key5] = arguments[_key5];
2337
+ }
2338
+ return this.translator?.exists(...args);
2339
+ }
2340
+ setDefaultNamespace(ns) {
2341
+ this.options.defaultNS = ns;
2342
+ }
2343
+ hasLoadedNamespace(ns) {
2344
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2345
+ if (!this.isInitialized) {
2346
+ this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
2347
+ return false;
2348
+ }
2349
+ if (!this.languages || !this.languages.length) {
2350
+ this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
2351
+ return false;
2352
+ }
2353
+ const lng = options.lng || this.resolvedLanguage || this.languages[0];
2354
+ const fallbackLng = this.options ? this.options.fallbackLng : false;
2355
+ const lastLng = this.languages[this.languages.length - 1];
2356
+ if (lng.toLowerCase() === "cimode") return true;
2357
+ const loadNotPending = (l, n) => {
2358
+ const loadState = this.services.backendConnector.state[`${l}|${n}`];
2359
+ return loadState === -1 || loadState === 0 || loadState === 2;
2360
+ };
2361
+ if (options.precheck) {
2362
+ const preResult = options.precheck(this, loadNotPending);
2363
+ if (preResult !== void 0) return preResult;
2364
+ }
2365
+ if (this.hasResourceBundle(lng, ns)) return true;
2366
+ if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2367
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2368
+ return false;
2369
+ }
2370
+ loadNamespaces(ns, callback) {
2371
+ const deferred = defer();
2372
+ if (!this.options.ns) {
2373
+ if (callback) callback();
2374
+ return Promise.resolve();
2375
+ }
2376
+ if (isString2(ns)) ns = [ns];
2377
+ ns.forEach((n) => {
2378
+ if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2379
+ });
2380
+ this.loadResources((err) => {
2381
+ deferred.resolve();
2382
+ if (callback) callback(err);
2383
+ });
2384
+ return deferred;
2385
+ }
2386
+ loadLanguages(lngs, callback) {
2387
+ const deferred = defer();
2388
+ if (isString2(lngs)) lngs = [lngs];
2389
+ const preloaded = this.options.preload || [];
2390
+ const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2391
+ if (!newLngs.length) {
2392
+ if (callback) callback();
2393
+ return Promise.resolve();
2394
+ }
2395
+ this.options.preload = preloaded.concat(newLngs);
2396
+ this.loadResources((err) => {
2397
+ deferred.resolve();
2398
+ if (callback) callback(err);
2399
+ });
2400
+ return deferred;
2401
+ }
2402
+ dir(lng) {
2403
+ if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2404
+ if (!lng) return "rtl";
2405
+ 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"];
2406
+ const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2407
+ return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
2408
+ }
2409
+ static createInstance() {
2410
+ let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2411
+ let callback = arguments.length > 1 ? arguments[1] : void 0;
2412
+ return new _I18n(options, callback);
2413
+ }
2414
+ cloneInstance() {
2415
+ let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2416
+ let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
2417
+ const forkResourceStore = options.forkResourceStore;
2418
+ if (forkResourceStore) delete options.forkResourceStore;
2419
+ const mergedOptions = {
2420
+ ...this.options,
2421
+ ...options,
2422
+ ...{
2423
+ isClone: true
2424
+ }
2425
+ };
2426
+ const clone = new _I18n(mergedOptions);
2427
+ if (options.debug !== void 0 || options.prefix !== void 0) {
2428
+ clone.logger = clone.logger.clone(options);
2429
+ }
2430
+ const membersToCopy = ["store", "services", "language"];
2431
+ membersToCopy.forEach((m) => {
2432
+ clone[m] = this[m];
2433
+ });
2434
+ clone.services = {
2435
+ ...this.services
2436
+ };
2437
+ clone.services.utils = {
2438
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2439
+ };
2440
+ if (forkResourceStore) {
2441
+ const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2442
+ prev[l] = {
2443
+ ...this.store.data[l]
2444
+ };
2445
+ return Object.keys(prev[l]).reduce((acc, n) => {
2446
+ acc[n] = {
2447
+ ...prev[l][n]
2448
+ };
2449
+ return acc;
2450
+ }, {});
2451
+ }, {});
2452
+ clone.store = new ResourceStore(clonedData, mergedOptions);
2453
+ clone.services.resourceStore = clone.store;
2454
+ }
2455
+ clone.translator = new Translator(clone.services, mergedOptions);
2456
+ clone.translator.on("*", function(event) {
2457
+ for (var _len6 = arguments.length, args = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
2458
+ args[_key6 - 1] = arguments[_key6];
2459
+ }
2460
+ clone.emit(event, ...args);
2461
+ });
2462
+ clone.init(mergedOptions, callback);
2463
+ clone.translator.options = mergedOptions;
2464
+ clone.translator.backendConnector.services.utils = {
2465
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2466
+ };
2467
+ return clone;
2468
+ }
2469
+ toJSON() {
2470
+ return {
2471
+ options: this.options,
2472
+ store: this.store,
2473
+ language: this.language,
2474
+ languages: this.languages,
2475
+ resolvedLanguage: this.resolvedLanguage
2476
+ };
2477
+ }
2478
+ };
2479
+ var instance = I18n.createInstance();
2480
+ instance.createInstance = I18n.createInstance;
2481
+ var createInstance = instance.createInstance;
2482
+ var dir = instance.dir;
2483
+ var init = instance.init;
2484
+ var loadResources = instance.loadResources;
2485
+ var reloadResources = instance.reloadResources;
2486
+ var use = instance.use;
2487
+ var changeLanguage = instance.changeLanguage;
2488
+ var getFixedT = instance.getFixedT;
2489
+ var t = instance.t;
2490
+ var exists = instance.exists;
2491
+ var setDefaultNamespace = instance.setDefaultNamespace;
2492
+ var hasLoadedNamespace2 = instance.hasLoadedNamespace;
2493
+ var loadNamespaces2 = instance.loadNamespaces;
2494
+ var loadLanguages2 = instance.loadLanguages;
2495
+
2496
+ // node_modules/i18next-browser-languagedetector/dist/esm/i18nextBrowserLanguageDetector.js
2497
+ var {
2498
+ slice,
2499
+ forEach
2500
+ } = [];
2501
+ function defaults(obj) {
2502
+ forEach.call(slice.call(arguments, 1), (source) => {
2503
+ if (source) {
2504
+ for (const prop in source) {
2505
+ if (obj[prop] === void 0) obj[prop] = source[prop];
2506
+ }
2507
+ }
2508
+ });
2509
+ return obj;
2510
+ }
2511
+ function hasXSS(input) {
2512
+ if (typeof input !== "string") return false;
2513
+ const xssPatterns = [/<\s*script.*?>/i, /<\s*\/\s*script\s*>/i, /<\s*img.*?on\w+\s*=/i, /<\s*\w+\s*on\w+\s*=.*?>/i, /javascript\s*:/i, /vbscript\s*:/i, /expression\s*\(/i, /eval\s*\(/i, /alert\s*\(/i, /document\.cookie/i, /document\.write\s*\(/i, /window\.location/i, /innerHTML/i];
2514
+ return xssPatterns.some((pattern) => pattern.test(input));
2515
+ }
2516
+ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
2517
+ var serializeCookie = function(name, val) {
2518
+ let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {
2519
+ path: "/"
2520
+ };
2521
+ const opt = options;
2522
+ const value = encodeURIComponent(val);
2523
+ let str = `${name}=${value}`;
2524
+ if (opt.maxAge > 0) {
2525
+ const maxAge = opt.maxAge - 0;
2526
+ if (Number.isNaN(maxAge)) throw new Error("maxAge should be a Number");
2527
+ str += `; Max-Age=${Math.floor(maxAge)}`;
2528
+ }
2529
+ if (opt.domain) {
2530
+ if (!fieldContentRegExp.test(opt.domain)) {
2531
+ throw new TypeError("option domain is invalid");
2532
+ }
2533
+ str += `; Domain=${opt.domain}`;
2534
+ }
2535
+ if (opt.path) {
2536
+ if (!fieldContentRegExp.test(opt.path)) {
2537
+ throw new TypeError("option path is invalid");
2538
+ }
2539
+ str += `; Path=${opt.path}`;
2540
+ }
2541
+ if (opt.expires) {
2542
+ if (typeof opt.expires.toUTCString !== "function") {
2543
+ throw new TypeError("option expires is invalid");
2544
+ }
2545
+ str += `; Expires=${opt.expires.toUTCString()}`;
2546
+ }
2547
+ if (opt.httpOnly) str += "; HttpOnly";
2548
+ if (opt.secure) str += "; Secure";
2549
+ if (opt.sameSite) {
2550
+ const sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
2551
+ switch (sameSite) {
2552
+ case true:
2553
+ str += "; SameSite=Strict";
2554
+ break;
2555
+ case "lax":
2556
+ str += "; SameSite=Lax";
2557
+ break;
2558
+ case "strict":
2559
+ str += "; SameSite=Strict";
2560
+ break;
2561
+ case "none":
2562
+ str += "; SameSite=None";
2563
+ break;
2564
+ default:
2565
+ throw new TypeError("option sameSite is invalid");
2566
+ }
2567
+ }
2568
+ if (opt.partitioned) str += "; Partitioned";
2569
+ return str;
2570
+ };
2571
+ var cookie = {
2572
+ create(name, value, minutes, domain) {
2573
+ let cookieOptions = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : {
2574
+ path: "/",
2575
+ sameSite: "strict"
2576
+ };
2577
+ if (minutes) {
2578
+ cookieOptions.expires = /* @__PURE__ */ new Date();
2579
+ cookieOptions.expires.setTime(cookieOptions.expires.getTime() + minutes * 60 * 1e3);
2580
+ }
2581
+ if (domain) cookieOptions.domain = domain;
2582
+ document.cookie = serializeCookie(name, value, cookieOptions);
2583
+ },
2584
+ read(name) {
2585
+ const nameEQ = `${name}=`;
2586
+ const ca = document.cookie.split(";");
2587
+ for (let i = 0; i < ca.length; i++) {
2588
+ let c = ca[i];
2589
+ while (c.charAt(0) === " ") c = c.substring(1, c.length);
2590
+ if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
2591
+ }
2592
+ return null;
2593
+ },
2594
+ remove(name, domain) {
2595
+ this.create(name, "", -1, domain);
2596
+ }
2597
+ };
2598
+ var cookie$1 = {
2599
+ name: "cookie",
2600
+ // Deconstruct the options object and extract the lookupCookie property
2601
+ lookup(_ref) {
2602
+ let {
2603
+ lookupCookie
2604
+ } = _ref;
2605
+ if (lookupCookie && typeof document !== "undefined") {
2606
+ return cookie.read(lookupCookie) || void 0;
2607
+ }
2608
+ return void 0;
2609
+ },
2610
+ // Deconstruct the options object and extract the lookupCookie, cookieMinutes, cookieDomain, and cookieOptions properties
2611
+ cacheUserLanguage(lng, _ref2) {
2612
+ let {
2613
+ lookupCookie,
2614
+ cookieMinutes,
2615
+ cookieDomain,
2616
+ cookieOptions
2617
+ } = _ref2;
2618
+ if (lookupCookie && typeof document !== "undefined") {
2619
+ cookie.create(lookupCookie, lng, cookieMinutes, cookieDomain, cookieOptions);
2620
+ }
2621
+ }
2622
+ };
2623
+ var querystring = {
2624
+ name: "querystring",
2625
+ // Deconstruct the options object and extract the lookupQuerystring property
2626
+ lookup(_ref) {
2627
+ let {
2628
+ lookupQuerystring
2629
+ } = _ref;
2630
+ let found;
2631
+ if (typeof window !== "undefined") {
2632
+ let {
2633
+ search
2634
+ } = window.location;
2635
+ if (!window.location.search && window.location.hash?.indexOf("?") > -1) {
2636
+ search = window.location.hash.substring(window.location.hash.indexOf("?"));
2637
+ }
2638
+ const query = search.substring(1);
2639
+ const params = query.split("&");
2640
+ for (let i = 0; i < params.length; i++) {
2641
+ const pos = params[i].indexOf("=");
2642
+ if (pos > 0) {
2643
+ const key = params[i].substring(0, pos);
2644
+ if (key === lookupQuerystring) {
2645
+ found = params[i].substring(pos + 1);
2646
+ }
2647
+ }
2648
+ }
2649
+ }
2650
+ return found;
2651
+ }
2652
+ };
2653
+ var hash = {
2654
+ name: "hash",
2655
+ // Deconstruct the options object and extract the lookupHash property and the lookupFromHashIndex property
2656
+ lookup(_ref) {
2657
+ let {
2658
+ lookupHash,
2659
+ lookupFromHashIndex
2660
+ } = _ref;
2661
+ let found;
2662
+ if (typeof window !== "undefined") {
2663
+ const {
2664
+ hash: hash2
2665
+ } = window.location;
2666
+ if (hash2 && hash2.length > 2) {
2667
+ const query = hash2.substring(1);
2668
+ if (lookupHash) {
2669
+ const params = query.split("&");
2670
+ for (let i = 0; i < params.length; i++) {
2671
+ const pos = params[i].indexOf("=");
2672
+ if (pos > 0) {
2673
+ const key = params[i].substring(0, pos);
2674
+ if (key === lookupHash) {
2675
+ found = params[i].substring(pos + 1);
2676
+ }
2677
+ }
2678
+ }
2679
+ }
2680
+ if (found) return found;
2681
+ if (!found && lookupFromHashIndex > -1) {
2682
+ const language = hash2.match(/\/([a-zA-Z-]*)/g);
2683
+ if (!Array.isArray(language)) return void 0;
2684
+ const index = typeof lookupFromHashIndex === "number" ? lookupFromHashIndex : 0;
2685
+ return language[index]?.replace("/", "");
2686
+ }
2687
+ }
2688
+ }
2689
+ return found;
2690
+ }
2691
+ };
2692
+ var hasLocalStorageSupport = null;
2693
+ var localStorageAvailable = () => {
2694
+ if (hasLocalStorageSupport !== null) return hasLocalStorageSupport;
2695
+ try {
2696
+ hasLocalStorageSupport = typeof window !== "undefined" && window.localStorage !== null;
2697
+ if (!hasLocalStorageSupport) {
2698
+ return false;
2699
+ }
2700
+ const testKey = "i18next.translate.boo";
2701
+ window.localStorage.setItem(testKey, "foo");
2702
+ window.localStorage.removeItem(testKey);
2703
+ } catch (e2) {
2704
+ hasLocalStorageSupport = false;
2705
+ }
2706
+ return hasLocalStorageSupport;
2707
+ };
2708
+ var localStorage = {
2709
+ name: "localStorage",
2710
+ // Deconstruct the options object and extract the lookupLocalStorage property
2711
+ lookup(_ref) {
2712
+ let {
2713
+ lookupLocalStorage
2714
+ } = _ref;
2715
+ if (lookupLocalStorage && localStorageAvailable()) {
2716
+ return window.localStorage.getItem(lookupLocalStorage) || void 0;
2717
+ }
2718
+ return void 0;
2719
+ },
2720
+ // Deconstruct the options object and extract the lookupLocalStorage property
2721
+ cacheUserLanguage(lng, _ref2) {
2722
+ let {
2723
+ lookupLocalStorage
2724
+ } = _ref2;
2725
+ if (lookupLocalStorage && localStorageAvailable()) {
2726
+ window.localStorage.setItem(lookupLocalStorage, lng);
2727
+ }
2728
+ }
2729
+ };
2730
+ var hasSessionStorageSupport = null;
2731
+ var sessionStorageAvailable = () => {
2732
+ if (hasSessionStorageSupport !== null) return hasSessionStorageSupport;
2733
+ try {
2734
+ hasSessionStorageSupport = typeof window !== "undefined" && window.sessionStorage !== null;
2735
+ if (!hasSessionStorageSupport) {
2736
+ return false;
2737
+ }
2738
+ const testKey = "i18next.translate.boo";
2739
+ window.sessionStorage.setItem(testKey, "foo");
2740
+ window.sessionStorage.removeItem(testKey);
2741
+ } catch (e2) {
2742
+ hasSessionStorageSupport = false;
2743
+ }
2744
+ return hasSessionStorageSupport;
2745
+ };
2746
+ var sessionStorage = {
2747
+ name: "sessionStorage",
2748
+ lookup(_ref) {
2749
+ let {
2750
+ lookupSessionStorage
2751
+ } = _ref;
2752
+ if (lookupSessionStorage && sessionStorageAvailable()) {
2753
+ return window.sessionStorage.getItem(lookupSessionStorage) || void 0;
2754
+ }
2755
+ return void 0;
2756
+ },
2757
+ cacheUserLanguage(lng, _ref2) {
2758
+ let {
2759
+ lookupSessionStorage
2760
+ } = _ref2;
2761
+ if (lookupSessionStorage && sessionStorageAvailable()) {
2762
+ window.sessionStorage.setItem(lookupSessionStorage, lng);
2763
+ }
2764
+ }
2765
+ };
2766
+ var navigator$1 = {
2767
+ name: "navigator",
2768
+ lookup(options) {
2769
+ const found = [];
2770
+ if (typeof navigator !== "undefined") {
2771
+ const {
2772
+ languages,
2773
+ userLanguage,
2774
+ language
2775
+ } = navigator;
2776
+ if (languages) {
2777
+ for (let i = 0; i < languages.length; i++) {
2778
+ found.push(languages[i]);
2779
+ }
2780
+ }
2781
+ if (userLanguage) {
2782
+ found.push(userLanguage);
2783
+ }
2784
+ if (language) {
2785
+ found.push(language);
2786
+ }
2787
+ }
2788
+ return found.length > 0 ? found : void 0;
2789
+ }
2790
+ };
2791
+ var htmlTag = {
2792
+ name: "htmlTag",
2793
+ // Deconstruct the options object and extract the htmlTag property
2794
+ lookup(_ref) {
2795
+ let {
2796
+ htmlTag: htmlTag2
2797
+ } = _ref;
2798
+ let found;
2799
+ const internalHtmlTag = htmlTag2 || (typeof document !== "undefined" ? document.documentElement : null);
2800
+ if (internalHtmlTag && typeof internalHtmlTag.getAttribute === "function") {
2801
+ found = internalHtmlTag.getAttribute("lang");
2802
+ }
2803
+ return found;
2804
+ }
2805
+ };
2806
+ var path = {
2807
+ name: "path",
2808
+ // Deconstruct the options object and extract the lookupFromPathIndex property
2809
+ lookup(_ref) {
2810
+ let {
2811
+ lookupFromPathIndex
2812
+ } = _ref;
2813
+ if (typeof window === "undefined") return void 0;
2814
+ const language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
2815
+ if (!Array.isArray(language)) return void 0;
2816
+ const index = typeof lookupFromPathIndex === "number" ? lookupFromPathIndex : 0;
2817
+ return language[index]?.replace("/", "");
2818
+ }
2819
+ };
2820
+ var subdomain = {
2821
+ name: "subdomain",
2822
+ lookup(_ref) {
2823
+ let {
2824
+ lookupFromSubdomainIndex
2825
+ } = _ref;
2826
+ const internalLookupFromSubdomainIndex = typeof lookupFromSubdomainIndex === "number" ? lookupFromSubdomainIndex + 1 : 1;
2827
+ const language = typeof window !== "undefined" && window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);
2828
+ if (!language) return void 0;
2829
+ return language[internalLookupFromSubdomainIndex];
2830
+ }
2831
+ };
2832
+ var canCookies = false;
2833
+ try {
2834
+ document.cookie;
2835
+ canCookies = true;
2836
+ } catch (e2) {
2837
+ }
2838
+ var order = ["querystring", "cookie", "localStorage", "sessionStorage", "navigator", "htmlTag"];
2839
+ if (!canCookies) order.splice(1, 1);
2840
+ var getDefaults2 = () => ({
2841
+ order,
2842
+ lookupQuerystring: "lng",
2843
+ lookupCookie: "i18next",
2844
+ lookupLocalStorage: "i18nextLng",
2845
+ lookupSessionStorage: "i18nextLng",
2846
+ // cache user language
2847
+ caches: ["localStorage"],
2848
+ excludeCacheFor: ["cimode"],
2849
+ // cookieMinutes: 10,
2850
+ // cookieDomain: 'myDomain'
2851
+ convertDetectedLanguage: (l) => l
2852
+ });
2853
+ var Browser = class {
2854
+ constructor(services) {
2855
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2856
+ this.type = "languageDetector";
2857
+ this.detectors = {};
2858
+ this.init(services, options);
2859
+ }
2860
+ init() {
2861
+ let services = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {
2862
+ languageUtils: {}
2863
+ };
2864
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2865
+ let i18nOptions = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
2866
+ this.services = services;
2867
+ this.options = defaults(options, this.options || {}, getDefaults2());
2868
+ if (typeof this.options.convertDetectedLanguage === "string" && this.options.convertDetectedLanguage.indexOf("15897") > -1) {
2869
+ this.options.convertDetectedLanguage = (l) => l.replace("-", "_");
2870
+ }
2871
+ if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
2872
+ this.i18nOptions = i18nOptions;
2873
+ this.addDetector(cookie$1);
2874
+ this.addDetector(querystring);
2875
+ this.addDetector(localStorage);
2876
+ this.addDetector(sessionStorage);
2877
+ this.addDetector(navigator$1);
2878
+ this.addDetector(htmlTag);
2879
+ this.addDetector(path);
2880
+ this.addDetector(subdomain);
2881
+ this.addDetector(hash);
2882
+ }
2883
+ addDetector(detector) {
2884
+ this.detectors[detector.name] = detector;
2885
+ return this;
2886
+ }
2887
+ detect() {
2888
+ let detectionOrder = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.options.order;
2889
+ let detected = [];
2890
+ detectionOrder.forEach((detectorName) => {
2891
+ if (this.detectors[detectorName]) {
2892
+ let lookup = this.detectors[detectorName].lookup(this.options);
2893
+ if (lookup && typeof lookup === "string") lookup = [lookup];
2894
+ if (lookup) detected = detected.concat(lookup);
2895
+ }
2896
+ });
2897
+ detected = detected.filter((d) => d !== void 0 && d !== null && !hasXSS(d)).map((d) => this.options.convertDetectedLanguage(d));
2898
+ if (this.services && this.services.languageUtils && this.services.languageUtils.getBestMatchFromCodes) return detected;
2899
+ return detected.length > 0 ? detected[0] : null;
2900
+ }
2901
+ cacheUserLanguage(lng) {
2902
+ let caches = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this.options.caches;
2903
+ if (!caches) return;
2904
+ if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
2905
+ caches.forEach((cacheName) => {
2906
+ if (this.detectors[cacheName]) this.detectors[cacheName].cacheUserLanguage(lng, this.options);
2907
+ });
2908
+ }
2909
+ };
2910
+ Browser.type = "languageDetector";
2911
+
2912
+ // src/locales/vi.json
2913
+ var vi_default = {
2914
+ "search...": "T\xECm ki\u1EBFm...",
2915
+ search: "T\xECm ki\u1EBFm",
2916
+ search_more: "T\xECm ki\u1EBFm th\xEAm",
2917
+ for: "cho",
2918
+ cancel: "H\u1EE7y",
2919
+ empty_data: "D\u1EEF li\u1EC7u tr\u1ED1ng",
2920
+ detail_button: "Chi ti\u1EBFt",
2921
+ cancel_button: "H\u1EE7y",
2922
+ choose: "Ch\u1ECDn",
2923
+ total: "T\u1ED5ng ti\u1EC1n",
2924
+ no: "Kh\xF4ng",
2925
+ loading: "\u0110ang t\u1EA3i",
2926
+ active: "Ho\u1EA1t \u0111\u1ED9ng",
2927
+ in_active: "Ng\u01B0ng ho\u1EA1t \u0111\u1ED9ng",
2928
+ new: "M\u1EDBi",
2929
+ add_line: "Th\xEAm d\xF2ng",
2930
+ choose_place: "Vui l\xF2ng ch\u1ECDn",
2931
+ filter_by: "B\u1ED9 l\u1ECDc",
2932
+ group_by: "Nh\xF3m theo",
2933
+ or: "ho\u1EB7c",
2934
+ second_ago: "gi\xE2y tr\u01B0\u1EDBc",
2935
+ minute_ago: "ph\xFAt tr\u01B0\u1EDBc",
2936
+ hour_ago: "gi\u1EDD tr\u01B0\u1EDBc",
2937
+ day_ago: "ng\xE0y tr\u01B0\u1EDBc",
2938
+ month_ago: "th\xE1ng tr\u01B0\u1EDBc",
2939
+ year_ago: "n\u0103m tr\u01B0\u1EDBc",
2940
+ second_future: "gi\xE2y n\u1EEFa",
2941
+ minute_future: "ph\xFAt n\u1EEFa",
2942
+ hour_future: "gi\u1EDD n\u1EEFa",
2943
+ day_future: "ng\xE0y n\u1EEFa",
2944
+ month_future: "th\xE1ng n\u1EEFa",
2945
+ year_future: "n\u0103m n\u1EEFa",
2946
+ now: "B\xE2y gi\u1EDD",
2947
+ download_file: "T\u1EA3i xu\u1ED1ng t\u1EC7p n\xE0y",
2948
+ upload_success: "T\u1EA3i t\u1EC7p l\xEAn th\xE0nh c\xF4ng",
2949
+ upload_failure: "T\u1EA3i t\u1EC7p l\xEAn th\u1EA5t b\u1EA1i",
2950
+ file_accept_single: "Ch\u1EC9 ch\u1EA5p nh\u1EADn c\xE1c \u0111\u1ECBnh d\u1EA1ng JPEG, PNG, PDF, MP4, XLS, XLXS, ZIP v\xE0 m\u1ED7i t\u1EC7p c\xF3 dung l\u01B0\u1EE3ng t\u1ED1i \u0111a l\xE0 10MB.",
2951
+ file_accept_total: "Ch\u1EC9 ch\u1EA5p nh\u1EADn c\xE1c \u0111\u1ECBnh d\u1EA1ng JPEG, PNG, PDF, MP4, XLS, XLXS, ZIP v\xE0 t\u1ED5ng dung l\u01B0\u1EE3ng t\u1ED1i \u0111a l\xE0 50MB.",
2952
+ must_required: "l\xE0 b\u1EAFt bu\u1ED9c.",
2953
+ "none-validated": "Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7",
2954
+ invalid_number: "\u0110\u1ECBnh d\u1EA1ng s\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7",
2955
+ upload_file_placeholder: "T\u1EA3i t\u1EC7p c\u1EE7a b\u1EA1n",
2956
+ "no-available": "Kh\xF4ng c\xF3 l\u1EF1a ch\u1ECDn n\xE0o",
2957
+ paid_amount: "S\u1ED1 ti\u1EC1n \u0111\xE3 tr\u1EA3",
2958
+ remanining_amount: "S\u1ED1 ti\u1EC1n c\xF2n l\u1EA1i",
2959
+ only_image_accept: "Ch\u1EC9 \u0111\u01B0\u1EE3c t\u1EA3i l\xEAn h\xECnh \u1EA3nh",
2960
+ "text-only": "Ch\u1EC9 \u0111\u01B0\u1EE3c nh\u1EADp ch\u1EEF (kh\xF4ng ch\u1EE9a s\u1ED1 v\xE0 k\xFD t\u1EF1 \u0111\u1EB7c bi\u1EC7t)",
2961
+ "number-only": "Ch\u1EC9 \u0111\u01B0\u1EE3c nh\u1EADp s\u1ED1 (kh\xF4ng ch\u1EE9a ch\u1EEF v\xE0 k\xFD t\u1EF1 \u0111\u1EB7c bi\u1EC7t)",
2962
+ "email-only": "Email kh\xF4ng h\u1EE3p l\u1EC7",
2963
+ "phone-only": "S\u1ED1 \u0111i\u1EC7n tho\u1EA1i kh\xF4ng h\u1EE3p l\u1EC7",
2964
+ message: "M\u1EADt kh\u1EA9u ph\u1EA3i c\xF3 t\u1EEB {{min}} \u0111\u1EBFn {{max}} k\xFD t\u1EF1",
2965
+ "message-text-error": " kh\xF4ng \u0111\u01B0\u1EE3c v\u01B0\u1EE3t qu\xE1 {{max}} k\xFD t\u1EF1",
2966
+ upcase: ", {{count}} ch\u1EEF in hoa",
2967
+ digit: ", {{count}} s\u1ED1",
2968
+ special: ", {{count}} k\xFD t\u1EF1 \u0111\u1EB7c bi\u1EC7t",
2969
+ upload_files_accept: "Ch\u1EC9 ch\u1EA5p nh\u1EADn c\xE1c \u0111\u1ECBnh d\u1EA1ng JPEG, PNG, PDF, MP4, XLS, XLXS, ZIP",
2970
+ show_all: "Xem t\u1EA5t c\u1EA3",
2971
+ upload_max_files: "B\u1EA1n ch\u1EC9 \u0111\u01B0\u1EE3c t\u1EA3i l\xEAn t\u1ED1i \u0111a 5 t\u1EADp tin v\xE0 5 \u1EA3nh",
2972
+ file_too_large: " M\u1ED7i file ho\u1EB7c h\xECnh \u1EA3nh dung l\u01B0\u1EE3ng t\u1ED1i \u0111a 10MB",
2973
+ remove_all: "X\xF3a t\u1EA5t c\u1EA3",
2974
+ download: "T\u1EA3i xu\u1ED1ng",
2975
+ please_enter: "Vui l\xF2ng nh\u1EADp"
2976
+ };
2977
+
2978
+ // src/locales/en.json
2979
+ var en_default = {
2980
+ "none-validated": "Invalid value",
2981
+ "search...": "Search...",
2982
+ search: "Search",
2983
+ search_more: "Search more",
2984
+ for: "for",
2985
+ cancel: "Cancel",
2986
+ choose: "Choose",
2987
+ total: "Total",
2988
+ no: "No",
2989
+ loading: "Loading",
2990
+ detail_button: "Detail",
2991
+ cancel_button: "Cancel",
2992
+ empty_data: "No data",
2993
+ new: "New",
2994
+ add_line: "Add a line",
2995
+ choose_place: "Please choose",
2996
+ filter_by: "Filter",
2997
+ group_by: "Group By",
2998
+ or: "or",
2999
+ now: "Now",
3000
+ second_ago: "seconds ago",
3001
+ minute_ago: "minutes ago",
3002
+ hour_ago: "hours ago",
3003
+ day_ago: "days ago",
3004
+ month_ago: "months ago",
3005
+ year_ago: "years ago",
3006
+ second_future: "seconds",
3007
+ minute_future: "minutes",
3008
+ hour_future: "hours",
3009
+ day_future: "days",
3010
+ month_future: "months",
3011
+ year_future: "years",
3012
+ download_file: "Download this file",
3013
+ upload_success: "Upload file success",
3014
+ upload_failure: "Upload file failure",
3015
+ file_accept_single: "Only JPEG, PNG, PDF, MP4, XLS, XLXS, ZIP, JSON formats are allowed, and each file should be up to 10MB.",
3016
+ file_accept_total: "Only JPEG, PNG, PDF, MP4, XLS, XLXS, ZIP, JSON formats are allowed, and total should be up to 50MB.",
3017
+ must_required: "is required",
3018
+ invalid_number: "Invalid number",
3019
+ active: "Active",
3020
+ in_active: "Inactive",
3021
+ upload_file_placeholder: "Upload your file",
3022
+ "no-available": "No options available",
3023
+ paid_amount: "Amount Paid",
3024
+ remanining_amount: "Amount Remaining",
3025
+ only_image_accept: "Only accept image",
3026
+ "text-only": "Only letters (no numbers or special characters)",
3027
+ "number-only": "Only enter numbers (no letters or special characters)",
3028
+ "email-only": "Invalid email address",
3029
+ "phone-only": "Invalid phone number",
3030
+ message: "Password must be between {{min}} and {{max}} characters",
3031
+ "message-text-error": " must not exceed {{max}} characters",
3032
+ upcase: ", {{count}} uppercase letter",
3033
+ digit: ", {{count}} digit",
3034
+ special: ", {{count}} special character",
3035
+ upload_files_accept: "Only JPEG, PNG, PDF, MP4, XLS, XLXS, ZIP, JSON formats are allowed",
3036
+ show_all: "Show all",
3037
+ upload_max_files: "You can only upload a maximum of 5 files and 5 images",
3038
+ file_too_large: "Image/file size exceeds the 10MB limit",
3039
+ remove_all: "Remove all",
3040
+ download: "Download",
3041
+ please_enter: "Please enter"
3042
+ };
3043
+
3044
+ // src/utils/i18n.ts
3045
+ instance.use(Browser).use(initReactI18next).init({
3046
+ resources: {
3047
+ vi: { translation: vi_default },
3048
+ en: { translation: en_default }
3049
+ },
3050
+ fallbackLng: "vi",
3051
+ lng: "vi_VN",
3052
+ debug: false,
3053
+ nonExplicitSupportedLngs: true,
3054
+ interpolation: {
3055
+ escapeValue: false
3056
+ },
3057
+ detection: {
3058
+ caches: ["cookie"]
3059
+ }
3060
+ });
3061
+
3062
+ // src/provider/index.tsx
3063
+ import { jsx } from "react/jsx-runtime";
3064
+ var I18nContext2 = createContext2(null);
3065
+ var useI18n = () => {
3066
+ const context = useContext4(I18nContext2);
3067
+ if (!context) {
3068
+ throw new Error("useI18n must be used within I18nProvider");
3069
+ }
3070
+ return context;
3071
+ };
3072
+
3073
+ // src/utils/date.ts
3074
+ var useFormatDate = () => {
3075
+ const { t: t2 } = useI18n();
3076
+ const getRelativeTime = (dateString) => {
3077
+ const units = [
3078
+ {
3079
+ unit: "year",
3080
+ seconds: 365 * 24 * 60 * 60,
3081
+ keyPast: "year_ago",
3082
+ keyFuture: "year_future"
3083
+ },
3084
+ {
3085
+ unit: "month",
3086
+ seconds: 30 * 24 * 60 * 60,
3087
+ keyPast: "month_ago",
3088
+ keyFuture: "month_future"
3089
+ },
3090
+ {
3091
+ unit: "day",
3092
+ seconds: 24 * 60 * 60,
3093
+ keyPast: "day_ago",
3094
+ keyFuture: "day_future"
3095
+ },
3096
+ {
3097
+ unit: "hour",
3098
+ seconds: 60 * 60,
3099
+ keyPast: "hour_ago",
3100
+ keyFuture: "hour_future"
3101
+ },
3102
+ {
3103
+ unit: "minute",
3104
+ seconds: 60,
3105
+ keyPast: "minute_ago",
3106
+ keyFuture: "minute_future"
3107
+ },
3108
+ {
3109
+ unit: "second",
3110
+ seconds: 1,
3111
+ keyPast: "second_ago",
3112
+ keyFuture: "second_future"
3113
+ }
3114
+ ];
3115
+ const currentDate = /* @__PURE__ */ new Date();
3116
+ let year, month, day, hours = 0, minutes = 0, seconds = 0;
3117
+ const parts = dateString.split(/[- :]/).map(Number);
3118
+ if (parts[0] > 31) {
3119
+ ;
3120
+ [year, month, day] = parts;
3121
+ } else {
3122
+ ;
3123
+ [day, month, year] = parts;
3124
+ }
3125
+ if (parts.length > 3) [hours, minutes, seconds] = parts.slice(3);
3126
+ const givenDate = new Date(year, month - 1, day, hours, minutes, seconds);
3127
+ if (hours === 0 && minutes === 0 && seconds === 0) {
3128
+ givenDate.setHours(23, 59, 59);
3129
+ }
3130
+ const timeDifferenceInSeconds = Math.floor(
3131
+ (givenDate.getTime() - currentDate.getTime()) / 1e3
3132
+ );
3133
+ const isFuture = timeDifferenceInSeconds > 0;
3134
+ const absoluteDiff = Math.abs(timeDifferenceInSeconds);
3135
+ for (const { seconds: seconds2, keyPast, keyFuture } of units) {
3136
+ let diff = absoluteDiff / seconds2;
3137
+ if (diff >= 1) {
3138
+ diff = isFuture ? Math.ceil(diff) : Math.floor(diff);
3139
+ return isFuture ? `${diff} ${t2(keyFuture, { count: diff })}` : `${diff} ${t2(keyPast, { count: diff })}`;
3140
+ }
3141
+ }
3142
+ return t2("now");
3143
+ };
3144
+ return { getRelativeTime };
3145
+ };
3146
+ var validateAndParseDate = (input, isDateTime = false) => {
3147
+ if (!input || typeof input !== "string") return null;
3148
+ const cleanInput = input.replace(/[^0-9-\/:\s]/g, "");
3149
+ const dateFormat = "YYYY-MM-DD";
3150
+ const dateTimeFormat = "YYYY-MM-DD HH:mm:ss";
3151
+ const currentDay = moment().format("DD");
3152
+ const currentMonth = moment().format("MM");
3153
+ const currentYear = moment().format("YYYY");
3154
+ const defaultTime = "00:00:00";
3155
+ const maxYear = parseInt(currentYear) + 10;
3156
+ const isValidDate = (day, month, year) => {
3157
+ const date = moment(`${day}-${month}-${year}`, "DD-MM-YYYY", true);
3158
+ return date.isValid();
3159
+ };
3160
+ const isValidTime = (hour, minute = "00", second = "00") => {
3161
+ const h = parseInt(hour, 10);
3162
+ const m = parseInt(minute, 10);
3163
+ const s = parseInt(second, 10);
3164
+ return h >= 0 && h <= 23 && m >= 0 && m <= 59 && s >= 0 && s <= 59;
3165
+ };
3166
+ const formatOutput = (day, month, year, time = defaultTime) => {
3167
+ let result = moment(
3168
+ `${day}-${month}-${year} ${time}`,
3169
+ "DD-MM-YYYY HH:mm:ss"
3170
+ );
3171
+ if (!result.isValid()) return null;
3172
+ if (isDateTime) {
3173
+ result = result.subtract(7, "hours");
3174
+ return result.format(dateTimeFormat);
3175
+ }
3176
+ return result.format(dateFormat);
3177
+ };
3178
+ if (isDateTime && input.match(
3179
+ /^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}\s+\d{1,2}(:\d{1,2}(:\d{1,2})?)?$/
3180
+ )) {
3181
+ const [datePart, timePart] = input.split(/\s+/);
3182
+ const dateParts = datePart.split(/[\/-]/);
3183
+ const timeParts = timePart.split(":");
3184
+ const day = dateParts[0].padStart(2, "0");
3185
+ const month = dateParts[1].padStart(2, "0");
3186
+ const year = dateParts[2].length <= 2 ? `20${dateParts[2].padStart(2, "0")}` : dateParts[2].padStart(4, "0");
3187
+ const hour = timeParts[0].padStart(2, "0");
3188
+ const minute = timeParts[1] ? timeParts[1].padStart(2, "0") : "00";
3189
+ const second = timeParts[2] ? timeParts[2].padStart(2, "0") : "00";
3190
+ if (isValidDate(day, month, year) && isValidTime(hour, minute, second)) {
3191
+ let result = moment(
3192
+ `${day}-${month}-${year} ${hour}:${minute}:${second}`,
3193
+ "DD-MM-YYYY HH:mm:ss"
3194
+ );
3195
+ if (!result.isValid()) return null;
3196
+ result = result.subtract(7, "hours");
3197
+ return result.format(dateTimeFormat);
3198
+ }
3199
+ return null;
3200
+ }
3201
+ if (cleanInput.match(/^\d{4}-\d{2}-\d{2}$/)) {
3202
+ const [year, month, day] = cleanInput.split("-");
3203
+ if (isValidDate(day, month, year)) {
3204
+ return formatOutput(day, month, year);
3205
+ }
3206
+ return null;
3207
+ }
3208
+ if (cleanInput.match(/^\d{1,2}\/\d{1,2}\/\d{2,4}$/)) {
3209
+ const [day, month, year] = cleanInput.split("/");
3210
+ const paddedDay = day.padStart(2, "0");
3211
+ const paddedMonth = month.padStart(2, "0");
3212
+ const fullYear = year.length <= 2 ? `20${year.padStart(2, "0")}` : year.padStart(4, "0");
3213
+ if (isValidDate(paddedDay, paddedMonth, fullYear)) {
3214
+ return formatOutput(paddedDay, paddedMonth, fullYear);
3215
+ }
3216
+ return null;
3217
+ }
3218
+ if (cleanInput.match(/^\d{1,2}-\d{1,2}-\d{2,4}$/)) {
3219
+ const [day, month, year] = cleanInput.split("-");
3220
+ const paddedDay = day.padStart(2, "0");
3221
+ const paddedMonth = month.padStart(2, "0");
3222
+ const fullYear = year.length <= 2 ? `20${year.padStart(2, "0")}` : year.padStart(4, "0");
3223
+ if (isValidDate(paddedDay, paddedMonth, fullYear)) {
3224
+ return formatOutput(paddedDay, paddedMonth, fullYear);
3225
+ }
3226
+ return null;
3227
+ }
3228
+ if (cleanInput.match(/^\d{1,2}[\/-]\d{1,2}$/)) {
3229
+ const [day, month] = cleanInput.split(/[\/-]/);
3230
+ const paddedDay = day.padStart(2, "0");
3231
+ const paddedMonth = month.padStart(2, "0");
3232
+ if (isValidDate(paddedDay, paddedMonth, currentYear)) {
3233
+ return formatOutput(paddedDay, paddedMonth, currentYear);
3234
+ }
3235
+ return null;
3236
+ }
3237
+ if (cleanInput.match(/^\d{4}$/)) {
3238
+ const num = parseInt(cleanInput, 10);
3239
+ if (num >= 2e3 && num <= maxYear) {
3240
+ if (isValidDate(currentDay, currentMonth, num.toString())) {
3241
+ return formatOutput(currentDay, currentMonth, num.toString());
3242
+ }
3243
+ return null;
3244
+ }
3245
+ const day = cleanInput.slice(0, 2);
3246
+ const month = cleanInput.slice(2, 4);
3247
+ if (isValidDate(day, month, currentYear)) {
3248
+ return formatOutput(day, month, currentYear);
3249
+ }
3250
+ return null;
3251
+ }
3252
+ if (cleanInput.startsWith("-") && /^\-\d+$/.test(cleanInput)) {
3253
+ const daysToSubtract = Math.abs(parseInt(cleanInput, 10));
3254
+ let result = moment().subtract(daysToSubtract, "days");
3255
+ if (isDateTime) {
3256
+ result = result.subtract(7, "hours");
3257
+ }
3258
+ if (result.isValid()) {
3259
+ return isDateTime ? result.format(dateTimeFormat) : result.format(dateFormat);
3260
+ }
3261
+ return null;
3262
+ }
3263
+ if (input.match(/^\d{1,2}[^0-9-\/]+\d{1,2}[^0-9-\/]+\d{2,4}.*$/)) {
3264
+ const parts = input.split(/[^0-9-\/]+/).filter(Boolean);
3265
+ const day = parts[0].padStart(2, "0");
3266
+ const month = parts[1].padStart(2, "0");
3267
+ let year = parts[2];
3268
+ year = year.length === 2 ? `20${year}` : year.padStart(4, "0");
3269
+ if (isValidDate(day, month, year)) {
3270
+ return formatOutput(day, month, year);
3271
+ }
3272
+ return null;
3273
+ }
3274
+ if (isDateTime) {
3275
+ if (cleanInput.length === 9) {
3276
+ const day = cleanInput.slice(0, 2);
3277
+ const month = cleanInput.slice(2, 4);
3278
+ const year = cleanInput.slice(4, 8);
3279
+ const hour = cleanInput.slice(8, 9).padStart(2, "0");
3280
+ if (isValidDate(day, month, year) && isValidTime(hour)) {
3281
+ let result = moment(
3282
+ `${day}-${month}-${year} ${hour}:00:00`,
3283
+ "DD-MM-YYYY HH:mm:ss"
3284
+ );
3285
+ if (!result.isValid()) return null;
3286
+ result = result.subtract(7, "hours");
3287
+ return result.format(dateTimeFormat);
3288
+ }
3289
+ return null;
3290
+ }
3291
+ if (cleanInput.length === 10) {
3292
+ const day = cleanInput.slice(0, 2);
3293
+ const month = cleanInput.slice(2, 4);
3294
+ const year = cleanInput.slice(4, 8);
3295
+ const hour = cleanInput.slice(8, 10);
3296
+ if (isValidDate(day, month, year) && isValidTime(hour)) {
3297
+ let result = moment(
3298
+ `${day}-${month}-${year} ${hour}:00:00`,
3299
+ "DD-MM-YYYY HH:mm:ss"
3300
+ );
3301
+ if (!result.isValid()) return null;
3302
+ result = result.subtract(7, "hours");
3303
+ return result.format(dateTimeFormat);
3304
+ }
3305
+ return null;
3306
+ }
3307
+ if (cleanInput.length === 11) {
3308
+ const day = cleanInput.slice(0, 2);
3309
+ const month = cleanInput.slice(2, 4);
3310
+ const year = cleanInput.slice(4, 8);
3311
+ const hour = cleanInput.slice(8, 10);
3312
+ const minute = cleanInput.slice(10, 11).padStart(2, "0");
3313
+ if (isValidDate(day, month, year) && isValidTime(hour, minute)) {
3314
+ let result = moment(
3315
+ `${day}-${month}-${year} ${hour}:${minute}:00`,
3316
+ "DD-MM-YYYY HH:mm:ss"
3317
+ );
3318
+ if (!result.isValid()) return null;
3319
+ result = result.subtract(7, "hours");
3320
+ return result.format(dateTimeFormat);
3321
+ }
3322
+ return null;
3323
+ }
3324
+ if (cleanInput.length === 12) {
3325
+ const day = cleanInput.slice(0, 2);
3326
+ const month = cleanInput.slice(2, 4);
3327
+ const year = cleanInput.slice(4, 8);
3328
+ const hour = cleanInput.slice(8, 10);
3329
+ const minute = cleanInput.slice(10, 12);
3330
+ if (isValidDate(day, month, year) && isValidTime(hour, minute)) {
3331
+ let result = moment(
3332
+ `${day}-${month}-${year} ${hour}:${minute}:00`,
3333
+ "DD-MM-YYYY HH:mm:ss"
3334
+ );
3335
+ if (!result.isValid()) return null;
3336
+ result = result.subtract(7, "hours");
3337
+ return result.format(dateTimeFormat);
3338
+ }
3339
+ return null;
3340
+ }
3341
+ if (cleanInput.length === 13) {
3342
+ const day = cleanInput.slice(0, 2);
3343
+ const month = cleanInput.slice(2, 4);
3344
+ const year = cleanInput.slice(4, 8);
3345
+ const hour = cleanInput.slice(8, 10);
3346
+ const minute = cleanInput.slice(10, 12);
3347
+ const second = cleanInput.slice(12, 13).padStart(2, "0");
3348
+ if (isValidDate(day, month, year) && isValidTime(hour, minute, second)) {
3349
+ let result = moment(
3350
+ `${day}-${month}-${year} ${hour}:${minute}:${second}`,
3351
+ "DD-MM-YYYY HH:mm:ss"
3352
+ );
3353
+ if (!result.isValid()) return null;
3354
+ result = result.subtract(7, "hours");
3355
+ return result.format(dateTimeFormat);
3356
+ }
3357
+ return null;
3358
+ }
3359
+ if (cleanInput.length === 14) {
3360
+ const day = cleanInput.slice(0, 2);
3361
+ const month = cleanInput.slice(2, 4);
3362
+ const year = cleanInput.slice(4, 8);
3363
+ const hour = cleanInput.slice(8, 10);
3364
+ const minute = cleanInput.slice(10, 12);
3365
+ const second = cleanInput.slice(12, 14);
3366
+ if (isValidDate(day, month, year) && isValidTime(hour, minute, second)) {
3367
+ let result = moment(
3368
+ `${day}-${month}-${year} ${hour}:${minute}:${second}`,
3369
+ "DD-MM-YYYY HH:mm:ss"
3370
+ );
3371
+ if (!result.isValid()) return null;
3372
+ result = result.subtract(7, "hours");
3373
+ return result.format(dateTimeFormat);
3374
+ }
3375
+ return null;
3376
+ }
3377
+ }
3378
+ const len = cleanInput.length;
3379
+ if (len === 1 || len === 2) {
3380
+ const paddedDay = cleanInput.padStart(2, "0");
3381
+ if (isValidDate(paddedDay, currentMonth, currentYear)) {
3382
+ return formatOutput(paddedDay, currentMonth, currentYear);
3383
+ }
3384
+ return null;
3385
+ }
3386
+ if (len === 3) {
3387
+ const day = cleanInput.slice(0, 2);
3388
+ const month = cleanInput.slice(2, 3).padStart(2, "0");
3389
+ if (isValidDate(day, month, currentYear)) {
3390
+ return formatOutput(day, month, currentYear);
3391
+ }
3392
+ return null;
3393
+ }
3394
+ if (len === 6) {
3395
+ const day = cleanInput.slice(0, 2);
3396
+ const month = cleanInput.slice(2, 4);
3397
+ let year = cleanInput.slice(4, 6);
3398
+ year = `20${year}`;
3399
+ if (parseInt(month) > 12) {
3400
+ if (isValidDate(day, currentMonth, currentYear)) {
3401
+ return formatOutput(day, currentMonth, currentYear);
3402
+ }
3403
+ return null;
3404
+ }
3405
+ if (isValidDate(day, month, year)) {
3406
+ return formatOutput(day, month, year);
3407
+ }
3408
+ return null;
3409
+ }
3410
+ if (len === 7) {
3411
+ return null;
3412
+ }
3413
+ if (len === 8) {
3414
+ const day = cleanInput.slice(0, 2);
3415
+ const month = cleanInput.slice(2, 4);
3416
+ const year = cleanInput.slice(4, 8);
3417
+ if (isValidDate(day, month, year)) {
3418
+ return formatOutput(day, month, year);
3419
+ }
3420
+ return null;
3421
+ }
3422
+ if (len > 8 && !isDateTime) {
3423
+ return null;
3424
+ }
3425
+ return null;
3426
+ };
3427
+
3428
+ // src/utils/color.ts
3429
+ var generateTagColors = (name, id) => {
3430
+ const combined = name + id / 2;
3431
+ let hash2 = 0;
3432
+ for (let i = 0; i < combined.length; i++) {
3433
+ hash2 = combined.charCodeAt(i) + ((hash2 << 5) - hash2);
3434
+ }
3435
+ const r = hash2 >> 16 & 255;
3436
+ const g = hash2 >> 8 & 255;
3437
+ const b = hash2 & 255;
3438
+ const rNorm = r / 255;
3439
+ const gNorm = g / 255;
3440
+ const bNorm = b / 255;
3441
+ const max = Math.max(rNorm, gNorm, bNorm);
3442
+ const min = Math.min(rNorm, gNorm, bNorm);
3443
+ const delta = max - min;
3444
+ let h = 0;
3445
+ if (delta !== 0) {
3446
+ if (max === rNorm) h = (gNorm - bNorm) / delta % 6;
3447
+ else if (max === gNorm) h = (bNorm - rNorm) / delta + 2;
3448
+ else h = (rNorm - gNorm) / delta + 4;
3449
+ }
3450
+ h = Math.round(h * 60);
3451
+ if (h < 0) h += 360;
3452
+ const bgS = 0.35;
3453
+ const bgL = 0.92;
3454
+ const borderS = 0.45;
3455
+ const borderL = 0.78;
3456
+ const textS = 0.55;
3457
+ const textL = 0.32;
3458
+ const hslToRgb = (h2, s, l) => {
3459
+ const c = (1 - Math.abs(2 * l - 1)) * s;
3460
+ const x = c * (1 - Math.abs(h2 / 60 % 2 - 1));
3461
+ const m = l - c / 2;
3462
+ let r2 = 0, g2 = 0, b2 = 0;
3463
+ if (0 <= h2 && h2 < 60) [r2, g2, b2] = [c, x, 0];
3464
+ else if (60 <= h2 && h2 < 120) [r2, g2, b2] = [x, c, 0];
3465
+ else if (120 <= h2 && h2 < 180) [r2, g2, b2] = [0, c, x];
3466
+ else if (180 <= h2 && h2 < 240) [r2, g2, b2] = [0, x, c];
3467
+ else if (240 <= h2 && h2 < 300) [r2, g2, b2] = [x, 0, c];
3468
+ else [r2, g2, b2] = [c, 0, x];
3469
+ return `rgb(${Math.round((r2 + m) * 255)}, ${Math.round(
3470
+ (g2 + m) * 255
3471
+ )}, ${Math.round((b2 + m) * 255)})`;
3472
+ };
3473
+ return {
3474
+ background: hslToRgb(h, bgS, bgL),
3475
+ // nh?t nh?t
3476
+ border: hslToRgb(h, borderS, borderL),
3477
+ // d?m hon background
3478
+ textColor: hslToRgb(h, textS, textL)
3479
+ // d?m nh?t
3480
+ };
3481
+ };
3482
+
3483
+ // src/utils/constants.ts
3484
+ var COLORS = [
3485
+ {
3486
+ name: "no_color",
3487
+ color: "RGBA(230.1375,221.3625,221.3625,1)",
3488
+ id: 0
3489
+ },
3490
+ {
3491
+ name: "red",
3492
+ color: "rgba(255,155.5,155.5,1)",
3493
+ id: 1
3494
+ },
3495
+ {
3496
+ name: "orange",
3497
+ color: "RGBA(247.0375,198.06116071,152.4625,1)",
3498
+ id: 2
3499
+ },
3500
+ {
3501
+ name: "yellow",
3502
+ color: "RGBA(252.88960843, 226.89175248, 135.61039157,1)",
3503
+ id: 3
3504
+ },
3505
+ {
3506
+ name: "cyan",
3507
+ color: "RGBA(187.45210396, 215.03675558, 248.04789604,1)",
3508
+ id: 4
3509
+ },
3510
+ {
3511
+ name: "purple",
3512
+ color: "RGBA(216.79194664, 167.70805336, 203.91748283,1)",
3513
+ id: 5
3514
+ },
3515
+ {
3516
+ name: "almond",
3517
+ color: "RGBA(247.84539474, 213.9484835, 199.65460526,1)",
3518
+ id: 6
3519
+ },
3520
+ {
3521
+ name: "teal",
3522
+ color: "RGBA(136.6125, 224.8875, 218.94591346,1)",
3523
+ id: 7
3524
+ },
3525
+ {
3526
+ name: "blue",
3527
+ color: "RGBA(150.60535714, 165.68382711, 248.89464286,1)",
3528
+ id: 8
3529
+ },
3530
+ {
3531
+ name: "raspberry",
3532
+ color: "RGBA(254.94583333, 157.55416667, 203.95543194,1)",
3533
+ id: 9
3534
+ },
3535
+ {
3536
+ name: "green",
3537
+ color: "RGBA(182.62075688, 236.87924312, 189.81831118,1)",
3538
+ id: 10
3539
+ },
3540
+ {
3541
+ name: "violet",
3542
+ color: "RGBA(230.11575613, 219.41069277, 252.08930723,1)",
3543
+ id: 11
3544
+ }
3545
+ ];
3546
+ var DOTS = "...";
3547
+ var SearchType = {
3548
+ FILTER: "filter_by",
3549
+ SEARCH: "search_by",
3550
+ GROUP: "group_by"
3551
+ };
3552
+ var MAX_FILE_SIZE = 10 * 1024 * 1024;
3553
+ export {
3554
+ ACCEPT_TYPES,
3555
+ ALLOWED_EXTS,
3556
+ ALLOWED_MIME_TYPES,
3557
+ COLORS,
3558
+ DOTS,
3559
+ SearchType,
3560
+ checkIsImageLink,
3561
+ convertFloatToTime,
3562
+ convertTimeToFloat,
3563
+ formatFileSize,
3564
+ formatFloatNumber,
3565
+ formatNumberOnly,
3566
+ generateTagColors,
3567
+ getFileLabel,
3568
+ getPasswordMessage,
3569
+ isBase64Image,
3570
+ parseFormattedNumber,
3571
+ range,
3572
+ uppercaseFirstLetter,
3573
+ useFormatDate,
3574
+ validateAndParseDate,
3575
+ validateInput
3576
+ };