@pie-element/venn-classification 0.1.1-next.6 → 0.1.1-next.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/author.js +2 -0
  2. package/dist/author/index.d.ts +8 -0
  3. package/dist/author/index.js +3828 -888
  4. package/dist/author/index.js.map +1 -1
  5. package/dist/browser/VennClassification-BgmjHIWB.js +3616 -0
  6. package/dist/browser/VennClassification-BgmjHIWB.js.map +1 -0
  7. package/dist/browser/author/index.js +2509 -2403
  8. package/dist/browser/author/index.js.map +1 -1
  9. package/dist/browser/controller/index.js +2 -2
  10. package/dist/browser/controller-CmzKcNfc.js +1774 -0
  11. package/dist/browser/controller-CmzKcNfc.js.map +1 -0
  12. package/dist/browser/delivery/index.js +86 -28
  13. package/dist/browser/delivery/index.js.map +1 -1
  14. package/dist/controller/index.d.ts +21 -7
  15. package/dist/controller/index.js +2394 -49
  16. package/dist/controller/index.js.map +1 -1
  17. package/dist/controller/region.d.ts +2 -2
  18. package/dist/delivery/dnd.d.ts +9 -0
  19. package/dist/delivery/index.d.ts +2 -20
  20. package/dist/delivery/index.js +3746 -830
  21. package/dist/delivery/index.js.map +1 -1
  22. package/dist/delivery/layout.d.ts +104 -34
  23. package/dist/delivery/tile-accessible-name.d.ts +13 -1
  24. package/dist/i18n.d.ts +9 -0
  25. package/dist/index.iife.js +14 -17
  26. package/dist/index.js +2 -6804
  27. package/dist/runtime-support.js +5 -5
  28. package/dist/runtime-support.js.map +1 -1
  29. package/dist/types.d.ts +7 -0
  30. package/package.json +3 -4
  31. package/dist/browser/VennClassification-DCPzzIcj.js +0 -3386
  32. package/dist/browser/VennClassification-DCPzzIcj.js.map +0 -1
  33. package/dist/browser/controller-DGuLVZuv.js +0 -249
  34. package/dist/browser/controller-DGuLVZuv.js.map +0 -1
  35. package/dist/index.js.map +0 -1
