@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/i18n.js
CHANGED
|
@@ -1,125 +1,96 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { getOrCreate as e } from "./_bounded-cache.js";
|
|
2
|
+
import { createFormatter as t } from "./format.js";
|
|
3
|
+
import { error as n } from "./_dev.js";
|
|
4
4
|
import { CatalogEntry as r, flattenStrings as i } from "./_catalog.js";
|
|
5
5
|
import { LinguaCountInVarsError as a, LinguaDisposedError as o, LinguaError as s, LinguaInvalidCountError as c, LinguaInvalidLocaleError as l, LinguaMissingLocaleError as u, LinguaNamespaceMissingError as d, LinguaRestoreError as f, checkDisposed as p } from "./errors.js";
|
|
6
|
-
import { createCatalogStore as m } from "./_catalog-store.js";
|
|
7
|
-
import { buildLocaleChain as
|
|
6
|
+
import { createCatalogStore as m, validateCatalogInDev as h } from "./_catalog-store.js";
|
|
7
|
+
import { buildLocaleChain as g, canon as _, createLocaleCaches as v } from "./_chain.js";
|
|
8
8
|
import { createNamespaceStore as y } from "./_namespace-store.js";
|
|
9
|
+
import { hasKey as b, translate as x, translatePlural as S } from "./_translate.js";
|
|
9
10
|
//#region src/i18n.ts
|
|
10
|
-
|
|
11
|
-
|
|
11
|
+
var C = 128;
|
|
12
|
+
function w(e, t, n) {
|
|
13
|
+
let { chain: r, set: i } = g(e, t, n);
|
|
12
14
|
return {
|
|
13
15
|
chain: r,
|
|
14
16
|
chainSet: i,
|
|
15
17
|
locale: e
|
|
16
18
|
};
|
|
17
19
|
}
|
|
18
|
-
function
|
|
19
|
-
|
|
20
|
-
return !r && n === 0 && i.push(`${e}.zero`), (t !== "zero" || r) && i.push(`${e}.${t}`), t !== "other" && i.push(`${e}.other`), i;
|
|
20
|
+
function T(e) {
|
|
21
|
+
return E(e);
|
|
21
22
|
}
|
|
22
|
-
function
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
if (L(e) !== void 0) return !0;
|
|
33
|
-
for (let t of O.chain) {
|
|
34
|
-
let n = E.resolve(t);
|
|
35
|
-
if (n && n.prefixes.has(e)) return !0;
|
|
36
|
-
}
|
|
37
|
-
return !1;
|
|
38
|
-
}, z = (e, t, r) => n(t.compiled, r, e, O.locale, M), B = (e, t) => {
|
|
39
|
-
let n = String(e), r = L(n);
|
|
40
|
-
return r ? z(n, r, t) : j(n, O.locale);
|
|
41
|
-
}, V = (e, t, n) => {
|
|
42
|
-
if (!Number.isFinite(t)) throw new c("`count` must be a finite number.");
|
|
43
|
-
let r = n?.vars, i = n?.ordinal ?? !1;
|
|
44
|
-
if (r && Object.hasOwn(r, "count")) throw new a("`tp` does not allow `vars.count`; `count` is injected automatically.");
|
|
45
|
-
let o = String(e), s = r ? {
|
|
46
|
-
count: t,
|
|
47
|
-
...r
|
|
48
|
-
} : { count: t };
|
|
49
|
-
for (let e of O.chain) {
|
|
50
|
-
let n = E.resolve(e);
|
|
51
|
-
if (!n) continue;
|
|
52
|
-
let r = x(o, v(e, t, i, d), t, i);
|
|
53
|
-
for (let e of r) {
|
|
54
|
-
let t = n.get(e);
|
|
55
|
-
if (t !== void 0) return z(e, t, s);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
return j(o, O.locale);
|
|
59
|
-
}, H = {
|
|
60
|
-
locale: O.locale,
|
|
23
|
+
function E(a, s) {
|
|
24
|
+
let c = a ?? {}, l = v(), u = (e) => _(e, l), d = Array.isArray(c.fallback) ? c.fallback.map(u) : c.fallback ? [u(c.fallback)] : [], g = !1, T = new AbortController(), D = m(() => g), O = y(() => g), k = w(u(c.locale ?? "en"), d, l), A = /* @__PURE__ */ new Set(), j = /* @__PURE__ */ new Set(), M = c.onMissingKey ?? ((e) => e), N = c.onMissingVar ?? ((e) => `{${e}}`), P = c.onSubscriberError ?? ((e) => n("subscriber error", e)), F, I = /* @__PURE__ */ new Map(), L = () => (F ||= t(() => k.locale), F), R = () => ({
|
|
25
|
+
caches: l,
|
|
26
|
+
catalogStore: D,
|
|
27
|
+
chain: k.chain,
|
|
28
|
+
locale: k.locale,
|
|
29
|
+
onMissingKey: M,
|
|
30
|
+
onMissingVar: N
|
|
31
|
+
}), z = (e) => b(R(), e), B = (e, t) => x(R(), String(e), t), V = (e, t, n) => S(R(), String(e), t, n), H = {
|
|
32
|
+
locale: k.locale,
|
|
61
33
|
t: B,
|
|
62
34
|
tp: V
|
|
63
35
|
}, U = () => {
|
|
64
36
|
H = {
|
|
65
|
-
locale:
|
|
37
|
+
locale: k.locale,
|
|
66
38
|
t: B,
|
|
67
39
|
tp: V
|
|
68
40
|
};
|
|
69
|
-
let e = [...
|
|
41
|
+
let e = [...A];
|
|
70
42
|
for (let t of e) try {
|
|
71
43
|
t(H);
|
|
72
44
|
} catch (e) {
|
|
73
|
-
|
|
45
|
+
P(e);
|
|
74
46
|
}
|
|
75
47
|
};
|
|
76
|
-
if (
|
|
77
|
-
|
|
78
|
-
},
|
|
48
|
+
if (D.onChange = (e) => {
|
|
49
|
+
k.chainSet.has(e) && U();
|
|
50
|
+
}, s?.catalogStore && D.seedFrom(s.catalogStore.snapshotCatalogs(), s.catalogStore.snapshotLoaders()), s?.nsStore && O.seedFrom(s.nsStore), c.catalogs) {
|
|
79
51
|
let e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map();
|
|
80
|
-
for (let [n, a] of Object.entries(
|
|
81
|
-
let o =
|
|
52
|
+
for (let [n, a] of Object.entries(c.catalogs)) {
|
|
53
|
+
let o = u(n);
|
|
82
54
|
if (typeof a == "function") t.set(o, a);
|
|
83
55
|
else {
|
|
84
56
|
let t = new r();
|
|
85
|
-
t.setAll(i(a)), e.set(o, t);
|
|
57
|
+
t.setAll(i(a)), e.set(o, t), h(o, a);
|
|
86
58
|
}
|
|
87
59
|
}
|
|
88
|
-
|
|
60
|
+
D.seedFrom(e, t);
|
|
89
61
|
}
|
|
90
|
-
let W = (e) =>
|
|
91
|
-
return {
|
|
62
|
+
let W = (e) => D.preload(u(e)), G = 0, K = {
|
|
92
63
|
get disposalSignal() {
|
|
93
64
|
return T.signal;
|
|
94
65
|
},
|
|
95
66
|
dispose() {
|
|
96
|
-
if (!
|
|
97
|
-
|
|
98
|
-
for (let e of [...
|
|
99
|
-
|
|
67
|
+
if (!g) {
|
|
68
|
+
g = !0, T.abort();
|
|
69
|
+
for (let e of [...j]) e();
|
|
70
|
+
j.clear(), A.clear(), D.dispose(), O.dispose(), I.clear();
|
|
100
71
|
}
|
|
101
72
|
},
|
|
102
73
|
get disposed() {
|
|
103
|
-
return
|
|
74
|
+
return g;
|
|
104
75
|
},
|
|
105
76
|
extend(e, t, n) {
|
|
106
|
-
p(
|
|
107
|
-
let r = n ?
|
|
108
|
-
return
|
|
77
|
+
p(g), O.registerNamespace(e, t);
|
|
78
|
+
let r = n ? u(n) : k.locale;
|
|
79
|
+
return O.loadNamespace(e, r, (e, t) => D.patch(e, t));
|
|
109
80
|
},
|
|
110
81
|
get fmt() {
|
|
111
|
-
return
|
|
82
|
+
return L();
|
|
112
83
|
},
|
|
113
84
|
fork(e) {
|
|
114
|
-
return
|
|
115
|
-
fallback: e?.fallback ?? (
|
|
116
|
-
locale: e?.locale ??
|
|
117
|
-
onMissingKey: e?.onMissingKey ??
|
|
118
|
-
onMissingVar: e?.onMissingVar ??
|
|
119
|
-
onSubscriberError: e?.onSubscriberError ??
|
|
85
|
+
return E({
|
|
86
|
+
fallback: e?.fallback ?? (d.length > 0 ? d : void 0),
|
|
87
|
+
locale: e?.locale ?? k.locale,
|
|
88
|
+
onMissingKey: e?.onMissingKey ?? c.onMissingKey,
|
|
89
|
+
onMissingVar: e?.onMissingVar ?? c.onMissingVar,
|
|
90
|
+
onSubscriberError: e?.onSubscriberError ?? c.onSubscriberError
|
|
120
91
|
}, {
|
|
121
|
-
catalogStore:
|
|
122
|
-
nsStore:
|
|
92
|
+
catalogStore: D,
|
|
93
|
+
nsStore: O
|
|
123
94
|
});
|
|
124
95
|
},
|
|
125
96
|
getSnapshot() {
|
|
@@ -127,118 +98,111 @@ function C(s, l) {
|
|
|
127
98
|
},
|
|
128
99
|
getState() {
|
|
129
100
|
let e = {};
|
|
130
|
-
for (let [t, n] of
|
|
101
|
+
for (let [t, n] of D.snapshotCatalogs()) e[t] = Object.fromEntries([...n.entries.entries()].map(([e, { message: t }]) => [e, t]));
|
|
131
102
|
return {
|
|
132
103
|
catalogs: e,
|
|
133
|
-
locale:
|
|
104
|
+
locale: k.locale
|
|
134
105
|
};
|
|
135
106
|
},
|
|
136
107
|
getSupportedLocales(e) {
|
|
137
|
-
let t = [...
|
|
108
|
+
let t = [...D.knownLocales()];
|
|
138
109
|
return e === !0 ? t.sort() : t;
|
|
139
110
|
},
|
|
140
111
|
has(e) {
|
|
141
|
-
return
|
|
112
|
+
return z(String(e));
|
|
142
113
|
},
|
|
143
114
|
isLoaded(e) {
|
|
144
115
|
try {
|
|
145
|
-
return
|
|
116
|
+
return D.isLoaded(u(e));
|
|
146
117
|
} catch {
|
|
147
118
|
return !1;
|
|
148
119
|
}
|
|
149
120
|
},
|
|
150
121
|
isNamespaceLoaded(e, t) {
|
|
151
|
-
if (!t) return
|
|
122
|
+
if (!t) return O.isLoaded(e, k.locale);
|
|
152
123
|
try {
|
|
153
|
-
return
|
|
124
|
+
return O.isLoaded(e, u(t));
|
|
154
125
|
} catch {
|
|
155
126
|
return !1;
|
|
156
127
|
}
|
|
157
128
|
},
|
|
158
129
|
isNamespaceRegistered(e) {
|
|
159
|
-
return
|
|
130
|
+
return O.isRegistered(e);
|
|
160
131
|
},
|
|
161
132
|
isRegistered(e) {
|
|
162
133
|
try {
|
|
163
|
-
return
|
|
134
|
+
return D.isRegistered(u(e));
|
|
164
135
|
} catch {
|
|
165
136
|
return !1;
|
|
166
137
|
}
|
|
167
138
|
},
|
|
168
139
|
loadNamespace(e, t) {
|
|
169
|
-
let n = t ?
|
|
170
|
-
return
|
|
140
|
+
let n = t ? u(t) : k.locale;
|
|
141
|
+
return O.loadNamespace(e, n, (e, t) => D.patch(e, t));
|
|
171
142
|
},
|
|
172
143
|
get locale() {
|
|
173
|
-
return
|
|
144
|
+
return k.locale;
|
|
174
145
|
},
|
|
175
146
|
preload: W,
|
|
176
147
|
register(e, t) {
|
|
177
|
-
let n =
|
|
178
|
-
return
|
|
148
|
+
let n = u(e);
|
|
149
|
+
return D.register(n, t, O);
|
|
179
150
|
},
|
|
180
151
|
registerNamespace(e, t) {
|
|
181
|
-
|
|
152
|
+
O.registerNamespace(e, t);
|
|
182
153
|
},
|
|
183
154
|
restoreState(e) {
|
|
184
|
-
if (p(
|
|
185
|
-
let t = /* @__PURE__ */ new Map(), n =
|
|
186
|
-
for (let e of n)
|
|
155
|
+
if (p(g), !Object.hasOwn(e.catalogs, e.locale)) throw new f(`restoreState: locale "${e.locale}" has no catalog in the provided state.`);
|
|
156
|
+
let t = /* @__PURE__ */ new Map(), n = D.knownLocales();
|
|
157
|
+
for (let e of n) O.clearLocale(e);
|
|
187
158
|
for (let [n, i] of Object.entries(e.catalogs)) {
|
|
188
|
-
let e =
|
|
159
|
+
let e = u(n), a = new r();
|
|
189
160
|
a.setAll(Object.entries(i)), t.set(e, a);
|
|
190
161
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
},
|
|
194
|
-
},
|
|
195
|
-
scope(
|
|
196
|
-
let
|
|
197
|
-
|
|
198
|
-
let r = {
|
|
162
|
+
D.dispose(), D.onChange = (e) => {
|
|
163
|
+
k.chainSet.has(e) && U();
|
|
164
|
+
}, D.seedFrom(t, /* @__PURE__ */ new Map()), k = w(u(e.locale), d, l), F?.clear(), U();
|
|
165
|
+
},
|
|
166
|
+
scope(t) {
|
|
167
|
+
let n = String(t);
|
|
168
|
+
return e(I, n, C, () => ({
|
|
199
169
|
get fmt() {
|
|
200
|
-
return
|
|
170
|
+
return L();
|
|
201
171
|
},
|
|
202
|
-
has: (e) =>
|
|
203
|
-
t: (e,
|
|
204
|
-
tp: (e,
|
|
205
|
-
};
|
|
206
|
-
return F.set(t, r), r;
|
|
172
|
+
has: (e) => z(`${n}.${e}`),
|
|
173
|
+
t: (e, t) => B(`${n}.${e}`, t),
|
|
174
|
+
tp: (e, t, r) => V(`${n}.${e}`, t, r)
|
|
175
|
+
}));
|
|
207
176
|
},
|
|
208
177
|
async setLocale(e) {
|
|
209
|
-
p(
|
|
210
|
-
let t =
|
|
211
|
-
if (
|
|
178
|
+
p(g);
|
|
179
|
+
let t = u(e);
|
|
180
|
+
if (k.locale === t) return;
|
|
212
181
|
let n = ++G;
|
|
213
|
-
await W(t), !(
|
|
182
|
+
await W(t), !(g || G !== n) && (k = w(t, d, l), F?.clear(), U());
|
|
214
183
|
},
|
|
215
184
|
subscribe: (e, t) => {
|
|
216
185
|
let n = t?.signal, r = () => {
|
|
217
|
-
|
|
186
|
+
A.delete(e), n?.removeEventListener("abort", r), j.delete(r);
|
|
218
187
|
};
|
|
219
|
-
if (
|
|
188
|
+
if (g) throw new o();
|
|
220
189
|
if (n?.aborted) return r;
|
|
221
190
|
if (t?.immediate === !0) try {
|
|
222
191
|
e(H);
|
|
223
192
|
} catch (e) {
|
|
224
|
-
return
|
|
193
|
+
return P(e), r;
|
|
225
194
|
}
|
|
226
|
-
return
|
|
195
|
+
return A.add(e), n?.addEventListener("abort", r, { once: !0 }), j.add(r), r;
|
|
227
196
|
},
|
|
228
197
|
[Symbol.dispose]() {
|
|
229
|
-
|
|
198
|
+
K.dispose();
|
|
230
199
|
},
|
|
231
200
|
t: B,
|
|
232
201
|
tp: V
|
|
233
202
|
};
|
|
234
|
-
|
|
235
|
-
function w(e) {
|
|
236
|
-
return e.getState();
|
|
237
|
-
}
|
|
238
|
-
function T(e, t) {
|
|
239
|
-
e.restoreState(t);
|
|
203
|
+
return K;
|
|
240
204
|
}
|
|
241
205
|
//#endregion
|
|
242
|
-
export { a as LinguaCountInVarsError, o as LinguaDisposedError, s as LinguaError, c as LinguaInvalidCountError, l as LinguaInvalidLocaleError, u as LinguaMissingLocaleError, d as LinguaNamespaceMissingError, f as LinguaRestoreError,
|
|
206
|
+
export { a as LinguaCountInVarsError, o as LinguaDisposedError, s as LinguaError, c as LinguaInvalidCountError, l as LinguaInvalidLocaleError, u as LinguaMissingLocaleError, d as LinguaNamespaceMissingError, f as LinguaRestoreError, T as createI18n };
|
|
243
207
|
|
|
244
208
|
//# sourceMappingURL=i18n.js.map
|
package/dist/i18n.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n.js","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":";;;;;;;;;AAoEA,SAAS,EAAW,GAAgB,GAAoB,GAAmC;CACzF,IAAM,EAAE,UAAO,WAAQ,EAAiB,GAAQ,GAAU,CAAM;CAEhE,OAAO;EAAE;EAAO,UAAU;EAAK;CAAO;AACxC;AAKA,SAAS,EAAkB,GAAc,GAAc,GAAe,GAA4B;CAChG,IAAM,IAAiB,CAAC;CAQxB,OANI,CAAC,KAAW,MAAU,KAAG,EAAK,KAAK,GAAG,EAAK,MAAM,IAEjD,MAAS,UAAU,MAAS,EAAK,KAAK,GAAG,EAAK,GAAG,GAAM,GAEvD,MAAS,WAAS,EAAK,KAAK,GAAG,EAAK,OAAO,GAExC;AACT;AAQA,SAAgB,EAA0C,GAAkC;CAC1F,OAAO,EAAmB,CAAM;AAClC;AASA,SAAS,EAA+C,GAAyB,GAA8B;CAC7G,IAAM,IAAsB,KAAU,CAAC,GAGjC,IAAuB,EAAmB,GAE1C,KAAU,MAAgB,EAAM,GAAK,CAAM,GAE3C,IAAW,MAAM,QAAQ,EAAI,QAAQ,IAAI,EAAI,SAAS,IAAI,CAAM,IAAI,EAAI,WAAW,CAAC,EAAO,EAAI,QAAQ,CAAC,IAAI,CAAC,GAG/G,IAAW,IACT,IAAoB,IAAI,gBAAgB,GAGxC,IAAgC,QAAyB,CAAQ,GACjE,IAA0B,QAA2B,CAAQ,GAG/D,IAAqB,EAAW,EAAO,EAAI,UAAU,IAAI,GAAG,GAAU,CAAM,GAG1E,oBAAc,IAAI,IAAsC,GACxD,oBAA4B,IAAI,IAAiB,GAEjD,IAAe,EAAI,kBAAkB,MAAgB,IACrD,IAAe,EAAI,kBAAkB,MAAoB,IAAI,EAAQ,KACrE,IAAoB,EAAI,uBAAuB,MAAmB,EAAS,oBAAoB,CAAK,IAGtG,GAGE,oBAAa,IA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AAQ;GACnB,SAAS,GAAO;IAGd,OAFA,EAAkB,CAAK,GAEhB;GACT;GAOF,OAJA,EAAY,IAAI,CAAQ,GACxB,GAAQ,iBAAiB,SAAS,GAAa,EAAE,MAAM,GAAK,CAAC,GAC7D,EAA0B,IAAI,CAAW,GAElC;EACT;EAkNE,CAAC,OAAO,WAAiB;GACvB,KAAK,QAAQ;EACf;EAEA,GAAG;EAEH,IAAI;CACN;AACF;AAkBA,SAAgB,EAAc,GAAuB;CACnD,OAAO,EAAK,SAAS;AACvB;AAcA,SAAgB,EAAY,GAAY,GAAwB;CAC9D,EAAK,aAAa,CAAK;AACzB"}
|
|
1
|
+
{"version":3,"file":"i18n.js","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 { 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":";;;;;;;;;;AAkEA,IAAM,IAAkB;AAWxB,SAA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;EACjB;EAEA,GAAG;EAEH,IAAI;CACN;CAEA,OAAO;AACT"}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./format.cjs"),t=require("./errors.cjs"),n=require("./i18n.cjs");exports.LinguaCountInVarsError=t.LinguaCountInVarsError,exports.LinguaDisposedError=t.LinguaDisposedError,exports.LinguaError=t.LinguaError,exports.LinguaInvalidCountError=t.LinguaInvalidCountError,exports.LinguaInvalidLocaleError=t.LinguaInvalidLocaleError,exports.LinguaMissingLocaleError=t.LinguaMissingLocaleError,exports.LinguaNamespaceMissingError=t.LinguaNamespaceMissingError,exports.LinguaRestoreError=t.LinguaRestoreError,exports.createFormatter=e.createFormatter,exports.createI18n=n.createI18n
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./format.cjs"),t=require("./errors.cjs"),n=require("./i18n.cjs");exports.LinguaCountInVarsError=t.LinguaCountInVarsError,exports.LinguaDisposedError=t.LinguaDisposedError,exports.LinguaError=t.LinguaError,exports.LinguaInvalidCountError=t.LinguaInvalidCountError,exports.LinguaInvalidLocaleError=t.LinguaInvalidLocaleError,exports.LinguaMissingLocaleError=t.LinguaMissingLocaleError,exports.LinguaNamespaceMissingError=t.LinguaNamespaceMissingError,exports.LinguaRestoreError=t.LinguaRestoreError,exports.createFormatter=e.createFormatter,exports.createI18n=n.createI18n;
|
package/dist/index.d.ts
CHANGED
|
@@ -9,5 +9,5 @@
|
|
|
9
9
|
export type { I18n, I18nOptions, I18nSnapshot, I18nState, Loader, Locale, LocaleSource, MessageBranchKeys, MessageLeafKeys, Messages, NamespaceFactory, ScopedI18n, SubscribeOptions, TpOptions, TranslateVars, Unsubscribe, } from './i18n';
|
|
10
10
|
export type { DurationFormatOptions, DurationValue, Formatter, ListFormatOptions } from './format';
|
|
11
11
|
export { createFormatter } from './format';
|
|
12
|
-
export { LinguaCountInVarsError, LinguaDisposedError, LinguaError, LinguaInvalidCountError, LinguaInvalidLocaleError, LinguaMissingLocaleError, LinguaNamespaceMissingError, LinguaRestoreError, createI18n,
|
|
12
|
+
export { LinguaCountInVarsError, LinguaDisposedError, LinguaError, LinguaInvalidCountError, LinguaInvalidLocaleError, LinguaMissingLocaleError, LinguaNamespaceMissingError, LinguaRestoreError, createI18n, } from './i18n';
|
|
13
13
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,YAAY,EACV,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,SAAS,EACT,MAAM,EACN,MAAM,EACN,YAAY,EACZ,iBAAiB,EACjB,eAAe,EACf,QAAQ,EACR,gBAAgB,EAChB,UAAU,EACV,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,GACZ,MAAM,QAAQ,CAAC;AAEhB,YAAY,EAAE,qBAAqB,EAAE,aAAa,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAEnG,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,WAAW,EACX,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,kBAAkB,EAClB,UAAU,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,YAAY,EACV,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,SAAS,EACT,MAAM,EACN,MAAM,EACN,YAAY,EACZ,iBAAiB,EACjB,eAAe,EACf,QAAQ,EACR,gBAAgB,EAChB,UAAU,EACV,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,GACZ,MAAM,QAAQ,CAAC;AAEhB,YAAY,EAAE,qBAAqB,EAAE,aAAa,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAEnG,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,WAAW,EACX,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,kBAAkB,EAClB,UAAU,GACX,MAAM,QAAQ,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createFormatter as e } from "./format.js";
|
|
2
2
|
import { LinguaCountInVarsError as t, LinguaDisposedError as n, LinguaError as r, LinguaInvalidCountError as i, LinguaInvalidLocaleError as a, LinguaMissingLocaleError as o, LinguaNamespaceMissingError as s, LinguaRestoreError as c } from "./errors.js";
|
|
3
|
-
import { createI18n as l
|
|
4
|
-
export { t as LinguaCountInVarsError, n as LinguaDisposedError, r as LinguaError, i as LinguaInvalidCountError, a as LinguaInvalidLocaleError, o as LinguaMissingLocaleError, s as LinguaNamespaceMissingError, c as LinguaRestoreError, e as createFormatter, l as createI18n
|
|
3
|
+
import { createI18n as l } from "./i18n.js";
|
|
4
|
+
export { t as LinguaCountInVarsError, n as LinguaDisposedError, r as LinguaError, i as LinguaInvalidCountError, a as LinguaInvalidLocaleError, o as LinguaMissingLocaleError, s as LinguaNamespaceMissingError, c as LinguaRestoreError, e as createFormatter, l as createI18n };
|
package/dist/lingua.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=128;function t(t,n,r){let i=t.get(n);if(i!==void 0)return i;let a=r();return t.size>=e&&t.delete(t.keys().next().value),t.set(n,a),a}var n=[`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`],r={days:`d`,hours:`h`,microseconds:`us`,milliseconds:`ms`,minutes:`min`,months:`mo`,nanoseconds:`ns`,seconds:`s`,weeks:`w`,years:`y`};function i(e){return n.map(t=>{let n=e[t];return typeof n==`number`?`${n}${r[t]}`:void 0}).filter(e=>e!==void 0).join(` `)}function a(e){let r=new Map,a=new Map,o=new Map,s=new Map,c=new Map,l=new Map,u=typeof e==`string`?()=>e:e;function d(e,t){if(!t)return e;let n={};for(let e of Object.keys(t).sort())n[e]=t[e];try{return`${e}:${JSON.stringify(n)}`}catch{return e}}return{clear(){r.clear(),a.clear(),o.clear(),s.clear(),c.clear(),l.clear()},currency(e,n,r){let i=u(),o={...r,currency:n,style:`currency`};return t(a,d(i,o),()=>new Intl.NumberFormat(i,o)).format(e)},date(e,n){let r=u();return t(o,d(r,n),()=>new Intl.DateTimeFormat(r,n)).format(e)},duration(e,r){let a=u(),o=Intl;return o.DurationFormat?n.every(t=>e[t]===void 0)?``:t(l,d(a,r),()=>new o.DurationFormat(a,r)).format(e):i(e)},list(e,n){let r=u(),i=e.map(e=>String(e)),a=n?.style??`long`,o=n?.type===`or`?`disjunction`:`conjunction`;return t(c,d(r,{style:a,type:o}),()=>new Intl.ListFormat(r,{style:a,type:o})).format(i)},number(e,n){let i=u();return t(r,d(i,n),()=>new Intl.NumberFormat(i,n)).format(e)},relative(e,n,r){let i=u();return t(s,d(i,r),()=>new Intl.RelativeTimeFormat(i,r)).format(e,n)}}}var o=new Set([`__proto__`,`constructor`,`prototype`]),s=!globalThis.__LINGUA_PROD__;function c(e){s&&console.warn(`[@vielzeug/lingua] ${e}`)}function l(e,...t){s&&console.error(`[@vielzeug/lingua] ${e}`,...t)}var u={2:[`one`,`other`],3:[`zero`,`one`,`other`],6:[`zero`,`one`,`two`,`few`,`many`,`other`]};function d(e){if(e.indexOf(`|`)===-1)return null;let t=e.split(`|`),n=u[t.length];if(!n)return c(`Pipe-plural shorthand with ${t.length} parts is not recognized (valid counts: 2, 3, 6). Treating as a plain string: "${e.slice(0,60)}${e.length>60?`…`:``}"`),null;if(t.some(e=>e.trim()===``))return null;let r={};for(let e=0;e<t.length;e++)r[n[e]]=t[e];return r}var f=/\{([\p{ID_Continue}-]+)\}/gu;function p(e){let t=[],n=0;for(let r of e.matchAll(f)){let{index:i}=r,a=i??0;a>n&&t.push(e.slice(n,a)),t.push({var:r[1]}),n=a+r[0].length}return n<e.length&&t.push(e.slice(n)),t}function m(e,t,n,r,i){let a=``;for(let o of e)if(typeof o==`string`)a+=o;else{let e=t?.[o.var];a+=e==null?i(o.var,n,r):String(e)}return a}var h=class e{entries=new Map;prefixes=new Set;get(e){return this.entries.get(e)}set(e,t){this.entries.set(e,{compiled:p(t),message:t});let n=e.indexOf(`.`);for(;n!==-1;)this.prefixes.add(e.slice(0,n)),n=e.indexOf(`.`,n+1)}setAll(e){for(let[t,n]of e)this.set(t,n)}clone(){let t=new e;for(let[e,n]of this.entries)t.entries.set(e,n);for(let e of this.prefixes)t.prefixes.add(e);return t}};function g(e,t=new Map,n){for(let[r,i]of Object.entries(e)){if(o.has(r))continue;let e=n?`${n}.${r}`:r;if(typeof i==`string`){let n=d(i);n?g(n,t,e):t.set(e,i)}else g(i,t,e)}return t}var _=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}},v=class extends _{constructor(){super(`Operation called on a disposed i18n instance.`)}},y=class extends _{},b=class extends _{},x=class extends _{},S=class extends _{},C=class extends _{},w=class extends _{};function T(e){if(e)throw new v}function E(e){return e?Promise.reject(new v):null}function D(e){let t=new Map,n=new Map,r=new Map,i=new Set,a,o=(e,n)=>{let r=t.get(e);r||(r=new h,t.set(e,r)),r.setAll(n)},s=i=>{let s=E(e());if(s)return s;if(t.has(i))return Promise.resolve();let c=n.get(i);if(!c)return Promise.reject(new x(`Missing locale source for "${i}".`));let l=r.get(i);if(l)return l;let u=c().then(e=>{n.get(i)===c&&(n.delete(i),o(i,g(e)),r.delete(i),a?.(i))},e=>{throw n.get(i)===c&&r.delete(i),e});return r.set(i,u),u};return{get catalogs(){return t},dispose(){t.clear(),n.clear(),r.clear(),i.clear(),a=void 0},isLoaded(e){return t.has(e)},isRegistered(e){return i.has(e)},knownLocales(){return[...i]},get onChange(){return a},set onChange(e){a=e},patch(t,r){return E(e())||(n.has(t)?s(t).then(()=>{e()||(o(t,g(r)),i.add(t),a?.(t))}):(o(t,g(r)),i.add(t),a?.(t),Promise.resolve()))},get pendingLoaders(){return n},preload:s,register(l,u,d){T(e()),r.delete(l),i.add(l);let f=d.clearLocale(l);f.length>0&&c(`register('${l}') cleared loaded namespace markers for: ${f.map(e=>`'${e}'`).join(`, `)}. Call loadNamespace() again to reload.`);let p;return typeof u==`function`?(n.set(l,u),t.delete(l),p=s(l)):(n.delete(l),t.delete(l),o(l,g(u)),p=Promise.resolve(),a?.(l)),p},resolve(e){return t.get(e)},seedFrom(e,r){for(let[n,r]of e)t.set(n,r.clone()),i.add(n);for(let[e,t]of r)n.set(e,t),i.add(e)}}}function O(){return{canon:new Map,chain:new Map,plural:new Map}}function k(e,t){let n=t.canon.get(e);if(n!==void 0)return n;let r;try{[r]=Intl.getCanonicalLocales(e)}catch{}if(!r)throw new S(`Invalid BCP 47 locale tag: "${e}".`);return t.canon.set(e,r),r}function A(e,t,n,r){let i=`${e}:${n?`ordinal`:`cardinal`}`,a=r.plural.get(i);return a||(a=new Intl.PluralRules(e,{type:n?`ordinal`:`cardinal`}),r.plural.set(i,a)),a.select(t)}function j(e,t){let n=new Set;for(let r of[e,...t]){n.add(r);let e=r.split(`-`);for(let t=e.length-1;t>0;t--)n.add(e.slice(0,t).join(`-`))}return{chain:[...n],set:n}}function M(e,t,n){let r=t.length===0?e:`${e}|${t.join(`,`)}`,i=n.chain.get(r);if(i)return i;let a=j(e,t);return n.chain.set(r,a),a}function N(e){let t=new Map,n=new Map,r=new Map;return{clearLocale(e){let t=[];for(let[r,i]of n.entries())i.delete(e)&&t.push(r);return t},dispose(){t.clear(),n.clear(),r.clear()},isLoaded(e,t){return n.get(e)?.has(t)??!1},isRegistered(e){return t.has(e)},loadNamespace(i,a,o){let s=E(e());if(s)return s;let c=t.get(i);if(!c)return Promise.reject(new C(`Namespace '${i}' is not registered. Call registerNamespace() first.`));if(n.get(i)?.has(a))return Promise.resolve();let l=r.get(i)?.get(a);if(l)return l;let u=c(a).then(e=>o(a,e)).then(()=>{let e=n.get(i);e||(e=new Set,n.set(i,e)),e.add(a),r.get(i)?.delete(a)},e=>{throw r.get(i)?.delete(a),e});return r.has(i)||r.set(i,new Map),r.get(i).set(a,u),u},registerNamespace(n,r){T(e()),t.set(n,r)},seedFrom(e){for(let[n,r]of e.snapshotRegistry())t.set(n,r);for(let[t,r]of e.snapshotLoaded())n.set(t,new Set(r))},snapshotLoaded(){return n},snapshotRegistry(){return t}}}function P(e,t,n){let{chain:r,set:i}=M(e,t,n);return{chain:r,chainSet:i,locale:e}}function F(e,t,n,r){let i=[];return!r&&n===0&&i.push(`${e}.zero`),(t!==`zero`||r)&&i.push(`${e}.${t}`),t!==`other`&&i.push(`${e}.other`),i}function I(e){return L(e)}function L(e,t){let n=e??{},r=O(),i=e=>k(e,r),o=Array.isArray(n.fallback)?n.fallback.map(i):n.fallback?[i(n.fallback)]:[],s=!1,c=new AbortController,u=D(()=>s),d=N(()=>s),f=P(i(n.locale??`en`),o,r),p=new Set,_=new Set,x=n.onMissingKey??(e=>e),S=n.onMissingVar??(e=>`{${e}}`),C=n.onSubscriberError??(e=>l(`subscriber error`,e)),E,j=new Map,M=()=>(E||=a(()=>f.locale),E),I=e=>{for(let t of f.chain){let n=u.resolve(t)?.get(e);if(n!==void 0)return n}},R=e=>{if(I(e)!==void 0)return!0;for(let t of f.chain){let n=u.resolve(t);if(n&&n.prefixes.has(e))return!0}return!1},z=(e,t,n)=>m(t.compiled,n,e,f.locale,S),B=(e,t)=>{let n=String(e),r=I(n);return r?z(n,r,t):x(n,f.locale)},V=(e,t,n)=>{if(!Number.isFinite(t))throw new y("`count` must be a finite number.");let i=n?.vars,a=n?.ordinal??!1;if(i&&Object.hasOwn(i,`count`))throw new b("`tp` does not allow `vars.count`; `count` is injected automatically.");let o=String(e),s=i?{count:t,...i}:{count:t};for(let e of f.chain){let n=u.resolve(e);if(!n)continue;let i=F(o,A(e,t,a,r),t,a);for(let e of i){let t=n.get(e);if(t!==void 0)return z(e,t,s)}}return x(o,f.locale)},H={locale:f.locale,t:B,tp:V},U=()=>{H={locale:f.locale,t:B,tp:V};let e=[...p];for(let t of e)try{t(H)}catch(e){C(e)}};if(u.onChange=e=>{f.chainSet.has(e)&&U()},t?.catalogStore&&u.seedFrom(t.catalogStore.catalogs,t.catalogStore.pendingLoaders),t?.nsStore&&d.seedFrom(t.nsStore),n.catalogs){let e=new Map,t=new Map;for(let[r,a]of Object.entries(n.catalogs)){let n=i(r);if(typeof a==`function`)t.set(n,a);else{let t=new h;t.setAll(g(a)),e.set(n,t)}}u.seedFrom(e,t)}let W=e=>u.preload(i(e)),G=0;return{get disposalSignal(){return c.signal},dispose(){if(!s){s=!0,c.abort();for(let e of[..._])e();_.clear(),p.clear(),u.dispose(),d.dispose(),j.clear()}},get disposed(){return s},extend(e,t,n){T(s),d.registerNamespace(e,t);let r=n?i(n):f.locale;return d.loadNamespace(e,r,(e,t)=>u.patch(e,t))},get fmt(){return M()},fork(e){return L({fallback:e?.fallback??(o.length>0?o:void 0),locale:e?.locale??f.locale,onMissingKey:e?.onMissingKey??n.onMissingKey,onMissingVar:e?.onMissingVar??n.onMissingVar,onSubscriberError:e?.onSubscriberError??n.onSubscriberError},{catalogStore:u,nsStore:d})},getSnapshot(){return H},getState(){let e={};for(let[t,n]of u.catalogs)e[t]=Object.fromEntries([...n.entries.entries()].map(([e,{message:t}])=>[e,t]));return{catalogs:e,locale:f.locale}},getSupportedLocales(e){let t=[...u.knownLocales()];return e===!0?t.sort():t},has(e){return R(String(e))},isLoaded(e){try{return u.isLoaded(i(e))}catch{return!1}},isNamespaceLoaded(e,t){if(!t)return d.isLoaded(e,f.locale);try{return d.isLoaded(e,i(t))}catch{return!1}},isNamespaceRegistered(e){return d.isRegistered(e)},isRegistered(e){try{return u.isRegistered(i(e))}catch{return!1}},loadNamespace(e,t){let n=t?i(t):f.locale;return d.loadNamespace(e,n,(e,t)=>u.patch(e,t))},get locale(){return f.locale},preload:W,register(e,t){let n=i(e);return u.register(n,t,d)},registerNamespace(e,t){d.registerNamespace(e,t)},restoreState(e){if(T(s),!Object.hasOwn(e.catalogs,e.locale))throw new w(`restoreState: locale "${e.locale}" has no catalog in the provided state.`);let t=new Map,n=u.knownLocales();for(let e of n)d.clearLocale(e);for(let[n,r]of Object.entries(e.catalogs)){let e=i(n),a=new h;a.setAll(Object.entries(r)),t.set(e,a)}u.dispose(),u.onChange=e=>{f.chainSet.has(e)&&U()},u.seedFrom(t,new Map),f=P(i(e.locale),o,r),E?.clear(),U()},scope(e){let t=String(e),n=j.get(t);if(n)return n;let r={get fmt(){return M()},has:e=>R(`${t}.${e}`),t:(e,n)=>B(`${t}.${e}`,n),tp:(e,n,r)=>V(`${t}.${e}`,n,r)};return j.set(t,r),r},async setLocale(e){T(s);let t=i(e);if(f.locale===t)return;let n=++G;await W(t),!(s||G!==n)&&(f=P(t,o,r),E?.clear(),U())},subscribe:(e,t)=>{let n=t?.signal,r=()=>{p.delete(e),n?.removeEventListener(`abort`,r),_.delete(r)};if(s)throw new v;if(n?.aborted)return r;if(t?.immediate===!0)try{e(H)}catch(e){return C(e),r}return p.add(e),n?.addEventListener(`abort`,r,{once:!0}),_.add(r),r},[Symbol.dispose](){this.dispose()},t:B,tp:V}}function R(e){return e.getState()}function z(e,t){e.restoreState(t)}exports.LinguaCountInVarsError=b,exports.LinguaDisposedError=v,exports.LinguaError=_,exports.LinguaInvalidCountError=y,exports.LinguaInvalidLocaleError=S,exports.LinguaMissingLocaleError=x,exports.LinguaNamespaceMissingError=C,exports.LinguaRestoreError=w,exports.createFormatter=a,exports.createI18n=I,exports.hydrateI18n=z,exports.serializeI18n=R;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./template-BZRFdmaQ.cjs");function t(e,t,n,r){if(e.has(t))return e.get(t);let i=r();return e.size>=n&&e.delete(e.keys().next().value),e.set(t,i),i}var n=128,r=[`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`],i={days:`d`,hours:`h`,microseconds:`us`,milliseconds:`ms`,minutes:`min`,months:`mo`,nanoseconds:`ns`,seconds:`s`,weeks:`w`,years:`y`};function a(e){return r.map(t=>{let n=e[t];return typeof n==`number`?`${n}${i[t]}`:void 0}).filter(e=>e!==void 0).join(` `)}function o(e){let i=new Map,o=new Map,s=new Map,c=new Map,l=new Map,u=new Map,d=typeof e==`string`?()=>e:e;function f(e,t){if(!t)return e;let n={};for(let e of Object.keys(t).sort())n[e]=t[e];try{return`${e}:${JSON.stringify(n)}`}catch{return e}}return{clear(){i.clear(),o.clear(),s.clear(),c.clear(),l.clear(),u.clear()},currency(e,r,i){let a=d(),s={...i,currency:r,style:`currency`};return t(o,f(a,s),n,()=>new Intl.NumberFormat(a,s)).format(e)},date(e,r){let i=d();return t(s,f(i,r),n,()=>new Intl.DateTimeFormat(i,r)).format(e)},duration(e,i){let o=d(),s=Intl;return s.DurationFormat?r.every(t=>e[t]===void 0)?``:t(u,f(o,i),n,()=>new s.DurationFormat(o,i)).format(e):a(e)},list(e,r){let i=d(),a=e.map(e=>String(e)),o=r?.style??`long`,s=r?.type===`or`?`disjunction`:`conjunction`;return t(l,f(i,{style:o,type:s}),n,()=>new Intl.ListFormat(i,{style:o,type:s})).format(a)},number(e,r){let a=d();return t(i,f(a,r),n,()=>new Intl.NumberFormat(a,r)).format(e)},relative(e,r,i){let a=d();return t(c,f(a,i),n,()=>new Intl.RelativeTimeFormat(a,i)).format(e,r)}}}var s=class t{entries=new Map;prefixes=new Set;get(e){return this.entries.get(e)}set(t,n){this.entries.set(t,{compiled:e.t(n),message:n});let r=t.indexOf(`.`);for(;r!==-1;)this.prefixes.add(t.slice(0,r)),r=t.indexOf(`.`,r+1)}setAll(e){for(let[t,n]of e)this.set(t,n)}clone(){let e=new t;for(let[t,n]of this.entries)e.entries.set(t,n);for(let t of this.prefixes)e.prefixes.add(t);return e}};function c(t,n=new Map,r){for(let[i,a]of Object.entries(t)){if(e.c.has(i))continue;let t=r?`${r}.${i}`:i;if(typeof a==`string`){let r=e.n(a);r?c(r,n,t):n.set(t,a)}else c(a,n,t)}return n}var l=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}},u=class extends l{constructor(){super(`Operation called on a disposed i18n instance.`)}},d=class extends l{},f=class extends l{},p=class extends l{},m=class extends l{},h=class extends l{},g=class extends l{};function _(e){if(e)throw new u}function v(e){return e?Promise.reject(new u):null}function y(t,n){e.i(()=>{Promise.resolve().then(()=>require("./validate-x7lFFyV2.cjs")).then(({validateCatalog:r})=>{for(let i of r(n,t))e.o(`catalog('${t}'): missing plural form '${i.form}' for key '${i.key}'.`)})})}function b(t){let n=new Map,r=new Map,i=new Map,a=new Set,o,l=(e,t)=>{let r=n.get(e);r||(r=new s,n.set(e,r)),r.setAll(t)},u=e=>{let a=v(t());if(a)return a;if(n.has(e))return Promise.resolve();let s=r.get(e);if(!s)return Promise.reject(new p(`Missing locale source for "${e}".`));let u=i.get(e);if(u)return u;let d=s().then(t=>{r.get(e)===s&&(r.delete(e),l(e,c(t)),y(e,t),i.delete(e),o?.(e))},t=>{throw r.get(e)===s&&i.delete(e),t});return i.set(e,d),d};return{dispose(){n.clear(),r.clear(),i.clear(),a.clear(),o=void 0},isLoaded(e){return n.has(e)},isRegistered(e){return a.has(e)},knownLocales(){return[...a]},get onChange(){return o},set onChange(e){o=e},patch(e,n){return v(t())||(r.has(e)?u(e).then(()=>{t()||(l(e,c(n)),a.add(e),o?.(e))}):(l(e,c(n)),a.add(e),o?.(e),Promise.resolve()))},preload:u,register(s,d,f){_(t()),i.delete(s),a.add(s);let p=f.clearLocale(s);p.length>0&&e.o(`register('${s}') cleared loaded namespace markers for: ${p.map(e=>`'${e}'`).join(`, `)}. Call loadNamespace() again to reload.`);let m;return typeof d==`function`?(r.set(s,d),n.delete(s),m=u(s)):(r.delete(s),n.delete(s),l(s,c(d)),y(s,d),m=Promise.resolve(),o?.(s)),m},resolve(e){return n.get(e)},seedFrom(e,t){for(let[t,r]of e)n.set(t,r.clone()),a.add(t);for(let[e,n]of t)r.set(e,n),a.add(e)},snapshotCatalogs(){return n},snapshotLoaders(){return r}}}function x(){return{canon:new Map,chain:new Map,plural:new Map}}function S(e,t){let n=t.canon.get(e);if(n!==void 0)return n;let r;try{[r]=Intl.getCanonicalLocales(e)}catch{}if(!r)throw new m(`Invalid BCP 47 locale tag: "${e}".`);return t.canon.set(e,r),r}function C(e,t,n,r){let i=`${e}:${n?`ordinal`:`cardinal`}`,a=r.plural.get(i);return a||(a=new Intl.PluralRules(e,{type:n?`ordinal`:`cardinal`}),r.plural.set(i,a)),a.select(t)}function w(e,t){let n=new Set;for(let r of[e,...t]){n.add(r);let e=r.split(`-`);for(let t=e.length-1;t>0;t--)n.add(e.slice(0,t).join(`-`))}return{chain:[...n],set:n}}function T(e,t,n){let r=t.length===0?e:`${e}|${t.join(`,`)}`,i=n.chain.get(r);if(i)return i;let a=w(e,t);return n.chain.set(r,a),a}function E(e){let t=new Map,n=new Map,r=new Map;return{clearLocale(e){let t=[];for(let[r,i]of n.entries())i.delete(e)&&t.push(r);return t},dispose(){t.clear(),n.clear(),r.clear()},isLoaded(e,t){return n.get(e)?.has(t)??!1},isRegistered(e){return t.has(e)},loadNamespace(i,a,o){let s=v(e());if(s)return s;let c=t.get(i);if(!c)return Promise.reject(new h(`Namespace '${i}' is not registered. Call registerNamespace() first.`));if(n.get(i)?.has(a))return Promise.resolve();let l=r.get(i)?.get(a);if(l)return l;let u=c(a).then(e=>o(a,e)).then(()=>{let e=n.get(i);e||(e=new Set,n.set(i,e)),e.add(a),r.get(i)?.delete(a)},e=>{throw r.get(i)?.delete(a),e});return r.has(i)||r.set(i,new Map),r.get(i).set(a,u),u},registerNamespace(n,r){_(e()),t.set(n,r)},seedFrom(e){for(let[n,r]of e.snapshotRegistry())t.set(n,r);for(let[t,r]of e.snapshotLoaded())n.set(t,new Set(r))},snapshotLoaded(){return n},snapshotRegistry(){return t}}}function D(e,t){for(let n of e.chain){let r=e.catalogStore.resolve(n)?.get(t);if(r!==void 0)return r}}function O(e,t){for(let n of e.chain)if(e.catalogStore.resolve(n)?.prefixes.has(t))return!0;return!1}function k(e,t){return D(e,t)!==void 0||O(e,t)}function A(t,n,r,i){return e.r(r.compiled,i,n,t.locale,t.onMissingVar)}function j(t,n,r){let i=D(t,n);return i?A(t,n,i,r):(e.i(()=>{O(t,n)&&e.o(`t('${n}') resolved to the missing-key fallback, but '${n}' exists as a plural branch — use tp('${n}', count) instead.`)}),t.onMissingKey(n,t.locale))}function M(e,t,n,r){let i=[];return!r&&n===0&&i.push(`${e}.zero`),(t!==`zero`||r)&&i.push(`${e}.${t}`),t!==`other`&&i.push(`${e}.other`),i}function N(e,t,n,r){if(!Number.isFinite(n))throw new d("`count` must be a finite number.");let i=r?.vars,a=r?.ordinal??!1;if(i&&Object.hasOwn(i,`count`))throw new f("`tp` does not allow `vars.count`; `count` is injected automatically.");let o=i?{count:n,...i}:{count:n};for(let r of e.chain){let i=e.catalogStore.resolve(r);if(!i)continue;let s=M(t,C(r,n,a,e.caches),n,a);for(let t of s){let n=i.get(t);if(n!==void 0)return A(e,t,n,o)}}return e.onMissingKey(t,e.locale)}var P=128;function F(e,t,n){let{chain:r,set:i}=T(e,t,n);return{chain:r,chainSet:i,locale:e}}function I(e){return L(e)}function L(n,r){let i=n??{},a=x(),l=e=>S(e,a),d=Array.isArray(i.fallback)?i.fallback.map(l):i.fallback?[l(i.fallback)]:[],f=!1,p=new AbortController,m=b(()=>f),h=E(()=>f),v=F(l(i.locale??`en`),d,a),C=new Set,w=new Set,T=i.onMissingKey??(e=>e),D=i.onMissingVar??(e=>`{${e}}`),O=i.onSubscriberError??(t=>e.a(`subscriber error`,t)),A,M=new Map,I=()=>(A||=o(()=>v.locale),A),R=()=>({caches:a,catalogStore:m,chain:v.chain,locale:v.locale,onMissingKey:T,onMissingVar:D}),z=e=>k(R(),e),B=(e,t)=>j(R(),String(e),t),V=(e,t,n)=>N(R(),String(e),t,n),H={locale:v.locale,t:B,tp:V},U=()=>{H={locale:v.locale,t:B,tp:V};let e=[...C];for(let t of e)try{t(H)}catch(e){O(e)}};if(m.onChange=e=>{v.chainSet.has(e)&&U()},r?.catalogStore&&m.seedFrom(r.catalogStore.snapshotCatalogs(),r.catalogStore.snapshotLoaders()),r?.nsStore&&h.seedFrom(r.nsStore),i.catalogs){let e=new Map,t=new Map;for(let[n,r]of Object.entries(i.catalogs)){let i=l(n);if(typeof r==`function`)t.set(i,r);else{let t=new s;t.setAll(c(r)),e.set(i,t),y(i,r)}}m.seedFrom(e,t)}let W=e=>m.preload(l(e)),G=0,K={get disposalSignal(){return p.signal},dispose(){if(!f){f=!0,p.abort();for(let e of[...w])e();w.clear(),C.clear(),m.dispose(),h.dispose(),M.clear()}},get disposed(){return f},extend(e,t,n){_(f),h.registerNamespace(e,t);let r=n?l(n):v.locale;return h.loadNamespace(e,r,(e,t)=>m.patch(e,t))},get fmt(){return I()},fork(e){return L({fallback:e?.fallback??(d.length>0?d:void 0),locale:e?.locale??v.locale,onMissingKey:e?.onMissingKey??i.onMissingKey,onMissingVar:e?.onMissingVar??i.onMissingVar,onSubscriberError:e?.onSubscriberError??i.onSubscriberError},{catalogStore:m,nsStore:h})},getSnapshot(){return H},getState(){let e={};for(let[t,n]of m.snapshotCatalogs())e[t]=Object.fromEntries([...n.entries.entries()].map(([e,{message:t}])=>[e,t]));return{catalogs:e,locale:v.locale}},getSupportedLocales(e){let t=[...m.knownLocales()];return e===!0?t.sort():t},has(e){return z(String(e))},isLoaded(e){try{return m.isLoaded(l(e))}catch{return!1}},isNamespaceLoaded(e,t){if(!t)return h.isLoaded(e,v.locale);try{return h.isLoaded(e,l(t))}catch{return!1}},isNamespaceRegistered(e){return h.isRegistered(e)},isRegistered(e){try{return m.isRegistered(l(e))}catch{return!1}},loadNamespace(e,t){let n=t?l(t):v.locale;return h.loadNamespace(e,n,(e,t)=>m.patch(e,t))},get locale(){return v.locale},preload:W,register(e,t){let n=l(e);return m.register(n,t,h)},registerNamespace(e,t){h.registerNamespace(e,t)},restoreState(e){if(_(f),!Object.hasOwn(e.catalogs,e.locale))throw new g(`restoreState: locale "${e.locale}" has no catalog in the provided state.`);let t=new Map,n=m.knownLocales();for(let e of n)h.clearLocale(e);for(let[n,r]of Object.entries(e.catalogs)){let e=l(n),i=new s;i.setAll(Object.entries(r)),t.set(e,i)}m.dispose(),m.onChange=e=>{v.chainSet.has(e)&&U()},m.seedFrom(t,new Map),v=F(l(e.locale),d,a),A?.clear(),U()},scope(e){let n=String(e);return t(M,n,P,()=>({get fmt(){return I()},has:e=>z(`${n}.${e}`),t:(e,t)=>B(`${n}.${e}`,t),tp:(e,t,r)=>V(`${n}.${e}`,t,r)}))},async setLocale(e){_(f);let t=l(e);if(v.locale===t)return;let n=++G;await W(t),!(f||G!==n)&&(v=F(t,d,a),A?.clear(),U())},subscribe:(e,t)=>{let n=t?.signal,r=()=>{C.delete(e),n?.removeEventListener(`abort`,r),w.delete(r)};if(f)throw new u;if(n?.aborted)return r;if(t?.immediate===!0)try{e(H)}catch(e){return O(e),r}return C.add(e),n?.addEventListener(`abort`,r,{once:!0}),w.add(r),r},[Symbol.dispose](){K.dispose()},t:B,tp:V};return K}exports.LinguaCountInVarsError=f,exports.LinguaDisposedError=u,exports.LinguaError=l,exports.LinguaInvalidCountError=d,exports.LinguaInvalidLocaleError=m,exports.LinguaMissingLocaleError=p,exports.LinguaNamespaceMissingError=h,exports.LinguaRestoreError=g,exports.createFormatter=o,exports.createI18n=I;
|
|
2
2
|
//# sourceMappingURL=lingua.cjs.map
|