@vielzeug/lingua 1.1.2 → 1.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_bounded-cache.cjs +2 -0
- package/dist/_bounded-cache.cjs.map +1 -0
- package/dist/_bounded-cache.d.ts +2 -0
- package/dist/_bounded-cache.d.ts.map +1 -0
- package/dist/_bounded-cache.js +10 -0
- package/dist/_bounded-cache.js.map +1 -0
- package/dist/_catalog-store.cjs +1 -1
- package/dist/_catalog-store.cjs.map +1 -1
- package/dist/_catalog-store.d.ts +5 -4
- package/dist/_catalog-store.d.ts.map +1 -1
- package/dist/_catalog-store.js +54 -47
- package/dist/_catalog-store.js.map +1 -1
- package/dist/_dev.cjs +1 -1
- package/dist/_dev.cjs.map +1 -1
- package/dist/_dev.js +4 -1
- package/dist/_dev.js.map +1 -1
- package/dist/_translate.cjs +2 -0
- package/dist/_translate.cjs.map +1 -0
- package/dist/_translate.d.ts +21 -0
- package/dist/_translate.d.ts.map +1 -0
- package/dist/_translate.js +54 -0
- package/dist/_translate.js.map +1 -0
- package/dist/format.cjs +1 -1
- package/dist/format.cjs.map +1 -1
- package/dist/format.d.ts.map +1 -1
- package/dist/format.js +39 -43
- package/dist/format.js.map +1 -1
- package/dist/i18n-types.d.ts +12 -1
- package/dist/i18n-types.d.ts.map +1 -1
- package/dist/i18n.cjs +1 -1
- package/dist/i18n.cjs.map +1 -1
- package/dist/i18n.d.ts +1 -29
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +91 -127
- package/dist/i18n.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/lingua.cjs +1 -1
- package/dist/lingua.cjs.map +1 -1
- package/dist/lingua.iife.js +1 -1
- package/dist/lingua.iife.js.map +1 -1
- package/dist/lingua.js +1 -1
- package/dist/lingua.js.map +1 -1
- package/dist/template-BZRFdmaQ.cjs +2 -0
- package/dist/template-BZRFdmaQ.cjs.map +1 -0
- package/dist/template-BihTfBYb.js +2 -0
- package/dist/template-BihTfBYb.js.map +1 -0
- package/dist/validate-D1U8TTeT.js +2 -0
- package/dist/validate-D1U8TTeT.js.map +1 -0
- package/dist/validate-x7lFFyV2.cjs +2 -0
- package/dist/validate-x7lFFyV2.cjs.map +1 -0
- package/dist/validate.cjs.map +1 -1
- package/dist/validate.d.ts +2 -1
- package/dist/validate.d.ts.map +1 -1
- package/dist/validate.js.map +1 -1
- package/package.json +2 -2
package/dist/format.js
CHANGED
|
@@ -1,10 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
let i = n();
|
|
5
|
-
return e.size >= 128 && e.delete(e.keys().next().value), e.set(t, i), i;
|
|
6
|
-
}
|
|
7
|
-
var t = [
|
|
1
|
+
import { getOrCreate as e } from "./_bounded-cache.js";
|
|
2
|
+
//#region src/format.ts
|
|
3
|
+
var t = 128, n = [
|
|
8
4
|
"years",
|
|
9
5
|
"months",
|
|
10
6
|
"weeks",
|
|
@@ -15,7 +11,7 @@ var t = [
|
|
|
15
11
|
"milliseconds",
|
|
16
12
|
"microseconds",
|
|
17
13
|
"nanoseconds"
|
|
18
|
-
],
|
|
14
|
+
], r = {
|
|
19
15
|
days: "d",
|
|
20
16
|
hours: "h",
|
|
21
17
|
microseconds: "us",
|
|
@@ -27,15 +23,15 @@ var t = [
|
|
|
27
23
|
weeks: "w",
|
|
28
24
|
years: "y"
|
|
29
25
|
};
|
|
30
|
-
function
|
|
31
|
-
return
|
|
32
|
-
let
|
|
33
|
-
return typeof
|
|
26
|
+
function i(e) {
|
|
27
|
+
return n.map((t) => {
|
|
28
|
+
let n = e[t];
|
|
29
|
+
return typeof n == "number" ? `${n}${r[t]}` : void 0;
|
|
34
30
|
}).filter((e) => e !== void 0).join(" ");
|
|
35
31
|
}
|
|
36
|
-
function
|
|
37
|
-
let
|
|
38
|
-
function
|
|
32
|
+
function a(r) {
|
|
33
|
+
let a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = typeof r == "string" ? () => r : r;
|
|
34
|
+
function f(e, t) {
|
|
39
35
|
if (!t) return e;
|
|
40
36
|
let n = {};
|
|
41
37
|
for (let e of Object.keys(t).sort()) n[e] = t[e];
|
|
@@ -47,45 +43,45 @@ function i(n) {
|
|
|
47
43
|
}
|
|
48
44
|
return {
|
|
49
45
|
clear() {
|
|
50
|
-
|
|
46
|
+
a.clear(), o.clear(), s.clear(), c.clear(), l.clear(), u.clear();
|
|
51
47
|
},
|
|
52
|
-
currency(
|
|
53
|
-
let
|
|
54
|
-
...
|
|
55
|
-
currency:
|
|
48
|
+
currency(n, r, i) {
|
|
49
|
+
let a = d(), s = {
|
|
50
|
+
...i,
|
|
51
|
+
currency: r,
|
|
56
52
|
style: "currency"
|
|
57
53
|
};
|
|
58
|
-
return e(
|
|
54
|
+
return e(o, f(a, s), t, () => new Intl.NumberFormat(a, s)).format(n);
|
|
59
55
|
},
|
|
60
|
-
date(
|
|
61
|
-
let
|
|
62
|
-
return e(
|
|
56
|
+
date(n, r) {
|
|
57
|
+
let i = d();
|
|
58
|
+
return e(s, f(i, r), t, () => new Intl.DateTimeFormat(i, r)).format(n);
|
|
63
59
|
},
|
|
64
|
-
duration(
|
|
65
|
-
let
|
|
66
|
-
return
|
|
60
|
+
duration(r, a) {
|
|
61
|
+
let o = d(), s = Intl;
|
|
62
|
+
return s.DurationFormat ? n.every((e) => r[e] === void 0) ? "" : e(u, f(o, a), t, () => new s.DurationFormat(o, a)).format(r) : i(r);
|
|
67
63
|
},
|
|
68
|
-
list(
|
|
69
|
-
let
|
|
70
|
-
return e(
|
|
71
|
-
style:
|
|
72
|
-
type:
|
|
73
|
-
}), () => new Intl.ListFormat(
|
|
74
|
-
style:
|
|
75
|
-
type:
|
|
76
|
-
})).format(
|
|
64
|
+
list(n, r) {
|
|
65
|
+
let i = d(), a = n.map((e) => String(e)), o = r?.style ?? "long", s = r?.type === "or" ? "disjunction" : "conjunction";
|
|
66
|
+
return e(l, f(i, {
|
|
67
|
+
style: o,
|
|
68
|
+
type: s
|
|
69
|
+
}), t, () => new Intl.ListFormat(i, {
|
|
70
|
+
style: o,
|
|
71
|
+
type: s
|
|
72
|
+
})).format(a);
|
|
77
73
|
},
|
|
78
|
-
number(
|
|
79
|
-
let
|
|
80
|
-
return e(
|
|
74
|
+
number(n, r) {
|
|
75
|
+
let i = d();
|
|
76
|
+
return e(a, f(i, r), t, () => new Intl.NumberFormat(i, r)).format(n);
|
|
81
77
|
},
|
|
82
|
-
relative(
|
|
83
|
-
let
|
|
84
|
-
return e(
|
|
78
|
+
relative(n, r, i) {
|
|
79
|
+
let a = d();
|
|
80
|
+
return e(c, f(a, i), t, () => new Intl.RelativeTimeFormat(a, i)).format(n, r);
|
|
85
81
|
}
|
|
86
82
|
};
|
|
87
83
|
}
|
|
88
84
|
//#endregion
|
|
89
|
-
export {
|
|
85
|
+
export { a as createFormatter };
|
|
90
86
|
|
|
91
87
|
//# sourceMappingURL=format.js.map
|
package/dist/format.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["/**\n * /lingua/format\n *\n * Standalone Intl formatter factory. Import from `/lingua/format`.\n * Creates formatters for numbers, dates, currencies, lists, durations, and relative time.\n *\n * Pass a static locale string or a reactive locale getter.\n *\n * @example\n * ```ts\n * import { createFormatter } from '@vielzeug/lingua/format';\n *\n * // Static locale\n * const fmt = createFormatter('en-US');\n *\n * // Reactive — always reads the current locale from the i18n instance\n * const fmt = createFormatter(() => i18n.locale);\n *\n * fmt.number(1_234.56);\n * fmt.currency(9.99, 'USD');\n * fmt.date(new Date());\n * fmt.relative(-1, 'day');\n * fmt.list(['A', 'B', 'C']);\n * fmt.duration({ hours: 1, minutes: 30 });\n * ```\n */\n\nconst FORMAT_CACHE_MAX = 128;\n\nfunction getOrCreate<F>(cache: Map<string, F>, key: string, build: () => F): F {\n const cached = cache.get(key);\n\n if (cached !== undefined) return cached;\n\n const value = build();\n\n if (cache.size >= FORMAT_CACHE_MAX) cache.delete(cache.keys().next().value as string);\n\n cache.set(key, value);\n\n return value;\n}\n\nexport type DurationValue = Partial<\n Record<\n | 'days'\n | 'hours'\n | 'microseconds'\n | 'milliseconds'\n | 'minutes'\n | 'months'\n | 'nanoseconds'\n | 'seconds'\n | 'weeks'\n | 'years',\n number\n >\n>;\n\nexport type DurationFormatOptions = {\n hours?: '2-digit' | 'numeric';\n microseconds?: 'numeric';\n milliseconds?: 'numeric';\n minutes?: '2-digit' | 'numeric';\n nanoseconds?: 'numeric';\n seconds?: '2-digit' | 'numeric';\n style?: 'digital' | 'long' | 'narrow' | 'short';\n};\n\nexport type ListFormatOptions = {\n style?: 'long' | 'narrow' | 'short';\n type?: 'and' | 'or';\n};\n\nexport type Formatter = {\n /**\n * Clears all cached `Intl` formatter instances. Useful after a locale change on a long-running\n * SSR server, or to reclaim memory.\n *\n * @note This clears the cache for **all callers sharing this formatter instance**. When called on\n * `i18n.fmt`, the cache is cleared for every part of the application that reads `i18n.fmt`.\n * `setLocale()` already calls `clear()` automatically — manual calls are rarely needed.\n */\n clear(): void;\n currency(value: number, currency: string, options?: Omit<Intl.NumberFormatOptions, 'currency' | 'style'>): string;\n date(value: Date | number, options?: Intl.DateTimeFormatOptions): string;\n /**\n * Formats a duration using `Intl.DurationFormat` when available, or a compact labeled fallback\n * (e.g. `'1h 30min'`). Returns `''` when every field of `value` is `undefined`.\n *\n * @note The fallback labels (`h`, `min`, `s`, `ms`, etc.) are English-only and are not\n * locale-aware. If `Intl.DurationFormat` is unavailable in your target environment and\n * you need localised duration output, provide your own formatter using the individual\n * duration fields from `DurationValue`.\n */\n duration(value: DurationValue, options?: DurationFormatOptions): string;\n list(value: Array<string | number>, options?: ListFormatOptions): string;\n /** Formats a number with the current locale. */\n number(value: number, options?: Intl.NumberFormatOptions): string;\n relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;\n};\n\n// ─── Internal ─────────────────────────────────────────────────────────────────\n\nconst DURATION_UNITS: Array<keyof DurationValue> = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n];\n\nconst DURATION_LABELS: Record<keyof DurationValue, string> = {\n days: 'd',\n hours: 'h',\n microseconds: 'us',\n milliseconds: 'ms',\n minutes: 'min',\n months: 'mo',\n nanoseconds: 'ns',\n seconds: 's',\n weeks: 'w',\n years: 'y',\n};\n\ntype DurationFormatterCtor = new (\n locale: string,\n options?: DurationFormatOptions,\n) => { format(value: DurationValue): string };\n\nfunction durationLabeled(value: DurationValue): string {\n return DURATION_UNITS.map((unit) => {\n const amount = value[unit];\n\n return typeof amount === 'number' ? `${amount}${DURATION_LABELS[unit]}` : undefined;\n })\n .filter((part): part is string => part !== undefined)\n .join(' ');\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/**\n * Creates a formatter bound to a locale. Pass a static locale string or a\n * reactive getter function `() => string` (e.g. `() => i18n.locale`).\n */\nexport function createFormatter(source: string | (() => string)): Formatter {\n const numberCache = new Map<string, Intl.NumberFormat>();\n const currencyCache = new Map<string, Intl.NumberFormat>();\n const dateCache = new Map<string, Intl.DateTimeFormat>();\n const relativeCache = new Map<string, Intl.RelativeTimeFormat>();\n const listCache = new Map<string, Intl.ListFormat>();\n const durationCache = new Map<string, { format(value: DurationValue): string }>();\n\n const getLocale = typeof source === 'string' ? () => source : source;\n\n function cachedKey(locale: string, options?: object): string {\n if (!options) return locale;\n\n const sorted: Record<string, unknown> = {};\n\n for (const key of Object.keys(options as Record<string, unknown>).sort()) {\n sorted[key] = (options as Record<string, unknown>)[key];\n }\n\n try {\n return `${locale}:${JSON.stringify(sorted)}`;\n } catch {\n // Circular references or BigInt values — fall back to locale-only key.\n // Multiple callers with different unserializable options will share the same formatter instance.\n return locale;\n }\n }\n\n return {\n clear() {\n numberCache.clear();\n currencyCache.clear();\n dateCache.clear();\n relativeCache.clear();\n listCache.clear();\n durationCache.clear();\n },\n\n currency(value, currency, options) {\n const locale = getLocale();\n const opts: Intl.NumberFormatOptions = { ...options, currency, style: 'currency' };\n\n return getOrCreate(currencyCache, cachedKey(locale, opts), () => new Intl.NumberFormat(locale, opts)).format(\n value,\n );\n },\n\n date(value, options) {\n const locale = getLocale();\n\n return getOrCreate(dateCache, cachedKey(locale, options), () => new Intl.DateTimeFormat(locale, options)).format(\n value,\n );\n },\n\n duration(value, options) {\n const locale = getLocale();\n const IntlExt = Intl as typeof Intl & { DurationFormat?: DurationFormatterCtor };\n\n if (!IntlExt.DurationFormat) return durationLabeled(value);\n\n if (DURATION_UNITS.every((u) => value[u] === undefined)) return '';\n\n return getOrCreate(\n durationCache,\n cachedKey(locale, options),\n () => new IntlExt.DurationFormat!(locale, options),\n ).format(value);\n },\n\n list(value, options) {\n const locale = getLocale();\n const items = value.map((v) => String(v));\n // list() has exactly two string options with small finite value domains.\n // We normalize both to their resolved defaults and build the key directly\n // rather than using cachedKey(). This also prevents cache misses when\n // callers pass { style: 'long', type: 'and' } vs {} (same ListFormat).\n const style = options?.style ?? 'long';\n const type = options?.type === 'or' ? 'disjunction' : 'conjunction';\n\n return getOrCreate(\n listCache,\n cachedKey(locale, { style, type }),\n () => new Intl.ListFormat(locale, { style, type }),\n ).format(items);\n },\n\n number(value, options) {\n const locale = getLocale();\n\n return getOrCreate(numberCache, cachedKey(locale, options), () => new Intl.NumberFormat(locale, options)).format(\n value,\n );\n },\n\n relative(value, unit, options) {\n const locale = getLocale();\n\n return getOrCreate(\n relativeCache,\n cachedKey(locale, options),\n () => new Intl.RelativeTimeFormat(locale, options),\n ).format(value, unit);\n },\n };\n}\n"],"mappings":"AA6BA,SAAS,EAAe,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G,CACF;EACF;EAEA,SAAS,GAAO,GAAM,GAAS;GAC7B,IAAM,IAAS,EAAU;GAEzB,OAAO,EACL,GACA,EAAU,GAAQ,CAAO,SACnB,IAAI,KAAK,mBAAmB,GAAQ,CAAO,CACnD,CAAC,CAAC,OAAO,GAAO,CAAI;EACtB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["/**\n * /lingua/format\n *\n * Standalone Intl formatter factory. Import from `/lingua/format`.\n * Creates formatters for numbers, dates, currencies, lists, durations, and relative time.\n *\n * Pass a static locale string or a reactive locale getter.\n *\n * @example\n * ```ts\n * import { createFormatter } from '@vielzeug/lingua/format';\n *\n * // Static locale\n * const fmt = createFormatter('en-US');\n *\n * // Reactive — always reads the current locale from the i18n instance\n * const fmt = createFormatter(() => i18n.locale);\n *\n * fmt.number(1_234.56);\n * fmt.currency(9.99, 'USD');\n * fmt.date(new Date());\n * fmt.relative(-1, 'day');\n * fmt.list(['A', 'B', 'C']);\n * fmt.duration({ hours: 1, minutes: 30 });\n * ```\n */\n\nimport { getOrCreate } from './_bounded-cache';\n\nconst FORMAT_CACHE_MAX = 128;\n\nexport type DurationValue = Partial<\n Record<\n | 'days'\n | 'hours'\n | 'microseconds'\n | 'milliseconds'\n | 'minutes'\n | 'months'\n | 'nanoseconds'\n | 'seconds'\n | 'weeks'\n | 'years',\n number\n >\n>;\n\nexport type DurationFormatOptions = {\n hours?: '2-digit' | 'numeric';\n microseconds?: 'numeric';\n milliseconds?: 'numeric';\n minutes?: '2-digit' | 'numeric';\n nanoseconds?: 'numeric';\n seconds?: '2-digit' | 'numeric';\n style?: 'digital' | 'long' | 'narrow' | 'short';\n};\n\nexport type ListFormatOptions = {\n style?: 'long' | 'narrow' | 'short';\n type?: 'and' | 'or';\n};\n\nexport type Formatter = {\n /**\n * Clears all cached `Intl` formatter instances. Useful after a locale change on a long-running\n * SSR server, or to reclaim memory.\n *\n * @note This clears the cache for **all callers sharing this formatter instance**. When called on\n * `i18n.fmt`, the cache is cleared for every part of the application that reads `i18n.fmt`.\n * `setLocale()` already calls `clear()` automatically — manual calls are rarely needed.\n */\n clear(): void;\n currency(value: number, currency: string, options?: Omit<Intl.NumberFormatOptions, 'currency' | 'style'>): string;\n date(value: Date | number, options?: Intl.DateTimeFormatOptions): string;\n /**\n * Formats a duration using `Intl.DurationFormat` when available, or a compact labeled fallback\n * (e.g. `'1h 30min'`). Returns `''` when every field of `value` is `undefined`.\n *\n * @note The fallback labels (`h`, `min`, `s`, `ms`, etc.) are English-only and are not\n * locale-aware. If `Intl.DurationFormat` is unavailable in your target environment and\n * you need localised duration output, provide your own formatter using the individual\n * duration fields from `DurationValue`.\n */\n duration(value: DurationValue, options?: DurationFormatOptions): string;\n list(value: Array<string | number>, options?: ListFormatOptions): string;\n /** Formats a number with the current locale. */\n number(value: number, options?: Intl.NumberFormatOptions): string;\n relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string;\n};\n\n// ─── Internal ─────────────────────────────────────────────────────────────────\n\nconst DURATION_UNITS: Array<keyof DurationValue> = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n];\n\nconst DURATION_LABELS: Record<keyof DurationValue, string> = {\n days: 'd',\n hours: 'h',\n microseconds: 'us',\n milliseconds: 'ms',\n minutes: 'min',\n months: 'mo',\n nanoseconds: 'ns',\n seconds: 's',\n weeks: 'w',\n years: 'y',\n};\n\ntype DurationFormatterCtor = new (\n locale: string,\n options?: DurationFormatOptions,\n) => { format(value: DurationValue): string };\n\nfunction durationLabeled(value: DurationValue): string {\n return DURATION_UNITS.map((unit) => {\n const amount = value[unit];\n\n return typeof amount === 'number' ? `${amount}${DURATION_LABELS[unit]}` : undefined;\n })\n .filter((part): part is string => part !== undefined)\n .join(' ');\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/**\n * Creates a formatter bound to a locale. Pass a static locale string or a\n * reactive getter function `() => string` (e.g. `() => i18n.locale`).\n */\nexport function createFormatter(source: string | (() => string)): Formatter {\n const numberCache = new Map<string, Intl.NumberFormat>();\n const currencyCache = new Map<string, Intl.NumberFormat>();\n const dateCache = new Map<string, Intl.DateTimeFormat>();\n const relativeCache = new Map<string, Intl.RelativeTimeFormat>();\n const listCache = new Map<string, Intl.ListFormat>();\n const durationCache = new Map<string, { format(value: DurationValue): string }>();\n\n const getLocale = typeof source === 'string' ? () => source : source;\n\n function cachedKey(locale: string, options?: object): string {\n if (!options) return locale;\n\n const sorted: Record<string, unknown> = {};\n\n for (const key of Object.keys(options as Record<string, unknown>).sort()) {\n sorted[key] = (options as Record<string, unknown>)[key];\n }\n\n try {\n return `${locale}:${JSON.stringify(sorted)}`;\n } catch {\n // Circular references or BigInt values — fall back to locale-only key.\n // Multiple callers with different unserializable options will share the same formatter instance.\n return locale;\n }\n }\n\n return {\n clear() {\n numberCache.clear();\n currencyCache.clear();\n dateCache.clear();\n relativeCache.clear();\n listCache.clear();\n durationCache.clear();\n },\n\n currency(value, currency, options) {\n const locale = getLocale();\n const opts: Intl.NumberFormatOptions = { ...options, currency, style: 'currency' };\n\n return getOrCreate(\n currencyCache,\n cachedKey(locale, opts),\n FORMAT_CACHE_MAX,\n () => new Intl.NumberFormat(locale, opts),\n ).format(value);\n },\n\n date(value, options) {\n const locale = getLocale();\n\n return getOrCreate(\n dateCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new Intl.DateTimeFormat(locale, options),\n ).format(value);\n },\n\n duration(value, options) {\n const locale = getLocale();\n const IntlExt = Intl as typeof Intl & { DurationFormat?: DurationFormatterCtor };\n\n if (!IntlExt.DurationFormat) return durationLabeled(value);\n\n if (DURATION_UNITS.every((u) => value[u] === undefined)) return '';\n\n return getOrCreate(\n durationCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new IntlExt.DurationFormat!(locale, options),\n ).format(value);\n },\n\n list(value, options) {\n const locale = getLocale();\n const items = value.map((v) => String(v));\n // list() has exactly two string options with small finite value domains.\n // We normalize both to their resolved defaults and build the key directly\n // rather than using cachedKey(). This also prevents cache misses when\n // callers pass { style: 'long', type: 'and' } vs {} (same ListFormat).\n const style = options?.style ?? 'long';\n const type = options?.type === 'or' ? 'disjunction' : 'conjunction';\n\n return getOrCreate(\n listCache,\n cachedKey(locale, { style, type }),\n FORMAT_CACHE_MAX,\n () => new Intl.ListFormat(locale, { style, type }),\n ).format(items);\n },\n\n number(value, options) {\n const locale = getLocale();\n\n return getOrCreate(\n numberCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new Intl.NumberFormat(locale, options),\n ).format(value);\n },\n\n relative(value, unit, options) {\n const locale = getLocale();\n\n return getOrCreate(\n relativeCache,\n cachedKey(locale, options),\n FORMAT_CACHE_MAX,\n () => new Intl.RelativeTimeFormat(locale, options),\n ).format(value, unit);\n },\n };\n}\n"],"mappings":";;AA6BA,IAAM,IAAmB,KA+DnB,IAA6C;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,GAEM,IAAuD;CAC3D,MAAM;CACN,OAAO;CACP,cAAc;CACd,cAAc;CACd,SAAS;CACT,QAAQ;CACR,aAAa;CACb,SAAS;CACT,OAAO;CACP,OAAO;AACT;AAOA,SAAS,EAAgB,GAA8B;CACrD,OAAO,EAAe,KAAK,MAAS;EAClC,IAAM,IAAS,EAAM;EAErB,OAAO,OAAO,KAAW,WAAW,GAAG,IAAS,EAAgB,OAAU,KAAA;CAC5E,CAAC,CAAC,CACC,QAAQ,MAAyB,MAAS,KAAA,CAAS,CAAC,CACpD,KAAK,GAAG;AACb;AAQA,SAAgB,EAAgB,GAA4C;CAC1E,IAAM,oBAAc,IAAI,IAA+B,GACjD,oBAAgB,IAAI,IAA+B,GACnD,oBAAY,IAAI,IAAiC,GACjD,oBAAgB,IAAI,IAAqC,GACzD,oBAAY,IAAI,IAA6B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M,OAAO,CAAC,CAAC,GAKlC,IAAQ,GAAS,SAAS,QAC1B,IAAO,GAAS,SAAS,OAAO,gBAAgB;GAEtD,OAAO,EACL,GACA,EAAU,GAAQ;IAAE;IAAO;GAAK,CAAC,GACjC,SACM,IAAI,KAAK,WAAW,GAAQ;IAAE;IAAO;GAAK,CAAC,CACnD,CAAC,CAAC,OAAO,CAAK;EAChB;EAEA,OAAO,GAAO,GAAS;GACrB,IAAM,IAAS,EAAU;GAEzB,OAAO,EACL,GACA,EAAU,GAAQ,CAAO,GACzB,SACM,IAAI,KAAK,aAAa,GAAQ,CAAO,CAC7C,CAAC,CAAC,OAAO,CAAK;EAChB;EAEA,SAAS,GAAO,GAAM,GAAS;GAC7B,IAAM,IAAS,EAAU;GAEzB,OAAO,EACL,GACA,EAAU,GAAQ,CAAO,GACzB,SACM,IAAI,KAAK,mBAAmB,GAAQ,CAAO,CACnD,CAAC,CAAC,OAAO,GAAO,CAAI;EACtB;CACF;AACF"}
|
package/dist/i18n-types.d.ts
CHANGED
|
@@ -143,6 +143,10 @@ export type I18n<M extends Messages = Messages> = {
|
|
|
143
143
|
* Returns `true` if the given key exists in the active fallback chain — either as a leaf
|
|
144
144
|
* string key or as a plural branch (any key under `key.` prefix).
|
|
145
145
|
*
|
|
146
|
+
* **Note:** a branch-only key (e.g. `items` when only `items.one`/`items.other` exist) makes
|
|
147
|
+
* `has()` return `true`, but `t()` can't resolve it — use `tp(key, count)` for those. Calling
|
|
148
|
+
* `t()` on a branch-only key logs a dev-mode warning pointing at this.
|
|
149
|
+
*
|
|
146
150
|
* @example
|
|
147
151
|
* i18n.has('inbox') // true for leaf or pipe-plural expanded branch
|
|
148
152
|
* i18n.has('inbox.one') // true for explicit sub-key
|
|
@@ -204,6 +208,10 @@ export type I18n<M extends Messages = Messages> = {
|
|
|
204
208
|
* @remarks The namespace registry is **not** included in `I18nState`. After restoring,
|
|
205
209
|
* call `extend()` for each namespace before relying on namespace-patched keys.
|
|
206
210
|
*
|
|
211
|
+
* @remarks Unlike `register()` and construction, this does **not** run the automatic
|
|
212
|
+
* dev-mode plural-form check — the assumption is that `state` was already registered (and
|
|
213
|
+
* therefore already checked) once on whatever system produced it.
|
|
214
|
+
*
|
|
207
215
|
* @throws `LinguaDisposedError` if called on a disposed instance.
|
|
208
216
|
* @throws `LinguaRestoreError` if the state's locale has no catalog.
|
|
209
217
|
*/
|
|
@@ -211,7 +219,10 @@ export type I18n<M extends Messages = Messages> = {
|
|
|
211
219
|
/**
|
|
212
220
|
* Returns a scoped translator. All `t()` / `tp()` calls are automatically prefixed with `${prefix}.`.
|
|
213
221
|
* The returned object is memoized — calling `scope(prefix)` with the same string always returns the
|
|
214
|
-
* same reference
|
|
222
|
+
* same reference, as long as it's still in the cache (bounded at 128 distinct prefixes; oldest
|
|
223
|
+
* evicts first). Intended for a static, finite set of prefixes (nav sections, form names, ...) —
|
|
224
|
+
* don't pass a dynamic per-item prefix (e.g. `scope(`item.${id}`)` in a list render), or the
|
|
225
|
+
* memoization guarantee stops holding once you exceed the bound.
|
|
215
226
|
*
|
|
216
227
|
* @example
|
|
217
228
|
* const nav = i18n.scope('nav');
|
package/dist/i18n-types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n-types.d.ts","sourceRoot":"","sources":["../src/i18n-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAE1C,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC;AAC5B,MAAM,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC;AAErC,YAAY,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,YAAY,EAAE,M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AOG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC;;;;;;OAMG;IACH,SAAS,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,YAAY,KAAK,IAAI,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,WAAW,CAAC;IAC/F,yFAAyF;IACzF,CAAC,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,aAAa,GAAG,MAAM,CAAC;IACzE;;;;;;OAMG;IACH,EAAE,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS,GAAG,MAAM,CAAC;CAC3F,CAAC"}
|
package/dist/i18n.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./
|
|
1
|
+
const e=require("./_bounded-cache.cjs"),t=require("./format.cjs"),n=require("./_dev.cjs"),r=require("./_catalog.cjs"),i=require("./errors.cjs"),a=require("./_catalog-store.cjs"),o=require("./_chain.cjs"),s=require("./_namespace-store.cjs"),c=require("./_translate.cjs");var l=128;function u(e,t,n){let{chain:r,set:i}=o.buildLocaleChain(e,t,n);return{chain:r,chainSet:i,locale:e}}function d(e){return f(e)}function f(d,p){let m=d??{},h=o.createLocaleCaches(),g=e=>o.canon(e,h),_=Array.isArray(m.fallback)?m.fallback.map(g):m.fallback?[g(m.fallback)]:[],v=!1,y=new AbortController,b=a.createCatalogStore(()=>v),x=s.createNamespaceStore(()=>v),S=u(g(m.locale??`en`),_,h),C=new Set,w=new Set,T=m.onMissingKey??(e=>e),E=m.onMissingVar??(e=>`{${e}}`),D=m.onSubscriberError??(e=>n.error(`subscriber error`,e)),O,k=new Map,A=()=>(O||=t.createFormatter(()=>S.locale),O),j=()=>({caches:h,catalogStore:b,chain:S.chain,locale:S.locale,onMissingKey:T,onMissingVar:E}),M=e=>c.hasKey(j(),e),N=(e,t)=>c.translate(j(),String(e),t),P=(e,t,n)=>c.translatePlural(j(),String(e),t,n),F={locale:S.locale,t:N,tp:P},I=()=>{F={locale:S.locale,t:N,tp:P};let e=[...C];for(let t of e)try{t(F)}catch(e){D(e)}};if(b.onChange=e=>{S.chainSet.has(e)&&I()},p?.catalogStore&&b.seedFrom(p.catalogStore.snapshotCatalogs(),p.catalogStore.snapshotLoaders()),p?.nsStore&&x.seedFrom(p.nsStore),m.catalogs){let e=new Map,t=new Map;for(let[n,i]of Object.entries(m.catalogs)){let o=g(n);if(typeof i==`function`)t.set(o,i);else{let t=new r.CatalogEntry;t.setAll(r.flattenStrings(i)),e.set(o,t),a.validateCatalogInDev(o,i)}}b.seedFrom(e,t)}let L=e=>b.preload(g(e)),R=0,z={get disposalSignal(){return y.signal},dispose(){if(!v){v=!0,y.abort();for(let e of[...w])e();w.clear(),C.clear(),b.dispose(),x.dispose(),k.clear()}},get disposed(){return v},extend(e,t,n){i.checkDisposed(v),x.registerNamespace(e,t);let r=n?g(n):S.locale;return x.loadNamespace(e,r,(e,t)=>b.patch(e,t))},get fmt(){return A()},fork(e){return f({fallback:e?.fallback??(_.length>0?_:void 0),locale:e?.locale??S.locale,onMissingKey:e?.onMissingKey??m.onMissingKey,onMissingVar:e?.onMissingVar??m.onMissingVar,onSubscriberError:e?.onSubscriberError??m.onSubscriberError},{catalogStore:b,nsStore:x})},getSnapshot(){return F},getState(){let e={};for(let[t,n]of b.snapshotCatalogs())e[t]=Object.fromEntries([...n.entries.entries()].map(([e,{message:t}])=>[e,t]));return{catalogs:e,locale:S.locale}},getSupportedLocales(e){let t=[...b.knownLocales()];return e===!0?t.sort():t},has(e){return M(String(e))},isLoaded(e){try{return b.isLoaded(g(e))}catch{return!1}},isNamespaceLoaded(e,t){if(!t)return x.isLoaded(e,S.locale);try{return x.isLoaded(e,g(t))}catch{return!1}},isNamespaceRegistered(e){return x.isRegistered(e)},isRegistered(e){try{return b.isRegistered(g(e))}catch{return!1}},loadNamespace(e,t){let n=t?g(t):S.locale;return x.loadNamespace(e,n,(e,t)=>b.patch(e,t))},get locale(){return S.locale},preload:L,register(e,t){let n=g(e);return b.register(n,t,x)},registerNamespace(e,t){x.registerNamespace(e,t)},restoreState(e){if(i.checkDisposed(v),!Object.hasOwn(e.catalogs,e.locale))throw new i.LinguaRestoreError(`restoreState: locale "${e.locale}" has no catalog in the provided state.`);let t=new Map,n=b.knownLocales();for(let e of n)x.clearLocale(e);for(let[n,i]of Object.entries(e.catalogs)){let e=g(n),a=new r.CatalogEntry;a.setAll(Object.entries(i)),t.set(e,a)}b.dispose(),b.onChange=e=>{S.chainSet.has(e)&&I()},b.seedFrom(t,new Map),S=u(g(e.locale),_,h),O?.clear(),I()},scope(t){let n=String(t);return e.getOrCreate(k,n,l,()=>({get fmt(){return A()},has:e=>M(`${n}.${e}`),t:(e,t)=>N(`${n}.${e}`,t),tp:(e,t,r)=>P(`${n}.${e}`,t,r)}))},async setLocale(e){i.checkDisposed(v);let t=g(e);if(S.locale===t)return;let n=++R;await L(t),!(v||R!==n)&&(S=u(t,_,h),O?.clear(),I())},subscribe:(e,t)=>{let n=t?.signal,r=()=>{C.delete(e),n?.removeEventListener(`abort`,r),w.delete(r)};if(v)throw new i.LinguaDisposedError;if(n?.aborted)return r;if(t?.immediate===!0)try{e(F)}catch(e){return D(e),r}return C.add(e),n?.addEventListener(`abort`,r,{once:!0}),w.add(r),r},[Symbol.dispose](){z.dispose()},t:N,tp:P};return z}exports.LinguaCountInVarsError=i.LinguaCountInVarsError,exports.LinguaDisposedError=i.LinguaDisposedError,exports.LinguaError=i.LinguaError,exports.LinguaInvalidCountError=i.LinguaInvalidCountError,exports.LinguaInvalidLocaleError=i.LinguaInvalidLocaleError,exports.LinguaMissingLocaleError=i.LinguaMissingLocaleError,exports.LinguaNamespaceMissingError=i.LinguaNamespaceMissingError,exports.LinguaRestoreError=i.LinguaRestoreError,exports.createI18n=d;
|
|
2
2
|
//# sourceMappingURL=i18n.cjs.map
|
package/dist/i18n.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n.cjs","names":[],"sources":["../src/i18n.ts"],"sourcesContent":["import type {\n I18n,\n I18nOptions,\n I18nSnapshot,\n I18nState,\n Locale,\n MessageBranchKeys,\n MessageLeafKeys,\n ScopedI18n,\n SubscribeOptions,\n TpOptions,\n TranslateVars,\n Unsubscribe,\n} from './i18n-types';\n\nimport { CatalogEntry, type Messages, flattenStrings } from './_catalog';\nimport { type CatalogStore, type Loader, type LocaleSource, createCatalogStore } from './_catalog-store';\nimport { type LocaleCaches, buildLocaleChain, canon, createLocaleCaches, selectPluralForm } from './_chain';\nimport { error as logError } from './_dev';\nimport { type NamespaceFactory, type NamespaceStore, createNamespaceStore } from './_namespace-store';\nimport {\n LinguaCountInVarsError,\n LinguaDisposedError,\n LinguaInvalidCountError,\n LinguaRestoreError,\n checkDisposed,\n} from './errors';\nimport { type Formatter, createFormatter } from './format';\nimport { type CompiledTemplate, renderTemplate } from './template';\n\nexport {\n LinguaCountInVarsError,\n LinguaDisposedError,\n LinguaError,\n LinguaInvalidCountError,\n LinguaInvalidLocaleError,\n LinguaMissingLocaleError,\n LinguaNamespaceMissingError,\n LinguaRestoreError,\n} from './errors';\n\nexport type {\n I18n,\n I18nOptions,\n I18nSnapshot,\n I18nState,\n Locale,\n MessageBranchKeys,\n MessageLeafKeys,\n ScopedI18n,\n SubscribeOptions,\n TpOptions,\n TranslateVars,\n Unsubscribe,\n} from './i18n-types';\nexport type { Loader, LocaleSource } from './_catalog-store';\nexport type { Messages } from './_catalog';\nexport type { NamespaceFactory } from './_namespace-store';\n\n// ─── Locale state ─────────────────────────────────────────────────────────────\n// Replaced atomically on every locale change.\n\ntype LocaleState = {\n readonly chain: readonly Locale[];\n readonly chainSet: ReadonlySet<Locale>;\n readonly locale: Locale;\n};\n\nfunction buildState(locale: Locale, fallback: Locale[], caches: LocaleCaches): LocaleState {\n const { chain, set } = buildLocaleChain(locale, fallback, caches);\n\n return { chain, chainSet: set, locale };\n}\n\n// ─── Plural key priority ──────────────────────────────────────────────────────\n// Cardinal zero: try .zero override first, then CLDR form, then .other as final fallback.\n// Ordinal / non-zero: try CLDR form, then .other as final fallback.\nfunction pluralKeyPriority(base: string, form: string, count: number, ordinal: boolean): string[] {\n const keys: string[] = [];\n\n if (!ordinal && count === 0) keys.push(`${base}.zero`);\n\n if (form !== 'zero' || ordinal) keys.push(`${base}.${form}`);\n\n if (form !== 'other') keys.push(`${base}.other`);\n\n return keys;\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/** Overload: explicit type parameter (strict typing) */\nexport function createI18n<M extends Messages>(config: I18nOptions<M>): I18n<M>;\n/** Overload: no type parameter (loose typing, allows heterogeneous catalogs) */\nexport function createI18n(config?: I18nOptions<Messages>): I18n<Messages>;\nexport function createI18n<M extends Messages = Messages>(config?: I18nOptions<M>): I18n<M> {\n return _createI18nImpl<M>(config);\n}\n\n// ─── Internal seed shape ──────────────────────────────────────────────────────\n\ntype I18nSeed<M extends Messages> = {\n catalogStore?: CatalogStore<M>;\n nsStore?: NamespaceStore;\n};\n\nfunction _createI18nImpl<M extends Messages = Messages>(config?: I18nOptions<M>, _seed?: I18nSeed<M>): I18n<M> {\n const cfg: I18nOptions<M> = config ?? {};\n\n // ─── Per-instance caches (no shared module-level state) ───────────────────\n const caches: LocaleCaches = createLocaleCaches();\n\n const canonL = (loc: string) => canon(loc, caches);\n\n const fallback = Array.isArray(cfg.fallback) ? cfg.fallback.map(canonL) : cfg.fallback ? [canonL(cfg.fallback)] : [];\n\n // ─── Disposal ─────────────────────────────────────────────────────────────\n let disposed = false;\n const disposeController = new AbortController();\n\n // ─── Bounded stores ───────────────────────────────────────────────────────\n const catalogStore: CatalogStore<M> = createCatalogStore(() => disposed);\n const nsStore: NamespaceStore = createNamespaceStore(() => disposed);\n\n // ─── Locale state ─────────────────────────────────────────────────────────\n let state: LocaleState = buildState(canonL(cfg.locale ?? 'en'), fallback, caches);\n\n // ─── Subscribers ──────────────────────────────────────────────────────────\n const subscribers = new Set<(snapshot: I18nSnapshot) => void>();\n const subscriptionUnsubscribers = new Set<Unsubscribe>();\n\n const onMissingKey = cfg.onMissingKey ?? ((key: string) => key);\n const onMissingVar = cfg.onMissingVar ?? ((varName: string) => `{${varName}}`);\n const onSubscriberError = cfg.onSubscriberError ?? ((error: unknown) => logError('subscriber error', error));\n\n // ─── Lazy formatter — avoids Intl overhead for SSR forks that only need t(). ──\n let _fmt: Formatter | undefined;\n\n // ─── Scope cache — stable object references per prefix for reactive framework renders. ──\n const scopeCache = new Map<string, ScopedI18n>();\n\n const getFormatter = (): Formatter => {\n if (!_fmt) _fmt = createFormatter(() => state.locale);\n\n return _fmt;\n };\n\n // ─── Translate helpers ────────────────────────────────────────────────────\n\n // Single-pass entry lookup across the active fallback chain.\n const findEntry = (key: string): { compiled: CompiledTemplate; message: string } | undefined => {\n for (const candidate of state.chain) {\n const found = catalogStore.resolve(candidate)?.get(key);\n\n if (found !== undefined) return found;\n }\n\n return undefined;\n };\n\n // Shared by has() and scope().has() — true if `base` exists as a leaf key or a plural branch prefix.\n const hasKey = (base: string): boolean => {\n if (findEntry(base) !== undefined) return true;\n\n for (const candidate of state.chain) {\n const catalog = catalogStore.resolve(candidate);\n\n if (!catalog) continue;\n\n if (catalog.prefixes.has(base)) return true;\n }\n\n return false;\n };\n\n const interpolate = (\n key: string,\n found: { compiled: CompiledTemplate; message: string },\n vars: TranslateVars | undefined,\n ): string => renderTemplate(found.compiled, vars, key, state.locale, onMissingVar);\n\n const translate = (key: MessageLeafKeys<M> | (string & {}), vars?: TranslateVars): string => {\n const base = String(key);\n const found = findEntry(base);\n\n if (!found) return onMissingKey(base, state.locale);\n\n return interpolate(base, found, vars);\n };\n\n const translatePlural = (key: MessageBranchKeys<M> | (string & {}), count: number, options?: TpOptions): string => {\n if (!Number.isFinite(count)) {\n throw new LinguaInvalidCountError('`count` must be a finite number.');\n }\n\n const vars = options?.vars;\n const ordinal = options?.ordinal ?? false;\n\n if (vars && Object.hasOwn(vars, 'count')) {\n throw new LinguaCountInVarsError('`tp` does not allow `vars.count`; `count` is injected automatically.');\n }\n\n const base = String(key);\n const mergedVars = vars ? { count, ...vars } : { count };\n\n // Walk the fallback chain locale-by-locale, selecting CLDR plural form using each\n // locale's own rules. This ensures cross-locale fallbacks produce grammatically correct forms.\n for (const candidate of state.chain) {\n const catalog = catalogStore.resolve(candidate);\n\n if (!catalog) continue;\n\n const form = selectPluralForm(candidate, count, ordinal, caches);\n const keys = pluralKeyPriority(base, form, count, ordinal);\n\n for (const k of keys) {\n const found = catalog.get(k);\n\n if (found !== undefined) {\n return interpolate(k, found, mergedVars);\n }\n }\n }\n\n return onMissingKey(base, state.locale);\n };\n\n // ─── bump() ───────────────────────────────────────────────────────────────\n // Rebuilds the snapshot and notifies all current subscribers.\n\n let snapshot: I18nSnapshot = {\n locale: state.locale,\n t: translate,\n tp: translatePlural,\n };\n\n const bump = (): void => {\n snapshot = { locale: state.locale, t: translate, tp: translatePlural };\n\n const listeners = [...subscribers];\n\n for (const listener of listeners) {\n try {\n listener(snapshot);\n } catch (error) {\n onSubscriberError(error);\n }\n }\n };\n\n // ─── Wire catalog store onChange → bump ───────────────────────────────────\n catalogStore.onChange = (loc: Locale) => {\n if (state.chainSet.has(loc)) bump();\n };\n\n // ─── Seed from parent fork ─────────────────────────────────────────────────\n if (_seed?.catalogStore) {\n catalogStore.seedFrom(_seed.catalogStore.catalogs, _seed.catalogStore.pendingLoaders);\n }\n\n if (_seed?.nsStore) {\n nsStore.seedFrom(_seed.nsStore);\n }\n\n // ─── Initial catalogs from config ─────────────────────────────────────────\n if (cfg.catalogs) {\n const staticEntries = new Map<Locale, CatalogEntry>();\n const loaderEntries = new Map<Locale, Loader<M>>();\n\n for (const [loc, source] of Object.entries(cfg.catalogs)) {\n const normalized = canonL(loc);\n\n if (typeof source === 'function') {\n loaderEntries.set(normalized, source as Loader<M>);\n } else {\n const entry = new CatalogEntry();\n\n entry.setAll(flattenStrings(source as M));\n staticEntries.set(normalized, entry);\n }\n }\n\n // Use seedFrom for zero-overhead init (no bump, no notifications during setup)\n catalogStore.seedFrom(staticEntries, loaderEntries);\n }\n\n // ─── Preload helper ───────────────────────────────────────────────────────\n\n const preload = (loc: Locale): Promise<void> => catalogStore.preload(canonL(loc));\n\n // ─── Monotonic generation counter — last writer wins for concurrent setLocale() ──\n let switchGen = 0;\n\n // ─── Subscribe helper ─────────────────────────────────────────────────────\n\n const subscribeInternal = (callback: (snapshot: I18nSnapshot) => void, options?: SubscribeOptions): Unsubscribe => {\n const signal = options?.signal;\n\n const unsubscribe = (): void => {\n subscribers.delete(callback);\n signal?.removeEventListener('abort', unsubscribe);\n subscriptionUnsubscribers.delete(unsubscribe);\n };\n\n if (disposed) throw new LinguaDisposedError();\n\n if (signal?.aborted) return unsubscribe;\n\n if (options?.immediate === true) {\n try {\n callback(snapshot);\n } catch (error) {\n onSubscriberError(error);\n\n return unsubscribe;\n }\n }\n\n subscribers.add(callback);\n signal?.addEventListener('abort', unsubscribe, { once: true });\n subscriptionUnsubscribers.add(unsubscribe);\n\n return unsubscribe;\n };\n\n // ─── Public object ─────────────────────────────────────────────────────────\n\n return {\n get disposalSignal(): AbortSignal {\n return disposeController.signal;\n },\n\n dispose(): void {\n if (disposed) return;\n\n disposed = true;\n disposeController.abort();\n for (const unsubscribe of [...subscriptionUnsubscribers]) unsubscribe();\n subscriptionUnsubscribers.clear();\n subscribers.clear();\n catalogStore.dispose();\n nsStore.dispose();\n scopeCache.clear();\n },\n\n get disposed(): boolean {\n return disposed;\n },\n\n extend(ns: string, factory: NamespaceFactory, loc?: Locale): Promise<void> {\n checkDisposed(disposed);\n\n nsStore.registerNamespace(ns, factory);\n\n const normalized = loc ? canonL(loc) : state.locale;\n\n return nsStore.loadNamespace(ns, normalized, (l, messages) => catalogStore.patch(l, messages));\n },\n\n get fmt(): Formatter {\n return getFormatter();\n },\n\n fork(overrides?: Omit<I18nOptions<M>, 'catalogs'>): I18n<M> {\n return _createI18nImpl(\n {\n fallback: overrides?.fallback ?? (fallback.length > 0 ? fallback : undefined),\n locale: overrides?.locale ?? state.locale,\n onMissingKey: overrides?.onMissingKey ?? cfg.onMissingKey,\n onMissingVar: overrides?.onMissingVar ?? cfg.onMissingVar,\n onSubscriberError: overrides?.onSubscriberError ?? cfg.onSubscriberError,\n },\n {\n catalogStore: catalogStore as CatalogStore<M>,\n nsStore: nsStore as NamespaceStore,\n },\n );\n },\n\n getSnapshot() {\n return snapshot;\n },\n\n getState(): I18nState {\n const catalogsOut: Record<Locale, Record<string, string>> = {};\n\n for (const [loc, entry] of catalogStore.catalogs) {\n catalogsOut[loc] = Object.fromEntries([...entry.entries.entries()].map(([k, { message }]) => [k, message]));\n }\n\n return { catalogs: catalogsOut, locale: state.locale };\n },\n\n getSupportedLocales(sorted?: boolean): Locale[] {\n const locales = [...catalogStore.knownLocales()];\n\n return sorted === true ? locales.sort() : locales;\n },\n\n has(key: MessageLeafKeys<M> | MessageBranchKeys<M> | (string & {})): boolean {\n return hasKey(String(key));\n },\n\n isLoaded(loc: Locale): boolean {\n try {\n return catalogStore.isLoaded(canonL(loc));\n } catch {\n return false;\n }\n },\n\n isNamespaceLoaded(ns: string, loc?: Locale): boolean {\n if (!loc) return nsStore.isLoaded(ns, state.locale);\n\n try {\n return nsStore.isLoaded(ns, canonL(loc));\n } catch {\n return false;\n }\n },\n\n isNamespaceRegistered(ns: string): boolean {\n return nsStore.isRegistered(ns);\n },\n\n isRegistered(loc: Locale): boolean {\n try {\n return catalogStore.isRegistered(canonL(loc));\n } catch {\n return false;\n }\n },\n\n loadNamespace(ns: string, loc?: Locale): Promise<void> {\n const normalized = loc ? canonL(loc) : state.locale;\n\n return nsStore.loadNamespace(ns, normalized, (l, messages) => catalogStore.patch(l, messages));\n },\n\n get locale(): Locale {\n return state.locale;\n },\n\n preload,\n\n register(loc: Locale, source: LocaleSource<M>): Promise<void> {\n const normalized = canonL(loc);\n\n return catalogStore.register(normalized, source, nsStore);\n },\n\n registerNamespace(ns: string, factory: NamespaceFactory): void {\n nsStore.registerNamespace(ns, factory);\n },\n\n restoreState(st: I18nState): void {\n checkDisposed(disposed);\n\n if (!Object.hasOwn(st.catalogs, st.locale)) {\n throw new LinguaRestoreError(`restoreState: locale \"${st.locale}\" has no catalog in the provided state.`);\n }\n\n const freshEntries = new Map<Locale, CatalogEntry>();\n const knownLocales = catalogStore.knownLocales();\n\n for (const knownLocale of knownLocales) {\n nsStore.clearLocale(knownLocale);\n }\n\n for (const [loc, flatCatalog] of Object.entries(st.catalogs)) {\n const normalized = canonL(loc);\n const entry = new CatalogEntry();\n\n entry.setAll(Object.entries(flatCatalog));\n freshEntries.set(normalized, entry);\n }\n\n // Dispose and re-seed the catalog store with the restored entries.\n // onChange is re-wired immediately after dispose.\n catalogStore.dispose();\n catalogStore.onChange = (loc: Locale) => {\n if (state.chainSet.has(loc)) bump();\n };\n catalogStore.seedFrom(freshEntries, new Map());\n\n const normalized = canonL(st.locale);\n\n state = buildState(normalized, fallback, caches);\n _fmt?.clear();\n bump();\n },\n\n scope(prefix: MessageBranchKeys<M> | (string & {})): ScopedI18n {\n const pre = String(prefix);\n const cached = scopeCache.get(pre);\n\n if (cached) return cached;\n\n const scoped: ScopedI18n = {\n get fmt() {\n return getFormatter();\n },\n has: (key) => hasKey(`${pre}.${key}`),\n t: (key, vars?) => translate(`${pre}.${key}`, vars),\n tp: (key, count, options?) => translatePlural(`${pre}.${key}`, count, options),\n };\n\n scopeCache.set(pre, scoped);\n\n return scoped;\n },\n\n async setLocale(next: Locale): Promise<void> {\n checkDisposed(disposed);\n\n const normalized = canonL(next);\n\n if (state.locale === normalized) return;\n\n // Monotonic generation counter — last writer wins.\n const gen = ++switchGen;\n\n await preload(normalized);\n\n if (disposed || switchGen !== gen) return;\n\n state = buildState(normalized, fallback, caches);\n _fmt?.clear();\n bump();\n },\n\n subscribe: subscribeInternal,\n\n [Symbol.dispose](): void {\n this.dispose();\n },\n\n t: translate,\n\n tp: translatePlural,\n };\n}\n\n// ─── SSR standalone helpers ───────────────────────────────────────────────────\n\n/**\n * Serialises the currently loaded catalogs and active locale into a plain object.\n * Pass the result to `hydrateI18n()` on the client.\n *\n * Prefer calling `i18n.getState()` directly — these standalone functions are provided\n * for convenience when you receive a plain `I18n` reference without the full type.\n *\n * **Warning:** Only fully resolved catalogs are included. Loader-only locales not yet\n * preloaded are omitted. Use `i18n.isLoaded(locale)` to verify before calling.\n *\n * **Warning:** The namespace registry is **not** serialized — factory functions cannot\n * be converted to JSON. After `hydrateI18n()`, call `extend()` again for each namespace\n * before relying on namespace-patched keys.\n */\nexport function serializeI18n(i18n: I18n): I18nState {\n return i18n.getState();\n}\n\n/**\n * Hydrates an i18n instance with pre-loaded state (e.g. from a server-rendered payload).\n *\n * Prefer calling `i18n.restoreState(state)` directly — these standalone functions are\n * provided for convenience.\n *\n * @remarks The namespace registry is **not** included in `I18nState`. After hydrating,\n * call `extend()` for each namespace before relying on namespace-patched keys.\n *\n * @throws `LinguaDisposedError` if called on a disposed instance.\n * @throws `LinguaRestoreError` if the state's locale has no catalog.\n */\nexport function hydrateI18n(i18n: I18n, state: I18nState): void {\n i18n.restoreState(state);\n}\n"],"mappings":"0OAoEA,SAAS,EAAW,EAAgB,EAAoB,EAAmC,CACzF,GAAM,CAAE,QAAO,OAAQ,EAAA,iBAAiB,EAAQ,EAAU,CAAM,EAEhE,MAAO,CAAE,QAAO,SAAU,EAAK,QAAO,CACxC,CAKA,SAAS,EAAkB,EAAc,EAAc,EAAe,EAA4B,CAChG,IAAM,EAAiB,CAAC,EAQxB,MANI,CAAC,GAAW,IAAU,GAAG,EAAK,KAAK,GAAG,EAAK,MAAM,GAEjD,IAAS,QAAU,IAAS,EAAK,KAAK,GAAG,EAAK,GAAG,GAAM,EAEvD,IAAS,SAAS,EAA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\n MessageLeafKeys,\n ScopedI18n,\n SubscribeOptions,\n TpOptions,\n TranslateVars,\n Unsubscribe,\n} from './i18n-types';\n\nimport { getOrCreate } from './_bounded-cache';\nimport { CatalogEntry, type Messages, flattenStrings } from './_catalog';\nimport {\n type CatalogStore,\n type Loader,\n type LocaleSource,\n createCatalogStore,\n validateCatalogInDev,\n} from './_catalog-store';\nimport { type LocaleCaches, buildLocaleChain, canon, createLocaleCaches } from './_chain';\nimport { error as logError } from './_dev';\nimport { type NamespaceFactory, type NamespaceStore, createNamespaceStore } from './_namespace-store';\nimport {\n type TranslateContext,\n hasKey as hasKeyIn,\n translate as translateIn,\n translatePlural as translatePluralIn,\n} from './_translate';\nimport { LinguaDisposedError, LinguaRestoreError, checkDisposed } from './errors';\nimport { type Formatter, createFormatter } from './format';\n\nexport {\n LinguaCountInVarsError,\n LinguaDisposedError,\n LinguaError,\n LinguaInvalidCountError,\n LinguaInvalidLocaleError,\n LinguaMissingLocaleError,\n LinguaNamespaceMissingError,\n LinguaRestoreError,\n} from './errors';\n\nexport type {\n I18n,\n I18nOptions,\n I18nSnapshot,\n I18nState,\n Locale,\n MessageBranchKeys,\n MessageLeafKeys,\n ScopedI18n,\n SubscribeOptions,\n TpOptions,\n TranslateVars,\n Unsubscribe,\n} from './i18n-types';\nexport type { Loader, LocaleSource } from './_catalog-store';\nexport type { Messages } from './_catalog';\nexport type { NamespaceFactory } from './_namespace-store';\n\n// Bound for the per-instance `scope()` cache — see its declaration below for why it's bounded.\nconst SCOPE_CACHE_MAX = 128;\n\n// ─── Locale state ─────────────────────────────────────────────────────────────\n// Replaced atomically on every locale change.\n\ntype LocaleState = {\n readonly chain: readonly Locale[];\n readonly chainSet: ReadonlySet<Locale>;\n readonly locale: Locale;\n};\n\nfunction buildState(locale: Locale, fallback: Locale[], caches: LocaleCaches): LocaleState {\n const { chain, set } = buildLocaleChain(locale, fallback, caches);\n\n return { chain, chainSet: set, locale };\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/** Overload: explicit type parameter (strict typing) */\nexport function createI18n<M extends Messages>(config: I18nOptions<M>): I18n<M>;\n/** Overload: no type parameter (loose typing, allows heterogeneous catalogs) */\nexport function createI18n(config?: I18nOptions<Messages>): I18n<Messages>;\nexport function createI18n<M extends Messages = Messages>(config?: I18nOptions<M>): I18n<M> {\n return _createI18nImpl<M>(config);\n}\n\n// ─── Internal seed shape ──────────────────────────────────────────────────────\n\ntype I18nSeed<M extends Messages> = {\n catalogStore?: CatalogStore<M>;\n nsStore?: NamespaceStore;\n};\n\nfunction _createI18nImpl<M extends Messages = Messages>(config?: I18nOptions<M>, _seed?: I18nSeed<M>): I18n<M> {\n const cfg: I18nOptions<M> = config ?? {};\n\n // ─── Per-instance caches (no shared module-level state) ───────────────────\n const caches: LocaleCaches = createLocaleCaches();\n\n const canonL = (loc: string) => canon(loc, caches);\n\n const fallback = Array.isArray(cfg.fallback) ? cfg.fallback.map(canonL) : cfg.fallback ? [canonL(cfg.fallback)] : [];\n\n // ─── Disposal ─────────────────────────────────────────────────────────────\n let disposed = false;\n const disposeController = new AbortController();\n\n // ─── Bounded stores ───────────────────────────────────────────────────────\n const catalogStore: CatalogStore<M> = createCatalogStore(() => disposed);\n const nsStore: NamespaceStore = createNamespaceStore(() => disposed);\n\n // ─── Locale state ─────────────────────────────────────────────────────────\n let state: LocaleState = buildState(canonL(cfg.locale ?? 'en'), fallback, caches);\n\n // ─── Subscribers ──────────────────────────────────────────────────────────\n const subscribers = new Set<(snapshot: I18nSnapshot) => void>();\n const subscriptionUnsubscribers = new Set<Unsubscribe>();\n\n const onMissingKey = cfg.onMissingKey ?? ((key: string) => key);\n const onMissingVar = cfg.onMissingVar ?? ((varName: string) => `{${varName}}`);\n const onSubscriberError = cfg.onSubscriberError ?? ((error: unknown) => logError('subscriber error', error));\n\n // ─── Lazy formatter — avoids Intl overhead for SSR forks that only need t(). ──\n let _fmt: Formatter | undefined;\n\n // ─── Scope cache — stable object references per prefix for reactive framework renders. ──\n // Bounded the same way format.ts bounds its Intl-formatter caches: `scope()` is meant for a\n // static, finite set of prefixes (nav sections, form names, ...), but nothing stopped a caller\n // from passing a dynamic per-item prefix (e.g. `scope(`item.${id}`)` in a list render) and\n // growing this unboundedly for the instance's lifetime. Oldest entry evicts past the cap.\n const scopeCache = new Map<string, ScopedI18n>();\n\n const getFormatter = (): Formatter => {\n if (!_fmt) _fmt = createFormatter(() => state.locale);\n\n return _fmt;\n };\n\n // ─── Translate helpers ────────────────────────────────────────────────────\n // The actual algorithm (fallback-chain lookup, plural-form selection, interpolation) lives in\n // `_translate.ts` — this instance just supplies fresh context (current locale/chain) per call.\n\n const translateContext = (): TranslateContext => ({\n caches,\n catalogStore,\n chain: state.chain,\n locale: state.locale,\n onMissingKey,\n onMissingVar,\n });\n\n // Shared by has() and scope().has().\n const hasKey = (base: string): boolean => hasKeyIn(translateContext(), base);\n\n const translate = (key: MessageLeafKeys<M> | (string & {}), vars?: TranslateVars): string =>\n translateIn(translateContext(), String(key), vars);\n\n const translatePlural = (key: MessageBranchKeys<M> | (string & {}), count: number, options?: TpOptions): string =>\n translatePluralIn(translateContext(), String(key), count, options);\n\n // ─── bump() ───────────────────────────────────────────────────────────────\n // Rebuilds the snapshot and notifies all current subscribers.\n\n let snapshot: I18nSnapshot = {\n locale: state.locale,\n t: translate,\n tp: translatePlural,\n };\n\n const bump = (): void => {\n snapshot = { locale: state.locale, t: translate, tp: translatePlural };\n\n const listeners = [...subscribers];\n\n for (const listener of listeners) {\n try {\n listener(snapshot);\n } catch (error) {\n onSubscriberError(error);\n }\n }\n };\n\n // ─── Wire catalog store onChange → bump ───────────────────────────────────\n catalogStore.onChange = (loc: Locale) => {\n if (state.chainSet.has(loc)) bump();\n };\n\n // ─── Seed from parent fork ─────────────────────────────────────────────────\n if (_seed?.catalogStore) {\n catalogStore.seedFrom(_seed.catalogStore.snapshotCatalogs(), _seed.catalogStore.snapshotLoaders());\n }\n\n if (_seed?.nsStore) {\n nsStore.seedFrom(_seed.nsStore);\n }\n\n // ─── Initial catalogs from config ─────────────────────────────────────────\n if (cfg.catalogs) {\n const staticEntries = new Map<Locale, CatalogEntry>();\n const loaderEntries = new Map<Locale, Loader<M>>();\n\n for (const [loc, source] of Object.entries(cfg.catalogs)) {\n const normalized = canonL(loc);\n\n if (typeof source === 'function') {\n loaderEntries.set(normalized, source as Loader<M>);\n } else {\n const entry = new CatalogEntry();\n\n entry.setAll(flattenStrings(source as M));\n staticEntries.set(normalized, entry);\n validateCatalogInDev(normalized, source as M);\n }\n }\n\n // Use seedFrom for zero-overhead init (no bump, no notifications during setup)\n catalogStore.seedFrom(staticEntries, loaderEntries);\n }\n\n // ─── Preload helper ───────────────────────────────────────────────────────\n\n const preload = (loc: Locale): Promise<void> => catalogStore.preload(canonL(loc));\n\n // ─── Monotonic generation counter — last writer wins for concurrent setLocale() ──\n let switchGen = 0;\n\n // ─── Subscribe helper ─────────────────────────────────────────────────────\n\n const subscribeInternal = (callback: (snapshot: I18nSnapshot) => void, options?: SubscribeOptions): Unsubscribe => {\n const signal = options?.signal;\n\n const unsubscribe = (): void => {\n subscribers.delete(callback);\n signal?.removeEventListener('abort', unsubscribe);\n subscriptionUnsubscribers.delete(unsubscribe);\n };\n\n if (disposed) throw new LinguaDisposedError();\n\n if (signal?.aborted) return unsubscribe;\n\n if (options?.immediate === true) {\n try {\n callback(snapshot);\n } catch (error) {\n onSubscriberError(error);\n\n return unsubscribe;\n }\n }\n\n subscribers.add(callback);\n signal?.addEventListener('abort', unsubscribe, { once: true });\n subscriptionUnsubscribers.add(unsubscribe);\n\n return unsubscribe;\n };\n\n // ─── Public object ─────────────────────────────────────────────────────────\n // Named `const` (not a bare `return { ... }`) so `[Symbol.dispose]` below can close over\n // `source` directly instead of `this` — `this` inside an object-literal method is only bound\n // when called as `obj.method()`; detaching it first (`const d = i18n[Symbol.dispose]; d()`,\n // the exact shape most framework cleanup-hook APIs expect) would otherwise throw.\n\n const source: I18n<M> = {\n get disposalSignal(): AbortSignal {\n return disposeController.signal;\n },\n\n dispose(): void {\n if (disposed) return;\n\n disposed = true;\n disposeController.abort();\n for (const unsubscribe of [...subscriptionUnsubscribers]) unsubscribe();\n subscriptionUnsubscribers.clear();\n subscribers.clear();\n catalogStore.dispose();\n nsStore.dispose();\n scopeCache.clear();\n },\n\n get disposed(): boolean {\n return disposed;\n },\n\n extend(ns: string, factory: NamespaceFactory, loc?: Locale): Promise<void> {\n checkDisposed(disposed);\n\n nsStore.registerNamespace(ns, factory);\n\n const normalized = loc ? canonL(loc) : state.locale;\n\n return nsStore.loadNamespace(ns, normalized, (l, messages) => catalogStore.patch(l, messages));\n },\n\n get fmt(): Formatter {\n return getFormatter();\n },\n\n fork(overrides?: Omit<I18nOptions<M>, 'catalogs'>): I18n<M> {\n return _createI18nImpl(\n {\n fallback: overrides?.fallback ?? (fallback.length > 0 ? fallback : undefined),\n locale: overrides?.locale ?? state.locale,\n onMissingKey: overrides?.onMissingKey ?? cfg.onMissingKey,\n onMissingVar: overrides?.onMissingVar ?? cfg.onMissingVar,\n onSubscriberError: overrides?.onSubscriberError ?? cfg.onSubscriberError,\n },\n {\n catalogStore,\n nsStore,\n },\n );\n },\n\n getSnapshot() {\n return snapshot;\n },\n\n getState(): I18nState {\n const catalogsOut: Record<Locale, Record<string, string>> = {};\n\n for (const [loc, entry] of catalogStore.snapshotCatalogs()) {\n catalogsOut[loc] = Object.fromEntries([...entry.entries.entries()].map(([k, { message }]) => [k, message]));\n }\n\n return { catalogs: catalogsOut, locale: state.locale };\n },\n\n getSupportedLocales(sorted?: boolean): Locale[] {\n const locales = [...catalogStore.knownLocales()];\n\n return sorted === true ? locales.sort() : locales;\n },\n\n has(key: MessageLeafKeys<M> | MessageBranchKeys<M> | (string & {})): boolean {\n return hasKey(String(key));\n },\n\n isLoaded(loc: Locale): boolean {\n try {\n return catalogStore.isLoaded(canonL(loc));\n } catch {\n return false;\n }\n },\n\n isNamespaceLoaded(ns: string, loc?: Locale): boolean {\n if (!loc) return nsStore.isLoaded(ns, state.locale);\n\n try {\n return nsStore.isLoaded(ns, canonL(loc));\n } catch {\n return false;\n }\n },\n\n isNamespaceRegistered(ns: string): boolean {\n return nsStore.isRegistered(ns);\n },\n\n isRegistered(loc: Locale): boolean {\n try {\n return catalogStore.isRegistered(canonL(loc));\n } catch {\n return false;\n }\n },\n\n loadNamespace(ns: string, loc?: Locale): Promise<void> {\n const normalized = loc ? canonL(loc) : state.locale;\n\n return nsStore.loadNamespace(ns, normalized, (l, messages) => catalogStore.patch(l, messages));\n },\n\n get locale(): Locale {\n return state.locale;\n },\n\n preload,\n\n register(loc: Locale, source: LocaleSource<M>): Promise<void> {\n const normalized = canonL(loc);\n\n return catalogStore.register(normalized, source, nsStore);\n },\n\n registerNamespace(ns: string, factory: NamespaceFactory): void {\n nsStore.registerNamespace(ns, factory);\n },\n\n restoreState(st: I18nState): void {\n checkDisposed(disposed);\n\n if (!Object.hasOwn(st.catalogs, st.locale)) {\n throw new LinguaRestoreError(`restoreState: locale \"${st.locale}\" has no catalog in the provided state.`);\n }\n\n const freshEntries = new Map<Locale, CatalogEntry>();\n const knownLocales = catalogStore.knownLocales();\n\n for (const knownLocale of knownLocales) {\n nsStore.clearLocale(knownLocale);\n }\n\n // No validateCatalogInDev() call here, unlike register()/construction/preload(): `state`\n // is already flattened dot-notation (I18nState.catalogs), not the nested Messages shape\n // validateCatalog() expects, and restoreState() exists specifically for cheap SSR\n // hydration of a payload that was already registered — and therefore already\n // validated — once on the system that produced it. Re-validating here would mean\n // un-flattening every restored catalog back into nested form on every hydration, for a\n // check that's already run.\n for (const [loc, flatCatalog] of Object.entries(st.catalogs)) {\n const normalized = canonL(loc);\n const entry = new CatalogEntry();\n\n entry.setAll(Object.entries(flatCatalog));\n freshEntries.set(normalized, entry);\n }\n\n // Dispose and re-seed the catalog store with the restored entries.\n // onChange is re-wired immediately after dispose.\n catalogStore.dispose();\n catalogStore.onChange = (loc: Locale) => {\n if (state.chainSet.has(loc)) bump();\n };\n catalogStore.seedFrom(freshEntries, new Map());\n\n const normalized = canonL(st.locale);\n\n state = buildState(normalized, fallback, caches);\n _fmt?.clear();\n bump();\n },\n\n scope(prefix: MessageBranchKeys<M> | (string & {})): ScopedI18n {\n const pre = String(prefix);\n\n return getOrCreate(scopeCache, pre, SCOPE_CACHE_MAX, () => ({\n get fmt() {\n return getFormatter();\n },\n has: (key) => hasKey(`${pre}.${key}`),\n t: (key, vars?) => translate(`${pre}.${key}`, vars),\n tp: (key, count, options?) => translatePlural(`${pre}.${key}`, count, options),\n }));\n },\n\n async setLocale(next: Locale): Promise<void> {\n checkDisposed(disposed);\n\n const normalized = canonL(next);\n\n if (state.locale === normalized) return;\n\n // Monotonic generation counter — last writer wins.\n const gen = ++switchGen;\n\n await preload(normalized);\n\n if (disposed || switchGen !== gen) return;\n\n state = buildState(normalized, fallback, caches);\n _fmt?.clear();\n bump();\n },\n\n subscribe: subscribeInternal,\n\n [Symbol.dispose](): void {\n source.dispose();\n },\n\n t: translate,\n\n tp: translatePlural,\n };\n\n return source;\n}\n"],"mappings":"8QAkEA,IAAM,EAAkB,IAWxB,SAAS,EAAW,EAAgB,EAAoB,EAAmC,CACzF,GAAM,CAAE,QAAO,OAAQ,EAAA,iBAAiB,EAAQ,EAAU,CAAM,EAEhE,MAAO,CAAE,QAAO,SAAU,EAAK,QAAO,CACxC,CAQA,SAAgB,EAA0C,EAAkC,CAC1F,OAAO,EAAmB,CAAM,CAClC,CASA,SAAS,EAA+C,EAAyB,EAA8B,CAC7G,IAAM,EAAsB,GAAU,CAAC,EAGjC,EAAuB,EAAA,mBAAmB,EAE1C,EAAU,GAAgB,EAAA,MAAM,EAAK,CAAM,EAE3C,EAAW,MAAM,QAAQ,EAAI,QAAQ,EAAI,EAAI,SAAS,IAAI,CAAM,EAAI,EAAI,SAAW,CAAC,EAAO,EAAI,QAAQ,CAAC,EAAI,CAAC,EAG/G,EAAW,GACT,EAAoB,IAAI,gBAGxB,EAAgC,EAAA,uBAAyB,C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9B,GAAI,EAAM,SAAW,EAAY,OAGjC,IAAM,EAAM,EAAE,EAEd,MAAM,EAAQ,CAAU,EAEpB,KAAY,IAAc,KAE9B,EAAQ,EAAW,EAAY,EAAU,CAAM,EAC/C,GAAM,MAAM,EACZ,EAAK,EACP,EAEA,WAhPyB,EAA4C,IAA4C,CACjH,IAAM,EAAS,GAAS,OAElB,MAA0B,CAC9B,EAAY,OAAO,CAAQ,EAC3B,GAAQ,oBAAoB,QAAS,CAAW,EAChD,EAA0B,OAAO,CAAW,CAC9C,EAEA,GAAI,EAAU,MAAM,IAAI,EAAA,oBAExB,GAAI,GAAQ,QAAS,OAAO,EAE5B,GAAI,GAAS,YAAc,GACzB,GAAI,CACF,EAAS,CAAQ,CACnB,OAAS,EAAO,CAGd,OAFA,EAAkB,CAAK,EAEhB,CACT,CAOF,OAJA,EAAY,IAAI,CAAQ,EACxB,GAAQ,iBAAiB,QAAS,EAAa,CAAE,KAAM,EAAK,CAAC,EAC7D,EAA0B,IAAI,CAAW,EAElC,CACT,EAsNE,CAAC,OAAO,UAAiB,CACvB,EAAO,QAAQ,CACjB,EAEA,EAAG,EAEH,GAAI,CACN,EAEA,OAAO,CACT"}
|
package/dist/i18n.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { I18n, I18nOptions
|
|
1
|
+
import type { I18n, I18nOptions } from './i18n-types';
|
|
2
2
|
import { type Messages } from './_catalog';
|
|
3
3
|
export { LinguaCountInVarsError, LinguaDisposedError, LinguaError, LinguaInvalidCountError, LinguaInvalidLocaleError, LinguaMissingLocaleError, LinguaNamespaceMissingError, LinguaRestoreError, } from './errors';
|
|
4
4
|
export type { I18n, I18nOptions, I18nSnapshot, I18nState, Locale, MessageBranchKeys, MessageLeafKeys, ScopedI18n, SubscribeOptions, TpOptions, TranslateVars, Unsubscribe, } from './i18n-types';
|
|
@@ -9,32 +9,4 @@ export type { NamespaceFactory } from './_namespace-store';
|
|
|
9
9
|
export declare function createI18n<M extends Messages>(config: I18nOptions<M>): I18n<M>;
|
|
10
10
|
/** Overload: no type parameter (loose typing, allows heterogeneous catalogs) */
|
|
11
11
|
export declare function createI18n(config?: I18nOptions<Messages>): I18n<Messages>;
|
|
12
|
-
/**
|
|
13
|
-
* Serialises the currently loaded catalogs and active locale into a plain object.
|
|
14
|
-
* Pass the result to `hydrateI18n()` on the client.
|
|
15
|
-
*
|
|
16
|
-
* Prefer calling `i18n.getState()` directly — these standalone functions are provided
|
|
17
|
-
* for convenience when you receive a plain `I18n` reference without the full type.
|
|
18
|
-
*
|
|
19
|
-
* **Warning:** Only fully resolved catalogs are included. Loader-only locales not yet
|
|
20
|
-
* preloaded are omitted. Use `i18n.isLoaded(locale)` to verify before calling.
|
|
21
|
-
*
|
|
22
|
-
* **Warning:** The namespace registry is **not** serialized — factory functions cannot
|
|
23
|
-
* be converted to JSON. After `hydrateI18n()`, call `extend()` again for each namespace
|
|
24
|
-
* before relying on namespace-patched keys.
|
|
25
|
-
*/
|
|
26
|
-
export declare function serializeI18n(i18n: I18n): I18nState;
|
|
27
|
-
/**
|
|
28
|
-
* Hydrates an i18n instance with pre-loaded state (e.g. from a server-rendered payload).
|
|
29
|
-
*
|
|
30
|
-
* Prefer calling `i18n.restoreState(state)` directly — these standalone functions are
|
|
31
|
-
* provided for convenience.
|
|
32
|
-
*
|
|
33
|
-
* @remarks The namespace registry is **not** included in `I18nState`. After hydrating,
|
|
34
|
-
* call `extend()` for each namespace before relying on namespace-patched keys.
|
|
35
|
-
*
|
|
36
|
-
* @throws `LinguaDisposedError` if called on a disposed instance.
|
|
37
|
-
* @throws `LinguaRestoreError` if the state's locale has no catalog.
|
|
38
|
-
*/
|
|
39
|
-
export declare function hydrateI18n(i18n: I18n, state: I18nState): void;
|
|
40
12
|
//# sourceMappingURL=i18n.d.ts.map
|
package/dist/i18n.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n.d.ts","sourceRoot":"","sources":["../src/i18n.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,IAAI,EACJ,WAAW,
|
|
1
|
+
{"version":3,"file":"i18n.d.ts","sourceRoot":"","sources":["../src/i18n.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,IAAI,EACJ,WAAW,EAWZ,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAgB,KAAK,QAAQ,EAAkB,MAAM,YAAY,CAAC;AAoBzE,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,WAAW,EACX,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,UAAU,CAAC;AAElB,YAAY,EACV,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,SAAS,EACT,MAAM,EACN,iBAAiB,EACjB,eAAe,EACf,UAAU,EACV,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,GACZ,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC7D,YAAY,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAsB3D,wDAAwD;AACxD,wBAAgB,UAAU,CAAC,CAAC,SAAS,QAAQ,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAChF,gFAAgF;AAChF,wBAAgB,UAAU,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC"}
|