@@ -1,13 +1,12 @@
1
1
  var defaults_default = {
2
2
  model: {
3
- id: "1",
4
- element: "venn-classification",
5
3
  prompt: "<p>Sort each tile into the correct region of the Venn diagram.</p>",
6
4
  promptEnabled: true,
7
5
  circles: [{ label: "Set A" }, { label: "Set B" }],
8
6
  tiles: [],
9
7
  regionLabels: {},
10
- scoringPolicy: "partialPerTile"
8
+ scoringPolicy: "partialPerTile",
9
+ teacherInstructionsEnabled: true
11
10
  },
12
11
  configuration: {
13
12
  prompt: {
@@ -21,8 +20,2352 @@ var defaults_default = {
21
20
  }
22
21
  };
23
22
  //#endregion
23
+ //#region ../../shared/translator/dist/en.js
24
+ var e$1 = {
25
+ translation: {
26
+ categorize: {
27
+ limitMaxChoicesPerCategory: "You've reached the limit of {{maxChoicesPerCategory}} responses per area. To add another response, one must first be removed.",
28
+ maxChoicesPerCategoryRestriction: "To change this value to {{maxChoicesPerCategory}}, each category must have {{maxChoicesPerCategory}} or fewer answer choice[s]."
29
+ },
30
+ ebsr: { part: "Part {{index}}" },
31
+ numberLine: {
32
+ addElementLimit_one: "You can only add {{count}} element",
33
+ addElementLimit_other: "You can only add {{count}} elements",
34
+ clearAll: "Clear all"
35
+ },
36
+ imageClozeAssociation: {
37
+ reachedLimit_one: "You’ve reached the limit of {{count}} response per area. To add another response, one must first be removed.",
38
+ reachedLimit_other: "Full"
39
+ },
40
+ drawingResponse: {
41
+ fillColor: "Fill color",
42
+ outlineColor: "Outline color",
43
+ noFill: "No fill",
44
+ lightblue: "Light blue",
45
+ lightyellow: "Light yellow",
46
+ red: "Red",
47
+ orange: "Orange",
48
+ yellow: "Yellow",
49
+ violet: "Violet",
50
+ blue: "Blue",
51
+ green: "Green",
52
+ white: "White",
53
+ black: "Black",
54
+ onDoubleClick: "Double click to edit this text. Press Enter to submit."
55
+ },
56
+ charting: {
57
+ addCategory: "Add category",
58
+ actions: "Actions",
59
+ add: "Add",
60
+ delete: "Delete",
61
+ newLabel: "New label",
62
+ reachedLimit_other: "There can't be more than {{count}} categories.",
63
+ keyLegend: {
64
+ incorrectAnswer: "Student incorrect answer",
65
+ correctAnswer: "Student correct answer",
66
+ correctKeyAnswer: "Answer key correct"
67
+ }
68
+ },
69
+ graphing: {
70
+ point: "Point",
71
+ circle: "Circle",
72
+ line: "Line",
73
+ parabola: "Parabola",
74
+ absolute: "Absolute Value",
75
+ exponential: "Exponential",
76
+ polygon: "Polygon",
77
+ ray: "Ray",
78
+ segment: "Segment",
79
+ sine: "Sine",
80
+ vector: "Vector",
81
+ label: "Label",
82
+ redo: "Redo",
83
+ reset: "Reset"
84
+ },
85
+ mathInline: { primaryCorrectWithAlternates: "Note: The answer shown above is the primary correct answer specified by the author for this item, but other answers may also be recognized as correct." },
86
+ mcPopulatedBlank: {
87
+ answerChoices: "Answer choices",
88
+ blankLabel: "blank",
89
+ emptyBlank: "(blank)",
90
+ blankPreSelectionHint: "The answer you choose will appear on the blank line above.",
91
+ correctAnswerSelected: "Correct answer selected",
92
+ incorrectAnswerSelected: "Incorrect answer selected",
93
+ selectedAnswerImage: "Selected answer image",
94
+ choiceImage: "Choice {{id}}",
95
+ clickToEnableAutoplay: "Click to enable audio autoplay",
96
+ audioResourceUnavailable: "Audio is enabled but no playable audio URL is configured.",
97
+ listen: "Listen",
98
+ listenSilentAlt: "Repeat instructions",
99
+ listenPlayingAlt: "Instructions are playing",
100
+ printAudio: "Audio:",
101
+ printTranscript: "Transcript:"
102
+ },
103
+ multipleChoice: {
104
+ minSelections: "Select at least {{minSelections}}.",
105
+ maxSelections_one: "Only {{maxSelections}} answer is allowed.",
106
+ maxSelections_other: "Only {{maxSelections}} answers are allowed.",
107
+ minmaxSelections_equal: "Select {{minSelections}}.",
108
+ minmaxSelections_range: "Select between {{minSelections}} and {{maxSelections}}."
109
+ },
110
+ selectText: {
111
+ correctAnswerSelected: "Correct",
112
+ correctAnswerNotSelected: "Correct Answer Not Selected",
113
+ incorrectSelection: "Incorrect Selection",
114
+ key: "Key"
115
+ },
116
+ simpleCloze: {
117
+ correctAnswerShown: "Correct answer",
118
+ correct: "Correct",
119
+ incorrect: "Incorrect",
120
+ unanswered: "No answer",
121
+ placeholder: "Enter your answer...",
122
+ answerInput: "Your answer",
123
+ printCorrectAnswer: "Correct answer:",
124
+ printAnswerBlank: "Answer blank"
125
+ },
126
+ vennClassification: {
127
+ tray: "Tiles to classify",
128
+ unknownTarget: "unknown",
129
+ cancelled: "Cancelled",
130
+ returnedToTray: "{{name}} returned to tray",
131
+ placedIn: "{{name}} placed in {{target}}",
132
+ pickedUp: "Picked up {{name}}",
133
+ pickedUpWithKeyboard: "Picked up {{name}}, drop target: {{target}}. Use arrow keys to choose a drop target, Enter to drop, Escape to cancel.",
134
+ dropTarget: "Drop target: {{target}}",
135
+ unsupportedCircles_one: "This diagram cannot be shown: it has {{count}} circle, and only {{supported}} are supported.",
136
+ unsupportedCircles_other: "This diagram cannot be shown: it has {{count}} circles, and only {{supported}} are supported.",
137
+ setNumber: "Set {{number}}",
138
+ regionOnly: "{{set}} only",
139
+ regionNeither: "Neither {{first}} nor {{second}}",
140
+ regionNoneOf: "None of {{sets}}",
141
+ regionAndSeparator: " and ",
142
+ tileFallbackName: "Tile",
143
+ tileNotPlaced: "not placed",
144
+ tileInRegion: "in {{region}}",
145
+ tileCorrect: "correct",
146
+ tileIncorrect: "incorrect"
147
+ }
148
+ },
149
+ common: {
150
+ undo: "Undo",
151
+ clearAll: "Clear all",
152
+ correct: "Correct",
153
+ incorrect: "Incorrect",
154
+ showCorrectAnswer: "Show correct answer",
155
+ hideCorrectAnswer: "Hide correct answer",
156
+ showTeacherInstructions: "Show Teacher Instructions",
157
+ hideTeacherInstructions: "Hide Teacher Instructions",
158
+ commonCorrectAnswerWithAlternates: "Note: The answer shown above is the most common correct answer for this item. One or more additional correct answers are also defined, and will also be recognized as correct.",
159
+ warning: "Warning",
160
+ showNote: "Show Note",
161
+ hideNote: "Hide Note",
162
+ cancel: "Cancel"
163
+ }
164
+ };
165
+ //#endregion
166
+ //#region ../../shared/translator/dist/es.js
167
+ var e = {
168
+ translation: {
169
+ categorize: {
170
+ limitMaxChoicesPerCategory: "Has alcanzado el límite de {{maxChoicesPerCategory}} respuestas por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.",
171
+ maxChoicesPerCategoryRestriction: "Para cambiar este valor a {{maxChoicesPerCategory}}, cada categoría debe tener {{maxChoicesPerCategory}} o menos opciones de respuesta"
172
+ },
173
+ ebsr: { part: "Parte {{index}}" },
174
+ numberLine: {
175
+ addElementLimit_one: "Solo puedes agregar {{count}} elemento",
176
+ addElementLimit_other: "Solo puedes agregar {{count}} elementos",
177
+ clearAll: "Borrar todo"
178
+ },
179
+ imageClozeAssociation: {
180
+ reachedLimit_one: "Has alcanzado el límite de {{count}} respuesta por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.",
181
+ reachedLimit_other: "Lleno"
182
+ },
183
+ drawingResponse: {
184
+ fillColor: "Color de relleno",
185
+ outlineColor: "Color del contorno",
186
+ noFill: "Sin relleno",
187
+ lightblue: "Azul claro",
188
+ lightyellow: "Amarillo claro",
189
+ red: "Rojo",
190
+ orange: "Naranja",
191
+ yellow: "Amarillo",
192
+ violet: "Violeta",
193
+ blue: "Azul",
194
+ green: "Verde",
195
+ white: "Blanco",
196
+ black: "Negro",
197
+ onDoubleClick: "Haz doble clic para revisar este texto. Presiona el botón de ingreso para enviar"
198
+ },
199
+ charting: {
200
+ addCategory: "Añadir categoría",
201
+ actions: "Acciones",
202
+ add: "Añadir",
203
+ delete: "Eliminar",
204
+ newLabel: "Nueva etiqueta",
205
+ reachedLimit_other: "No puede haber más de {{count}} categorías.",
206
+ keyLegend: {
207
+ incorrectAnswer: "Respuesta incorrecta del estudiante",
208
+ correctAnswer: "Respuesta correcta del estudiante",
209
+ correctKeyAnswer: "Clave de respuesta correcta"
210
+ }
211
+ },
212
+ graphing: {
213
+ point: "Punto",
214
+ circle: "Circulo",
215
+ line: "Línea",
216
+ parabola: "Parábola",
217
+ absolute: "Valor absoluto",
218
+ exponential: "Exponencial",
219
+ polygon: "Polígono",
220
+ ray: "Semirrecta",
221
+ segment: "Segmento ",
222
+ sine: "Seno",
223
+ vector: "Vector",
224
+ label: "Etiqueta",
225
+ redo: "Rehacer",
226
+ reset: "Reiniciar"
227
+ },
228
+ mathInline: { primaryCorrectWithAlternates: "Nota: La respuesta que se muestra arriba es la respuesta correcta principal especificada por el autor para esta pregunta, pero también se pueden reconocer otras respuestas como correctas." },
229
+ mcPopulatedBlank: {
230
+ answerChoices: "Opciones de respuesta",
231
+ blankLabel: "espacio en blanco",
232
+ emptyBlank: "(en blanco)",
233
+ blankPreSelectionHint: "La respuesta que elijas aparecerá en la línea en blanco de arriba.",
234
+ correctAnswerSelected: "Respuesta correcta seleccionada",
235
+ incorrectAnswerSelected: "Respuesta incorrecta seleccionada",
236
+ selectedAnswerImage: "Imagen de la respuesta seleccionada",
237
+ choiceImage: "Opción {{id}}",
238
+ clickToEnableAutoplay: "Haz clic para activar la reproducción automática del audio",
239
+ audioResourceUnavailable: "El audio está activado, pero no hay una URL de audio reproducible configurada.",
240
+ listen: "Escuchar",
241
+ listenSilentAlt: "Escuchar. Repetir las instrucciones.",
242
+ listenPlayingAlt: "Escuchar. Estas son las instrucciones.",
243
+ printAudio: "Audio:",
244
+ printTranscript: "Transcripción:"
245
+ },
246
+ multipleChoice: {
247
+ minSelections: "Seleccione al menos {{minSelections}}.",
248
+ maxSelections_one: "Sólo se permite {{maxSelections}} respuesta.",
249
+ maxSelections_other: "Sólo se permiten {{maxSelections}} respuestas.",
250
+ minmaxSelections_equal: "Seleccione {{minSelections}}.",
251
+ minmaxSelections_range: "Seleccione entre {{minSelections}} y {{maxSelections}}."
252
+ },
253
+ selectText: {
254
+ correctAnswerSelected: "Respuesta Correcta",
255
+ correctAnswerNotSelected: "Respuesta Correcta No Seleccionada",
256
+ incorrectSelection: "Selección Incorrecta",
257
+ key: "Clave"
258
+ },
259
+ simpleCloze: {
260
+ correctAnswerShown: "Respuesta correcta",
261
+ correct: "Correcto",
262
+ incorrect: "Incorrecto",
263
+ unanswered: "Sin respuesta",
264
+ placeholder: "Escribe tu respuesta...",
265
+ answerInput: "Tu respuesta",
266
+ printCorrectAnswer: "Respuesta correcta:",
267
+ printAnswerBlank: "Espacio para la respuesta"
268
+ },
269
+ vennClassification: {
270
+ tray: "Fichas para clasificar",
271
+ unknownTarget: "desconocido",
272
+ cancelled: "Cancelado",
273
+ returnedToTray: "Se devolvió {{name}} a la bandeja",
274
+ placedIn: "Se colocó {{name}} en {{target}}",
275
+ pickedUp: "Se tomó {{name}}",
276
+ pickedUpWithKeyboard: "Se tomó {{name}}, destino: {{target}}. Usa las flechas para elegir un destino, Enter para soltar y Escape para cancelar.",
277
+ dropTarget: "Destino: {{target}}",
278
+ unsupportedCircles_one: "No se puede mostrar este diagrama: tiene {{count}} círculo, y solo se admiten {{supported}}.",
279
+ unsupportedCircles_other: "No se puede mostrar este diagrama: tiene {{count}} círculos, y solo se admiten {{supported}}.",
280
+ setNumber: "Conjunto {{number}}",
281
+ regionOnly: "Solo {{set}}",
282
+ regionNeither: "Ni {{first}} ni {{second}}",
283
+ regionNoneOf: "Ninguno de {{sets}}",
284
+ regionAndSeparator: " y ",
285
+ tileFallbackName: "Ficha",
286
+ tileNotPlaced: "sin colocar",
287
+ tileInRegion: "en {{region}}",
288
+ tileCorrect: "correcta",
289
+ tileIncorrect: "incorrecta"
290
+ }
291
+ },
292
+ common: {
293
+ undo: "Deshacer",
294
+ clearAll: "Borrar todo",
295
+ correct: "Correcto",
296
+ incorrect: "Incorrecto",
297
+ showCorrectAnswer: "Mostrar respuesta correcta",
298
+ hideCorrectAnswer: "Ocultar respuesta correcta",
299
+ showTeacherInstructions: "Mostrar instrucciones para el maestro",
300
+ hideTeacherInstructions: "Ocultar instrucciones para el maestro",
301
+ commonCorrectAnswerWithAlternates: "Nota: La respuesta que se muestra arriba es la respuesta correcta más común para esta pregunta. También se definen una o más respuestas correctas adicionales, y también se reconocerán como correctas.",
302
+ warning: "Advertencia",
303
+ showNote: "Mostrar Nota",
304
+ hideNote: "Ocultar Nota",
305
+ cancel: "Cancelar"
306
+ }
307
+ };
308
+ //#endregion
309
+ //#region ../../../node_modules/.bun/i18next@25.10.10+1fb4c65d43e298b9/node_modules/i18next/dist/esm/i18next.js
310
+ var isString = (obj) => typeof obj === "string";
311
+ var defer = () => {
312
+ let res;
313
+ let rej;
314
+ const promise = new Promise((resolve, reject) => {
315
+ res = resolve;
316
+ rej = reject;
317
+ });
318
+ promise.resolve = res;
319
+ promise.reject = rej;
320
+ return promise;
321
+ };
322
+ var makeString = (object) => {
323
+ if (object == null) return "";
324
+ return "" + object;
325
+ };
326
+ var copy = (a, s, t) => {
327
+ a.forEach((m) => {
328
+ if (s[m]) t[m] = s[m];
329
+ });
330
+ };
331
+ var lastOfPathSeparatorRegExp = /###/g;
332
+ var cleanKey = (key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
333
+ var canNotTraverseDeeper = (object) => !object || isString(object);
334
+ var getLastOfPath = (object, path, Empty) => {
335
+ const stack = !isString(path) ? path : path.split(".");
336
+ let stackIndex = 0;
337
+ while (stackIndex < stack.length - 1) {
338
+ if (canNotTraverseDeeper(object)) return {};
339
+ const key = cleanKey(stack[stackIndex]);
340
+ if (!object[key] && Empty) object[key] = new Empty();
341
+ if (Object.prototype.hasOwnProperty.call(object, key)) object = object[key];
342
+ else object = {};
343
+ ++stackIndex;
344
+ }
345
+ if (canNotTraverseDeeper(object)) return {};
346
+ return {
347
+ obj: object,
348
+ k: cleanKey(stack[stackIndex])
349
+ };
350
+ };
351
+ var setPath = (object, path, newValue) => {
352
+ const { obj, k } = getLastOfPath(object, path, Object);
353
+ if (obj !== void 0 || path.length === 1) {
354
+ obj[k] = newValue;
355
+ return;
356
+ }
357
+ let e = path[path.length - 1];
358
+ let p = path.slice(0, path.length - 1);
359
+ let last = getLastOfPath(object, p, Object);
360
+ while (last.obj === void 0 && p.length) {
361
+ e = `${p[p.length - 1]}.${e}`;
362
+ p = p.slice(0, p.length - 1);
363
+ last = getLastOfPath(object, p, Object);
364
+ if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") last.obj = void 0;
365
+ }
366
+ last.obj[`${last.k}.${e}`] = newValue;
367
+ };
368
+ var pushPath = (object, path, newValue, concat) => {
369
+ const { obj, k } = getLastOfPath(object, path, Object);
370
+ obj[k] = obj[k] || [];
371
+ obj[k].push(newValue);
372
+ };
373
+ var getPath = (object, path) => {
374
+ const { obj, k } = getLastOfPath(object, path);
375
+ if (!obj) return void 0;
376
+ if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0;
377
+ return obj[k];
378
+ };
379
+ var getPathWithDefaults = (data, defaultData, key) => {
380
+ const value = getPath(data, key);
381
+ if (value !== void 0) return value;
382
+ return getPath(defaultData, key);
383
+ };
384
+ var deepExtend = (target, source, overwrite) => {
385
+ for (const prop in source) if (prop !== "__proto__" && prop !== "constructor") if (prop in target) if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
386
+ if (overwrite) target[prop] = source[prop];
387
+ } else deepExtend(target[prop], source[prop], overwrite);
388
+ else target[prop] = source[prop];
389
+ return target;
390
+ };
391
+ var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
392
+ var _entityMap = {
393
+ "&": "&amp;",
394
+ "<": "&lt;",
395
+ ">": "&gt;",
396
+ "\"": "&quot;",
397
+ "'": "&#39;",
398
+ "/": "&#x2F;"
399
+ };
400
+ var escape = (data) => {
401
+ if (isString(data)) return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
402
+ return data;
403
+ };
404
+ var RegExpCache = class {
405
+ constructor(capacity) {
406
+ this.capacity = capacity;
407
+ this.regExpMap = /* @__PURE__ */ new Map();
408
+ this.regExpQueue = [];
409
+ }
410
+ getRegExp(pattern) {
411
+ const regExpFromCache = this.regExpMap.get(pattern);
412
+ if (regExpFromCache !== void 0) return regExpFromCache;
413
+ const regExpNew = new RegExp(pattern);
414
+ if (this.regExpQueue.length === this.capacity) this.regExpMap.delete(this.regExpQueue.shift());
415
+ this.regExpMap.set(pattern, regExpNew);
416
+ this.regExpQueue.push(pattern);
417
+ return regExpNew;
418
+ }
419
+ };
420
+ var chars = [
421
+ " ",
422
+ ",",
423
+ "?",
424
+ "!",
425
+ ";"
426
+ ];
427
+ var looksLikeObjectPathRegExpCache = new RegExpCache(20);
428
+ var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
429
+ nsSeparator = nsSeparator || "";
430
+ keySeparator = keySeparator || "";
431
+ const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
432
+ if (possibleChars.length === 0) return true;
433
+ const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
434
+ let matched = !r.test(key);
435
+ if (!matched) {
436
+ const ki = key.indexOf(keySeparator);
437
+ if (ki > 0 && !r.test(key.substring(0, ki))) matched = true;
438
+ }
439
+ return matched;
440
+ };
441
+ var deepFind = (obj, path, keySeparator = ".") => {
442
+ if (!obj) return void 0;
443
+ if (obj[path]) {
444
+ if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0;
445
+ return obj[path];
446
+ }
447
+ const tokens = path.split(keySeparator);
448
+ let current = obj;
449
+ for (let i = 0; i < tokens.length;) {
450
+ if (!current || typeof current !== "object") return;
451
+ let next;
452
+ let nextPath = "";
453
+ for (let j = i; j < tokens.length; ++j) {
454
+ if (j !== i) nextPath += keySeparator;
455
+ nextPath += tokens[j];
456
+ next = current[nextPath];
457
+ if (next !== void 0) {
458
+ if ([
459
+ "string",
460
+ "number",
461
+ "boolean"
462
+ ].indexOf(typeof next) > -1 && j < tokens.length - 1) continue;
463
+ i += j - i + 1;
464
+ break;
465
+ }
466
+ }
467
+ current = next;
468
+ }
469
+ return current;
470
+ };
471
+ var getCleanedCode = (code) => code?.replace(/_/g, "-");
472
+ var consoleLogger = {
473
+ type: "logger",
474
+ log(args) {
475
+ this.output("log", args);
476
+ },
477
+ warn(args) {
478
+ this.output("warn", args);
479
+ },
480
+ error(args) {
481
+ this.output("error", args);
482
+ },
483
+ output(type, args) {
484
+ console?.[type]?.apply?.(console, args);
485
+ }
486
+ };
487
+ var baseLogger = new class Logger {
488
+ constructor(concreteLogger, options = {}) {
489
+ this.init(concreteLogger, options);
490
+ }
491
+ init(concreteLogger, options = {}) {
492
+ this.prefix = options.prefix || "i18next:";
493
+ this.logger = concreteLogger || consoleLogger;
494
+ this.options = options;
495
+ this.debug = options.debug;
496
+ }
497
+ log(...args) {
498
+ return this.forward(args, "log", "", true);
499
+ }
500
+ warn(...args) {
501
+ return this.forward(args, "warn", "", true);
502
+ }
503
+ error(...args) {
504
+ return this.forward(args, "error", "");
505
+ }
506
+ deprecate(...args) {
507
+ return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
508
+ }
509
+ forward(args, lvl, prefix, debugOnly) {
510
+ if (debugOnly && !this.debug) return null;
511
+ if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
512
+ return this.logger[lvl](args);
513
+ }
514
+ create(moduleName) {
515
+ return new Logger(this.logger, {
516
+ prefix: `${this.prefix}:${moduleName}:`,
517
+ ...this.options
518
+ });
519
+ }
520
+ clone(options) {
521
+ options = options || this.options;
522
+ options.prefix = options.prefix || this.prefix;
523
+ return new Logger(this.logger, options);
524
+ }
525
+ }();
526
+ var EventEmitter = class {
527
+ constructor() {
528
+ this.observers = {};
529
+ }
530
+ on(events, listener) {
531
+ events.split(" ").forEach((event) => {
532
+ if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
533
+ const numListeners = this.observers[event].get(listener) || 0;
534
+ this.observers[event].set(listener, numListeners + 1);
535
+ });
536
+ return this;
537
+ }
538
+ off(event, listener) {
539
+ if (!this.observers[event]) return;
540
+ if (!listener) {
541
+ delete this.observers[event];
542
+ return;
543
+ }
544
+ this.observers[event].delete(listener);
545
+ }
546
+ emit(event, ...args) {
547
+ if (this.observers[event]) Array.from(this.observers[event].entries()).forEach(([observer, numTimesAdded]) => {
548
+ for (let i = 0; i < numTimesAdded; i++) observer(...args);
549
+ });
550
+ if (this.observers["*"]) Array.from(this.observers["*"].entries()).forEach(([observer, numTimesAdded]) => {
551
+ for (let i = 0; i < numTimesAdded; i++) observer.apply(observer, [event, ...args]);
552
+ });
553
+ }
554
+ };
555
+ var ResourceStore = class extends EventEmitter {
556
+ constructor(data, options = {
557
+ ns: ["translation"],
558
+ defaultNS: "translation"
559
+ }) {
560
+ super();
561
+ this.data = data || {};
562
+ this.options = options;
563
+ if (this.options.keySeparator === void 0) this.options.keySeparator = ".";
564
+ if (this.options.ignoreJSONStructure === void 0) this.options.ignoreJSONStructure = true;
565
+ }
566
+ addNamespaces(ns) {
567
+ if (this.options.ns.indexOf(ns) < 0) this.options.ns.push(ns);
568
+ }
569
+ removeNamespaces(ns) {
570
+ const index = this.options.ns.indexOf(ns);
571
+ if (index > -1) this.options.ns.splice(index, 1);
572
+ }
573
+ getResource(lng, ns, key, options = {}) {
574
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
575
+ const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
576
+ let path;
577
+ if (lng.indexOf(".") > -1) path = lng.split(".");
578
+ else {
579
+ path = [lng, ns];
580
+ if (key) if (Array.isArray(key)) path.push(...key);
581
+ else if (isString(key) && keySeparator) path.push(...key.split(keySeparator));
582
+ else path.push(key);
583
+ }
584
+ const result = getPath(this.data, path);
585
+ if (!result && !ns && !key && lng.indexOf(".") > -1) {
586
+ lng = path[0];
587
+ ns = path[1];
588
+ key = path.slice(2).join(".");
589
+ }
590
+ if (result || !ignoreJSONStructure || !isString(key)) return result;
591
+ return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
592
+ }
593
+ addResource(lng, ns, key, value, options = { silent: false }) {
594
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
595
+ let path = [lng, ns];
596
+ if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
597
+ if (lng.indexOf(".") > -1) {
598
+ path = lng.split(".");
599
+ value = ns;
600
+ ns = path[1];
601
+ }
602
+ this.addNamespaces(ns);
603
+ setPath(this.data, path, value);
604
+ if (!options.silent) this.emit("added", lng, ns, key, value);
605
+ }
606
+ addResources(lng, ns, resources, options = { silent: false }) {
607
+ for (const m in resources) if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], { silent: true });
608
+ if (!options.silent) this.emit("added", lng, ns, resources);
609
+ }
610
+ addResourceBundle(lng, ns, resources, deep, overwrite, options = {
611
+ silent: false,
612
+ skipCopy: false
613
+ }) {
614
+ let path = [lng, ns];
615
+ if (lng.indexOf(".") > -1) {
616
+ path = lng.split(".");
617
+ deep = resources;
618
+ resources = ns;
619
+ ns = path[1];
620
+ }
621
+ this.addNamespaces(ns);
622
+ let pack = getPath(this.data, path) || {};
623
+ if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
624
+ if (deep) deepExtend(pack, resources, overwrite);
625
+ else pack = {
626
+ ...pack,
627
+ ...resources
628
+ };
629
+ setPath(this.data, path, pack);
630
+ if (!options.silent) this.emit("added", lng, ns, resources);
631
+ }
632
+ removeResourceBundle(lng, ns) {
633
+ if (this.hasResourceBundle(lng, ns)) delete this.data[lng][ns];
634
+ this.removeNamespaces(ns);
635
+ this.emit("removed", lng, ns);
636
+ }
637
+ hasResourceBundle(lng, ns) {
638
+ return this.getResource(lng, ns) !== void 0;
639
+ }
640
+ getResourceBundle(lng, ns) {
641
+ if (!ns) ns = this.options.defaultNS;
642
+ return this.getResource(lng, ns);
643
+ }
644
+ getDataByLanguage(lng) {
645
+ return this.data[lng];
646
+ }
647
+ hasLanguageSomeTranslations(lng) {
648
+ const data = this.getDataByLanguage(lng);
649
+ return !!(data && Object.keys(data) || []).find((v) => data[v] && Object.keys(data[v]).length > 0);
650
+ }
651
+ toJSON() {
652
+ return this.data;
653
+ }
654
+ };
655
+ var postProcessor = {
656
+ processors: {},
657
+ addPostProcessor(module) {
658
+ this.processors[module.name] = module;
659
+ },
660
+ handle(processors, value, key, options, translator) {
661
+ processors.forEach((processor) => {
662
+ value = this.processors[processor]?.process(value, key, options, translator) ?? value;
663
+ });
664
+ return value;
665
+ }
666
+ };
667
+ var PATH_KEY = Symbol("i18next/PATH_KEY");
668
+ function createProxy() {
669
+ const state = [];
670
+ const handler = Object.create(null);
671
+ let proxy;
672
+ handler.get = (target, key) => {
673
+ proxy?.revoke?.();
674
+ if (key === PATH_KEY) return state;
675
+ state.push(key);
676
+ proxy = Proxy.revocable(target, handler);
677
+ return proxy.proxy;
678
+ };
679
+ return Proxy.revocable(Object.create(null), handler).proxy;
680
+ }
681
+ function keysFromSelector(selector, opts) {
682
+ const { [PATH_KEY]: path } = selector(createProxy());
683
+ const keySeparator = opts?.keySeparator ?? ".";
684
+ const nsSeparator = opts?.nsSeparator ?? ":";
685
+ if (path.length > 1 && nsSeparator) {
686
+ const ns = opts?.ns;
687
+ const nsArray = Array.isArray(ns) ? ns : null;
688
+ if (nsArray && nsArray.length > 1 && nsArray.slice(1).includes(path[0])) return `${path[0]}${nsSeparator}${path.slice(1).join(keySeparator)}`;
689
+ }
690
+ return path.join(keySeparator);
691
+ }
692
+ var checkedLoadedFor = {};
693
+ var shouldHandleAsObject = (res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number";
694
+ var Translator = class Translator extends EventEmitter {
695
+ constructor(services, options = {}) {
696
+ super();
697
+ copy([
698
+ "resourceStore",
699
+ "languageUtils",
700
+ "pluralResolver",
701
+ "interpolator",
702
+ "backendConnector",
703
+ "i18nFormat",
704
+ "utils"
705
+ ], services, this);
706
+ this.options = options;
707
+ if (this.options.keySeparator === void 0) this.options.keySeparator = ".";
708
+ this.logger = baseLogger.create("translator");
709
+ }
710
+ changeLanguage(lng) {
711
+ if (lng) this.language = lng;
712
+ }
713
+ exists(key, o = { interpolation: {} }) {
714
+ const opt = { ...o };
715
+ if (key == null) return false;
716
+ const resolved = this.resolve(key, opt);
717
+ if (resolved?.res === void 0) return false;
718
+ const isObject = shouldHandleAsObject(resolved.res);
719
+ if (opt.returnObjects === false && isObject) return false;
720
+ return true;
721
+ }
722
+ extractFromKey(key, opt) {
723
+ let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
724
+ if (nsSeparator === void 0) nsSeparator = ":";
725
+ const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
726
+ let namespaces = opt.ns || this.options.defaultNS || [];
727
+ const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
728
+ const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
729
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
730
+ const m = key.match(this.interpolator.nestingRegexp);
731
+ if (m && m.length > 0) return {
732
+ key,
733
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
734
+ };
735
+ const parts = key.split(nsSeparator);
736
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
737
+ key = parts.join(keySeparator);
738
+ }
739
+ return {
740
+ key,
741
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
742
+ };
743
+ }
744
+ translate(keys, o, lastKey) {
745
+ let opt = typeof o === "object" ? { ...o } : o;
746
+ if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) opt = this.options.overloadTranslationOptionHandler(arguments);
747
+ if (typeof opt === "object") opt = { ...opt };
748
+ if (!opt) opt = {};
749
+ if (keys == null) return "";
750
+ if (typeof keys === "function") keys = keysFromSelector(keys, {
751
+ ...this.options,
752
+ ...opt
753
+ });
754
+ if (!Array.isArray(keys)) keys = [String(keys)];
755
+ keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
756
+ ...this.options,
757
+ ...opt
758
+ }) : String(k));
759
+ const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails;
760
+ const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
761
+ const { key, namespaces } = this.extractFromKey(keys[keys.length - 1], opt);
762
+ const namespace = namespaces[namespaces.length - 1];
763
+ let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
764
+ if (nsSeparator === void 0) nsSeparator = ":";
765
+ const lng = opt.lng || this.language;
766
+ const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
767
+ if (lng?.toLowerCase() === "cimode") {
768
+ if (appendNamespaceToCIMode) {
769
+ if (returnDetails) return {
770
+ res: `${namespace}${nsSeparator}${key}`,
771
+ usedKey: key,
772
+ exactUsedKey: key,
773
+ usedLng: lng,
774
+ usedNS: namespace,
775
+ usedParams: this.getUsedParamsDetails(opt)
776
+ };
777
+ return `${namespace}${nsSeparator}${key}`;
778
+ }
779
+ if (returnDetails) return {
780
+ res: key,
781
+ usedKey: key,
782
+ exactUsedKey: key,
783
+ usedLng: lng,
784
+ usedNS: namespace,
785
+ usedParams: this.getUsedParamsDetails(opt)
786
+ };
787
+ return key;
788
+ }
789
+ const resolved = this.resolve(keys, opt);
790
+ let res = resolved?.res;
791
+ const resUsedKey = resolved?.usedKey || key;
792
+ const resExactUsedKey = resolved?.exactUsedKey || key;
793
+ const noObject = [
794
+ "[object Number]",
795
+ "[object Function]",
796
+ "[object RegExp]"
797
+ ];
798
+ const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays;
799
+ const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
800
+ const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
801
+ const hasDefaultValue = Translator.hasDefaultValue(opt);
802
+ const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : "";
803
+ const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, { ordinal: false }) : "";
804
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
805
+ const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
806
+ let resForObjHndl = res;
807
+ if (handleAsObjectInI18nFormat && !res && hasDefaultValue) resForObjHndl = defaultValue;
808
+ const handleAsObject = shouldHandleAsObject(resForObjHndl);
809
+ const resType = Object.prototype.toString.apply(resForObjHndl);
810
+ if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
811
+ if (!opt.returnObjects && !this.options.returnObjects) {
812
+ if (!this.options.returnedObjectHandler) this.logger.warn("accessing an object - but returnObjects options is not enabled!");
813
+ const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
814
+ ...opt,
815
+ ns: namespaces
816
+ }) : `key '${key} (${this.language})' returned an object instead of string.`;
817
+ if (returnDetails) {
818
+ resolved.res = r;
819
+ resolved.usedParams = this.getUsedParamsDetails(opt);
820
+ return resolved;
821
+ }
822
+ return r;
823
+ }
824
+ if (keySeparator) {
825
+ const resTypeIsArray = Array.isArray(resForObjHndl);
826
+ const copy = resTypeIsArray ? [] : {};
827
+ const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
828
+ for (const m in resForObjHndl) if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
829
+ const deepKey = `${newKeyToUse}${keySeparator}${m}`;
830
+ if (hasDefaultValue && !res) copy[m] = this.translate(deepKey, {
831
+ ...opt,
832
+ defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0,
833
+ joinArrays: false,
834
+ ns: namespaces
835
+ });
836
+ else copy[m] = this.translate(deepKey, {
837
+ ...opt,
838
+ joinArrays: false,
839
+ ns: namespaces
840
+ });
841
+ if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
842
+ }
843
+ res = copy;
844
+ }
845
+ } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
846
+ res = res.join(joinArrays);
847
+ if (res) res = this.extendTranslation(res, keys, opt, lastKey);
848
+ } else {
849
+ let usedDefault = false;
850
+ let usedKey = false;
851
+ if (!this.isValidLookup(res) && hasDefaultValue) {
852
+ usedDefault = true;
853
+ res = defaultValue;
854
+ }
855
+ if (!this.isValidLookup(res)) {
856
+ usedKey = true;
857
+ res = key;
858
+ }
859
+ const resForMissing = (opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey) && usedKey ? void 0 : res;
860
+ const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
861
+ if (usedKey || usedDefault || updateMissing) {
862
+ this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
863
+ if (keySeparator) {
864
+ const fk = this.resolve(key, {
865
+ ...opt,
866
+ keySeparator: false
867
+ });
868
+ 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.");
869
+ }
870
+ let lngs = [];
871
+ const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
872
+ if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) for (let i = 0; i < fallbackLngs.length; i++) lngs.push(fallbackLngs[i]);
873
+ else if (this.options.saveMissingTo === "all") lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
874
+ else lngs.push(opt.lng || this.language);
875
+ const send = (l, k, specificDefaultValue) => {
876
+ const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
877
+ if (this.options.missingKeyHandler) this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
878
+ else if (this.backendConnector?.saveMissing) this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
879
+ this.emit("missingKey", l, namespace, k, res);
880
+ };
881
+ if (this.options.saveMissing) if (this.options.saveMissingPlurals && needsPluralHandling) lngs.forEach((language) => {
882
+ const suffixes = this.pluralResolver.getSuffixes(language, opt);
883
+ if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) suffixes.push(`${this.options.pluralSeparator}zero`);
884
+ suffixes.forEach((suffix) => {
885
+ send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
886
+ });
887
+ });
888
+ else send(lngs, key, defaultValue);
889
+ }
890
+ res = this.extendTranslation(res, keys, opt, resolved, lastKey);
891
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}${nsSeparator}${key}`;
892
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : void 0, opt);
893
+ }
894
+ if (returnDetails) {
895
+ resolved.res = res;
896
+ resolved.usedParams = this.getUsedParamsDetails(opt);
897
+ return resolved;
898
+ }
899
+ return res;
900
+ }
901
+ extendTranslation(res, key, opt, resolved, lastKey) {
902
+ if (this.i18nFormat?.parse) res = this.i18nFormat.parse(res, {
903
+ ...this.options.interpolation.defaultVariables,
904
+ ...opt
905
+ }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, { resolved });
906
+ else if (!opt.skipInterpolation) {
907
+ if (opt.interpolation) this.interpolator.init({
908
+ ...opt,
909
+ interpolation: {
910
+ ...this.options.interpolation,
911
+ ...opt.interpolation
912
+ }
913
+ });
914
+ const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
915
+ let nestBef;
916
+ if (skipOnVariables) {
917
+ const nb = res.match(this.interpolator.nestingRegexp);
918
+ nestBef = nb && nb.length;
919
+ }
920
+ let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
921
+ if (this.options.interpolation.defaultVariables) data = {
922
+ ...this.options.interpolation.defaultVariables,
923
+ ...data
924
+ };
925
+ res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
926
+ if (skipOnVariables) {
927
+ const na = res.match(this.interpolator.nestingRegexp);
928
+ const nestAft = na && na.length;
929
+ if (nestBef < nestAft) opt.nest = false;
930
+ }
931
+ if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
932
+ if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
933
+ if (lastKey?.[0] === args[0] && !opt.context) {
934
+ this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
935
+ return null;
936
+ }
937
+ return this.translate(...args, key);
938
+ }, opt);
939
+ if (opt.interpolation) this.interpolator.reset();
940
+ }
941
+ const postProcess = opt.postProcess || this.options.postProcess;
942
+ const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
943
+ if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
944
+ i18nResolved: {
945
+ ...resolved,
946
+ usedParams: this.getUsedParamsDetails(opt)
947
+ },
948
+ ...opt
949
+ } : opt, this);
950
+ return res;
951
+ }
952
+ resolve(keys, opt = {}) {
953
+ let found;
954
+ let usedKey;
955
+ let exactUsedKey;
956
+ let usedLng;
957
+ let usedNS;
958
+ if (isString(keys)) keys = [keys];
959
+ if (Array.isArray(keys)) keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
960
+ ...this.options,
961
+ ...opt
962
+ }) : k);
963
+ keys.forEach((k) => {
964
+ if (this.isValidLookup(found)) return;
965
+ const extracted = this.extractFromKey(k, opt);
966
+ const key = extracted.key;
967
+ usedKey = key;
968
+ let namespaces = extracted.namespaces;
969
+ if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
970
+ const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
971
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
972
+ const needsContextHandling = opt.context !== void 0 && (isString(opt.context) || typeof opt.context === "number") && opt.context !== "";
973
+ const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
974
+ namespaces.forEach((ns) => {
975
+ if (this.isValidLookup(found)) return;
976
+ usedNS = ns;
977
+ if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
978
+ checkedLoadedFor[`${codes[0]}-${ns}`] = true;
979
+ 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!!!");
980
+ }
981
+ codes.forEach((code) => {
982
+ if (this.isValidLookup(found)) return;
983
+ usedLng = code;
984
+ const finalKeys = [key];
985
+ if (this.i18nFormat?.addLookupKeys) this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
986
+ else {
987
+ let pluralSuffix;
988
+ if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
989
+ const zeroSuffix = `${this.options.pluralSeparator}zero`;
990
+ const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
991
+ if (needsPluralHandling) {
992
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
993
+ finalKeys.push(key + pluralSuffix);
994
+ if (needsZeroSuffixLookup) finalKeys.push(key + zeroSuffix);
995
+ }
996
+ if (needsContextHandling) {
997
+ const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`;
998
+ finalKeys.push(contextKey);
999
+ if (needsPluralHandling) {
1000
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
1001
+ finalKeys.push(contextKey + pluralSuffix);
1002
+ if (needsZeroSuffixLookup) finalKeys.push(contextKey + zeroSuffix);
1003
+ }
1004
+ }
1005
+ }
1006
+ let possibleKey;
1007
+ while (possibleKey = finalKeys.pop()) if (!this.isValidLookup(found)) {
1008
+ exactUsedKey = possibleKey;
1009
+ found = this.getResource(code, ns, possibleKey, opt);
1010
+ }
1011
+ });
1012
+ });
1013
+ });
1014
+ return {
1015
+ res: found,
1016
+ usedKey,
1017
+ exactUsedKey,
1018
+ usedLng,
1019
+ usedNS
1020
+ };
1021
+ }
1022
+ isValidLookup(res) {
1023
+ return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
1024
+ }
1025
+ getResource(code, ns, key, options = {}) {
1026
+ if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
1027
+ return this.resourceStore.getResource(code, ns, key, options);
1028
+ }
1029
+ getUsedParamsDetails(options = {}) {
1030
+ const optionsKeys = [
1031
+ "defaultValue",
1032
+ "ordinal",
1033
+ "context",
1034
+ "replace",
1035
+ "lng",
1036
+ "lngs",
1037
+ "fallbackLng",
1038
+ "ns",
1039
+ "keySeparator",
1040
+ "nsSeparator",
1041
+ "returnObjects",
1042
+ "returnDetails",
1043
+ "joinArrays",
1044
+ "postProcess",
1045
+ "interpolation"
1046
+ ];
1047
+ const useOptionsReplaceForData = options.replace && !isString(options.replace);
1048
+ let data = useOptionsReplaceForData ? options.replace : options;
1049
+ if (useOptionsReplaceForData && typeof options.count !== "undefined") data.count = options.count;
1050
+ if (this.options.interpolation.defaultVariables) data = {
1051
+ ...this.options.interpolation.defaultVariables,
1052
+ ...data
1053
+ };
1054
+ if (!useOptionsReplaceForData) {
1055
+ data = { ...data };
1056
+ for (const key of optionsKeys) delete data[key];
1057
+ }
1058
+ return data;
1059
+ }
1060
+ static hasDefaultValue(options) {
1061
+ const prefix = "defaultValue";
1062
+ for (const option in options) if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, 12) && void 0 !== options[option]) return true;
1063
+ return false;
1064
+ }
1065
+ };
1066
+ var LanguageUtil = class {
1067
+ constructor(options) {
1068
+ this.options = options;
1069
+ this.supportedLngs = this.options.supportedLngs || false;
1070
+ this.logger = baseLogger.create("languageUtils");
1071
+ }
1072
+ getScriptPartFromCode(code) {
1073
+ code = getCleanedCode(code);
1074
+ if (!code || code.indexOf("-") < 0) return null;
1075
+ const p = code.split("-");
1076
+ if (p.length === 2) return null;
1077
+ p.pop();
1078
+ if (p[p.length - 1].toLowerCase() === "x") return null;
1079
+ return this.formatLanguageCode(p.join("-"));
1080
+ }
1081
+ getLanguagePartFromCode(code) {
1082
+ code = getCleanedCode(code);
1083
+ if (!code || code.indexOf("-") < 0) return code;
1084
+ const p = code.split("-");
1085
+ return this.formatLanguageCode(p[0]);
1086
+ }
1087
+ formatLanguageCode(code) {
1088
+ if (isString(code) && code.indexOf("-") > -1) {
1089
+ let formattedCode;
1090
+ try {
1091
+ formattedCode = Intl.getCanonicalLocales(code)[0];
1092
+ } catch (e) {}
1093
+ if (formattedCode && this.options.lowerCaseLng) formattedCode = formattedCode.toLowerCase();
1094
+ if (formattedCode) return formattedCode;
1095
+ if (this.options.lowerCaseLng) return code.toLowerCase();
1096
+ return code;
1097
+ }
1098
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1099
+ }
1100
+ isSupportedCode(code) {
1101
+ if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) code = this.getLanguagePartFromCode(code);
1102
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1103
+ }
1104
+ getBestMatchFromCodes(codes) {
1105
+ if (!codes) return null;
1106
+ let found;
1107
+ codes.forEach((code) => {
1108
+ if (found) return;
1109
+ const cleanedLng = this.formatLanguageCode(code);
1110
+ if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
1111
+ });
1112
+ if (!found && this.options.supportedLngs) codes.forEach((code) => {
1113
+ if (found) return;
1114
+ const lngScOnly = this.getScriptPartFromCode(code);
1115
+ if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
1116
+ const lngOnly = this.getLanguagePartFromCode(code);
1117
+ if (this.isSupportedCode(lngOnly)) return found = lngOnly;
1118
+ found = this.options.supportedLngs.find((supportedLng) => {
1119
+ if (supportedLng === lngOnly) return supportedLng;
1120
+ if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
1121
+ if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
1122
+ if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
1123
+ });
1124
+ });
1125
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1126
+ return found;
1127
+ }
1128
+ getFallbackCodes(fallbacks, code) {
1129
+ if (!fallbacks) return [];
1130
+ if (typeof fallbacks === "function") fallbacks = fallbacks(code);
1131
+ if (isString(fallbacks)) fallbacks = [fallbacks];
1132
+ if (Array.isArray(fallbacks)) return fallbacks;
1133
+ if (!code) return fallbacks.default || [];
1134
+ let found = fallbacks[code];
1135
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1136
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
1137
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1138
+ if (!found) found = fallbacks.default;
1139
+ return found || [];
1140
+ }
1141
+ toResolveHierarchy(code, fallbackCode) {
1142
+ const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1143
+ const codes = [];
1144
+ const addCode = (c) => {
1145
+ if (!c) return;
1146
+ if (this.isSupportedCode(c)) codes.push(c);
1147
+ else this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1148
+ };
1149
+ if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
1150
+ if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
1151
+ if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
1152
+ if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
1153
+ } else if (isString(code)) addCode(this.formatLanguageCode(code));
1154
+ fallbackCodes.forEach((fc) => {
1155
+ if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
1156
+ });
1157
+ return codes;
1158
+ }
1159
+ };
1160
+ var suffixesOrder = {
1161
+ zero: 0,
1162
+ one: 1,
1163
+ two: 2,
1164
+ few: 3,
1165
+ many: 4,
1166
+ other: 5
1167
+ };
1168
+ var dummyRule = {
1169
+ select: (count) => count === 1 ? "one" : "other",
1170
+ resolvedOptions: () => ({ pluralCategories: ["one", "other"] })
1171
+ };
1172
+ var PluralResolver = class {
1173
+ constructor(languageUtils, options = {}) {
1174
+ this.languageUtils = languageUtils;
1175
+ this.options = options;
1176
+ this.logger = baseLogger.create("pluralResolver");
1177
+ this.pluralRulesCache = {};
1178
+ }
1179
+ clearCache() {
1180
+ this.pluralRulesCache = {};
1181
+ }
1182
+ getRule(code, options = {}) {
1183
+ const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
1184
+ const type = options.ordinal ? "ordinal" : "cardinal";
1185
+ const cacheKey = JSON.stringify({
1186
+ cleanedCode,
1187
+ type
1188
+ });
1189
+ if (cacheKey in this.pluralRulesCache) return this.pluralRulesCache[cacheKey];
1190
+ let rule;
1191
+ try {
1192
+ rule = new Intl.PluralRules(cleanedCode, { type });
1193
+ } catch (err) {
1194
+ if (typeof Intl === "undefined") {
1195
+ this.logger.error("No Intl support, please use an Intl polyfill!");
1196
+ return dummyRule;
1197
+ }
1198
+ if (!code.match(/-|_/)) return dummyRule;
1199
+ const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1200
+ rule = this.getRule(lngPart, options);
1201
+ }
1202
+ this.pluralRulesCache[cacheKey] = rule;
1203
+ return rule;
1204
+ }
1205
+ needsPlural(code, options = {}) {
1206
+ let rule = this.getRule(code, options);
1207
+ if (!rule) rule = this.getRule("dev", options);
1208
+ return rule?.resolvedOptions().pluralCategories.length > 1;
1209
+ }
1210
+ getPluralFormsOfKey(code, key, options = {}) {
1211
+ return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
1212
+ }
1213
+ getSuffixes(code, options = {}) {
1214
+ let rule = this.getRule(code, options);
1215
+ if (!rule) rule = this.getRule("dev", options);
1216
+ if (!rule) return [];
1217
+ return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
1218
+ }
1219
+ getSuffix(code, count, options = {}) {
1220
+ const rule = this.getRule(code, options);
1221
+ if (rule) return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
1222
+ this.logger.warn(`no plural rule found for: ${code}`);
1223
+ return this.getSuffix("dev", count, options);
1224
+ }
1225
+ };
1226
+ var deepFindWithDefaults = (data, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => {
1227
+ let path = getPathWithDefaults(data, defaultData, key);
1228
+ if (!path && ignoreJSONStructure && isString(key)) {
1229
+ path = deepFind(data, key, keySeparator);
1230
+ if (path === void 0) path = deepFind(defaultData, key, keySeparator);
1231
+ }
1232
+ return path;
1233
+ };
1234
+ var regexSafe = (val) => val.replace(/\$/g, "$$$$");
1235
+ var Interpolator = class {
1236
+ constructor(options = {}) {
1237
+ this.logger = baseLogger.create("interpolator");
1238
+ this.options = options;
1239
+ this.format = options?.interpolation?.format || ((value) => value);
1240
+ this.init(options);
1241
+ }
1242
+ init(options = {}) {
1243
+ if (!options.interpolation) options.interpolation = { escapeValue: true };
1244
+ const { escape: escape$1, escapeValue, useRawValueToEscape, prefix, prefixEscaped, suffix, suffixEscaped, formatSeparator, unescapeSuffix, unescapePrefix, nestingPrefix, nestingPrefixEscaped, nestingSuffix, nestingSuffixEscaped, nestingOptionsSeparator, maxReplaces, alwaysFormat } = options.interpolation;
1245
+ this.escape = escape$1 !== void 0 ? escape$1 : escape;
1246
+ this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
1247
+ this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
1248
+ this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
1249
+ this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
1250
+ this.formatSeparator = formatSeparator || ",";
1251
+ this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
1252
+ this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
1253
+ this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
1254
+ this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
1255
+ this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
1256
+ this.maxReplaces = maxReplaces || 1e3;
1257
+ this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
1258
+ this.resetRegExp();
1259
+ }
1260
+ reset() {
1261
+ if (this.options) this.init(this.options);
1262
+ }
1263
+ resetRegExp() {
1264
+ const getOrResetRegExp = (existingRegExp, pattern) => {
1265
+ if (existingRegExp?.source === pattern) {
1266
+ existingRegExp.lastIndex = 0;
1267
+ return existingRegExp;
1268
+ }
1269
+ return new RegExp(pattern, "g");
1270
+ };
1271
+ this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1272
+ this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1273
+ this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1274
+ }
1275
+ interpolate(str, data, lng, options) {
1276
+ let match;
1277
+ let value;
1278
+ let replaces;
1279
+ const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1280
+ const handleFormat = (key) => {
1281
+ if (key.indexOf(this.formatSeparator) < 0) {
1282
+ const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1283
+ return this.alwaysFormat ? this.format(path, void 0, lng, {
1284
+ ...options,
1285
+ ...data,
1286
+ interpolationkey: key
1287
+ }) : path;
1288
+ }
1289
+ const p = key.split(this.formatSeparator);
1290
+ const k = p.shift().trim();
1291
+ const f = p.join(this.formatSeparator).trim();
1292
+ return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1293
+ ...options,
1294
+ ...data,
1295
+ interpolationkey: k
1296
+ });
1297
+ };
1298
+ this.resetRegExp();
1299
+ const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1300
+ const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1301
+ [{
1302
+ regex: this.regexpUnescape,
1303
+ safeValue: (val) => regexSafe(val)
1304
+ }, {
1305
+ regex: this.regexp,
1306
+ safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1307
+ }].forEach((todo) => {
1308
+ replaces = 0;
1309
+ while (match = todo.regex.exec(str)) {
1310
+ const matchedVar = match[1].trim();
1311
+ value = handleFormat(matchedVar);
1312
+ if (value === void 0) if (typeof missingInterpolationHandler === "function") {
1313
+ const temp = missingInterpolationHandler(str, match, options);
1314
+ value = isString(temp) ? temp : "";
1315
+ } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) value = "";
1316
+ else if (skipOnVariables) {
1317
+ value = match[0];
1318
+ continue;
1319
+ } else {
1320
+ this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1321
+ value = "";
1322
+ }
1323
+ else if (!isString(value) && !this.useRawValueToEscape) value = makeString(value);
1324
+ const safeValue = todo.safeValue(value);
1325
+ str = str.replace(match[0], safeValue);
1326
+ if (skipOnVariables) {
1327
+ todo.regex.lastIndex += value.length;
1328
+ todo.regex.lastIndex -= match[0].length;
1329
+ } else todo.regex.lastIndex = 0;
1330
+ replaces++;
1331
+ if (replaces >= this.maxReplaces) break;
1332
+ }
1333
+ });
1334
+ return str;
1335
+ }
1336
+ nest(str, fc, options = {}) {
1337
+ let match;
1338
+ let value;
1339
+ let clonedOptions;
1340
+ const handleHasOptions = (key, inheritedOptions) => {
1341
+ const sep = this.nestingOptionsSeparator;
1342
+ if (key.indexOf(sep) < 0) return key;
1343
+ const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`));
1344
+ let optionsString = `{${c[1]}`;
1345
+ key = c[0];
1346
+ optionsString = this.interpolate(optionsString, clonedOptions);
1347
+ const matchedSingleQuotes = optionsString.match(/'/g);
1348
+ const matchedDoubleQuotes = optionsString.match(/"/g);
1349
+ if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) optionsString = optionsString.replace(/'/g, "\"");
1350
+ try {
1351
+ clonedOptions = JSON.parse(optionsString);
1352
+ if (inheritedOptions) clonedOptions = {
1353
+ ...inheritedOptions,
1354
+ ...clonedOptions
1355
+ };
1356
+ } catch (e) {
1357
+ this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1358
+ return `${key}${sep}${optionsString}`;
1359
+ }
1360
+ if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1361
+ return key;
1362
+ };
1363
+ while (match = this.nestingRegexp.exec(str)) {
1364
+ let formatters = [];
1365
+ clonedOptions = { ...options };
1366
+ clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1367
+ clonedOptions.applyPostProcessor = false;
1368
+ delete clonedOptions.defaultValue;
1369
+ const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf("}") + 1 : match[1].indexOf(this.formatSeparator);
1370
+ if (keyEndIndex !== -1) {
1371
+ formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean);
1372
+ match[1] = match[1].slice(0, keyEndIndex);
1373
+ }
1374
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1375
+ if (value && match[0] === str && !isString(value)) return value;
1376
+ if (!isString(value)) value = makeString(value);
1377
+ if (!value) {
1378
+ this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1379
+ value = "";
1380
+ }
1381
+ if (formatters.length) value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1382
+ ...options,
1383
+ interpolationkey: match[1].trim()
1384
+ }), value.trim());
1385
+ str = str.replace(match[0], value);
1386
+ this.regexp.lastIndex = 0;
1387
+ }
1388
+ return str;
1389
+ }
1390
+ };
1391
+ var parseFormatStr = (formatStr) => {
1392
+ let formatName = formatStr.toLowerCase().trim();
1393
+ const formatOptions = {};
1394
+ if (formatStr.indexOf("(") > -1) {
1395
+ const p = formatStr.split("(");
1396
+ formatName = p[0].toLowerCase().trim();
1397
+ const optStr = p[1].substring(0, p[1].length - 1);
1398
+ if (formatName === "currency" && optStr.indexOf(":") < 0) {
1399
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1400
+ } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
1401
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
1402
+ } else optStr.split(";").forEach((opt) => {
1403
+ if (opt) {
1404
+ const [key, ...rest] = opt.split(":");
1405
+ const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
1406
+ const trimmedKey = key.trim();
1407
+ if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1408
+ if (val === "false") formatOptions[trimmedKey] = false;
1409
+ if (val === "true") formatOptions[trimmedKey] = true;
1410
+ if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1411
+ }
1412
+ });
1413
+ }
1414
+ return {
1415
+ formatName,
1416
+ formatOptions
1417
+ };
1418
+ };
1419
+ var createCachedFormatter = (fn) => {
1420
+ const cache = {};
1421
+ return (v, l, o) => {
1422
+ let optForCache = o;
1423
+ if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) optForCache = {
1424
+ ...optForCache,
1425
+ [o.interpolationkey]: void 0
1426
+ };
1427
+ const key = l + JSON.stringify(optForCache);
1428
+ let frm = cache[key];
1429
+ if (!frm) {
1430
+ frm = fn(getCleanedCode(l), o);
1431
+ cache[key] = frm;
1432
+ }
1433
+ return frm(v);
1434
+ };
1435
+ };
1436
+ var createNonCachedFormatter = (fn) => (v, l, o) => fn(getCleanedCode(l), o)(v);
1437
+ var Formatter = class {
1438
+ constructor(options = {}) {
1439
+ this.logger = baseLogger.create("formatter");
1440
+ this.options = options;
1441
+ this.init(options);
1442
+ }
1443
+ init(services, options = { interpolation: {} }) {
1444
+ this.formatSeparator = options.interpolation.formatSeparator || ",";
1445
+ const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1446
+ this.formats = {
1447
+ number: cf((lng, opt) => {
1448
+ const formatter = new Intl.NumberFormat(lng, { ...opt });
1449
+ return (val) => formatter.format(val);
1450
+ }),
1451
+ currency: cf((lng, opt) => {
1452
+ const formatter = new Intl.NumberFormat(lng, {
1453
+ ...opt,
1454
+ style: "currency"
1455
+ });
1456
+ return (val) => formatter.format(val);
1457
+ }),
1458
+ datetime: cf((lng, opt) => {
1459
+ const formatter = new Intl.DateTimeFormat(lng, { ...opt });
1460
+ return (val) => formatter.format(val);
1461
+ }),
1462
+ relativetime: cf((lng, opt) => {
1463
+ const formatter = new Intl.RelativeTimeFormat(lng, { ...opt });
1464
+ return (val) => formatter.format(val, opt.range || "day");
1465
+ }),
1466
+ list: cf((lng, opt) => {
1467
+ const formatter = new Intl.ListFormat(lng, { ...opt });
1468
+ return (val) => formatter.format(val);
1469
+ })
1470
+ };
1471
+ }
1472
+ add(name, fc) {
1473
+ this.formats[name.toLowerCase().trim()] = fc;
1474
+ }
1475
+ addCached(name, fc) {
1476
+ this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1477
+ }
1478
+ format(value, format, lng, options = {}) {
1479
+ const formats = format.split(this.formatSeparator);
1480
+ if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) {
1481
+ const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1);
1482
+ formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1483
+ }
1484
+ return formats.reduce((mem, f) => {
1485
+ const { formatName, formatOptions } = parseFormatStr(f);
1486
+ if (this.formats[formatName]) {
1487
+ let formatted = mem;
1488
+ try {
1489
+ const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1490
+ const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1491
+ formatted = this.formats[formatName](mem, l, {
1492
+ ...formatOptions,
1493
+ ...options,
1494
+ ...valOptions
1495
+ });
1496
+ } catch (error) {
1497
+ this.logger.warn(error);
1498
+ }
1499
+ return formatted;
1500
+ } else this.logger.warn(`there was no format function for ${formatName}`);
1501
+ return mem;
1502
+ }, value);
1503
+ }
1504
+ };
1505
+ var removePending = (q, name) => {
1506
+ if (q.pending[name] !== void 0) {
1507
+ delete q.pending[name];
1508
+ q.pendingCount--;
1509
+ }
1510
+ };
1511
+ var Connector = class extends EventEmitter {
1512
+ constructor(backend, store, services, options = {}) {
1513
+ super();
1514
+ this.backend = backend;
1515
+ this.store = store;
1516
+ this.services = services;
1517
+ this.languageUtils = services.languageUtils;
1518
+ this.options = options;
1519
+ this.logger = baseLogger.create("backendConnector");
1520
+ this.waitingReads = [];
1521
+ this.maxParallelReads = options.maxParallelReads || 10;
1522
+ this.readingCalls = 0;
1523
+ this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1524
+ this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1525
+ this.state = {};
1526
+ this.queue = [];
1527
+ this.backend?.init?.(services, options.backend, options);
1528
+ }
1529
+ queueLoad(languages, namespaces, options, callback) {
1530
+ const toLoad = {};
1531
+ const pending = {};
1532
+ const toLoadLanguages = {};
1533
+ const toLoadNamespaces = {};
1534
+ languages.forEach((lng) => {
1535
+ let hasAllNamespaces = true;
1536
+ namespaces.forEach((ns) => {
1537
+ const name = `${lng}|${ns}`;
1538
+ if (!options.reload && this.store.hasResourceBundle(lng, ns)) this.state[name] = 2;
1539
+ else if (this.state[name] < 0);
1540
+ else if (this.state[name] === 1) {
1541
+ if (pending[name] === void 0) pending[name] = true;
1542
+ } else {
1543
+ this.state[name] = 1;
1544
+ hasAllNamespaces = false;
1545
+ if (pending[name] === void 0) pending[name] = true;
1546
+ if (toLoad[name] === void 0) toLoad[name] = true;
1547
+ if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
1548
+ }
1549
+ });
1550
+ if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1551
+ });
1552
+ if (Object.keys(toLoad).length || Object.keys(pending).length) this.queue.push({
1553
+ pending,
1554
+ pendingCount: Object.keys(pending).length,
1555
+ loaded: {},
1556
+ errors: [],
1557
+ callback
1558
+ });
1559
+ return {
1560
+ toLoad: Object.keys(toLoad),
1561
+ pending: Object.keys(pending),
1562
+ toLoadLanguages: Object.keys(toLoadLanguages),
1563
+ toLoadNamespaces: Object.keys(toLoadNamespaces)
1564
+ };
1565
+ }
1566
+ loaded(name, err, data) {
1567
+ const s = name.split("|");
1568
+ const lng = s[0];
1569
+ const ns = s[1];
1570
+ if (err) this.emit("failedLoading", lng, ns, err);
1571
+ if (!err && data) this.store.addResourceBundle(lng, ns, data, void 0, void 0, { skipCopy: true });
1572
+ this.state[name] = err ? -1 : 2;
1573
+ if (err && data) this.state[name] = 0;
1574
+ const loaded = {};
1575
+ this.queue.forEach((q) => {
1576
+ pushPath(q.loaded, [lng], ns);
1577
+ removePending(q, name);
1578
+ if (err) q.errors.push(err);
1579
+ if (q.pendingCount === 0 && !q.done) {
1580
+ Object.keys(q.loaded).forEach((l) => {
1581
+ if (!loaded[l]) loaded[l] = {};
1582
+ const loadedKeys = q.loaded[l];
1583
+ if (loadedKeys.length) loadedKeys.forEach((n) => {
1584
+ if (loaded[l][n] === void 0) loaded[l][n] = true;
1585
+ });
1586
+ });
1587
+ q.done = true;
1588
+ if (q.errors.length) q.callback(q.errors);
1589
+ else q.callback();
1590
+ }
1591
+ });
1592
+ this.emit("loaded", loaded);
1593
+ this.queue = this.queue.filter((q) => !q.done);
1594
+ }
1595
+ read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1596
+ if (!lng.length) return callback(null, {});
1597
+ if (this.readingCalls >= this.maxParallelReads) {
1598
+ this.waitingReads.push({
1599
+ lng,
1600
+ ns,
1601
+ fcName,
1602
+ tried,
1603
+ wait,
1604
+ callback
1605
+ });
1606
+ return;
1607
+ }
1608
+ this.readingCalls++;
1609
+ const resolver = (err, data) => {
1610
+ this.readingCalls--;
1611
+ if (this.waitingReads.length > 0) {
1612
+ const next = this.waitingReads.shift();
1613
+ this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1614
+ }
1615
+ if (err && data && tried < this.maxRetries) {
1616
+ setTimeout(() => {
1617
+ this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1618
+ }, wait);
1619
+ return;
1620
+ }
1621
+ callback(err, data);
1622
+ };
1623
+ const fc = this.backend[fcName].bind(this.backend);
1624
+ if (fc.length === 2) {
1625
+ try {
1626
+ const r = fc(lng, ns);
1627
+ if (r && typeof r.then === "function") r.then((data) => resolver(null, data)).catch(resolver);
1628
+ else resolver(null, r);
1629
+ } catch (err) {
1630
+ resolver(err);
1631
+ }
1632
+ return;
1633
+ }
1634
+ return fc(lng, ns, resolver);
1635
+ }
1636
+ prepareLoading(languages, namespaces, options = {}, callback) {
1637
+ if (!this.backend) {
1638
+ this.logger.warn("No backend was added via i18next.use. Will not load resources.");
1639
+ return callback && callback();
1640
+ }
1641
+ if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1642
+ if (isString(namespaces)) namespaces = [namespaces];
1643
+ const toLoad = this.queueLoad(languages, namespaces, options, callback);
1644
+ if (!toLoad.toLoad.length) {
1645
+ if (!toLoad.pending.length) callback();
1646
+ return null;
1647
+ }
1648
+ toLoad.toLoad.forEach((name) => {
1649
+ this.loadOne(name);
1650
+ });
1651
+ }
1652
+ load(languages, namespaces, callback) {
1653
+ this.prepareLoading(languages, namespaces, {}, callback);
1654
+ }
1655
+ reload(languages, namespaces, callback) {
1656
+ this.prepareLoading(languages, namespaces, { reload: true }, callback);
1657
+ }
1658
+ loadOne(name, prefix = "") {
1659
+ const s = name.split("|");
1660
+ const lng = s[0];
1661
+ const ns = s[1];
1662
+ this.read(lng, ns, "read", void 0, void 0, (err, data) => {
1663
+ if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1664
+ if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1665
+ this.loaded(name, err, data);
1666
+ });
1667
+ }
1668
+ saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
1669
+ if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1670
+ 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!!!");
1671
+ return;
1672
+ }
1673
+ if (key === void 0 || key === null || key === "") return;
1674
+ if (this.backend?.create) {
1675
+ const opts = {
1676
+ ...options,
1677
+ isUpdate
1678
+ };
1679
+ const fc = this.backend.create.bind(this.backend);
1680
+ if (fc.length < 6) try {
1681
+ let r;
1682
+ if (fc.length === 5) r = fc(languages, namespace, key, fallbackValue, opts);
1683
+ else r = fc(languages, namespace, key, fallbackValue);
1684
+ if (r && typeof r.then === "function") r.then((data) => clb(null, data)).catch(clb);
1685
+ else clb(null, r);
1686
+ } catch (err) {
1687
+ clb(err);
1688
+ }
1689
+ else fc(languages, namespace, key, fallbackValue, clb, opts);
1690
+ }
1691
+ if (!languages || !languages[0]) return;
1692
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
1693
+ }
1694
+ };
1695
+ var get = () => ({
1696
+ debug: false,
1697
+ initAsync: true,
1698
+ ns: ["translation"],
1699
+ defaultNS: ["translation"],
1700
+ fallbackLng: ["dev"],
1701
+ fallbackNS: false,
1702
+ supportedLngs: false,
1703
+ nonExplicitSupportedLngs: false,
1704
+ load: "all",
1705
+ preload: false,
1706
+ simplifyPluralSuffix: true,
1707
+ keySeparator: ".",
1708
+ nsSeparator: ":",
1709
+ pluralSeparator: "_",
1710
+ contextSeparator: "_",
1711
+ partialBundledLanguages: false,
1712
+ saveMissing: false,
1713
+ updateMissing: false,
1714
+ saveMissingTo: "fallback",
1715
+ saveMissingPlurals: true,
1716
+ missingKeyHandler: false,
1717
+ missingInterpolationHandler: false,
1718
+ postProcess: false,
1719
+ postProcessPassResolved: false,
1720
+ returnNull: false,
1721
+ returnEmptyString: true,
1722
+ returnObjects: false,
1723
+ joinArrays: false,
1724
+ returnedObjectHandler: false,
1725
+ parseMissingKeyHandler: false,
1726
+ appendNamespaceToMissingKey: false,
1727
+ appendNamespaceToCIMode: false,
1728
+ overloadTranslationOptionHandler: (args) => {
1729
+ let ret = {};
1730
+ if (typeof args[1] === "object") ret = args[1];
1731
+ if (isString(args[1])) ret.defaultValue = args[1];
1732
+ if (isString(args[2])) ret.tDescription = args[2];
1733
+ if (typeof args[2] === "object" || typeof args[3] === "object") {
1734
+ const options = args[3] || args[2];
1735
+ Object.keys(options).forEach((key) => {
1736
+ ret[key] = options[key];
1737
+ });
1738
+ }
1739
+ return ret;
1740
+ },
1741
+ interpolation: {
1742
+ escapeValue: true,
1743
+ format: (value) => value,
1744
+ prefix: "{{",
1745
+ suffix: "}}",
1746
+ formatSeparator: ",",
1747
+ unescapePrefix: "-",
1748
+ nestingPrefix: "$t(",
1749
+ nestingSuffix: ")",
1750
+ nestingOptionsSeparator: ",",
1751
+ maxReplaces: 1e3,
1752
+ skipOnVariables: true
1753
+ },
1754
+ cacheInBuiltFormats: true
1755
+ });
1756
+ var transformOptions = (options) => {
1757
+ if (isString(options.ns)) options.ns = [options.ns];
1758
+ if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1759
+ if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1760
+ if (options.supportedLngs?.indexOf?.("cimode") < 0) options.supportedLngs = options.supportedLngs.concat(["cimode"]);
1761
+ if (typeof options.initImmediate === "boolean") options.initAsync = options.initImmediate;
1762
+ return options;
1763
+ };
1764
+ var noop = () => {};
1765
+ var bindMemberFunctions = (inst) => {
1766
+ Object.getOwnPropertyNames(Object.getPrototypeOf(inst)).forEach((mem) => {
1767
+ if (typeof inst[mem] === "function") inst[mem] = inst[mem].bind(inst);
1768
+ });
1769
+ };
1770
+ var SUPPORT_NOTICE_KEY = "__i18next_supportNoticeShown";
1771
+ var getSupportNoticeShown = () => {
1772
+ if (typeof globalThis !== "undefined" && !!globalThis[SUPPORT_NOTICE_KEY]) return true;
1773
+ if (typeof process !== "undefined" && process.env && process.env.I18NEXT_NO_SUPPORT_NOTICE) return true;
1774
+ if (typeof process !== "undefined" && process.env && process.env.NODE_ENV === "production") return true;
1775
+ return false;
1776
+ };
1777
+ var setSupportNoticeShown = () => {
1778
+ if (typeof globalThis !== "undefined") globalThis[SUPPORT_NOTICE_KEY] = true;
1779
+ };
1780
+ var usesLocize = (inst) => {
1781
+ if (inst?.modules?.backend?.name?.indexOf("Locize") > 0) return true;
1782
+ if (inst?.modules?.backend?.constructor?.name?.indexOf("Locize") > 0) return true;
1783
+ if (inst?.options?.backend?.backends) {
1784
+ if (inst.options.backend.backends.some((b) => b?.name?.indexOf("Locize") > 0 || b?.constructor?.name?.indexOf("Locize") > 0)) return true;
1785
+ }
1786
+ if (inst?.options?.backend?.projectId) return true;
1787
+ if (inst?.options?.backend?.backendOptions) {
1788
+ if (inst.options.backend.backendOptions.some((b) => b?.projectId)) return true;
1789
+ }
1790
+ return false;
1791
+ };
1792
+ var instance = class I18n extends EventEmitter {
1793
+ constructor(options = {}, callback) {
1794
+ super();
1795
+ this.options = transformOptions(options);
1796
+ this.services = {};
1797
+ this.logger = baseLogger;
1798
+ this.modules = { external: [] };
1799
+ bindMemberFunctions(this);
1800
+ if (callback && !this.isInitialized && !options.isClone) {
1801
+ if (!this.options.initAsync) {
1802
+ this.init(options, callback);
1803
+ return this;
1804
+ }
1805
+ setTimeout(() => {
1806
+ this.init(options, callback);
1807
+ }, 0);
1808
+ }
1809
+ }
1810
+ init(options = {}, callback) {
1811
+ this.isInitializing = true;
1812
+ if (typeof options === "function") {
1813
+ callback = options;
1814
+ options = {};
1815
+ }
1816
+ if (options.defaultNS == null && options.ns) {
1817
+ if (isString(options.ns)) options.defaultNS = options.ns;
1818
+ else if (options.ns.indexOf("translation") < 0) options.defaultNS = options.ns[0];
1819
+ }
1820
+ const defOpts = get();
1821
+ this.options = {
1822
+ ...defOpts,
1823
+ ...this.options,
1824
+ ...transformOptions(options)
1825
+ };
1826
+ this.options.interpolation = {
1827
+ ...defOpts.interpolation,
1828
+ ...this.options.interpolation
1829
+ };
1830
+ if (options.keySeparator !== void 0) this.options.userDefinedKeySeparator = options.keySeparator;
1831
+ if (options.nsSeparator !== void 0) this.options.userDefinedNsSeparator = options.nsSeparator;
1832
+ if (typeof this.options.overloadTranslationOptionHandler !== "function") this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;
1833
+ if (this.options.showSupportNotice !== false && !usesLocize(this) && !getSupportNoticeShown()) {
1834
+ if (typeof console !== "undefined" && typeof console.info !== "undefined") console.info("🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙");
1835
+ setSupportNoticeShown();
1836
+ }
1837
+ const createClassOnDemand = (ClassOrObject) => {
1838
+ if (!ClassOrObject) return null;
1839
+ if (typeof ClassOrObject === "function") return new ClassOrObject();
1840
+ return ClassOrObject;
1841
+ };
1842
+ if (!this.options.isClone) {
1843
+ if (this.modules.logger) baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1844
+ else baseLogger.init(null, this.options);
1845
+ let formatter;
1846
+ if (this.modules.formatter) formatter = this.modules.formatter;
1847
+ else formatter = Formatter;
1848
+ const lu = new LanguageUtil(this.options);
1849
+ this.store = new ResourceStore(this.options.resources, this.options);
1850
+ const s = this.services;
1851
+ s.logger = baseLogger;
1852
+ s.resourceStore = this.store;
1853
+ s.languageUtils = lu;
1854
+ s.pluralResolver = new PluralResolver(lu, {
1855
+ prepend: this.options.pluralSeparator,
1856
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
1857
+ });
1858
+ if (this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format) this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1859
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1860
+ s.formatter = createClassOnDemand(formatter);
1861
+ if (s.formatter.init) s.formatter.init(s, this.options);
1862
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1863
+ }
1864
+ s.interpolator = new Interpolator(this.options);
1865
+ s.utils = { hasLoadedNamespace: this.hasLoadedNamespace.bind(this) };
1866
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1867
+ s.backendConnector.on("*", (event, ...args) => {
1868
+ this.emit(event, ...args);
1869
+ });
1870
+ if (this.modules.languageDetector) {
1871
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1872
+ if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1873
+ }
1874
+ if (this.modules.i18nFormat) {
1875
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1876
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
1877
+ }
1878
+ this.translator = new Translator(this.services, this.options);
1879
+ this.translator.on("*", (event, ...args) => {
1880
+ this.emit(event, ...args);
1881
+ });
1882
+ this.modules.external.forEach((m) => {
1883
+ if (m.init) m.init(this);
1884
+ });
1885
+ }
1886
+ this.format = this.options.interpolation.format;
1887
+ if (!callback) callback = noop;
1888
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1889
+ const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1890
+ if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
1891
+ }
1892
+ if (!this.services.languageDetector && !this.options.lng) this.logger.warn("init: no languageDetector is used and no lng is defined");
1893
+ [
1894
+ "getResource",
1895
+ "hasResourceBundle",
1896
+ "getResourceBundle",
1897
+ "getDataByLanguage"
1898
+ ].forEach((fcName) => {
1899
+ this[fcName] = (...args) => this.store[fcName](...args);
1900
+ });
1901
+ [
1902
+ "addResource",
1903
+ "addResources",
1904
+ "addResourceBundle",
1905
+ "removeResourceBundle"
1906
+ ].forEach((fcName) => {
1907
+ this[fcName] = (...args) => {
1908
+ this.store[fcName](...args);
1909
+ return this;
1910
+ };
1911
+ });
1912
+ const deferred = defer();
1913
+ const load = () => {
1914
+ const finish = (err, t) => {
1915
+ this.isInitializing = false;
1916
+ if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
1917
+ this.isInitialized = true;
1918
+ if (!this.options.isClone) this.logger.log("initialized", this.options);
1919
+ this.emit("initialized", this.options);
1920
+ deferred.resolve(t);
1921
+ callback(err, t);
1922
+ };
1923
+ if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1924
+ this.changeLanguage(this.options.lng, finish);
1925
+ };
1926
+ if (this.options.resources || !this.options.initAsync) load();
1927
+ else setTimeout(load, 0);
1928
+ return deferred;
1929
+ }
1930
+ loadResources(language, callback = noop) {
1931
+ let usedCallback = callback;
1932
+ const usedLng = isString(language) ? language : this.language;
1933
+ if (typeof language === "function") usedCallback = language;
1934
+ if (!this.options.resources || this.options.partialBundledLanguages) {
1935
+ if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1936
+ const toLoad = [];
1937
+ const append = (lng) => {
1938
+ if (!lng) return;
1939
+ if (lng === "cimode") return;
1940
+ this.services.languageUtils.toResolveHierarchy(lng).forEach((l) => {
1941
+ if (l === "cimode") return;
1942
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
1943
+ });
1944
+ };
1945
+ if (!usedLng) this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((l) => append(l));
1946
+ else append(usedLng);
1947
+ this.options.preload?.forEach?.((l) => append(l));
1948
+ this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
1949
+ if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1950
+ usedCallback(e);
1951
+ });
1952
+ } else usedCallback(null);
1953
+ }
1954
+ reloadResources(lngs, ns, callback) {
1955
+ const deferred = defer();
1956
+ if (typeof lngs === "function") {
1957
+ callback = lngs;
1958
+ lngs = void 0;
1959
+ }
1960
+ if (typeof ns === "function") {
1961
+ callback = ns;
1962
+ ns = void 0;
1963
+ }
1964
+ if (!lngs) lngs = this.languages;
1965
+ if (!ns) ns = this.options.ns;
1966
+ if (!callback) callback = noop;
1967
+ this.services.backendConnector.reload(lngs, ns, (err) => {
1968
+ deferred.resolve();
1969
+ callback(err);
1970
+ });
1971
+ return deferred;
1972
+ }
1973
+ use(module) {
1974
+ if (!module) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
1975
+ if (!module.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
1976
+ if (module.type === "backend") this.modules.backend = module;
1977
+ if (module.type === "logger" || module.log && module.warn && module.error) this.modules.logger = module;
1978
+ if (module.type === "languageDetector") this.modules.languageDetector = module;
1979
+ if (module.type === "i18nFormat") this.modules.i18nFormat = module;
1980
+ if (module.type === "postProcessor") postProcessor.addPostProcessor(module);
1981
+ if (module.type === "formatter") this.modules.formatter = module;
1982
+ if (module.type === "3rdParty") this.modules.external.push(module);
1983
+ return this;
1984
+ }
1985
+ setResolvedLanguage(l) {
1986
+ if (!l || !this.languages) return;
1987
+ if (["cimode", "dev"].indexOf(l) > -1) return;
1988
+ for (let li = 0; li < this.languages.length; li++) {
1989
+ const lngInLngs = this.languages[li];
1990
+ if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue;
1991
+ if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
1992
+ this.resolvedLanguage = lngInLngs;
1993
+ break;
1994
+ }
1995
+ }
1996
+ if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
1997
+ this.resolvedLanguage = l;
1998
+ this.languages.unshift(l);
1999
+ }
2000
+ }
2001
+ changeLanguage(lng, callback) {
2002
+ this.isLanguageChangingTo = lng;
2003
+ const deferred = defer();
2004
+ this.emit("languageChanging", lng);
2005
+ const setLngProps = (l) => {
2006
+ this.language = l;
2007
+ this.languages = this.services.languageUtils.toResolveHierarchy(l);
2008
+ this.resolvedLanguage = void 0;
2009
+ this.setResolvedLanguage(l);
2010
+ };
2011
+ const done = (err, l) => {
2012
+ if (l) {
2013
+ if (this.isLanguageChangingTo === lng) {
2014
+ setLngProps(l);
2015
+ this.translator.changeLanguage(l);
2016
+ this.isLanguageChangingTo = void 0;
2017
+ this.emit("languageChanged", l);
2018
+ this.logger.log("languageChanged", l);
2019
+ }
2020
+ } else this.isLanguageChangingTo = void 0;
2021
+ deferred.resolve((...args) => this.t(...args));
2022
+ if (callback) callback(err, (...args) => this.t(...args));
2023
+ };
2024
+ const setLng = (lngs) => {
2025
+ if (!lng && !lngs && this.services.languageDetector) lngs = [];
2026
+ const fl = isString(lngs) ? lngs : lngs && lngs[0];
2027
+ const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
2028
+ if (l) {
2029
+ if (!this.language) setLngProps(l);
2030
+ if (!this.translator.language) this.translator.changeLanguage(l);
2031
+ this.services.languageDetector?.cacheUserLanguage?.(l);
2032
+ }
2033
+ this.loadResources(l, (err) => {
2034
+ done(err, l);
2035
+ });
2036
+ };
2037
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) setLng(this.services.languageDetector.detect());
2038
+ else if (!lng && this.services.languageDetector && this.services.languageDetector.async) if (this.services.languageDetector.detect.length === 0) this.services.languageDetector.detect().then(setLng);
2039
+ else this.services.languageDetector.detect(setLng);
2040
+ else setLng(lng);
2041
+ return deferred;
2042
+ }
2043
+ getFixedT(lng, ns, keyPrefix) {
2044
+ const fixedT = (key, opts, ...rest) => {
2045
+ let o;
2046
+ if (typeof opts !== "object") o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2047
+ else o = { ...opts };
2048
+ o.lng = o.lng || fixedT.lng;
2049
+ o.lngs = o.lngs || fixedT.lngs;
2050
+ o.ns = o.ns || fixedT.ns;
2051
+ if (o.keyPrefix !== "") o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2052
+ const selectorOpts = {
2053
+ ...this.options,
2054
+ ...o
2055
+ };
2056
+ if (typeof o.keyPrefix === "function") o.keyPrefix = keysFromSelector(o.keyPrefix, selectorOpts);
2057
+ const keySeparator = this.options.keySeparator || ".";
2058
+ let resultKey;
2059
+ if (o.keyPrefix && Array.isArray(key)) resultKey = key.map((k) => {
2060
+ if (typeof k === "function") k = keysFromSelector(k, selectorOpts);
2061
+ return `${o.keyPrefix}${keySeparator}${k}`;
2062
+ });
2063
+ else {
2064
+ if (typeof key === "function") key = keysFromSelector(key, selectorOpts);
2065
+ resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2066
+ }
2067
+ return this.t(resultKey, o);
2068
+ };
2069
+ if (isString(lng)) fixedT.lng = lng;
2070
+ else fixedT.lngs = lng;
2071
+ fixedT.ns = ns;
2072
+ fixedT.keyPrefix = keyPrefix;
2073
+ return fixedT;
2074
+ }
2075
+ t(...args) {
2076
+ return this.translator?.translate(...args);
2077
+ }
2078
+ exists(...args) {
2079
+ return this.translator?.exists(...args);
2080
+ }
2081
+ setDefaultNamespace(ns) {
2082
+ this.options.defaultNS = ns;
2083
+ }
2084
+ hasLoadedNamespace(ns, options = {}) {
2085
+ if (!this.isInitialized) {
2086
+ this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
2087
+ return false;
2088
+ }
2089
+ if (!this.languages || !this.languages.length) {
2090
+ this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
2091
+ return false;
2092
+ }
2093
+ const lng = options.lng || this.resolvedLanguage || this.languages[0];
2094
+ const fallbackLng = this.options ? this.options.fallbackLng : false;
2095
+ const lastLng = this.languages[this.languages.length - 1];
2096
+ if (lng.toLowerCase() === "cimode") return true;
2097
+ const loadNotPending = (l, n) => {
2098
+ const loadState = this.services.backendConnector.state[`${l}|${n}`];
2099
+ return loadState === -1 || loadState === 0 || loadState === 2;
2100
+ };
2101
+ if (options.precheck) {
2102
+ const preResult = options.precheck(this, loadNotPending);
2103
+ if (preResult !== void 0) return preResult;
2104
+ }
2105
+ if (this.hasResourceBundle(lng, ns)) return true;
2106
+ if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2107
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2108
+ return false;
2109
+ }
2110
+ loadNamespaces(ns, callback) {
2111
+ const deferred = defer();
2112
+ if (!this.options.ns) {
2113
+ if (callback) callback();
2114
+ return Promise.resolve();
2115
+ }
2116
+ if (isString(ns)) ns = [ns];
2117
+ ns.forEach((n) => {
2118
+ if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2119
+ });
2120
+ this.loadResources((err) => {
2121
+ deferred.resolve();
2122
+ if (callback) callback(err);
2123
+ });
2124
+ return deferred;
2125
+ }
2126
+ loadLanguages(lngs, callback) {
2127
+ const deferred = defer();
2128
+ if (isString(lngs)) lngs = [lngs];
2129
+ const preloaded = this.options.preload || [];
2130
+ const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2131
+ if (!newLngs.length) {
2132
+ if (callback) callback();
2133
+ return Promise.resolve();
2134
+ }
2135
+ this.options.preload = preloaded.concat(newLngs);
2136
+ this.loadResources((err) => {
2137
+ deferred.resolve();
2138
+ if (callback) callback(err);
2139
+ });
2140
+ return deferred;
2141
+ }
2142
+ dir(lng) {
2143
+ if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2144
+ if (!lng) return "rtl";
2145
+ try {
2146
+ const l = new Intl.Locale(lng);
2147
+ if (l && l.getTextInfo) {
2148
+ const ti = l.getTextInfo();
2149
+ if (ti && ti.direction) return ti.direction;
2150
+ }
2151
+ } catch (e) {}
2152
+ const rtlLngs = [
2153
+ "ar",
2154
+ "shu",
2155
+ "sqr",
2156
+ "ssh",
2157
+ "xaa",
2158
+ "yhd",
2159
+ "yud",
2160
+ "aao",
2161
+ "abh",
2162
+ "abv",
2163
+ "acm",
2164
+ "acq",
2165
+ "acw",
2166
+ "acx",
2167
+ "acy",
2168
+ "adf",
2169
+ "ads",
2170
+ "aeb",
2171
+ "aec",
2172
+ "afb",
2173
+ "ajp",
2174
+ "apc",
2175
+ "apd",
2176
+ "arb",
2177
+ "arq",
2178
+ "ars",
2179
+ "ary",
2180
+ "arz",
2181
+ "auz",
2182
+ "avl",
2183
+ "ayh",
2184
+ "ayl",
2185
+ "ayn",
2186
+ "ayp",
2187
+ "bbz",
2188
+ "pga",
2189
+ "he",
2190
+ "iw",
2191
+ "ps",
2192
+ "pbt",
2193
+ "pbu",
2194
+ "pst",
2195
+ "prp",
2196
+ "prd",
2197
+ "ug",
2198
+ "ur",
2199
+ "ydd",
2200
+ "yds",
2201
+ "yih",
2202
+ "ji",
2203
+ "yi",
2204
+ "hbo",
2205
+ "men",
2206
+ "xmn",
2207
+ "fa",
2208
+ "jpr",
2209
+ "peo",
2210
+ "pes",
2211
+ "prs",
2212
+ "dv",
2213
+ "sam",
2214
+ "ckb"
2215
+ ];
2216
+ const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2217
+ if (lng.toLowerCase().indexOf("-latn") > 1) return "ltr";
2218
+ return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
2219
+ }
2220
+ static createInstance(options = {}, callback) {
2221
+ const instance = new I18n(options, callback);
2222
+ instance.createInstance = I18n.createInstance;
2223
+ return instance;
2224
+ }
2225
+ cloneInstance(options = {}, callback = noop) {
2226
+ const forkResourceStore = options.forkResourceStore;
2227
+ if (forkResourceStore) delete options.forkResourceStore;
2228
+ const mergedOptions = {
2229
+ ...this.options,
2230
+ ...options,
2231
+ isClone: true
2232
+ };
2233
+ const clone = new I18n(mergedOptions);
2234
+ if (options.debug !== void 0 || options.prefix !== void 0) clone.logger = clone.logger.clone(options);
2235
+ [
2236
+ "store",
2237
+ "services",
2238
+ "language"
2239
+ ].forEach((m) => {
2240
+ clone[m] = this[m];
2241
+ });
2242
+ clone.services = { ...this.services };
2243
+ clone.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) };
2244
+ if (forkResourceStore) {
2245
+ clone.store = new ResourceStore(Object.keys(this.store.data).reduce((prev, l) => {
2246
+ prev[l] = { ...this.store.data[l] };
2247
+ prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2248
+ acc[n] = { ...prev[l][n] };
2249
+ return acc;
2250
+ }, prev[l]);
2251
+ return prev;
2252
+ }, {}), mergedOptions);
2253
+ clone.services.resourceStore = clone.store;
2254
+ }
2255
+ if (options.interpolation) {
2256
+ const mergedInterpolation = {
2257
+ ...get().interpolation,
2258
+ ...this.options.interpolation,
2259
+ ...options.interpolation
2260
+ };
2261
+ const mergedForInterpolator = {
2262
+ ...mergedOptions,
2263
+ interpolation: mergedInterpolation
2264
+ };
2265
+ clone.services.interpolator = new Interpolator(mergedForInterpolator);
2266
+ }
2267
+ clone.translator = new Translator(clone.services, mergedOptions);
2268
+ clone.translator.on("*", (event, ...args) => {
2269
+ clone.emit(event, ...args);
2270
+ });
2271
+ clone.init(mergedOptions, callback);
2272
+ clone.translator.options = mergedOptions;
2273
+ clone.translator.backendConnector.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) };
2274
+ return clone;
2275
+ }
2276
+ toJSON() {
2277
+ return {
2278
+ options: this.options,
2279
+ store: this.store,
2280
+ language: this.language,
2281
+ languages: this.languages,
2282
+ resolvedLanguage: this.resolvedLanguage
2283
+ };
2284
+ }
2285
+ }.createInstance();
2286
+ instance.createInstance;
2287
+ instance.dir;
2288
+ instance.init;
2289
+ instance.loadResources;
2290
+ instance.reloadResources;
2291
+ instance.use;
2292
+ instance.changeLanguage;
2293
+ instance.getFixedT;
2294
+ instance.t;
2295
+ instance.exists;
2296
+ instance.setDefaultNamespace;
2297
+ instance.hasLoadedNamespace;
2298
+ instance.loadNamespaces;
2299
+ instance.loadLanguages;
2300
+ //#endregion
2301
+ //#region ../../shared/translator/dist/index.js
2302
+ instance.init({
2303
+ fallbackLng: "en",
2304
+ lng: "en",
2305
+ showSupportNotice: !1,
2306
+ resources: {
2307
+ en: e$1,
2308
+ es: e
2309
+ }
2310
+ });
2311
+ //#endregion
2312
+ //#region src/i18n.ts
2313
+ var { translator } = {
2314
+ translator: {
2315
+ ...instance,
2316
+ t: (e, t) => {
2317
+ let { lng: r } = t;
2318
+ switch (r) {
2319
+ case "en_US":
2320
+ case "en-US":
2321
+ t.lng = "en";
2322
+ break;
2323
+ case "es_ES":
2324
+ case "es-ES":
2325
+ case "es_MX":
2326
+ case "es-MX":
2327
+ t.lng = "es";
2328
+ break;
2329
+ default: break;
2330
+ }
2331
+ return instance.t(e, {
2332
+ lng: r,
2333
+ ...t
2334
+ });
2335
+ }
2336
+ },
2337
+ languageOptions: [{
2338
+ value: "en_US",
2339
+ label: "English (US)"
2340
+ }, {
2341
+ value: "es_ES",
2342
+ label: "Spanish"
2343
+ }]
2344
+ };
2345
+ /**
2346
+ * A learner-facing string in `language`, the model's `language`. i18next falls
2347
+ * back to English for a language or key it does not hold. Values are not
2348
+ * HTML-escaped: they are circle and tile names, and Svelte escapes what it
2349
+ * renders.
2350
+ */
2351
+ function t(key, language, values = {}) {
2352
+ return translator.t(`translation:vennClassification:${key}`, {
2353
+ lng: language,
2354
+ ...values,
2355
+ interpolation: { escapeValue: false }
2356
+ });
2357
+ }
2358
+ //#endregion
24
2359
  //#region src/controller/region.ts
25
2360
  /**
2361
+ * Region helpers for the venn-classification controller.
2362
+ *
2363
+ * A region is a sorted-ascending array of circle indexes. These helpers deal
2364
+ * with keying, labelling, and equality in a layout-agnostic way so that both
2365
+ * the controller (for scoring / validation) and delivery (for rendering)
2366
+ * can share them.
2367
+ */
2368
+ /**
26
2369
  * Returns the canonical region key: sorted-ascending indexes joined by commas.
27
2370
  * Outside / "neither" region is the empty string.
28
2371
  */
@@ -74,16 +2417,19 @@ function enumerateRegions(circleCount) {
74
2417
  * [0,1] -> "<X> and <Y>"
75
2418
  * [0,1,2] -> "<X> and <Y> and <Z>"
76
2419
  */
77
- function composeRegionLabel(circles, region) {
2420
+ function composeRegionLabel(circles, region, language) {
78
2421
  const norm = normalizeRegion(region);
79
- const labels = norm.map((i) => circles[i]?.label ?? `Set ${i + 1}`);
80
- const circleCount = circles.length;
2422
+ const setLabel = (i) => circles[i]?.label ?? t("setNumber", language, { number: i + 1 });
2423
+ const labels = norm.map(setLabel);
81
2424
  if (norm.length === 0) {
82
- if (circleCount === 2) return `Neither ${circles[0]?.label ?? "Set 1"} nor ${circles[1]?.label ?? "Set 2"}`;
83
- return `None of ${circles.map((c, i) => c?.label ?? `Set ${i + 1}`).join(", ")}`;
2425
+ if (circles.length === 2) return t("regionNeither", language, {
2426
+ first: setLabel(0),
2427
+ second: setLabel(1)
2428
+ });
2429
+ return t("regionNoneOf", language, { sets: circles.map((_, i) => setLabel(i)).join(", ") });
84
2430
  }
85
- if (norm.length === 1) return `${labels[0]} only`;
86
- return labels.join(" and ");
2431
+ if (norm.length === 1) return t("regionOnly", language, { set: labels[0] });
2432
+ return labels.join(t("regionAndSeparator", language));
87
2433
  }
88
2434
  /**
89
2435
  * Resolve the label for a region, preferring an author-supplied override from
@@ -94,7 +2440,7 @@ function getRegionLabel(model, region) {
94
2440
  const key = regionKey(region);
95
2441
  const override = model.regionLabels?.[key];
96
2442
  if (typeof override === "string" && override.trim().length > 0) return override;
97
- return composeRegionLabel(model.circles ?? [], region);
2443
+ return composeRegionLabel(model.circles ?? [], region, model.language);
98
2444
  }
99
2445
  //#endregion
100
2446
  //#region src/controller/index.ts
@@ -104,7 +2450,6 @@ function getRegionLabel(model, region) {
104
2450
  * plus the 3-set layout/picker once that work ships.
105
2451
  */
106
2452
  var SUPPORTED_CIRCLE_COUNTS = /* @__PURE__ */ new Set([2]);
107
- var isEmptyObject = (value) => !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
108
2453
  function tilePlainLabel(label) {
109
2454
  return String(label ?? "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
110
2455
  }
@@ -167,32 +2512,29 @@ function getCorrectnessMap(model, session) {
167
2512
  for (const tile of model.tiles ?? []) out[tile.id] = getTileCorrectness(tile, placements[tile.id] ?? null);
168
2513
  return out;
169
2514
  }
2515
+ /**
2516
+ * The scoring policy in force: the model's `scoringPolicy`, overridden to
2517
+ * all-or-nothing by `env.partialScoring === false` - the rule the React
2518
+ * elements apply through `partialScoring.enabled(model, env)`.
2519
+ */
2520
+ function effectiveScoringPolicy(model, env) {
2521
+ if (model.scoringPolicy === "allOrNothing" || env?.partialScoring === false) return "allOrNothing";
2522
+ return "partialPerTile";
2523
+ }
2524
+ var EMPTY_OUTCOME = {
2525
+ score: 0,
2526
+ empty: true,
2527
+ traceLog: ["Student did not place any tiles. Score is 0."]
2528
+ };
2529
+ /**
2530
+ * Score a session. Scores in every mode, as multiple-choice does: a player
2531
+ * calls this with the env it scores under, not only `evaluate`.
2532
+ */
170
2533
  function outcome(question, session, env = {}) {
171
2534
  return new Promise((resolve) => {
172
- if (!session || isEmptyObject(session) || !session.placements || Object.keys(session.placements).length === 0) {
173
- resolve({
174
- score: 0,
175
- empty: true
176
- });
177
- return;
178
- }
179
- if (env.mode !== "evaluate") {
180
- resolve({
181
- score: void 0,
182
- completed: void 0
183
- });
184
- return;
185
- }
186
2535
  const model = createDefaultModel(question || void 0);
187
- const tiles = model.tiles || [];
188
- if (tiles.length === 0) {
189
- resolve({
190
- score: 0,
191
- empty: true
192
- });
193
- return;
194
- }
195
- const placements = session.placements || {};
2536
+ const tiles = model.tiles;
2537
+ const placements = session?.placements ?? {};
196
2538
  let correct = 0;
197
2539
  let answered = 0;
198
2540
  for (const tile of tiles) {
@@ -203,16 +2545,22 @@ function outcome(question, session, env = {}) {
203
2545
  }
204
2546
  if (answered === 0) {
205
2547
  resolve({
206
- score: 0,
207
- empty: true
2548
+ ...EMPTY_OUTCOME,
2549
+ traceLog: [...EMPTY_OUTCOME.traceLog]
208
2550
  });
209
2551
  return;
210
2552
  }
211
- if ((model.scoringPolicy === "allOrNothing" ? "allOrNothing" : "partialPerTile") === "allOrNothing") {
212
- resolve({ score: correct === tiles.length ? 1 : 0 });
213
- return;
214
- }
215
- resolve({ score: correct / tiles.length });
2553
+ const policy = effectiveScoringPolicy(model, env);
2554
+ const score = policy === "allOrNothing" ? correct === tiles.length ? 1 : 0 : Number.parseFloat((correct / tiles.length).toFixed(2));
2555
+ resolve({
2556
+ score,
2557
+ empty: false,
2558
+ traceLog: [
2559
+ `Student placed ${answered} of ${tiles.length} tile(s); ${correct} in the correct region.`,
2560
+ `Score calculated using ${policy === "allOrNothing" ? "all-or-nothing" : "partial"} scoring.`,
2561
+ `Final score: ${score}.`
2562
+ ]
2563
+ });
216
2564
  });
217
2565
  }
218
2566
  /**
@@ -242,6 +2590,7 @@ function model(question, session, env = {}) {
242
2590
  }),
243
2591
  regionLabels: { ...normalizedQuestion.regionLabels || {} },
244
2592
  scoringPolicy: normalizedQuestion.scoringPolicy ?? "partialPerTile",
2593
+ language: normalizedQuestion.language,
245
2594
  disabled: safeEnv.mode !== "gather",
246
2595
  mode: safeEnv.mode,
247
2596
  env: safeEnv
@@ -252,10 +2601,8 @@ function model(question, session, env = {}) {
252
2601
  out.correctRegionsById = correctRegionsById;
253
2602
  out.correctness = getCorrectnessMap(normalizedQuestion, session);
254
2603
  }
255
- if (safeEnv.role === "instructor" && (safeEnv.mode === "view" || safeEnv.mode === "evaluate")) {
256
- const anyQ = normalizedQuestion;
257
- out.teacherInstructions = anyQ.teacherInstructionsEnabled ? anyQ.teacherInstructions ?? null : null;
258
- } else out.teacherInstructions = null;
2604
+ if (safeEnv.role === "instructor" && (safeEnv.mode === "view" || safeEnv.mode === "evaluate")) out.teacherInstructions = normalizedQuestion.teacherInstructionsEnabled ? normalizedQuestion.teacherInstructions ?? null : null;
2605
+ else out.teacherInstructions = null;
259
2606
  resolve(out);
260
2607
  });
261
2608
  }
@@ -270,7 +2617,6 @@ function createCorrectResponseSession(question, env = {}) {
270
2617
  for (const tile of model.tiles) placements[tile.id] = normalizeRegion(tile.correctRegion);
271
2618
  resolve({
272
2619
  id: "1",
273
- element: "venn-classification",
274
2620
  placements,
275
2621
  completed: true
276
2622
  });
@@ -350,12 +2696,11 @@ function buildPreviewSession(model) {
350
2696
  for (const tile of m.tiles) placements[tile.id] = normalizeRegion(tile.correctRegion);
351
2697
  return {
352
2698
  id: "preview",
353
- element: "venn-classification",
354
2699
  placements,
355
2700
  completed: true
356
2701
  };
357
2702
  }
358
2703
  //#endregion
359
- export { SUPPORTED_CIRCLE_COUNTS, buildPreviewSession, composeRegionLabel, createCorrectResponseSession, createDefaultModel, enumerateRegions, getCorrectnessMap, getRegionLabel, getTileCorrectness, isComplete, model, normalizeRegion, normalizeSession, outcome, regionKey, regionsEqual, validate };
2704
+ export { SUPPORTED_CIRCLE_COUNTS, buildPreviewSession, composeRegionLabel, createCorrectResponseSession, createDefaultModel, effectiveScoringPolicy, enumerateRegions, getCorrectnessMap, getRegionLabel, getTileCorrectness, isComplete, model, normalizeRegion, normalizeSession, outcome, regionKey, regionsEqual, validate };
360
2705
 
361
2706
  //# sourceMappingURL=index.js.map