@vielzeug/i18nit 2.0.0 → 3.0.1
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/README.md +145 -51
- package/dist/format.d.ts +54 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/i18n.cjs +1 -1
- package/dist/i18n.cjs.map +1 -1
- package/dist/i18n.d.ts +5 -77
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +156 -202
- package/dist/i18n.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/types.d.ts +62 -83
- package/dist/types.d.ts.map +1 -1
- package/package.json +11 -12
- package/dist/core.cjs +0 -2
- package/dist/core.cjs.map +0 -1
- package/dist/core.d.ts +0 -35
- package/dist/core.d.ts.map +0 -1
- package/dist/core.js +0 -53
- package/dist/core.js.map +0 -1
- package/dist/helpers.cjs +0 -2
- package/dist/helpers.cjs.map +0 -1
- package/dist/helpers.d.ts +0 -20
- package/dist/helpers.d.ts.map +0 -1
- package/dist/helpers.js +0 -47
- package/dist/helpers.js.map +0 -1
- package/dist/i18nit.cjs +0 -2
- package/dist/i18nit.cjs.map +0 -1
- package/dist/i18nit.d.ts +0 -3
- package/dist/i18nit.d.ts.map +0 -1
- package/dist/i18nit.js +0 -2
- package/dist/i18nit.js.map +0 -1
- package/dist/interpolate.cjs +0 -2
- package/dist/interpolate.cjs.map +0 -1
- package/dist/interpolate.d.ts +0 -11
- package/dist/interpolate.d.ts.map +0 -1
- package/dist/interpolate.js +0 -13
- package/dist/interpolate.js.map +0 -1
- package/dist/intl.cjs +0 -2
- package/dist/intl.cjs.map +0 -1
- package/dist/intl.d.ts +0 -16
- package/dist/intl.d.ts.map +0 -1
- package/dist/intl.js +0 -65
- package/dist/intl.js.map +0 -1
package/dist/i18n.js
CHANGED
|
@@ -1,218 +1,172 @@
|
|
|
1
|
-
import { BoundView as e } from "./core.js";
|
|
2
|
-
import { BoundedMap as t, deepMerge as n, isMessageValue as r, resolvePath as i } from "./helpers.js";
|
|
3
|
-
import { formatDate as a, formatList as o, formatNumber as s, formatRelative as c, getPluralForm as l, makeIntlCaches as u } from "./intl.js";
|
|
4
|
-
import { interpolate as d } from "./interpolate.js";
|
|
5
1
|
//#region src/i18n.ts
|
|
6
|
-
var
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
#a = /* @__PURE__ */ new Set();
|
|
13
|
-
#o = new t(128);
|
|
14
|
-
#s;
|
|
15
|
-
#c;
|
|
16
|
-
#l = null;
|
|
17
|
-
#u = null;
|
|
18
|
-
#d = !1;
|
|
19
|
-
#f = 0;
|
|
20
|
-
#p = null;
|
|
21
|
-
#m;
|
|
22
|
-
#h = u();
|
|
23
|
-
#g;
|
|
24
|
-
constructor({ fallback: t, loaders: n, locale: l = "en", messages: u, onDiagnostic: d, onMissing: f } = {}) {
|
|
25
|
-
if (this.#e = l, this.#t = Array.isArray(t) ? t : t ? [t] : [], this.#s = f, this.#c = d, u) for (let [e, t] of Object.entries(u)) this.#n.set(e, structuredClone(t));
|
|
26
|
-
if (n) for (let [e, t] of Object.entries(n)) this.#r.set(e, t);
|
|
27
|
-
this.#m = {
|
|
28
|
-
checkOwn: (e, t) => {
|
|
29
|
-
let n = this.#n.get(t);
|
|
30
|
-
if (!n) return !1;
|
|
31
|
-
let a = i(n, e);
|
|
32
|
-
return a !== void 0 && r(a);
|
|
33
|
-
},
|
|
34
|
-
findMessage: (e, t) => this.#b(e, t),
|
|
35
|
-
formatDate: (e, t, n) => a(this.#h, e, t, n),
|
|
36
|
-
formatList: (e, t, n) => o(this.#h, e, t, n),
|
|
37
|
-
formatNumber: (e, t, n) => s(this.#h, e, t, n),
|
|
38
|
-
formatRelative: (e, t, n, r) => c(this.#h, e, t, n, r),
|
|
39
|
-
getLocale: () => this.#e,
|
|
40
|
-
translate: (e, t, n) => this.#S(e, t, n)
|
|
41
|
-
}, this.#g = new e(this.#m, null);
|
|
2
|
+
var e = /\{([\p{ID_Continue}\-.]+)\}/gu;
|
|
3
|
+
function t(e) {
|
|
4
|
+
try {
|
|
5
|
+
return Intl.getCanonicalLocales(e)[0] ?? e;
|
|
6
|
+
} catch {
|
|
7
|
+
return e;
|
|
42
8
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
set locale(e) {
|
|
50
|
-
this.#e !== e && (this.#e = e, this.#y("locale-change"));
|
|
51
|
-
}
|
|
52
|
-
async setLocale(e) {
|
|
53
|
-
e !== this.#e && (await this.load(e), this.locale = e);
|
|
54
|
-
}
|
|
55
|
-
add(e, t) {
|
|
56
|
-
let r = this.#n.get(e) ?? {};
|
|
57
|
-
this.#n.set(e, n(r, t)), this.#l = null, this.#x(this.#e).includes(e) && this.#y("catalog-update");
|
|
58
|
-
}
|
|
59
|
-
replace(e, t) {
|
|
60
|
-
this.#n.set(e, structuredClone(t)), this.#l = null, this.#x(this.#e).includes(e) && this.#y("catalog-update");
|
|
61
|
-
}
|
|
62
|
-
has(e) {
|
|
63
|
-
return this.#g.has(e);
|
|
64
|
-
}
|
|
65
|
-
hasOwn(e) {
|
|
66
|
-
return this.#g.hasOwn(e);
|
|
67
|
-
}
|
|
68
|
-
hasLocale(e) {
|
|
69
|
-
return this.#n.has(e);
|
|
70
|
-
}
|
|
71
|
-
async load(...e) {
|
|
72
|
-
await Promise.all(e.map((e) => this.#C(e)));
|
|
73
|
-
}
|
|
74
|
-
async reload(e) {
|
|
75
|
-
this.#r.has(e) && (this.#n.delete(e), this.#l = null, await this.#C(e));
|
|
76
|
-
}
|
|
77
|
-
registerLoader(e, t) {
|
|
78
|
-
this.#r.set(e, t), this.#u = null;
|
|
79
|
-
}
|
|
80
|
-
get loadableLocales() {
|
|
81
|
-
return this.#u ??= [...this.#r.keys()], this.#u;
|
|
82
|
-
}
|
|
83
|
-
t(e, t) {
|
|
84
|
-
return this.#g.t(e, t);
|
|
85
|
-
}
|
|
86
|
-
number(e, t) {
|
|
87
|
-
return this.#g.number(e, t);
|
|
88
|
-
}
|
|
89
|
-
date(e, t) {
|
|
90
|
-
return this.#g.date(e, t);
|
|
91
|
-
}
|
|
92
|
-
list(e, t = "and") {
|
|
93
|
-
return this.#g.list(e, t);
|
|
94
|
-
}
|
|
95
|
-
relative(e, t, n) {
|
|
96
|
-
return this.#g.relative(e, t, n);
|
|
97
|
-
}
|
|
98
|
-
currency(e, t, n) {
|
|
99
|
-
return this.#g.currency(e, t, n);
|
|
100
|
-
}
|
|
101
|
-
withLocale(e) {
|
|
102
|
-
return this.#g.withLocale(e);
|
|
103
|
-
}
|
|
104
|
-
scope(e) {
|
|
105
|
-
return this.#g.scope(e);
|
|
9
|
+
}
|
|
10
|
+
function n(e, t) {
|
|
11
|
+
let n = e;
|
|
12
|
+
for (let e of t.split(".")) {
|
|
13
|
+
if (typeof n != "object" || !n || !Object.hasOwn(n, e)) return;
|
|
14
|
+
n = n[e];
|
|
106
15
|
}
|
|
107
|
-
|
|
108
|
-
|
|
16
|
+
return n;
|
|
17
|
+
}
|
|
18
|
+
function r(e, t) {
|
|
19
|
+
let n = /* @__PURE__ */ new Set();
|
|
20
|
+
for (let r of [e, ...t]) {
|
|
21
|
+
n.add(r);
|
|
22
|
+
let e = r.split("-");
|
|
23
|
+
for (let t = e.length - 1; t > 0; t--) n.add(e.slice(0, t).join("-"));
|
|
24
|
+
}
|
|
25
|
+
return [...n];
|
|
26
|
+
}
|
|
27
|
+
function i(e, t, n, r) {
|
|
28
|
+
let i = `${t}:${r ? "ordinal" : "cardinal"}`, a = e.get(i);
|
|
29
|
+
if (!a) {
|
|
109
30
|
try {
|
|
110
|
-
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
let e = this.#p;
|
|
114
|
-
this.#p = null, this.#y(e);
|
|
115
|
-
}
|
|
31
|
+
a = new Intl.PluralRules(t, { type: r ? "ordinal" : "cardinal" });
|
|
32
|
+
} catch {
|
|
33
|
+
a = { select: (e) => e === 1 ? "one" : "other" };
|
|
116
34
|
}
|
|
35
|
+
e.set(i, a);
|
|
117
36
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
37
|
+
return a.select(n);
|
|
38
|
+
}
|
|
39
|
+
function a(t, r, i, a, o) {
|
|
40
|
+
return t.includes("{") ? t.replace(e, (e, t) => {
|
|
41
|
+
let s = r == null ? void 0 : n(r, t);
|
|
42
|
+
return s == null ? o({
|
|
43
|
+
key: i,
|
|
44
|
+
locale: a,
|
|
45
|
+
type: "var",
|
|
46
|
+
varName: t
|
|
47
|
+
}) : String(s);
|
|
48
|
+
}) : t;
|
|
49
|
+
}
|
|
50
|
+
function o(e) {
|
|
51
|
+
let o = e ?? {}, s = t(o.locale ?? "en"), c = Array.isArray(o.fallback) ? o.fallback.map(t) : o.fallback ? [t(o.fallback)] : [], l = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Set(), f = /* @__PURE__ */ new Map(), p = o.onMissing ?? ((e) => e.type === "key" ? e.key : `{${e.varName}}`), m = o.onSubscriberError ?? (() => {}), h = 0, g = {
|
|
52
|
+
locale: s,
|
|
53
|
+
version: h
|
|
54
|
+
}, _ = r(s, c), v = 0, y = () => {
|
|
55
|
+
h++, g = {
|
|
56
|
+
locale: s,
|
|
57
|
+
version: h
|
|
58
|
+
};
|
|
59
|
+
let e = [...d];
|
|
60
|
+
for (let t of e) try {
|
|
61
|
+
t(g);
|
|
124
62
|
} catch (e) {
|
|
125
|
-
|
|
63
|
+
m(e);
|
|
126
64
|
}
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
this.#d = !0, this.#a.clear(), this.#n.clear(), this.#r.clear(), this.#i.clear(), this.#o.clear(), this.#l = null, this.#u = null;
|
|
131
|
-
}
|
|
132
|
-
[Symbol.dispose]() {
|
|
133
|
-
this.dispose();
|
|
134
|
-
}
|
|
135
|
-
async [Symbol.asyncDispose]() {
|
|
136
|
-
await Promise.allSettled([...this.#i.values()]), this.dispose();
|
|
137
|
-
}
|
|
138
|
-
#_(e) {
|
|
139
|
-
this.#c ? this.#c({
|
|
140
|
-
error: e,
|
|
141
|
-
kind: "subscriber-error"
|
|
142
|
-
}) : console.error("[i18nit] Subscriber threw:", e);
|
|
143
|
-
}
|
|
144
|
-
#v(e, t) {
|
|
145
|
-
this.#c ? this.#c({
|
|
146
|
-
error: e,
|
|
147
|
-
kind: "loader-error",
|
|
148
|
-
locale: t
|
|
149
|
-
}) : console.warn("[i18nit] Loader error:", e);
|
|
150
|
-
}
|
|
151
|
-
#y(e) {
|
|
152
|
-
if (this.#f > 0) {
|
|
153
|
-
this.#p !== "locale-change" && (this.#p = e);
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
156
|
-
let t = {
|
|
157
|
-
locale: this.#e,
|
|
158
|
-
reason: e
|
|
159
|
-
};
|
|
160
|
-
for (let e of this.#a) try {
|
|
161
|
-
e(t);
|
|
65
|
+
}, b = (e, t = !1) => {
|
|
66
|
+
if (d.add(e), t) try {
|
|
67
|
+
e(g);
|
|
162
68
|
} catch (e) {
|
|
163
|
-
|
|
69
|
+
m(e);
|
|
164
70
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
for (let
|
|
168
|
-
let
|
|
169
|
-
if (!
|
|
170
|
-
let
|
|
171
|
-
if (
|
|
71
|
+
return () => d.delete(e);
|
|
72
|
+
}, x = (e) => {
|
|
73
|
+
for (let t of _) {
|
|
74
|
+
let r = l.get(t)?.messages;
|
|
75
|
+
if (!r) continue;
|
|
76
|
+
let i = n(r, e);
|
|
77
|
+
if (typeof i == "string") return i;
|
|
172
78
|
}
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
let
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
if (
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
let
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
this.#d || this.replace(e, n);
|
|
203
|
-
} catch (t) {
|
|
204
|
-
throw this.#v(t, e), t;
|
|
205
|
-
} finally {
|
|
206
|
-
this.#i.delete(e);
|
|
207
|
-
}
|
|
79
|
+
}, S = (e, t) => {
|
|
80
|
+
if (typeof t == "function") {
|
|
81
|
+
l.set(e, {
|
|
82
|
+
kind: "dynamic",
|
|
83
|
+
loader: t
|
|
84
|
+
});
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
l.set(e, {
|
|
88
|
+
kind: "static",
|
|
89
|
+
messages: t
|
|
90
|
+
});
|
|
91
|
+
}, C = (e, n) => {
|
|
92
|
+
let r = t(e);
|
|
93
|
+
S(r, n), _.includes(r) && y();
|
|
94
|
+
};
|
|
95
|
+
if (o.catalogs) for (let [e, n] of Object.entries(o.catalogs)) S(t(e), n);
|
|
96
|
+
let w = async (e) => {
|
|
97
|
+
let n = t(e), r = l.get(n);
|
|
98
|
+
if (!r) throw Error(`Missing locale source for "${n}".`);
|
|
99
|
+
if (r.kind === "static" || r.messages) return;
|
|
100
|
+
let i = u.get(n);
|
|
101
|
+
if (i?.entry === r) {
|
|
102
|
+
await i.task;
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
let a = (async () => {
|
|
106
|
+
let e = await r.loader(n);
|
|
107
|
+
l.get(n) === r && (r.messages = e, _.includes(n) && y());
|
|
208
108
|
})();
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
109
|
+
u.set(n, {
|
|
110
|
+
entry: r,
|
|
111
|
+
task: a
|
|
112
|
+
});
|
|
113
|
+
try {
|
|
114
|
+
await a;
|
|
115
|
+
} finally {
|
|
116
|
+
u.get(n)?.task === a && u.delete(n);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
function T(e, t) {
|
|
120
|
+
let n = String(e), r = x(n);
|
|
121
|
+
return r === void 0 ? p({
|
|
122
|
+
key: n,
|
|
123
|
+
locale: s,
|
|
124
|
+
type: "key"
|
|
125
|
+
}) : a(r, t, n, s, p);
|
|
126
|
+
}
|
|
127
|
+
function E(e, t, n) {
|
|
128
|
+
if (!Number.isFinite(t)) throw TypeError("`count` must be a finite number.");
|
|
129
|
+
if (n?.vars && Object.hasOwn(n.vars, "count")) throw Error("`tp` does not allow `vars.count`; `count` is injected automatically.");
|
|
130
|
+
let r = String(e), o = n?.ordinal === !0, c = i(f, s, t, o), l = x(!o && t === 0 ? `${r}.zero` : `${r}.${c}`) ?? x(`${r}.other`);
|
|
131
|
+
return l === void 0 ? p({
|
|
132
|
+
key: r,
|
|
133
|
+
locale: s,
|
|
134
|
+
type: "key"
|
|
135
|
+
}) : a(l, {
|
|
136
|
+
...n?.vars ?? {},
|
|
137
|
+
count: t
|
|
138
|
+
}, r, s, p);
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
getSnapshot() {
|
|
142
|
+
return g;
|
|
143
|
+
},
|
|
144
|
+
getSupportedLocales(e) {
|
|
145
|
+
let t = [...l.keys()];
|
|
146
|
+
return e?.sorted === !0 ? t.sort() : t;
|
|
147
|
+
},
|
|
148
|
+
has(e) {
|
|
149
|
+
return x(String(e)) !== void 0;
|
|
150
|
+
},
|
|
151
|
+
get locale() {
|
|
152
|
+
return s;
|
|
153
|
+
},
|
|
154
|
+
preload: w,
|
|
155
|
+
register: C,
|
|
156
|
+
async setLocale(e) {
|
|
157
|
+
let n = t(e);
|
|
158
|
+
if (s === n) return;
|
|
159
|
+
let i = ++v;
|
|
160
|
+
await w(n), i === v && (s = n, _ = r(s, c), y());
|
|
161
|
+
},
|
|
162
|
+
subscribe(e, t) {
|
|
163
|
+
return b(e, t?.immediate === !0);
|
|
164
|
+
},
|
|
165
|
+
t: T,
|
|
166
|
+
tp: E
|
|
167
|
+
};
|
|
214
168
|
}
|
|
215
169
|
//#endregion
|
|
216
|
-
export {
|
|
170
|
+
export { o as createI18n };
|
|
217
171
|
|
|
218
172
|
//# sourceMappingURL=i18n.js.map
|
package/dist/i18n.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n.js","names":["#caches","#view","#locale","#fallbacks","#onMissing","#onDiagnostic","#catalogs","#loaders","#core","#findMessage","#translate","#localesCache","#notify","#getLocaleChain","#loadOne","#loadersCache","#batchDepth","#pendingNotify","#subscribers","#diagnoseSubscriber","#disposed","#loading","#chainCache","#diagnoseLoader"],"sources":["../src/i18n.ts"],"sourcesContent":["import type {\n BoundI18n,\n DiagnosticEvent,\n I18nOptions,\n Loader,\n Locale,\n LocaleChangeEvent,\n LocaleChangeReason,\n MessageValue,\n Messages,\n NamespaceKeys,\n TranslationKeyParam,\n Unsubscribe,\n Vars,\n} from './types';\n\nimport { BoundView, type I18nCore } from './core';\nimport { BoundedMap, deepMerge, isMessageValue, resolvePath } from './helpers';\nimport { interpolate } from './interpolate';\nimport {\n type IntlCaches,\n formatDate,\n formatList,\n formatNumber,\n formatRelative,\n getPluralForm,\n makeIntlCaches,\n} from './intl';\n\nexport class I18n<T extends Messages = Messages> implements BoundI18n<T> {\n #locale: Locale;\n #fallbacks: Locale[];\n #catalogs = new Map<Locale, Messages>();\n #loaders = new Map<Locale, Loader>();\n #loading = new Map<Locale, Promise<void>>();\n #subscribers = new Set<(event: LocaleChangeEvent) => void>();\n /** Bounded at 128 entries — prevents unbounded growth when locale tags come from user input. */\n #chainCache = new BoundedMap<Locale, Locale[]>(128);\n #onMissing?: (key: string, locale: Locale) => string | undefined;\n #onDiagnostic?: (event: DiagnosticEvent) => void;\n #localesCache: Locale[] | null = null;\n #loadersCache: Locale[] | null = null;\n #disposed = false;\n #batchDepth = 0;\n #pendingNotify: LocaleChangeReason | null = null;\n #core: I18nCore;\n\n // Instance-scoped Intl caches — GC'd with the instance (important for SSR with many locales).\n readonly #caches: IntlCaches = makeIntlCaches();\n\n /** Internal BoundView — I18n delegates its BoundI18n surface here to avoid duplicating every method. */\n readonly #view: BoundView<T>;\n\n constructor({ fallback, loaders, locale = 'en', messages, onDiagnostic, onMissing }: I18nOptions<T> = {}) {\n this.#locale = locale;\n this.#fallbacks = Array.isArray(fallback) ? fallback : fallback ? [fallback] : [];\n this.#onMissing = onMissing;\n this.#onDiagnostic = onDiagnostic;\n\n if (messages) {\n for (const [l, m] of Object.entries(messages)) {\n // Deep-clone at init so external mutations to the source object can't corrupt the catalog.\n this.#catalogs.set(l, structuredClone(m) as Messages);\n }\n }\n\n if (loaders) for (const [l, fn] of Object.entries(loaders)) this.#loaders.set(l, fn);\n\n this.#core = {\n checkOwn: (key: string, locale: Locale) => {\n const catalog = this.#catalogs.get(locale);\n\n if (!catalog) return false;\n\n const value = resolvePath(catalog, key);\n\n return value !== undefined && isMessageValue(value);\n },\n findMessage: (key: string, locale: Locale) => this.#findMessage(key, locale),\n formatDate: (value, options, locale) => formatDate(this.#caches, value, options, locale),\n formatList: (items, locale, type) => formatList(this.#caches, items, locale, type),\n formatNumber: (value, options, locale) => formatNumber(this.#caches, value, options, locale),\n formatRelative: (value, unit, options, locale) => formatRelative(this.#caches, value, unit, options, locale),\n getLocale: () => this.#locale,\n translate: (key, vars, locale) => this.#translate(key, vars, locale),\n };\n\n this.#view = new BoundView<T>(this.#core, null);\n }\n\n /* -------------------- Locale -------------------- */\n\n get locale(): Locale {\n return this.#locale;\n }\n\n get locales(): Locale[] {\n this.#localesCache ??= [...this.#catalogs.keys()];\n\n return this.#localesCache;\n }\n\n set locale(value: Locale) {\n if (this.#locale === value) return;\n\n if (import.meta.env?.DEV && !this.#catalogs.has(value) && this.#loaders.has(value)) {\n console.warn(\n `[i18nit] locale \"${value}\" has a registered loader but is not loaded. ` +\n 'Use setLocale() to load and switch atomically.',\n );\n }\n\n this.#locale = value;\n this.#notify('locale-change');\n }\n\n async setLocale(locale: Locale): Promise<void> {\n if (locale === this.#locale) return;\n\n await this.load(locale);\n this.locale = locale;\n }\n\n /* -------------------- Message Management -------------------- */\n\n /** Deep-merges messages into an existing locale catalog. */\n add(locale: Locale, messages: Messages): void {\n const existing = this.#catalogs.get(locale) ?? {};\n\n this.#catalogs.set(locale, deepMerge(existing, messages));\n this.#localesCache = null;\n\n if (this.#getLocaleChain(this.#locale).includes(locale)) this.#notify('catalog-update');\n }\n\n /** Replaces the entire locale catalog for `locale` with a deep clone of `messages`. */\n replace(locale: Locale, messages: Messages): void {\n this.#catalogs.set(locale, structuredClone(messages));\n this.#localesCache = null;\n\n if (this.#getLocaleChain(this.#locale).includes(locale)) this.#notify('catalog-update');\n }\n\n has(key: string): boolean {\n return this.#view.has(key);\n }\n\n /** Like `has()`, but only checks the exact locale without walking the fallback chain. */\n hasOwn(key: string): boolean {\n return this.#view.hasOwn(key);\n }\n\n hasLocale(locale: Locale): boolean {\n return this.#catalogs.has(locale);\n }\n\n /* -------------------- Async Loaders -------------------- */\n\n async load(...locales: Locale[]): Promise<void> {\n await Promise.all(locales.map((locale) => this.#loadOne(locale)));\n }\n\n /**\n * Force-reloads a locale catalog even if already populated. Useful for hot-reload and forced bundle refresh.\n * No-op (with a dev warning) when no loader is registered for the locale, to prevent silently clearing the catalog.\n */\n async reload(locale: Locale): Promise<void> {\n if (!this.#loaders.has(locale)) {\n if (import.meta.env?.DEV) {\n console.warn(`[i18nit] reload(\"${locale}\") skipped — no loader registered for this locale.`);\n }\n\n return;\n }\n\n this.#catalogs.delete(locale);\n this.#localesCache = null;\n await this.#loadOne(locale);\n }\n\n registerLoader(locale: Locale, loader: Loader): void {\n this.#loaders.set(locale, loader);\n this.#loadersCache = null;\n }\n\n /** Returns the locale keys for which a loader has been registered. */\n get loadableLocales(): Locale[] {\n this.#loadersCache ??= [...this.#loaders.keys()];\n\n return this.#loadersCache;\n }\n\n /* -------------------- BoundI18n surface (delegated to #view) -------------------- */\n\n /**\n * Translates a key with optional interpolation variables.\n * Locale must be loaded first via `load()` or provided via `messages` in config.\n * For a per-call locale override use `withLocale(locale).t(key, vars)`.\n */\n t(key: TranslationKeyParam<T>, vars?: Vars): string {\n return this.#view.t(key, vars);\n }\n\n number(value: number, options?: Intl.NumberFormatOptions): string {\n return this.#view.number(value, options);\n }\n\n date(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return this.#view.date(value, options);\n }\n\n list(items: unknown[], type: 'and' | 'or' = 'and'): string {\n return this.#view.list(items, type);\n }\n\n relative(value: number, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions): string {\n return this.#view.relative(value, unit, options);\n }\n\n currency(value: number, currency: string, options?: Omit<Intl.NumberFormatOptions, 'style' | 'currency'>): string {\n return this.#view.currency(value, currency, options);\n }\n\n /**\n * Returns a bound interface that translates in the given locale without\n * changing the active locale on the instance. Useful for SSR and\n * multi-locale rendering in a single pass.\n */\n withLocale(locale: Locale): BoundI18n<T> {\n return this.#view.withLocale(locale);\n }\n\n /**\n * Returns a translator scoped to a key namespace prefix. Reacts to locale changes on the\n * instance. When `T` is a concrete message type, the returned `BoundI18n` is narrowed to\n * the subtree type so `t()` autocomplete works within the scope.\n * Only keys whose values are nested message objects are valid scope targets.\n */\n scope<K extends NamespaceKeys<T>>(ns: K): BoundI18n<T[K] & Messages> {\n return this.#view.scope(ns);\n }\n\n /* -------------------- Subscriptions -------------------- */\n\n /**\n * Executes `fn` while deferring subscriber notifications. A single notification fires\n * after `fn` completes, collapsing any number of `add()` / `replace()` calls made within.\n * Nested `batch()` calls are supported; notification fires when the outermost batch exits.\n * If both a locale change and a catalog update are triggered, `'locale-change'` takes priority.\n *\n * @remarks\n * `batch()` is synchronous. Async operations (e.g. `load()`) started inside `fn` complete\n * after the batch exits and will notify subscribers individually. To batch-load multiple\n * locales and notify once, await `load()` before entering the batch:\n * ```ts\n * await i18n.load('fr', 'de');\n * i18n.batch(() => { i18n.locale = 'fr'; });\n * ```\n */\n batch(fn: () => void): void {\n this.#batchDepth++;\n\n try {\n fn();\n } finally {\n this.#batchDepth--;\n\n if (this.#batchDepth === 0 && this.#pendingNotify !== null) {\n const reason = this.#pendingNotify;\n\n this.#pendingNotify = null;\n this.#notify(reason);\n }\n }\n }\n\n subscribe(listener: (event: LocaleChangeEvent) => void, immediate?: boolean): Unsubscribe {\n this.#subscribers.add(listener);\n\n if (immediate) {\n try {\n listener({ locale: this.#locale, reason: 'locale-change' });\n } catch (err) {\n this.#diagnoseSubscriber(err);\n }\n }\n\n return () => this.#subscribers.delete(listener);\n }\n\n /** Releases all resources held by this instance. */\n dispose(): void {\n this.#disposed = true;\n this.#subscribers.clear();\n this.#catalogs.clear();\n this.#loaders.clear();\n this.#loading.clear();\n this.#chainCache.clear();\n this.#localesCache = null;\n this.#loadersCache = null;\n }\n\n /** Enables `using i18n = createI18n(...)` for deterministic resource release. */\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n /**\n * Awaits any in-flight `load()` calls and then releases all resources.\n * Enables `await using i18n = createI18n(...)` in environments that support `Symbol.asyncDispose`.\n */\n async [Symbol.asyncDispose](): Promise<void> {\n await Promise.allSettled([...this.#loading.values()]);\n this.dispose();\n }\n\n /* -------------------- Private -------------------- */\n\n #diagnoseSubscriber(error: unknown): void {\n if (this.#onDiagnostic) {\n this.#onDiagnostic({ error, kind: 'subscriber-error' });\n } else {\n console.error('[i18nit] Subscriber threw:', error);\n }\n }\n\n #diagnoseLoader(error: unknown, locale: Locale): void {\n if (this.#onDiagnostic) {\n this.#onDiagnostic({ error, kind: 'loader-error', locale });\n } else {\n console.warn('[i18nit] Loader error:', error);\n }\n }\n\n #notify(reason: LocaleChangeReason): void {\n if (this.#batchDepth > 0) {\n // 'locale-change' takes priority over 'catalog-update' if both occur in one batch\n if (this.#pendingNotify !== 'locale-change') this.#pendingNotify = reason;\n\n return;\n }\n\n const event: LocaleChangeEvent = { locale: this.#locale, reason };\n\n for (const listener of this.#subscribers) {\n try {\n listener(event);\n } catch (err) {\n this.#diagnoseSubscriber(err);\n }\n }\n }\n\n #findMessage(key: string, locale: Locale): MessageValue | undefined {\n for (const loc of this.#getLocaleChain(locale)) {\n const messages = this.#catalogs.get(loc);\n\n if (!messages) continue;\n\n const value = resolvePath(messages, key);\n\n if (value !== undefined && isMessageValue(value)) return value;\n }\n\n return undefined;\n }\n\n #getLocaleChain(locale: Locale): Locale[] {\n const cached = this.#chainCache.get(locale);\n\n if (cached) return cached;\n\n const seen = new Set<Locale>();\n const push = (l: Locale) => {\n seen.add(l);\n\n const parts = l.split('-');\n\n for (let i = parts.length - 1; i > 0; i--) {\n seen.add(parts.slice(0, i).join('-'));\n }\n };\n\n push(locale);\n for (const fallback of this.#fallbacks) push(fallback);\n\n const chain = [...seen];\n\n this.#chainCache.set(locale, chain);\n\n return chain;\n }\n\n #translate(key: string, vars: Vars | undefined, locale: Locale): string {\n const message = this.#findMessage(key, locale);\n\n if (message === undefined) return this.#onMissing?.(key, locale) ?? key;\n\n if (typeof message === 'string') return interpolate(message, vars ?? {}, locale, this.#caches);\n\n const v = vars ?? {};\n\n if (import.meta.env?.DEV && v.count === undefined) {\n console.warn(`[i18nit] Key \"${key}\" is a plural message but vars.count is missing. Defaulting to 0.`);\n }\n\n const count = Number(v.count ?? 0);\n const form = count === 0 && message.zero !== undefined ? 'zero' : getPluralForm(this.#caches, locale, count);\n\n return interpolate(message[form] ?? message.other, v, locale, this.#caches);\n }\n\n #loadOne(locale: Locale): Promise<void> {\n if (this.#loading.has(locale)) return this.#loading.get(locale)!;\n\n if (this.#catalogs.has(locale)) return Promise.resolve();\n\n const loader = this.#loaders.get(locale);\n\n if (!loader) return Promise.resolve();\n\n const promise = (async () => {\n try {\n const messages = await loader(locale);\n\n // Use replace() so the loader result is the authoritative catalog for this locale,\n // not merged on top of any pre-seeded static messages.\n if (!this.#disposed) this.replace(locale, messages);\n } catch (error) {\n this.#diagnoseLoader(error, locale);\n throw error;\n } finally {\n this.#loading.delete(locale);\n }\n })();\n\n this.#loading.set(locale, promise);\n\n return promise;\n }\n}\n\nexport function createI18n<T extends Messages = Messages>(config?: I18nOptions<T>): I18n<T> {\n return new I18n<T>(config);\n}\n"],"mappings":";;;;;AA6BA,IAAa,IAAb,MAAyE;CACvE;CACA;CACA,qBAAY,IAAI,KAAuB;CACvC,qBAAW,IAAI,KAAqB;CACpC,qBAAW,IAAI,KAA4B;CAC3C,qBAAe,IAAI,KAAyC;CAE5D,KAAc,IAAI,EAA6B,IAAI;CACnD;CACA;CACA,KAAiC;CACjC,KAAiC;CACjC,KAAY;CACZ,KAAc;CACd,KAA4C;CAC5C;CAGA,KAA+B,GAAgB;CAG/C;CAEA,YAAY,EAAE,aAAU,YAAS,YAAS,MAAM,aAAU,iBAAc,iBAA8B,EAAE,EAAE;AAMxG,MALA,MAAA,IAAe,GACf,MAAA,IAAkB,MAAM,QAAQ,EAAS,GAAG,IAAW,IAAW,CAAC,EAAS,GAAG,EAAE,EACjF,MAAA,IAAkB,GAClB,MAAA,IAAqB,GAEjB,EACF,MAAK,IAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,EAAS,CAE3C,OAAA,EAAe,IAAI,GAAG,gBAAgB,EAAE,CAAa;AAIzD,MAAI,EAAS,MAAK,IAAM,CAAC,GAAG,MAAO,OAAO,QAAQ,EAAQ,CAAE,OAAA,EAAc,IAAI,GAAG,EAAG;AAqBpF,EAnBA,MAAA,IAAa;GACX,WAAW,GAAa,MAAmB;IACzC,IAAM,IAAU,MAAA,EAAe,IAAI,EAAO;AAE1C,QAAI,CAAC,EAAS,QAAO;IAErB,IAAM,IAAQ,EAAY,GAAS,EAAI;AAEvC,WAAO,MAAU,KAAA,KAAa,EAAe,EAAM;;GAErD,cAAc,GAAa,MAAmB,MAAA,EAAkB,GAAK,EAAO;GAC5E,aAAa,GAAO,GA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MAAA,EAAe,IAAI,EAAO,CAAE,QAAO,QAAQ,SAAS;EAExD,IAAM,IAAS,MAAA,EAAc,IAAI,EAAO;AAExC,MAAI,CAAC,EAAQ,QAAO,QAAQ,SAAS;EAErC,IAAM,KAAW,YAAY;AAC3B,OAAI;IACF,IAAM,IAAW,MAAM,EAAO,EAAO;AAIrC,IAAK,MAAA,KAAgB,KAAK,QAAQ,GAAQ,EAAS;YAC5C,GAAO;AAEd,UADA,MAAA,EAAqB,GAAO,EAAO,EAC7B;aACE;AACR,UAAA,EAAc,OAAO,EAAO;;MAE5B;AAIJ,SAFA,MAAA,EAAc,IAAI,GAAQ,EAAQ,EAE3B;;;AAIX,SAAgB,EAA0C,GAAkC;AAC1F,QAAO,IAAI,EAAQ,EAAO"}
|
|
1
|
+
{"version":3,"file":"i18n.js","names":[],"sources":["../src/i18n.ts"],"sourcesContent":["import type {\n AnyKey,\n I18n,\n I18nOptions,\n I18nSnapshot,\n Loader,\n Locale,\n LocaleSource,\n MessageBranchKeys,\n MessageLeafKeys,\n Messages,\n MissingInfo,\n PluralTranslateOptions,\n SubscribeOptions,\n TranslateVars,\n Unsubscribe,\n} from './types';\n\ntype PluralRuleSelector = { select: (count: number) => string };\ntype PluralCaches = Map<string, PluralRuleSelector>;\ntype LocaleRecord<M extends Messages> =\n | { kind: 'dynamic'; loader: Loader<M>; messages?: M }\n | { kind: 'static'; messages: M };\ntype LoadingRecord<M extends Messages> = {\n entry: Extract<LocaleRecord<M>, { kind: 'dynamic' }>;\n task: Promise<void>;\n};\n\nconst INTERPOLATION_PATTERN = /\\{([\\p{ID_Continue}\\-.]+)\\}/gu;\n\nfunction canon(locale: string): string {\n try {\n return Intl.getCanonicalLocales(locale)[0] ?? locale;\n } catch {\n return locale;\n }\n}\n\nfunction resolvePath(obj: Record<string, unknown>, path: string): unknown {\n let value: unknown = obj;\n\n for (const part of path.split('.')) {\n if (value == null || typeof value !== 'object') return undefined;\n\n if (!Object.hasOwn(value as object, part)) return undefined;\n\n value = (value as Record<string, unknown>)[part];\n }\n\n return value;\n}\n\nfunction buildLocaleChain(locale: Locale, fallback: Locale[]): Locale[] {\n const seen = new Set<Locale>();\n\n for (const value of [locale, ...fallback]) {\n seen.add(value);\n\n const parts = value.split('-');\n\n for (let i = parts.length - 1; i > 0; i--) {\n seen.add(parts.slice(0, i).join('-'));\n }\n }\n\n return [...seen];\n}\n\nfunction selectPluralForm(cache: PluralCaches, locale: Locale, count: number, ordinal: boolean): string {\n const key = `${locale}:${ordinal ? 'ordinal' : 'cardinal'}`;\n let rules = cache.get(key);\n\n if (!rules) {\n try {\n rules = new Intl.PluralRules(locale, { type: ordinal ? 'ordinal' : 'cardinal' });\n } catch {\n rules = { select: (value: number) => (value === 1 ? 'one' : 'other') };\n }\n\n cache.set(key, rules);\n }\n\n return rules.select(count);\n}\n\nfunction interpolate(\n template: string,\n vars: TranslateVars | undefined,\n key: string,\n locale: Locale,\n onMissing: (info: MissingInfo) => string,\n): string {\n if (!template.includes('{')) return template;\n\n return template.replace(INTERPOLATION_PATTERN, (_match, varName: string) => {\n const value = vars != null ? resolvePath(vars, varName) : undefined;\n\n if (value == null) {\n return onMissing({ key, locale, type: 'var', varName });\n }\n\n return String(value);\n });\n}\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 const cfg = (config ?? {}) as I18nOptions<M>;\n let locale = canon(cfg.locale ?? 'en');\n const fallback = Array.isArray(cfg.fallback) ? cfg.fallback.map(canon) : cfg.fallback ? [canon(cfg.fallback)] : [];\n\n const registry = new Map<Locale, LocaleRecord<M>>();\n const loading = new Map<Locale, LoadingRecord<M>>();\n const subscribers = new Set<(snapshot: I18nSnapshot) => void>();\n const pluralCache: PluralCaches = new Map();\n const onMissing =\n cfg.onMissing ??\n ((info: MissingInfo) => {\n if (info.type === 'key') return info.key;\n\n return `{${info.varName}}`;\n });\n const onSubscriberError = cfg.onSubscriberError ?? (() => {});\n\n let version = 0;\n let snapshot: I18nSnapshot = { locale, version };\n let activeChain = buildLocaleChain(locale, fallback);\n let switchId = 0;\n\n const bump = (): void => {\n version++;\n snapshot = { locale, version };\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 const addListener = (callback: (snapshot: I18nSnapshot) => void, immediate = false): Unsubscribe => {\n subscribers.add(callback);\n\n if (immediate) {\n try {\n callback(snapshot);\n } catch (error) {\n onSubscriberError(error);\n }\n }\n\n return () => subscribers.delete(callback);\n };\n\n const findMessage = (key: string): string | undefined => {\n for (const candidate of activeChain) {\n const messages = registry.get(candidate)?.messages;\n\n if (!messages) continue;\n\n const value = resolvePath(messages, key);\n\n if (typeof value === 'string') return value;\n }\n\n return undefined;\n };\n\n const setLocaleSource = (normalized: Locale, source: LocaleSource<M>): void => {\n if (typeof source === 'function') {\n registry.set(normalized, { kind: 'dynamic', loader: source as Loader<M> });\n\n return;\n }\n\n registry.set(normalized, { kind: 'static', messages: source as M });\n };\n\n const register = (loc: Locale, source: LocaleSource<M>): void => {\n const normalized = canon(loc);\n\n setLocaleSource(normalized, source);\n\n if (activeChain.includes(normalized)) bump();\n };\n\n if (cfg.catalogs) {\n for (const [loc, source] of Object.entries(cfg.catalogs)) {\n setLocaleSource(canon(loc), source as LocaleSource<M>);\n }\n }\n\n const preload = async (loc: Locale): Promise<void> => {\n const normalized = canon(loc);\n const entry = registry.get(normalized);\n\n if (!entry) {\n throw new Error(`Missing locale source for \"${normalized}\".`);\n }\n\n if (entry.kind === 'static') return;\n\n if (entry.messages) return;\n\n const active = loading.get(normalized);\n\n if (active?.entry === entry) {\n await active.task;\n\n return;\n }\n\n const task = (async () => {\n const messages = await entry.loader(normalized);\n\n // Only apply if the registry entry is still the exact object we started\n // loading from. Any call to register() replaces the entry with a new\n // object, so a stale loader result from a superseded source is discarded.\n if (registry.get(normalized) !== entry) return;\n\n entry.messages = messages;\n\n if (activeChain.includes(normalized)) bump();\n })();\n\n loading.set(normalized, { entry, task });\n\n try {\n await task;\n } finally {\n if (loading.get(normalized)?.task === task) {\n loading.delete(normalized);\n }\n }\n };\n\n function translate(key: MessageLeafKeys<M> | AnyKey, vars?: TranslateVars): string {\n const base = String(key);\n const message = findMessage(base);\n\n return message === undefined\n ? onMissing({ key: base, locale, type: 'key' })\n : interpolate(message, vars, base, locale, onMissing);\n }\n\n function translatePlural(\n key: MessageBranchKeys<M> | AnyKey,\n count: number,\n options?: PluralTranslateOptions,\n ): string {\n if (!Number.isFinite(count)) {\n throw new TypeError('`count` must be a finite number.');\n }\n\n if (options?.vars && Object.hasOwn(options.vars, 'count')) {\n throw new Error('`tp` does not allow `vars.count`; `count` is injected automatically.');\n }\n\n const base = String(key);\n const ordinal = options?.ordinal === true;\n const form = selectPluralForm(pluralCache, locale, count, ordinal);\n const selectedKey = !ordinal && count === 0 ? `${base}.zero` : `${base}.${form}`;\n const message = findMessage(selectedKey) ?? findMessage(`${base}.other`);\n\n if (message === undefined) {\n return onMissing({ key: base, locale, type: 'key' });\n }\n\n return interpolate(message, { ...(options?.vars ?? {}), count }, base, locale, onMissing);\n }\n\n return {\n getSnapshot() {\n return snapshot;\n },\n\n getSupportedLocales(options): Locale[] {\n const locales = [...registry.keys()];\n\n // Code-point sort: deterministic across all environments and locales.\n return options?.sorted === true ? locales.sort() : locales;\n },\n\n has(key: MessageLeafKeys<M> | AnyKey): boolean {\n return findMessage(String(key)) !== undefined;\n },\n\n get locale(): Locale {\n return locale;\n },\n\n preload,\n\n register,\n\n async setLocale(next: Locale): Promise<void> {\n const normalized = canon(next);\n\n if (locale === normalized) return;\n\n const id = ++switchId;\n\n await preload(normalized);\n\n if (id !== switchId) return;\n\n locale = normalized;\n activeChain = buildLocaleChain(locale, fallback);\n bump();\n },\n\n subscribe(callback: (snapshot: I18nSnapshot) => void, options?: SubscribeOptions): Unsubscribe {\n return addListener(callback, options?.immediate === true);\n },\n\n t: translate,\n tp: translatePlural,\n };\n}\n"],"mappings":";AA4BA,IAAM,IAAwB;AAE9B,SAAS,EAAM,GAAwB;CACrC,IAAI;EACF,OAAO,KAAK,oBAAoB,CAAM,EAAE,MAAM;CAChD,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,EAAY,GAA8B,GAAuB;CACxE,IAAI,IAAiB;CAErB,KAAK,IAAM,KAAQ,EAAK,MAAM,GAAG,GAAG;EAGlC,IAFqB,OAAO,KAAU,aAAlC,KAEA,CAAC,OAAO,OAAO,GAAiB,CAAI,GAAG;EAE3C,IAAS,EAAkC;CAC7C;CAEA,OAAO;AACT;AAEA,SAAS,EAAiB,GAAgB,GAA8B;CACtE,IAAM,oBAAO,IAAI,IAAY;CAE7B,KAAK,IAAM,KAAS,CAAC,GAAQ,GAAG,CAAQ,GAAG;EACzC,EAAK,IAAI,CAAK;EAEd,IAAM,IAAQ,EAAM,MAAM,GAAG;EAE7B,KAAK,IAAI,IAAI,EAAM,SAAS,GAAG,IAAI,GAAG,KACpC,EAAK,IAAI,EAAM,MAAM,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC;CAExC;CAEA,OAAO,CAAC,GAAG,CAAI;AACjB;AAEA,SAAS,EAAiB,GAAqB,GAAgB,GAAe,GAA0B;CACtG,IAAM,IAAM,GAAG,EAAO,GAAG,IAAU,YAAY,cAC3C,IAAQ,EAAM,IAAI,CAAG;CAEzB,IAAI,CAAC,GAAO;EACV,IAAI;GACF,IAAQ,IAAI,KAAK,YAAY,GAAQ,EAAE,MAAM,IAAU,YAAY,WAAW,CAAC;EACjF,QAAQ;GACN,IAAQ,EAAE,SAAS,MAAmB,MAAU,IAAI,QAAQ,QAAS;EACvE;EAEA,EAAM,IAAI,GAAK,CAAK;CACtB;CAEA,OAAO,EAAM,OAAO,CAAK;AAC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,EAAQ,CAAU,GAEpB,MAAO,MAEX,IAAS,GACT,IAAc,EAAiB,GAAQ,CAAQ,GAC/C,EAAK;EACP;EAEA,UAAU,GAA4C,GAAyC;GAC7F,OAAO,EAAY,GAAU,GAAS,cAAc,EAAI;EAC1D;EAEA,GAAG;EACH,IAAI;CACN;AACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./i18n.cjs`);exports.
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./i18n.cjs`);exports.createI18n=e.createI18n;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** @vielzeug/i18nit — Lightweight, type-safe i18n
|
|
2
|
-
export type {
|
|
3
|
-
export { createI18n
|
|
1
|
+
/** @vielzeug/i18nit — Lightweight, type-safe i18n runtime. */
|
|
2
|
+
export type { AnyKey, I18n, I18nOptions, I18nSnapshot, Loader, Locale, LocaleSource, MessageBranchKeys, MessageLeafKeys, Messages, MissingInfo, PluralTranslateOptions, SupportedLocalesOptions, SubscribeOptions, TranslateVars, Unsubscribe, } from './types';
|
|
3
|
+
export { createI18n } from './i18n';
|
|
4
4
|
//# 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,8DAA8D;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAE9D,YAAY,EACV,MAAM,EACN,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,MAAM,EACN,MAAM,EACN,YAAY,EACZ,iBAAiB,EACjB,eAAe,EACf,QAAQ,EACR,WAAW,EACX,sBAAsB,EACtB,uBAAuB,EACvB,gBAAgB,EAChB,aAAa,EACb,WAAW,GACZ,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { e as
|
|
1
|
+
import { createI18n as e } from "./i18n.js";
|
|
2
|
+
export { e as createI18n };
|
package/dist/types.d.ts
CHANGED
|
@@ -1,97 +1,76 @@
|
|
|
1
1
|
export type Locale = string;
|
|
2
2
|
export type Unsubscribe = () => void;
|
|
3
|
-
export
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
export interface Messages {
|
|
4
|
+
[key: string]: string | Messages;
|
|
5
|
+
}
|
|
6
|
+
export type TranslateVars = Record<string, unknown>;
|
|
7
|
+
export type Loader<M extends Messages = Messages> = (locale: Locale) => Promise<M>;
|
|
8
|
+
export type LocaleSource<M extends Messages = Messages> = M | Loader<M>;
|
|
9
|
+
export type PluralTranslateOptions = {
|
|
10
|
+
ordinal?: boolean;
|
|
11
|
+
vars?: TranslateVars;
|
|
6
12
|
};
|
|
7
|
-
export type
|
|
8
|
-
|
|
9
|
-
[key: string]: MessageValue | Messages;
|
|
13
|
+
export type SupportedLocalesOptions = {
|
|
14
|
+
sorted?: boolean;
|
|
10
15
|
};
|
|
11
|
-
export type
|
|
12
|
-
|
|
13
|
-
* Recursively makes all message keys optional, allowing partial locale catalogs.
|
|
14
|
-
* Use when a secondary locale only translates a subset of the primary locale's messages.
|
|
15
|
-
*/
|
|
16
|
-
export type DeepPartialMessages<T extends Messages> = {
|
|
17
|
-
[K in keyof T]?: T[K] extends MessageValue ? MessageValue : T[K] extends Messages ? DeepPartialMessages<T[K]> : MessageValue;
|
|
18
|
-
};
|
|
19
|
-
/**
|
|
20
|
-
* Recursive type that extracts all dot-notation keys from a Messages shape for type-safe translation.
|
|
21
|
-
* Type-safe resolution is provided up to 8 levels of nesting; deeper paths resolve to `string`.
|
|
22
|
-
*/
|
|
23
|
-
export type TranslationKey<T extends Messages, P extends string = '', D extends readonly 0[] = []> = D['length'] extends 8 ? string : {
|
|
24
|
-
[K in keyof T & string]: T[K] extends MessageValue ? P extends '' ? K : `${P}.${K}` : T[K] extends Messages ? TranslationKey<T[K], P extends '' ? K : `${P}.${K}`, [...D, 0]> : never;
|
|
25
|
-
}[keyof T & string];
|
|
26
|
-
/** The `key` parameter type for `t()` — enforces known dot-notation paths when `T` is concrete, allows any string otherwise. */
|
|
27
|
-
export type TranslationKeyParam<T extends Messages> = [TranslationKey<T>] extends [never] ? string : TranslationKey<T> | (string & {});
|
|
28
|
-
/** Extracts dot-notation keys from `T` whose final value is `PluralMessages`, for compile-time `count` enforcement. */
|
|
29
|
-
export type PluralKeys<T extends Messages, P extends string = '', D extends readonly 0[] = []> = D['length'] extends 8 ? never : {
|
|
30
|
-
[K in keyof T & string]: T[K] extends PluralMessages ? P extends '' ? K : `${P}.${K}` : T[K] extends Messages ? PluralKeys<T[K], P extends '' ? K : `${P}.${K}`, [...D, 0]> : never;
|
|
31
|
-
}[keyof T & string];
|
|
32
|
-
export type Loader = (locale: Locale) => Promise<Messages>;
|
|
33
|
-
/** The reason a `subscribe()` listener was notified. */
|
|
34
|
-
export type LocaleChangeReason = 'locale-change' | 'catalog-update';
|
|
35
|
-
/** Payload passed to every `subscribe()` listener. */
|
|
36
|
-
export type LocaleChangeEvent = {
|
|
16
|
+
export type MissingInfo = {
|
|
17
|
+
key: string;
|
|
37
18
|
locale: Locale;
|
|
38
|
-
|
|
39
|
-
};
|
|
40
|
-
/** Type alias for a `subscribe()` listener function. */
|
|
41
|
-
export type LocaleChangeListener = (event: LocaleChangeEvent) => void;
|
|
42
|
-
/**
|
|
43
|
-
* Diagnostic event passed to `onDiagnostic`. Each `kind` carries relevant context:
|
|
44
|
-
* - `'subscriber-error'` — a subscriber callback threw; treat as a programming error.
|
|
45
|
-
* - `'loader-error'` — a locale loader rejected; treat as a recoverable I/O failure.
|
|
46
|
-
*/
|
|
47
|
-
export type DiagnosticEvent = {
|
|
48
|
-
error: unknown;
|
|
49
|
-
kind: 'subscriber-error';
|
|
19
|
+
type: 'key';
|
|
50
20
|
} | {
|
|
51
|
-
|
|
52
|
-
kind: 'loader-error';
|
|
21
|
+
key: string;
|
|
53
22
|
locale: Locale;
|
|
23
|
+
type: 'var';
|
|
24
|
+
varName: string;
|
|
25
|
+
};
|
|
26
|
+
export type I18nSnapshot = {
|
|
27
|
+
readonly locale: Locale;
|
|
28
|
+
readonly version: number;
|
|
54
29
|
};
|
|
55
|
-
|
|
56
|
-
export type
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
-
|
|
30
|
+
export type AnyKey = string & {};
|
|
31
|
+
export type SubscribeOptions = {
|
|
32
|
+
immediate?: boolean;
|
|
33
|
+
};
|
|
34
|
+
type Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8];
|
|
35
|
+
export type MessageLeafKeys<T, P extends string = '', D extends number = 7> = [D] extends [0] ? never : T extends string ? P : T extends Record<string, unknown> ? {
|
|
36
|
+
[K in string & keyof T]: MessageLeafKeys<T[K], P extends '' ? K : `${P}.${K}`, Depth[D]>;
|
|
37
|
+
}[string & keyof T] : never;
|
|
38
|
+
export type MessageBranchKeys<T, P extends string = '', D extends number = 7> = [D] extends [0] ? never : T extends Record<string, unknown> ? {
|
|
39
|
+
[K in string & keyof T]: T[K] extends string ? never : (P extends '' ? K : `${P}.${K}`) | MessageBranchKeys<T[K], P extends '' ? K : `${P}.${K}`, Depth[D]>;
|
|
40
|
+
}[string & keyof T] : never;
|
|
41
|
+
/**
|
|
42
|
+
* Configuration for i18n instances.
|
|
43
|
+
* When `M` is not explicitly provided, it defaults to the broad `Messages` type,
|
|
44
|
+
* allowing heterogeneous catalogs. When `M` is explicit, strict type checking applies.
|
|
45
|
+
*/
|
|
46
|
+
export type I18nOptions<M extends Messages = Messages> = {
|
|
47
|
+
/** Locale registry. Values can be static messages or async loaders. */
|
|
48
|
+
catalogs?: Record<Locale, LocaleSource<M>>;
|
|
60
49
|
fallback?: Locale | Locale[];
|
|
61
|
-
loaders?: Record<Locale, Loader>;
|
|
62
50
|
locale?: Locale;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
* For a partial secondary locale, annotate it with `DeepPartialMessages<M>` to get compile-time
|
|
66
|
-
* checks that the subset matches the primary locale's shape.
|
|
67
|
-
*/
|
|
68
|
-
messages?: Record<string, T | DeepPartialMessages<T>>;
|
|
69
|
-
/**
|
|
70
|
-
* Receives diagnostic events for both subscriber errors and loader failures.
|
|
71
|
-
* `'subscriber-error'` events indicate a programming error in a listener.
|
|
72
|
-
* `'loader-error'` events are recoverable I/O failures and include the failing `locale`.
|
|
73
|
-
* Defaults to `console.error` for subscriber errors and `console.warn` for loader errors.
|
|
74
|
-
*/
|
|
75
|
-
onDiagnostic?: (event: DiagnosticEvent) => void;
|
|
76
|
-
onMissing?: (key: string, locale: Locale) => string | undefined;
|
|
51
|
+
onMissing?: (info: MissingInfo) => string;
|
|
52
|
+
onSubscriberError?: (error: unknown) => void;
|
|
77
53
|
};
|
|
78
|
-
export type
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
|
|
84
|
-
list(items: unknown[], type?: 'and' | 'or'): string;
|
|
54
|
+
export type I18n<M extends Messages = Messages> = {
|
|
55
|
+
/** Snapshot version starts at 0 and increments by 1 per observable change. */
|
|
56
|
+
getSnapshot(): I18nSnapshot;
|
|
57
|
+
getSupportedLocales(options?: SupportedLocalesOptions): Locale[];
|
|
58
|
+
/** Check if a key exists. Accepts literal keys from M, or any dynamic string. */
|
|
59
|
+
has(key: MessageLeafKeys<M> | AnyKey): boolean;
|
|
85
60
|
readonly locale: Locale;
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
61
|
+
preload(locale: Locale): Promise<void>;
|
|
62
|
+
register(locale: Locale, source: LocaleSource<M>): void;
|
|
63
|
+
setLocale(locale: Locale): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Subscribes to locale/catalog changes.
|
|
66
|
+
* - Default: callback runs only on changes.
|
|
67
|
+
* - `{ immediate: true }`: callback runs immediately with current snapshot and on every change.
|
|
68
|
+
*/
|
|
69
|
+
subscribe(callback: (snapshot: I18nSnapshot) => void, options?: SubscribeOptions): Unsubscribe;
|
|
70
|
+
/** Get a translation. Accepts literal keys from M, or any dynamic string. */
|
|
71
|
+
t(key: MessageLeafKeys<M> | AnyKey, vars?: TranslateVars): string;
|
|
72
|
+
/** Get a pluralized translation from branch keys. */
|
|
73
|
+
tp(key: MessageBranchKeys<M> | AnyKey, count: number, options?: PluralTranslateOptions): string;
|
|
96
74
|
};
|
|
75
|
+
export {};
|
|
97
76
|
//# sourceMappingURL=types.d.ts.map
|