@vielzeug/lingua 26.11.12 → 26.11.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/_resources.cjs +1 -1
  2. package/dist/_resources.cjs.map +1 -1
  3. package/dist/_resources.d.ts +2 -3
  4. package/dist/_resources.d.ts.map +1 -1
  5. package/dist/_resources.js +2 -4
  6. package/dist/_resources.js.map +1 -1
  7. package/dist/_template.cjs +1 -1
  8. package/dist/_template.cjs.map +1 -1
  9. package/dist/_template.d.ts +0 -2
  10. package/dist/_template.d.ts.map +1 -1
  11. package/dist/_template.js +1 -15
  12. package/dist/_template.js.map +1 -1
  13. package/dist/errors.cjs +1 -1
  14. package/dist/errors.cjs.map +1 -1
  15. package/dist/errors.d.ts +0 -2
  16. package/dist/errors.d.ts.map +1 -1
  17. package/dist/errors.js +2 -2
  18. package/dist/errors.js.map +1 -1
  19. package/dist/i18n.cjs +1 -1
  20. package/dist/i18n.cjs.map +1 -1
  21. package/dist/i18n.d.ts +5 -14
  22. package/dist/i18n.d.ts.map +1 -1
  23. package/dist/i18n.js +38 -55
  24. package/dist/i18n.js.map +1 -1
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.d.ts +3 -3
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +4 -4
  29. package/dist/lingua.cjs +1 -1
  30. package/dist/lingua.cjs.map +1 -1
  31. package/dist/lingua.iife.js +1 -1
  32. package/dist/lingua.iife.js.map +1 -1
  33. package/dist/lingua.js +55 -107
  34. package/dist/lingua.js.map +1 -1
  35. package/dist/ripple.cjs +1 -1
  36. package/dist/ripple.cjs.map +1 -1
  37. package/dist/ripple.d.ts +6 -7
  38. package/dist/ripple.d.ts.map +1 -1
  39. package/dist/ripple.js +3 -4
  40. package/dist/ripple.js.map +1 -1
  41. package/dist/translator.cjs +1 -1
  42. package/dist/translator.cjs.map +1 -1
  43. package/dist/translator.d.ts +8 -12
  44. package/dist/translator.d.ts.map +1 -1
  45. package/dist/translator.js +28 -45
  46. package/dist/translator.js.map +1 -1
  47. package/dist/types.d.ts +7 -23
  48. package/dist/types.d.ts.map +1 -1
  49. package/package.json +3 -3
package/dist/lingua.js CHANGED
@@ -15,20 +15,6 @@ function renderText(e, t, n) {
15
15
  return r == null ? n(e.value) : String(r);
16
16
  }).join("");
17
17
  }
18
- function renderParts(e, t, n) {
19
- let r = [];
20
- for (let i of e) typeof i == "string" ? i !== "" && r.push({
21
- type: "text",
22
- value: i
23
- }) : Object.hasOwn(t, i.value) ? r.push({
24
- type: "value",
25
- value: t[i.value]
26
- }) : r.push({
27
- type: "text",
28
- value: n(i.value)
29
- });
30
- return r;
31
- }
32
18
  // src/errors.ts
33
19
  var LinguaError = class extends Error {
34
20
  constructor(e, t) {
@@ -38,7 +24,7 @@ var LinguaError = class extends Error {
38
24
  constructor() {
39
25
  super("Operation called on a disposed i18n instance.");
40
26
  }
41
- }, LinguaInvalidCatalogError = class extends LinguaError {}, LinguaInvalidLocaleError = class extends LinguaError {}, LinguaInvalidPluralCountError = class extends LinguaError {}, LinguaInvalidStateError = class extends LinguaError {}, LinguaMissingCatalogError = class extends LinguaError {}, LinguaMissingKeyError = class extends LinguaError {}, LinguaMissingValueError = class extends LinguaError {}, t = /* @__PURE__ */ new Set([
27
+ }, LinguaInvalidCatalogError = class extends LinguaError {}, LinguaInvalidLocaleError = class extends LinguaError {}, LinguaInvalidPluralCountError = class extends LinguaError {}, LinguaMissingCatalogError = class extends LinguaError {}, LinguaMissingKeyError = class extends LinguaError {}, LinguaMissingValueError = class extends LinguaError {}, t = /* @__PURE__ */ new Set([
42
28
  "__proto__",
43
29
  "constructor",
44
30
  "prototype"
@@ -129,18 +115,16 @@ function createCatalogStore(e) {
129
115
  catalogMap() {
130
116
  return new Map([...t].map(([e, { compiled: t }]) => [e, t]));
131
117
  },
132
- hydrate,
133
118
  isLoaded(e) {
134
119
  return t.has(canonicalLocale(e));
135
120
  },
136
121
  load,
137
- state(e) {
122
+ serialized(e) {
138
123
  let n = {};
139
124
  for (let [e, { catalog: r }] of t) n[e] = r;
140
125
  return {
141
126
  catalogs: n,
142
- locale: e,
143
- version: 1
127
+ locale: e
144
128
  };
145
129
  }
146
130
  };
@@ -150,7 +134,7 @@ function resolveMissing(e, t) {
150
134
  if (e === "throw") throw t.name ? new LinguaMissingValueError(`Missing interpolation value "${t.name}" for key "${t.key}" in locale "${t.locale}".`) : new LinguaMissingKeyError(`Missing translation key "${t.key}" in locale "${t.locale}".`);
151
135
  return typeof e == "function" ? e(t) : t.name ? `{${t.name}}` : t.key;
152
136
  }
153
- function createTranslatorFromCompiled(e, t = {}) {
137
+ function createTranslateEngine(e, t = {}) {
154
138
  let n = canonicalLocale(t.locale ?? "en"), r = localeChain(n, (Array.isArray(t.fallback) ? t.fallback : t.fallback ? [t.fallback] : []).map(canonicalLocale)), i = t.missing, missingKey = (e) => resolveMissing(i, {
155
139
  key: e,
156
140
  locale: n
@@ -169,140 +153,104 @@ function createTranslatorFromCompiled(e, t = {}) {
169
153
  }, templateFor = (e, t) => {
170
154
  let n = resolve(e);
171
155
  if (!n) return;
172
- if (n.message.kind === "text") return "count" in t ? void 0 : {
173
- key: e,
174
- template: n.message.template
175
- };
156
+ if (n.message.kind === "text") return "count" in t ? void 0 : n.message.template;
176
157
  if (!("count" in t) || !Number.isFinite(t.count)) {
177
158
  if ("count" in t) throw new LinguaInvalidPluralCountError("`count` must be a finite number.");
178
159
  return;
179
160
  }
180
- let r = t.count === 0 && !t.ordinal ? "zero" : pluralCategory(n.locale, t.count, t.ordinal ?? !1), i = n.message.forms.get(r) ?? n.message.forms.get("other");
181
- return i ? {
182
- key: e,
183
- template: i
184
- } : void 0;
185
- }, valuesFor = (e) => "count" in e ? {
186
- count: e.count,
187
- ...e.values
188
- } : e.values ?? {}, partsDynamic = (e, t) => {
189
- let n = templateFor(e, t);
190
- return n ? renderParts(n.template, valuesFor(t), (e) => missingValue(e, n.key)) : [{
191
- type: "text",
192
- value: missingKey(e)
193
- }];
194
- }, translateDynamic = (e, t = {}) => {
161
+ let r = pluralCategory(n.locale, t.count, t.ordinal ?? !1);
162
+ return n.message.forms.get(r) ?? n.message.forms.get("other");
163
+ }, translate = (e, t = {}) => {
195
164
  let n = templateFor(e, t);
196
- return n ? renderText(n.template, valuesFor(t), (e) => missingValue(e, n.key)) : missingKey(e);
165
+ return n ? renderText(n, "count" in t ? {
166
+ count: t.count,
167
+ ...t.values
168
+ } : t.values ?? {}, (t) => missingValue(t, e)) : missingKey(e);
197
169
  };
198
170
  return {
199
171
  locale: n,
200
- parts(e, t) {
201
- return partsDynamic(e, t);
202
- },
203
- partsDynamic,
204
- translate(e, t = {}) {
205
- return translateDynamic(e, t);
206
- },
207
- translateDynamic
172
+ translate
208
173
  };
209
174
  }
210
175
  function createTranslator(e, t) {
211
- let n = canonicalLocale(t?.locale ?? "en");
212
- return createTranslatorFromCompiled(/* @__PURE__ */ new Map([[n, compileCatalog(e)]]), {
213
- ...t,
214
- locale: n
215
- });
176
+ let n = createTranslateEngine(/* @__PURE__ */ new Map([[canonicalLocale(t?.locale ?? "en"), compileCatalog(e)]]), t);
177
+ return {
178
+ locale: n.locale,
179
+ translate: n.translate
180
+ };
216
181
  }
217
182
  // src/i18n.ts
218
183
  function createI18n(e) {
219
- if (e.state && e.state.version !== 1) throw new LinguaInvalidStateError(`Unsupported lingua state version: ${String(e.state.version)}.`);
220
- let t = e.fallback, n = (Array.isArray(t) ? t : t ? [t] : []).map(canonicalLocale), r = new AbortController(), i = /* @__PURE__ */ new Set(), a = !1, o = canonicalLocale(e.locale ?? e.state?.locale ?? "en"), s = 0, c = 0, l = createCatalogStore({
184
+ let t = (Array.isArray(e.fallback) ? e.fallback : e.fallback ? [e.fallback] : []).map(canonicalLocale), n = new AbortController(), r = /* @__PURE__ */ new Set(), i = !1, a = canonicalLocale(e.locale ?? "en"), o = 0, s = createCatalogStore({
221
185
  catalogs: e.catalogs,
222
186
  loadCatalog: e.loadCatalog
223
- });
224
- if (e.state) for (let [t, n] of Object.entries(e.state.catalogs)) l.hydrate(t, n);
225
- let loadTargets = async (e) => {
226
- let t = [];
227
- for (let r of /* @__PURE__ */ new Set([e, ...n])) await l.load(r) && t.push(r);
228
- return t;
229
- }, buildTranslator = () => {
230
- let r = localeChain(o, n).some(l.isLoaded) ? e.missing : () => {
231
- throw new LinguaMissingCatalogError(`No catalog loaded for locale "${o}". Call load() before translating.`);
187
+ }), loadTargets = async (e) => {
188
+ let n = [];
189
+ for (let r of /* @__PURE__ */ new Set([e, ...t])) await s.load(r) && n.push(r);
190
+ return n;
191
+ }, buildEngine = () => {
192
+ let n = localeChain(a, t).some(s.isLoaded) ? e.missing : () => {
193
+ throw new LinguaMissingCatalogError(`No catalog loaded for locale "${a}". Call load() before translating.`);
232
194
  };
233
- return createTranslatorFromCompiled(l.catalogMap(), {
234
- fallback: t,
235
- locale: o,
236
- missing: r
195
+ return createTranslateEngine(s.catalogMap(), {
196
+ ...e,
197
+ locale: a,
198
+ missing: n
237
199
  });
238
- }, buildSnapshot = () => ({
239
- locale: o,
240
- revision: s,
241
- translator: buildTranslator()
242
- }), u = buildSnapshot(), assertLive = () => {
243
- if (a) throw new LinguaDisposedError();
200
+ }, assertLive = () => {
201
+ if (i) throw new LinguaDisposedError();
244
202
  }, dispose = () => {
245
- a || (a = !0, i.clear(), r.abort());
246
- }, dispatch = (e) => {
247
- try {
248
- e(u);
249
- } catch {}
203
+ i || (i = !0, r.clear(), n.abort());
250
204
  }, notify = () => {
251
- s++, u = buildSnapshot();
252
- for (let e of [...i]) dispatch(e);
253
- }, relevant = (e) => localeChain(o, n).includes(e);
205
+ c = buildEngine();
206
+ for (let e of [...r]) try {
207
+ e(a);
208
+ } catch {}
209
+ }, relevant = (e) => localeChain(a, t).includes(e), c = buildEngine();
254
210
  return {
255
211
  get disposalSignal() {
256
- return r.signal;
212
+ return n.signal;
257
213
  },
258
214
  dispose,
259
215
  get disposed() {
260
- return a;
216
+ return i;
261
217
  },
262
218
  getSnapshot() {
263
- return u;
219
+ return a;
264
220
  },
265
221
  isLoaded(e) {
266
- return !a && l.isLoaded(e?.locale ?? o);
222
+ return !i && s.isLoaded(e?.locale ?? a);
267
223
  },
268
224
  async load(e) {
269
225
  assertLive();
270
- let t = canonicalLocale(e?.locale ?? o), n = await loadTargets(t);
226
+ let t = canonicalLocale(e?.locale ?? a), n = await loadTargets(t);
271
227
  assertLive(), n.some(relevant) && notify();
272
228
  },
273
229
  get locale() {
274
- return o;
275
- },
276
- parts(e, t) {
277
- return u.translator.partsDynamic(e, t);
278
- },
279
- partsDynamic(e, t) {
280
- return u.translator.partsDynamic(e, t);
230
+ return a;
281
231
  },
282
232
  serialize() {
283
- return assertLive(), l.state(o);
233
+ return assertLive(), s.serialized(a);
284
234
  },
285
235
  async setLocale(e) {
286
236
  assertLive();
287
- let t = canonicalLocale(e), n = ++c, r = await loadTargets(t);
288
- assertLive(), n === c && (t === o ? r.some(relevant) && notify() : (o = t, notify()));
237
+ let t = canonicalLocale(e), n = ++o, r = await loadTargets(t);
238
+ assertLive(), n === o && (t === a ? r.some(relevant) && notify() : (a = t, notify()));
289
239
  },
290
240
  subscribe(e, t) {
291
241
  if (assertLive(), t?.signal?.aborted) return () => {};
292
242
  let unsubscribe = () => {
293
- i.delete(e), t?.signal?.removeEventListener("abort", unsubscribe);
243
+ r.delete(e), t?.signal?.removeEventListener("abort", unsubscribe);
294
244
  };
295
- return t?.signal?.addEventListener("abort", unsubscribe, { once: !0 }), i.add(e), t?.immediate && dispatch(e), unsubscribe;
245
+ if (t?.signal?.addEventListener("abort", unsubscribe, { once: !0 }), r.add(e), t?.immediate) try {
246
+ e(a);
247
+ } catch {}
248
+ return unsubscribe;
296
249
  },
297
- [Symbol.dispose]: dispose,
298
- translate(e, t = {}) {
299
- return u.translator.translateDynamic(e, t);
300
- },
301
- translateDynamic(e, t) {
302
- return u.translator.translateDynamic(e, t);
303
- }
250
+ translate: (e, t) => c.translate(e, t),
251
+ [Symbol.dispose]: dispose
304
252
  };
305
253
  }
306
- export { LinguaDisposedError, LinguaError, LinguaInvalidCatalogError, LinguaInvalidLocaleError, LinguaInvalidPluralCountError, LinguaInvalidStateError, LinguaMissingCatalogError, LinguaMissingKeyError, LinguaMissingValueError, catalogKeys, createI18n, createTranslator };
254
+ export { LinguaDisposedError, LinguaError, LinguaInvalidCatalogError, LinguaInvalidLocaleError, LinguaInvalidPluralCountError, LinguaMissingCatalogError, LinguaMissingKeyError, LinguaMissingValueError, catalogKeys, createI18n, createTranslator };
307
255
 
308
256
  //# sourceMappingURL=lingua.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"lingua.js","names":["error","interpolation","parts","offset","match","value","index","part","values","missing","result","message","opts","unsafeKeys","node","messages","prefix","key","forms","form","template","catalog","pluralRules","canonical","locale","chain","candidate","fallback","length","ordinal","rules","count","loaded","tasks","options","requestedLocale","existing","task","error","compiled","catalogs","loadedLocale","strategy","info","found","category","name","fallbackLocales","controller","subscribers","disposed","revision","transition","stateLocale","changed","target","snapshot","listener","loadOptions","targetLocale","translateOptions","next","nextLocale","request","subscribeOptions"],"sources":["../src/_template.ts","../src/errors.ts","../src/_catalog.ts","../src/catalog.ts","../src/_dev.ts","../src/_locale.ts","../src/_resources.ts","../src/translator.ts","../src/i18n.ts"],"sourcesContent":["import type { Part } from './types';\n\nexport type TemplatePart = string | { readonly value: string };\nexport type Template = readonly TemplatePart[];\n\nconst interpolation = /\\{([\\p{ID_Continue}-]+)\\}/gu;\n\nexport function compileTemplate(value: string): Template {\n const parts: TemplatePart[] = [];\n let offset = 0;\n\n for (const match of value.matchAll(interpolation)) {\n const index = match.index ?? 0;\n\n if (index > offset) parts.push(value.slice(offset, index));\n\n parts.push({ value: match[1] });\n offset = index + match[0].length;\n }\n\n if (offset < value.length) parts.push(value.slice(offset));\n\n return parts;\n}\n\nexport function renderText(\n parts: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n): string {\n return parts\n .map((part) => {\n if (typeof part === 'string') return part;\n\n const value = Object.hasOwn(values, part.value) ? values[part.value] : undefined;\n\n return value == null ? missing(part.value) : String(value);\n })\n .join('');\n}\n\nexport function renderParts<V>(\n parts: Template,\n values: Record<string, V | number>,\n missing: (name: string) => string,\n): Array<Part<V | number>> {\n const result: Array<Part<V | number>> = [];\n\n for (const part of parts) {\n if (typeof part === 'string') {\n if (part !== '') result.push({ type: 'text', value: part });\n\n continue;\n }\n\n if (Object.hasOwn(values, part.value)) {\n result.push({ type: 'value', value: values[part.value]! as V | number });\n } else {\n result.push({ type: 'text', value: missing(part.value) });\n }\n }\n\n return result;\n}\n","export class LinguaError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed i18n instance.');\n }\n}\n\nexport class LinguaInvalidCatalogError extends LinguaError {}\nexport class LinguaInvalidLocaleError extends LinguaError {}\nexport class LinguaInvalidPluralCountError extends LinguaError {}\nexport class LinguaInvalidStateError extends LinguaError {}\nexport class LinguaMissingCatalogError extends LinguaError {}\nexport class LinguaMissingKeyError extends LinguaError {}\nexport class LinguaMissingValueError extends LinguaError {}\n","import { compileTemplate, type Template } from './_template';\nimport { LinguaInvalidCatalogError } from './errors';\nimport type { Catalog, CatalogNode, PluralMessage } from './types';\n\nconst unsafeKeys = new Set(['__proto__', 'constructor', 'prototype']);\n\nexport type CompiledText = { readonly kind: 'text'; readonly template: Template };\nexport type CompiledPlural = { readonly forms: ReadonlyMap<string, Template>; readonly kind: 'plural' };\nexport type CompiledMessage = CompiledPlural | CompiledText;\nexport type CompiledCatalog = ReadonlyMap<string, CompiledMessage>;\n\nexport function isPluralMessage(node: CatalogNode): node is PluralMessage {\n return typeof node === 'object' && node !== null && Object.hasOwn(node, 'plural');\n}\n\n/** Compile explicit catalog nodes once. Nested objects only group keys; plural intent is never inferred. */\nexport function compileCatalog(catalog: Catalog): CompiledCatalog {\n const messages = new Map<string, CompiledMessage>();\n\n const visit = (node: CatalogNode, prefix: string): void => {\n if (typeof node === 'string') {\n messages.set(prefix, { kind: 'text', template: compileTemplate(node) });\n\n return;\n }\n\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n throw new LinguaInvalidCatalogError(`Catalog node \"${prefix}\" must be a string, plural message, or object.`);\n }\n\n if (isPluralMessage(node)) {\n if (Reflect.ownKeys(node).some((key) => key !== 'plural')) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must contain only a \"plural\" property.`);\n }\n\n if (typeof node.plural !== 'object' || node.plural === null || Array.isArray(node.plural)) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must provide an object of string forms.`);\n }\n\n const forms = new Map<string, Template>();\n\n for (const [form, template] of Object.entries(node.plural)) {\n if (typeof template !== 'string') {\n throw new LinguaInvalidCatalogError(`Plural form \"${prefix}.${form}\" must be a string.`);\n }\n\n forms.set(form, compileTemplate(template));\n }\n\n messages.set(prefix, { forms, kind: 'plural' });\n\n return;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (unsafeKeys.has(key)) {\n throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n }\n\n visit(value, prefix ? `${prefix}.${key}` : key);\n }\n };\n\n for (const [key, value] of Object.entries(catalog)) {\n if (unsafeKeys.has(key)) throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n\n visit(value, key);\n }\n\n return messages;\n}\n","import { compileCatalog } from './_catalog';\nimport type { Catalog, MessageKey } from './types';\n\n/** Enumerate every message key in a catalog as a dotted path.\n *\n * Traverses nested grouping objects and explicit `{ plural: ... }` messages,\n * producing the same dotted paths that `MessageKey<C>` represents at the type\n * level. Use this to derive key arrays from the catalog itself instead of\n * maintaining a parallel list that can go stale.\n *\n * Pass any catalog subtree to enumerate group-scoped keys. For an `I18n`\n * instance, pass its current locale catalog explicitly.\n *\n * @example\n * ```ts\n * const messages = {\n * nav: { home: '...', settings: '...' },\n * };\n * const keys = catalogKeys(messages); // ['nav.home', 'nav.settings']\n * const navKeys = catalogKeys(messages.nav); // ['home', 'settings']\n *\n * // From an i18n instance: read the current locale's catalog first\n * const i18n = createI18n({ catalogs: { en: messages }, locale: 'en' });\n * const state = i18n.serialize();\n * const allKeys = catalogKeys(state.catalogs[state.locale]);\n * ```\n */\nexport function catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>> {\n return [...compileCatalog(catalog).keys()] as unknown as ReadonlyArray<MessageKey<C>>;\n}\n","export const isDev = !(globalThis as { __LINGUA_PROD__?: boolean }).__LINGUA_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/lingua] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/lingua] ${msg}`, ...args);\n}\n","import { LinguaInvalidLocaleError } from './errors';\nimport type { Locale } from './types';\n\nconst pluralRules = new Map<string, Intl.PluralRules>();\n\nexport function canonicalLocale(locale: string): Locale {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n\n if (canonical) return canonical;\n } catch {\n // Error below names the failed public input.\n }\n\n throw new LinguaInvalidLocaleError(`Invalid BCP 47 locale tag: \"${locale}\".`);\n}\n\nexport function localeChain(locale: Locale, fallback: readonly Locale[]): readonly Locale[] {\n const chain = new Set<Locale>();\n\n for (const candidate of [locale, ...fallback]) {\n const parts = candidate.split('-');\n\n for (let length = parts.length; length > 0; length--) {\n chain.add(parts.slice(0, length).join('-'));\n }\n }\n\n return [...chain];\n}\n\nexport function pluralCategory(locale: Locale, count: number, ordinal: boolean): Intl.LDMLPluralRule {\n const key = `${locale}:${ordinal ? 'ordinal' : 'cardinal'}`;\n let rules = pluralRules.get(key);\n\n if (!rules) {\n rules = new Intl.PluralRules(locale, { type: ordinal ? 'ordinal' : 'cardinal' });\n pluralRules.set(key, rules);\n }\n\n return rules.select(count);\n}\n","import { type CompiledCatalog, compileCatalog } from './_catalog';\nimport { canonicalLocale } from './_locale';\nimport { LinguaMissingCatalogError } from './errors';\nimport type { Catalog, Catalogs, Locale, TranslationState } from './types';\n\ntype CatalogStoreOptions<C extends Catalog> = {\n readonly catalogs?: Catalogs<C>;\n readonly loadCatalog?: (locale: Locale) => Promise<C> | C;\n};\n\n/** One catalog state machine owns loaded catalogs and in-flight loading work. */\nexport function createCatalogStore<C extends Catalog>(options: CatalogStoreOptions<C>) {\n const loaded = new Map<Locale, { readonly catalog: C; readonly compiled: CompiledCatalog }>();\n const tasks = new Map<Locale, Promise<void>>();\n\n const hydrate = (locale: Locale, catalog: C): void => {\n loaded.set(canonicalLocale(locale), { catalog, compiled: compileCatalog(catalog) });\n };\n\n for (const [locale, catalog] of Object.entries(options.catalogs ?? {})) hydrate(locale, catalog);\n\n const load = async (requestedLocale: Locale): Promise<boolean> => {\n const locale = canonicalLocale(requestedLocale);\n\n if (loaded.has(locale)) return false;\n\n const existing = tasks.get(locale);\n\n if (existing) {\n await existing;\n\n return false;\n }\n\n if (!options.loadCatalog) {\n throw new LinguaMissingCatalogError(`No catalog source provided for locale \"${locale}\".`);\n }\n\n const task = Promise.resolve(options.loadCatalog(locale)).then(\n (catalog) => {\n hydrate(locale, catalog);\n tasks.delete(locale);\n },\n (error: unknown) => {\n tasks.delete(locale);\n throw error;\n },\n );\n\n tasks.set(locale, task);\n await task;\n\n return true;\n };\n\n return {\n catalogMap(): ReadonlyMap<Locale, CompiledCatalog> {\n return new Map([...loaded].map(([locale, { compiled }]) => [locale, compiled]));\n },\n hydrate,\n isLoaded(locale: Locale): boolean {\n return loaded.has(canonicalLocale(locale));\n },\n load,\n state(locale: Locale): TranslationState<C> {\n const catalogs: Catalogs<C> = {};\n\n for (const [loadedLocale, { catalog }] of loaded) catalogs[loadedLocale] = catalog;\n\n return { catalogs, locale, version: 1 };\n },\n };\n}\n","import { type CompiledCatalog, type CompiledMessage, compileCatalog } from './_catalog';\nimport { isDev, warn } from './_dev';\nimport { canonicalLocale, localeChain, pluralCategory } from './_locale';\nimport { renderParts, renderText, type Template } from './_template';\nimport { LinguaInvalidPluralCountError, LinguaMissingKeyError, LinguaMissingValueError } from './errors';\nimport type {\n Catalog,\n Locale,\n MissingInfo,\n MissingStrategy,\n Part,\n PluralKey,\n PluralOptions,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n} from './types';\n\nexport type Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n parts<V>(key: TextKey<C>, options: TranslateOptions & { values: Record<string, V> }): Array<Part<V>>;\n parts<V>(key: PluralKey<C>, options: PluralOptions & { values?: Record<string, V> }): Array<Part<number | V>>;\n partsDynamic<V>(\n key: string,\n options: (TranslateOptions | PluralOptions) & { values?: Record<string, V> },\n ): Array<Part<number | V>>;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n translateDynamic(key: string, options?: TranslateOptions | PluralOptions): string;\n};\n\ntype InternalOptions = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n};\n\nfunction resolveMissing(strategy: MissingStrategy | undefined, info: MissingInfo): string {\n if (strategy === 'throw') {\n throw info.name\n ? new LinguaMissingValueError(\n `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`,\n )\n : new LinguaMissingKeyError(`Missing translation key \"${info.key}\" in locale \"${info.locale}\".`);\n }\n\n if (typeof strategy === 'function') return strategy(info);\n\n // 'key' or undefined (default)\n if (strategy === undefined && isDev) {\n warn(\n info.name\n ? `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`\n : `Missing translation key \"${info.key}\" in locale \"${info.locale}\".`,\n );\n }\n\n return info.name ? `{${info.name}}` : info.key;\n}\n\ntype ResolvedMessage = { readonly locale: Locale; readonly message: CompiledMessage };\n\nexport function createTranslatorFromCompiled<C extends Catalog>(\n catalogs: ReadonlyMap<Locale, CompiledCatalog>,\n options: InternalOptions = {},\n): Translator<C> {\n const locale = canonicalLocale(options.locale ?? 'en');\n const fallback = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const chain = localeChain(locale, fallback);\n const missing = options.missing;\n\n const missingKey = (key: string): string => resolveMissing(missing, { key, locale });\n const missingValue = (name: string, key: string): string => resolveMissing(missing, { key, locale, name });\n\n const resolve = (key: string): ResolvedMessage | undefined => {\n for (const candidate of chain) {\n const message = catalogs.get(candidate)?.get(key);\n\n if (message) return { locale: candidate, message };\n }\n\n return undefined;\n };\n\n const templateFor = (\n key: string,\n options: TranslateOptions | PluralOptions,\n ): { key: string; template: Template } | undefined => {\n const found = resolve(key);\n\n if (!found) return undefined;\n\n if (found.message.kind === 'text') {\n if ('count' in options) return undefined;\n\n return { key, template: found.message.template };\n }\n\n if (!('count' in options) || !Number.isFinite(options.count)) {\n if ('count' in options) throw new LinguaInvalidPluralCountError('`count` must be a finite number.');\n\n return undefined;\n }\n\n const category =\n options.count === 0 && !options.ordinal\n ? 'zero'\n : pluralCategory(found.locale, options.count, options.ordinal ?? false);\n const template = found.message.forms.get(category) ?? found.message.forms.get('other');\n\n return template ? { key, template } : undefined;\n };\n\n const valuesFor = (options: TranslateOptions | PluralOptions): Record<string, unknown> =>\n 'count' in options ? { count: options.count, ...options.values } : (options.values ?? {});\n\n const partsDynamic = <V>(\n key: string,\n options: (TranslateOptions | PluralOptions) & { values?: Record<string, V> },\n ): Array<Part<number | V>> => {\n const found = templateFor(key, options);\n\n if (!found) return [{ type: 'text', value: missingKey(key) }];\n\n return renderParts(found.template, valuesFor(options) as Record<string, V | number>, (name) =>\n missingValue(name, found.key),\n );\n };\n\n const translateDynamic = (key: string, options: TranslateOptions | PluralOptions = {}): string => {\n const found = templateFor(key, options);\n\n if (!found) return missingKey(key);\n\n return renderText(found.template, valuesFor(options), (name) => missingValue(name, found.key));\n };\n\n return {\n locale,\n parts(key: string, options: (TranslateOptions | PluralOptions) & { values?: Record<string, unknown> }) {\n return partsDynamic(key, options);\n },\n partsDynamic,\n translate(key: string, options: TranslateOptions | PluralOptions = {}) {\n return translateDynamic(key, options);\n },\n translateDynamic,\n } as Translator<C>;\n}\n\n/** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */\nexport function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C> {\n const locale = canonicalLocale(options?.locale ?? 'en');\n const compiled = new Map<Locale, CompiledCatalog>([[locale, compileCatalog(catalog)]]);\n\n return createTranslatorFromCompiled<C>(compiled, { ...options, locale });\n}\n","import { error as logError } from './_dev';\nimport { canonicalLocale, localeChain } from './_locale';\nimport { createCatalogStore } from './_resources';\nimport { LinguaDisposedError, LinguaInvalidStateError, LinguaMissingCatalogError } from './errors';\nimport { createTranslatorFromCompiled, type Translator } from './translator';\nimport type { Catalog, I18nOptions, Locale, SubscribeOptions, TranslationState } from './types';\n\nexport type I18nSnapshot<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n readonly revision: number;\n /**\n * Translator for this snapshot's locale and loaded catalogs. Components can hold the\n * snapshot and translate through it without importing the whole i18n instance; always\n * re-read it after a notification instead of caching a translator across snapshots.\n */\n readonly translator: Translator<C>;\n};\n\nexport type I18n<C extends Catalog = Catalog> = Translator<C> & {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n getSnapshot(): I18nSnapshot<C>;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): TranslationState<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (snapshot: I18nSnapshot<C>) => void, options?: SubscribeOptions): () => void;\n};\n\nexport function createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C> {\n if (options.state && options.state.version !== 1) {\n throw new LinguaInvalidStateError(`Unsupported lingua state version: ${String(options.state.version)}.`);\n }\n\n const fallback = options.fallback;\n const fallbackLocales = (Array.isArray(fallback) ? fallback : fallback ? [fallback] : []).map(canonicalLocale);\n const controller = new AbortController();\n const subscribers = new Set<(snapshot: I18nSnapshot<C>) => void>();\n let disposed = false;\n let locale = canonicalLocale(options.locale ?? options.state?.locale ?? 'en');\n let revision = 0;\n let transition = 0;\n\n const catalogs = createCatalogStore<C>({ catalogs: options.catalogs, loadCatalog: options.loadCatalog });\n\n // Hydrate from serialized state (SSR).\n if (options.state) {\n for (const [stateLocale, catalog] of Object.entries(options.state.catalogs)) {\n catalogs.hydrate(stateLocale, catalog);\n }\n }\n\n const loadTargets = async (target: Locale): Promise<readonly Locale[]> => {\n const changed: Locale[] = [];\n\n for (const candidate of new Set([target, ...fallbackLocales])) {\n if (await catalogs.load(candidate)) changed.push(candidate);\n }\n\n return changed;\n };\n\n const buildTranslator = (): Translator<C> => {\n const ready = localeChain(locale, fallbackLocales).some(catalogs.isLoaded);\n const missing = ready\n ? options.missing\n : () => {\n throw new LinguaMissingCatalogError(\n `No catalog loaded for locale \"${locale}\". Call load() before translating.`,\n );\n };\n\n return createTranslatorFromCompiled<C>(catalogs.catalogMap(), { fallback, locale, missing });\n };\n\n const buildSnapshot = (): I18nSnapshot<C> => ({ locale, revision, translator: buildTranslator() });\n\n let snapshot = buildSnapshot();\n\n const assertLive = (): void => {\n if (disposed) throw new LinguaDisposedError();\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n subscribers.clear();\n controller.abort();\n };\n\n const dispatch = (listener: (next: I18nSnapshot<C>) => void): void => {\n try {\n listener(snapshot);\n } catch (error) {\n logError('subscriber error', error);\n }\n };\n\n const notify = (): void => {\n revision++;\n snapshot = buildSnapshot();\n\n for (const listener of [...subscribers]) dispatch(listener);\n };\n\n const relevant = (candidate: Locale): boolean => localeChain(locale, fallbackLocales).includes(candidate);\n\n return {\n get disposalSignal() {\n return controller.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n getSnapshot() {\n return snapshot;\n },\n isLoaded(loadOptions) {\n return !disposed && catalogs.isLoaded(loadOptions?.locale ?? locale);\n },\n async load(loadOptions) {\n assertLive();\n\n const targetLocale = canonicalLocale(loadOptions?.locale ?? locale);\n const changed = await loadTargets(targetLocale);\n\n assertLive();\n if (changed.some(relevant)) notify();\n },\n get locale() {\n return locale;\n },\n parts(key: string, translateOptions) {\n return snapshot.translator.partsDynamic(key, translateOptions);\n },\n partsDynamic(key, translateOptions) {\n return snapshot.translator.partsDynamic(key, translateOptions);\n },\n serialize() {\n assertLive();\n\n return catalogs.state(locale);\n },\n async setLocale(nextLocale) {\n assertLive();\n\n const next = canonicalLocale(nextLocale);\n const request = ++transition;\n const changed = await loadTargets(next);\n\n assertLive();\n if (request !== transition) return;\n\n if (next === locale) {\n if (changed.some(relevant)) notify();\n\n return;\n }\n\n locale = next;\n notify();\n },\n subscribe(listener, subscribeOptions) {\n assertLive();\n\n if (subscribeOptions?.signal?.aborted) return () => {};\n\n const unsubscribe = (): void => {\n subscribers.delete(listener);\n subscribeOptions?.signal?.removeEventListener('abort', unsubscribe);\n };\n\n subscribeOptions?.signal?.addEventListener('abort', unsubscribe, { once: true });\n subscribers.add(listener);\n\n if (subscribeOptions?.immediate) dispatch(listener);\n\n return unsubscribe;\n },\n [Symbol.dispose]: dispose,\n translate(key: string, translateOptions = {}) {\n return snapshot.translator.translateDynamic(key, translateOptions);\n },\n translateDynamic(key, translateOptions) {\n return snapshot.translator.translateDynamic(key, translateOptions);\n },\n } as I18n<C>;\n}\n"],"mappings":";AAKA,IAAMC,IAAgB;AAEtB,SAAgB,gBAAgB,GAAyB;CACvD,IAAMC,IAAwB,CAAC,GAC3BC,IAAS;CAEb,KAAK,IAAMC,KAASC,EAAM,SAASJ,CAAa,GAAG;EACjD,IAAMK,IAAQF,EAAM,SAAS;EAK7B,AAHIE,IAAQH,KAAQD,EAAM,KAAKG,EAAM,MAAMF,GAAQG,CAAK,CAAC,GAEzDJ,EAAM,KAAK,EAAE,OAAOE,EAAM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WAAW,GACPE,MAAYX,MAEZS,MAASrC,IACP8B,EAAQ,KAAK,QAAQ,KAAG,OAAO,KAKrC,IAASO,GACT,OAAO;EACT;EACA,UAAU,GAAU,GAAkB;GAGpC,IAFA,WAAW,GAEPG,GAAkB,QAAQ,SAAS,aAAa,CAAC;GAErD,IAAM,oBAA0B;IAE9B,AADAf,EAAY,OAAOQ,CAAQ,GAC3BO,GAAkB,QAAQ,oBAAoB,SAAS,WAAW;GACpE;GAOA,OALAA,GAAkB,QAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,GAAK,CAAC,GAC/Ef,EAAY,IAAIQ,CAAQ,GAEpBO,GAAkB,aAAW,SAASP,CAAQ,GAE3C;EACT;GACC,OAAO,UAAU;EAClB,UAAU,GAAa,IAAmB,CAAC,GAAG;GAC5C,OAAOD,EAAS,WAAW,iBAAiBvC,GAAK2C,CAAgB;EACnE;EACA,iBAAiB,GAAK,GAAkB;GACtC,OAAOJ,EAAS,WAAW,iBAAiBvC,GAAK2C,CAAgB;EACnE;CACF;AACF"}
1
+ {"version":3,"file":"lingua.js","names":["error","interpolation","parts","offset","match","value","index","part","values","missing","message","opts","unsafeKeys","node","messages","prefix","key","forms","form","template","catalog","pluralRules","canonical","locale","chain","candidate","fallback","length","ordinal","rules","count","loaded","tasks","options","requestedLocale","existing","task","error","compiled","catalogs","loadedLocale","strategy","info","found","category","name","engine","fallbackLocales","controller","subscribers","disposed","transition","changed","target","effectiveMissing","listener","loadOptions","targetLocale","next","nextLocale","request","subscribeOptions","translateOptions"],"sources":["../src/_template.ts","../src/errors.ts","../src/_catalog.ts","../src/catalog.ts","../src/_dev.ts","../src/_locale.ts","../src/_resources.ts","../src/translator.ts","../src/i18n.ts"],"sourcesContent":["export type TemplatePart = string | { readonly value: string };\nexport type Template = readonly TemplatePart[];\n\nconst interpolation = /\\{([\\p{ID_Continue}-]+)\\}/gu;\n\nexport function compileTemplate(value: string): Template {\n const parts: TemplatePart[] = [];\n let offset = 0;\n\n for (const match of value.matchAll(interpolation)) {\n const index = match.index ?? 0;\n\n if (index > offset) parts.push(value.slice(offset, index));\n\n parts.push({ value: match[1] });\n offset = index + match[0].length;\n }\n\n if (offset < value.length) parts.push(value.slice(offset));\n\n return parts;\n}\n\nexport function renderText(\n parts: Template,\n values: Record<string, unknown>,\n missing: (name: string) => string,\n): string {\n return parts\n .map((part) => {\n if (typeof part === 'string') return part;\n\n const value = Object.hasOwn(values, part.value) ? values[part.value] : undefined;\n\n return value == null ? missing(part.value) : String(value);\n })\n .join('');\n}\n","export class LinguaError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class LinguaDisposedError extends LinguaError {\n constructor() {\n super('Operation called on a disposed i18n instance.');\n }\n}\n\nexport class LinguaInvalidCatalogError extends LinguaError {}\nexport class LinguaInvalidLocaleError extends LinguaError {}\nexport class LinguaInvalidPluralCountError extends LinguaError {}\nexport class LinguaMissingCatalogError extends LinguaError {}\nexport class LinguaMissingKeyError extends LinguaError {}\nexport class LinguaMissingValueError extends LinguaError {}\n","import { compileTemplate, type Template } from './_template';\nimport { LinguaInvalidCatalogError } from './errors';\nimport type { Catalog, CatalogNode, PluralMessage } from './types';\n\nconst unsafeKeys = new Set(['__proto__', 'constructor', 'prototype']);\n\nexport type CompiledText = { readonly kind: 'text'; readonly template: Template };\nexport type CompiledPlural = { readonly forms: ReadonlyMap<string, Template>; readonly kind: 'plural' };\nexport type CompiledMessage = CompiledPlural | CompiledText;\nexport type CompiledCatalog = ReadonlyMap<string, CompiledMessage>;\n\nexport function isPluralMessage(node: CatalogNode): node is PluralMessage {\n return typeof node === 'object' && node !== null && Object.hasOwn(node, 'plural');\n}\n\n/** Compile explicit catalog nodes once. Nested objects only group keys; plural intent is never inferred. */\nexport function compileCatalog(catalog: Catalog): CompiledCatalog {\n const messages = new Map<string, CompiledMessage>();\n\n const visit = (node: CatalogNode, prefix: string): void => {\n if (typeof node === 'string') {\n messages.set(prefix, { kind: 'text', template: compileTemplate(node) });\n\n return;\n }\n\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n throw new LinguaInvalidCatalogError(`Catalog node \"${prefix}\" must be a string, plural message, or object.`);\n }\n\n if (isPluralMessage(node)) {\n if (Reflect.ownKeys(node).some((key) => key !== 'plural')) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must contain only a \"plural\" property.`);\n }\n\n if (typeof node.plural !== 'object' || node.plural === null || Array.isArray(node.plural)) {\n throw new LinguaInvalidCatalogError(`Plural message \"${prefix}\" must provide an object of string forms.`);\n }\n\n const forms = new Map<string, Template>();\n\n for (const [form, template] of Object.entries(node.plural)) {\n if (typeof template !== 'string') {\n throw new LinguaInvalidCatalogError(`Plural form \"${prefix}.${form}\" must be a string.`);\n }\n\n forms.set(form, compileTemplate(template));\n }\n\n messages.set(prefix, { forms, kind: 'plural' });\n\n return;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (unsafeKeys.has(key)) {\n throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n }\n\n visit(value, prefix ? `${prefix}.${key}` : key);\n }\n };\n\n for (const [key, value] of Object.entries(catalog)) {\n if (unsafeKeys.has(key)) throw new LinguaInvalidCatalogError(`Catalog key \"${key}\" is reserved.`);\n\n visit(value, key);\n }\n\n return messages;\n}\n","import { compileCatalog } from './_catalog';\nimport type { Catalog, MessageKey } from './types';\n\n/** Enumerate every message key in a catalog as a dotted path.\n *\n * Traverses nested grouping objects and explicit `{ plural: ... }` messages,\n * producing the same dotted paths that `MessageKey<C>` represents at the type\n * level. Use this to derive key arrays from the catalog itself instead of\n * maintaining a parallel list that can go stale.\n *\n * Pass any catalog subtree to enumerate group-scoped keys. For an `I18n`\n * instance, pass its current locale catalog explicitly.\n *\n * @example\n * ```ts\n * const messages = {\n * nav: { home: '...', settings: '...' },\n * };\n * const keys = catalogKeys(messages); // ['nav.home', 'nav.settings']\n * const navKeys = catalogKeys(messages.nav); // ['home', 'settings']\n *\n * // From an i18n instance: read the current locale's catalog first\n * const i18n = createI18n({ catalogs: { en: messages }, locale: 'en' });\n * const state = i18n.serialize();\n * const allKeys = catalogKeys(state.catalogs[state.locale]);\n * ```\n */\nexport function catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>> {\n return [...compileCatalog(catalog).keys()] as unknown as ReadonlyArray<MessageKey<C>>;\n}\n","export const isDev = !(globalThis as { __LINGUA_PROD__?: boolean }).__LINGUA_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/lingua] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/lingua] ${msg}`, ...args);\n}\n","import { LinguaInvalidLocaleError } from './errors';\nimport type { Locale } from './types';\n\nconst pluralRules = new Map<string, Intl.PluralRules>();\n\nexport function canonicalLocale(locale: string): Locale {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n\n if (canonical) return canonical;\n } catch {\n // Error below names the failed public input.\n }\n\n throw new LinguaInvalidLocaleError(`Invalid BCP 47 locale tag: \"${locale}\".`);\n}\n\nexport function localeChain(locale: Locale, fallback: readonly Locale[]): readonly Locale[] {\n const chain = new Set<Locale>();\n\n for (const candidate of [locale, ...fallback]) {\n const parts = candidate.split('-');\n\n for (let length = parts.length; length > 0; length--) {\n chain.add(parts.slice(0, length).join('-'));\n }\n }\n\n return [...chain];\n}\n\nexport function pluralCategory(locale: Locale, count: number, ordinal: boolean): Intl.LDMLPluralRule {\n const key = `${locale}:${ordinal ? 'ordinal' : 'cardinal'}`;\n let rules = pluralRules.get(key);\n\n if (!rules) {\n rules = new Intl.PluralRules(locale, { type: ordinal ? 'ordinal' : 'cardinal' });\n pluralRules.set(key, rules);\n }\n\n return rules.select(count);\n}\n","import { type CompiledCatalog, compileCatalog } from './_catalog';\nimport { canonicalLocale } from './_locale';\nimport { LinguaMissingCatalogError } from './errors';\nimport type { Catalog, Catalogs, Locale, SerializedI18n } from './types';\n\ntype CatalogStoreOptions<C extends Catalog> = {\n readonly catalogs?: Catalogs<C>;\n readonly loadCatalog?: (locale: Locale) => Promise<C> | C;\n};\n\n/** One catalog state machine owns loaded catalogs and in-flight loading work. */\nexport function createCatalogStore<C extends Catalog>(options: CatalogStoreOptions<C>) {\n const loaded = new Map<Locale, { readonly catalog: C; readonly compiled: CompiledCatalog }>();\n const tasks = new Map<Locale, Promise<void>>();\n\n const hydrate = (locale: Locale, catalog: C): void => {\n loaded.set(canonicalLocale(locale), { catalog, compiled: compileCatalog(catalog) });\n };\n\n for (const [locale, catalog] of Object.entries(options.catalogs ?? {})) hydrate(locale, catalog);\n\n const load = async (requestedLocale: Locale): Promise<boolean> => {\n const locale = canonicalLocale(requestedLocale);\n\n if (loaded.has(locale)) return false;\n\n const existing = tasks.get(locale);\n\n if (existing) {\n await existing;\n\n return false;\n }\n\n if (!options.loadCatalog) {\n throw new LinguaMissingCatalogError(`No catalog source provided for locale \"${locale}\".`);\n }\n\n const task = Promise.resolve(options.loadCatalog(locale)).then(\n (catalog) => {\n hydrate(locale, catalog);\n tasks.delete(locale);\n },\n (error: unknown) => {\n tasks.delete(locale);\n throw error;\n },\n );\n\n tasks.set(locale, task);\n await task;\n\n return true;\n };\n\n return {\n catalogMap(): ReadonlyMap<Locale, CompiledCatalog> {\n return new Map([...loaded].map(([locale, { compiled }]) => [locale, compiled]));\n },\n isLoaded(locale: Locale): boolean {\n return loaded.has(canonicalLocale(locale));\n },\n load,\n serialized(locale: Locale): SerializedI18n<C> {\n const catalogs: Catalogs<C> = {};\n\n for (const [loadedLocale, { catalog }] of loaded) catalogs[loadedLocale] = catalog;\n\n return { catalogs, locale };\n },\n };\n}\n","import { type CompiledCatalog, type CompiledMessage, compileCatalog } from './_catalog';\nimport { isDev, warn } from './_dev';\nimport { canonicalLocale, localeChain, pluralCategory } from './_locale';\nimport { renderText, type Template } from './_template';\nimport { LinguaInvalidPluralCountError, LinguaMissingKeyError, LinguaMissingValueError } from './errors';\nimport type {\n Catalog,\n Locale,\n MissingInfo,\n MissingStrategy,\n PluralKey,\n PluralOptions,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n} from './types';\n\nexport type Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n};\n\n/** Loose translate signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseTranslate = (key: string, options?: TranslateOptions | PluralOptions) => string;\n\nfunction resolveMissing(strategy: MissingStrategy | undefined, info: MissingInfo): string {\n if (strategy === 'throw') {\n throw info.name\n ? new LinguaMissingValueError(\n `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`,\n )\n : new LinguaMissingKeyError(`Missing translation key \"${info.key}\" in locale \"${info.locale}\".`);\n }\n\n if (typeof strategy === 'function') return strategy(info);\n\n // 'key' or undefined (default)\n if (strategy === undefined && isDev) {\n warn(\n info.name\n ? `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`\n : `Missing translation key \"${info.key}\" in locale \"${info.locale}\".`,\n );\n }\n\n return info.name ? `{${info.name}}` : info.key;\n}\n\n/** Internal engine: resolves and renders any string key against compiled catalogs for a fixed locale. */\nexport function createTranslateEngine(\n catalogs: ReadonlyMap<Locale, CompiledCatalog>,\n options: InternalOptions = {},\n): { readonly locale: Locale; readonly translate: LooseTranslate } {\n const locale = canonicalLocale(options.locale ?? 'en');\n const fallback = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const chain = localeChain(locale, fallback);\n const missing = options.missing;\n\n const missingKey = (key: string): string => resolveMissing(missing, { key, locale });\n const missingValue = (name: string, key: string): string => resolveMissing(missing, { key, locale, name });\n\n const resolve = (key: string): { readonly locale: Locale; readonly message: CompiledMessage } | undefined => {\n for (const candidate of chain) {\n const message = catalogs.get(candidate)?.get(key);\n\n if (message) return { locale: candidate, message };\n }\n\n return undefined;\n };\n\n const templateFor = (key: string, options: TranslateOptions | PluralOptions): Template | undefined => {\n const found = resolve(key);\n\n if (!found) return undefined;\n\n if (found.message.kind === 'text') {\n if ('count' in options) return undefined;\n\n return found.message.template;\n }\n\n if (!('count' in options) || !Number.isFinite(options.count)) {\n if ('count' in options) throw new LinguaInvalidPluralCountError('`count` must be a finite number.');\n\n return undefined;\n }\n\n const category = pluralCategory(found.locale, options.count, options.ordinal ?? false);\n\n return found.message.forms.get(category) ?? found.message.forms.get('other');\n };\n\n const translate = (key: string, options: TranslateOptions | PluralOptions = {}): string => {\n const template = templateFor(key, options);\n\n if (!template) return missingKey(key);\n\n const values: Record<string, unknown> =\n 'count' in options ? { count: options.count, ...options.values } : (options.values ?? {});\n\n return renderText(template, values, (name) => missingValue(name, key));\n };\n\n return { locale, translate };\n}\n\ntype InternalOptions = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n};\n\n/** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */\nexport function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C> {\n const engine = createTranslateEngine(\n new Map([[canonicalLocale(options?.locale ?? 'en'), compileCatalog(catalog)]]),\n options,\n );\n\n return { locale: engine.locale, translate: engine.translate };\n}\n","import { error as logError } from './_dev';\nimport { canonicalLocale, localeChain } from './_locale';\nimport { createCatalogStore } from './_resources';\nimport { LinguaDisposedError, LinguaMissingCatalogError } from './errors';\nimport { createTranslateEngine, type Translator } from './translator';\nimport type {\n Catalog,\n I18nOptions,\n Locale,\n PluralOptions,\n SerializedI18n,\n SubscribeOptions,\n TranslateOptions,\n} from './types';\n\nexport type I18n<C extends Catalog = Catalog> = Translator<C> & {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n /** Current locale. Referentially stable until the locale changes, so frameworks can use it directly as a store snapshot. */\n getSnapshot(): Locale;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): SerializedI18n<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;\n};\n\nexport function createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C> {\n const fallbackLocales = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const controller = new AbortController();\n const subscribers = new Set<(locale: Locale) => void>();\n let disposed = false;\n let locale = canonicalLocale(options.locale ?? 'en');\n let transition = 0;\n\n const catalogs = createCatalogStore<C>({ catalogs: options.catalogs, loadCatalog: options.loadCatalog });\n\n const loadTargets = async (target: Locale): Promise<readonly Locale[]> => {\n const changed: Locale[] = [];\n\n for (const candidate of new Set([target, ...fallbackLocales])) {\n if (await catalogs.load(candidate)) changed.push(candidate);\n }\n\n return changed;\n };\n\n const buildEngine = () => {\n const ready = localeChain(locale, fallbackLocales).some(catalogs.isLoaded);\n const effectiveMissing = ready\n ? options.missing\n : (): never => {\n throw new LinguaMissingCatalogError(\n `No catalog loaded for locale \"${locale}\". Call load() before translating.`,\n );\n };\n\n return createTranslateEngine(catalogs.catalogMap(), { ...options, locale, missing: effectiveMissing });\n };\n\n const assertLive = (): void => {\n if (disposed) throw new LinguaDisposedError();\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n subscribers.clear();\n controller.abort();\n };\n\n const notify = (): void => {\n engine = buildEngine();\n\n for (const listener of [...subscribers]) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n };\n\n const relevant = (candidate: Locale): boolean => localeChain(locale, fallbackLocales).includes(candidate);\n\n let engine = buildEngine();\n\n const instance: I18n<C> = {\n get disposalSignal() {\n return controller.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n getSnapshot() {\n return locale;\n },\n isLoaded(loadOptions) {\n return !disposed && catalogs.isLoaded(loadOptions?.locale ?? locale);\n },\n async load(loadOptions) {\n assertLive();\n\n const targetLocale = canonicalLocale(loadOptions?.locale ?? locale);\n const changed = await loadTargets(targetLocale);\n\n assertLive();\n if (changed.some(relevant)) notify();\n },\n get locale() {\n return locale;\n },\n serialize() {\n assertLive();\n\n return catalogs.serialized(locale);\n },\n async setLocale(nextLocale) {\n assertLive();\n\n const next = canonicalLocale(nextLocale);\n const request = ++transition;\n const changed = await loadTargets(next);\n\n assertLive();\n if (request !== transition) return;\n\n if (next === locale) {\n if (changed.some(relevant)) notify();\n\n return;\n }\n\n locale = next;\n notify();\n },\n subscribe(listener, subscribeOptions) {\n assertLive();\n\n if (subscribeOptions?.signal?.aborted) return () => {};\n\n const unsubscribe = (): void => {\n subscribers.delete(listener);\n subscribeOptions?.signal?.removeEventListener('abort', unsubscribe);\n };\n\n subscribeOptions?.signal?.addEventListener('abort', unsubscribe, { once: true });\n subscribers.add(listener);\n\n if (subscribeOptions?.immediate) {\n try {\n listener(locale);\n } catch (error) {\n logError('subscriber error', error);\n }\n }\n\n return unsubscribe;\n },\n translate: (key: string, translateOptions?: TranslateOptions | PluralOptions): string =>\n engine.translate(key, translateOptions),\n [Symbol.dispose]: dispose,\n };\n\n return instance;\n}\n"],"mappings":";AAGA,IAAMC,IAAgB;AAEtB,SAAgB,gBAAgB,GAAyB;CACvD,IAAMC,IAAwB,CAAC,GAC3BC,IAAS;CAEb,KAAK,IAAMC,KAASC,EAAM,SAASJ,CAAa,GAAG;EACjD,IAAMK,IAAQF,EAAM,SAAS;EAK7B,AAHIE,IAAQH,KAAQD,EAAM,KAAKG,EAAM,MAAMF,GAAQG,CAAK,CAAC,GAEzDJ,EAAM,KAAK,EAAE,OAAOE,EAAM,GAAG,CAAC,GAC9B,IAASE,IAAQF,EAAM,EAAE,CAAC;CAC5B;CAIA,OAFID,IAASE,EAAM,UAAQH,EAAM,KAAKG,EAAM,MAA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BM,GAAkB,WACpB,IAAI;IACF,EAAStC,CAAM;GACjB,QAAgB,CAEhB;GAGF,OAAO;EACT;EACA,YAAY,GAAa,MACvBuB,EAAO,UAAU9B,GAAK8C,CAAgB;GACvC,OAAO,UAAU;CAGb;AACT"}
package/dist/ripple.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/ripple");function createReactiveI18n(t){let n=(0,e.fromSubscribable)({getSnapshot:()=>t.locale,subscribe:e=>t.subscribe(()=>e())});return{i18n:t,locale:n,translate:(e,r)=>(n.value,t.translateDynamic(e,r)),translateDynamic:(e,r)=>(n.value,t.translateDynamic(e,r))}}exports.createReactiveI18n=createReactiveI18n;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/ripple");function createReactiveI18n(t){let n=(0,e.fromSubscribable)({getSnapshot:()=>t.getSnapshot(),subscribe:e=>t.subscribe(()=>e())}),translate=(e,r)=>(n.value,t.translate(e,r));return{i18n:t,locale:n,translate}}exports.createReactiveI18n=createReactiveI18n;
2
2
  //# sourceMappingURL=ripple.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ripple.cjs","names":["fromSubscribable","_vielzeug_ripple","locale","i18n","listener","key","options"],"sources":["../src/ripple.ts"],"sourcesContent":["import { fromSubscribable, type Readable } from '@vielzeug/ripple';\n\nimport type { I18n } from './i18n';\nimport type { Catalog, Locale, MessageKey, PluralOptions, TranslateOptions } from './types';\n\n/** A lingua instance mirrored into ripple readables so templates react to locale changes. */\nexport interface ReactiveI18n<C extends Catalog> {\n /** The underlying instance for imperative work (`setLocale`, `load`, disposal). */\n readonly i18n: I18n<C>;\n /** Reactive locale: reading it inside a computed/template registers the dependency. */\n readonly locale: Readable<Locale>;\n /** Translate a text or plural key; re-evaluates whenever the locale changes. */\n translate(key: MessageKey<C>, options?: TranslateOptions | PluralOptions): string;\n /** Translate a runtime-assembled key; re-evaluates whenever the locale changes. */\n translateDynamic(key: string, options?: TranslateOptions | PluralOptions): string;\n}\n\n/**\n * Bridges a lingua instance into ripple so translated strings are reactive.\n *\n * `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()`\n * computes once and never re-runs, since it registers no tracked dependency. Both translate\n * methods here first read the reactive {@link ReactiveI18n.locale}, so any binding built on them\n * re-evaluates the instant `setLocale()` resolves.\n */\nexport function createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C> {\n const locale = fromSubscribable<Locale>({\n getSnapshot: () => i18n.locale,\n subscribe: (listener) => i18n.subscribe(() => listener()),\n });\n\n return {\n i18n,\n locale,\n translate: (key, options) => {\n void locale.value;\n return i18n.translateDynamic(key, options);\n },\n translateDynamic: (key, options) => {\n void locale.value;\n return i18n.translateDynamic(key, options);\n },\n };\n}\n"],"mappings":"A,qGAyBA,SAAgB,mBAAsC,EAAgC,CACpF,IAAME,GAAA,EAASF,EAAAA,iBAAAA,CAAyB,CACtC,gBAAmBG,EAAK,OACxB,UAAY,GAAaA,EAAK,cAAgBC,EAAS,CAAC,CAC1D,CAAC,EAED,MAAO,CACL,OACA,SACA,WAAY,EAAK,KACfF,EAAY,MACLC,EAAK,iBAAiBE,EAAKC,CAAO,GAE3C,kBAAmB,EAAK,KACtBJ,EAAY,MACLC,EAAK,iBAAiBE,EAAKC,CAAO,EAE7C,CACF,C"}
1
+ {"version":3,"file":"ripple.cjs","names":["fromSubscribable","_vielzeug_ripple","locale","i18n","listener","key","options"],"sources":["../src/ripple.ts"],"sourcesContent":["import { fromSubscribable, type Readable } from '@vielzeug/ripple';\n\nimport type { I18n } from './i18n';\nimport type { Translator } from './translator';\nimport type { Catalog, Locale, PluralOptions, TranslateOptions } from './types';\n\n/** A lingua instance mirrored into ripple readables so templates react to locale changes. */\nexport interface ReactiveI18n<C extends Catalog> {\n /** The underlying instance for imperative work (`setLocale`, `load`, disposal). */\n readonly i18n: I18n<C>;\n /** Reactive locale: reading it inside a computed/template registers the dependency. */\n readonly locale: Readable<Locale>;\n /** Translate a text or plural key; re-evaluates whenever the locale changes. */\n readonly translate: Translator<C>['translate'];\n}\n\n/**\n * Bridges a lingua instance into ripple so translated strings are reactive.\n *\n * `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()`\n * computes once and never re-runs, since it registers no tracked dependency. The bridge's\n * `translate` reads the reactive {@link ReactiveI18n.locale} first, so any binding built on\n * it re-evaluates the instant `setLocale()` resolves.\n */\nexport function createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C> {\n const locale = fromSubscribable<Locale>({\n getSnapshot: () => i18n.getSnapshot(),\n subscribe: (listener) => i18n.subscribe(() => listener()),\n });\n\n const translate = (key: string, options?: TranslateOptions | PluralOptions): string => {\n void locale.value;\n return i18n.translate(key as never, options as never);\n };\n\n return { i18n, locale, translate: translate as ReactiveI18n<C>['translate'] };\n}\n"],"mappings":"A,qGAwBA,SAAgB,mBAAsC,EAAgC,CACpF,IAAME,GAAA,EAASF,EAAAA,iBAAAA,CAAyB,CACtC,gBAAmBG,EAAK,YAAY,EACpC,UAAY,GAAaA,EAAK,cAAgBC,EAAS,CAAC,CAC1D,CAAC,EAEK,WAAa,EAAa,KAC9BF,EAAY,MACLC,EAAK,UAAUE,EAAcC,CAAgB,GAGtD,MAAO,CAAE,OAAM,SAAmB,SAA0C,CAC9E,C"}
package/dist/ripple.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type Readable } from '@vielzeug/ripple';
2
2
  import type { I18n } from './i18n';
3
- import type { Catalog, Locale, MessageKey, PluralOptions, TranslateOptions } from './types';
3
+ import type { Translator } from './translator';
4
+ import type { Catalog, Locale } from './types';
4
5
  /** A lingua instance mirrored into ripple readables so templates react to locale changes. */
5
6
  export interface ReactiveI18n<C extends Catalog> {
6
7
  /** The underlying instance for imperative work (`setLocale`, `load`, disposal). */
@@ -8,17 +9,15 @@ export interface ReactiveI18n<C extends Catalog> {
8
9
  /** Reactive locale: reading it inside a computed/template registers the dependency. */
9
10
  readonly locale: Readable<Locale>;
10
11
  /** Translate a text or plural key; re-evaluates whenever the locale changes. */
11
- translate(key: MessageKey<C>, options?: TranslateOptions | PluralOptions): string;
12
- /** Translate a runtime-assembled key; re-evaluates whenever the locale changes. */
13
- translateDynamic(key: string, options?: TranslateOptions | PluralOptions): string;
12
+ readonly translate: Translator<C>['translate'];
14
13
  }
15
14
  /**
16
15
  * Bridges a lingua instance into ripple so translated strings are reactive.
17
16
  *
18
17
  * `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()`
19
- * computes once and never re-runs, since it registers no tracked dependency. Both translate
20
- * methods here first read the reactive {@link ReactiveI18n.locale}, so any binding built on them
21
- * re-evaluates the instant `setLocale()` resolves.
18
+ * computes once and never re-runs, since it registers no tracked dependency. The bridge's
19
+ * `translate` reads the reactive {@link ReactiveI18n.locale} first, so any binding built on
20
+ * it re-evaluates the instant `setLocale()` resolves.
22
21
  */
23
22
  export declare function createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C>;
24
23
  //# sourceMappingURL=ripple.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ripple.d.ts","sourceRoot":"","sources":["../src/ripple.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEnE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE5F,6FAA6F;AAC7F,MAAM,WAAW,YAAY,CAAC,CAAC,SAAS,OAAO;IAC7C,mFAAmF;IACnF,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IACvB,uFAAuF;IACvF,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IAClC,gFAAgF;IAChF,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,aAAa,GAAG,MAAM,CAAC;IAClF,mFAAmF;IACnF,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,aAAa,GAAG,MAAM,CAAC;CACnF;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAkBpF"}
1
+ {"version":3,"file":"ripple.d.ts","sourceRoot":"","sources":["../src/ripple.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEnE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAmC,MAAM,SAAS,CAAC;AAEhF,6FAA6F;AAC7F,MAAM,WAAW,YAAY,CAAC,CAAC,SAAS,OAAO;IAC7C,mFAAmF;IACnF,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IACvB,uFAAuF;IACvF,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IAClC,gFAAgF;IAChF,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;CAChD;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAYpF"}
package/dist/ripple.js CHANGED
@@ -2,14 +2,13 @@ import { fromSubscribable as e } from "@vielzeug/ripple";
2
2
  // src/ripple.ts
3
3
  function createReactiveI18n(t) {
4
4
  let n = e({
5
- getSnapshot: () => t.locale,
5
+ getSnapshot: () => t.getSnapshot(),
6
6
  subscribe: (e) => t.subscribe(() => e())
7
- });
7
+ }), translate = (e, r) => (n.value, t.translate(e, r));
8
8
  return {
9
9
  i18n: t,
10
10
  locale: n,
11
- translate: (e, r) => (n.value, t.translateDynamic(e, r)),
12
- translateDynamic: (e, r) => (n.value, t.translateDynamic(e, r))
11
+ translate
13
12
  };
14
13
  }
15
14
  export { createReactiveI18n };
@@ -1 +1 @@
1
- {"version":3,"file":"ripple.js","names":["locale","fromSubscribable","i18n","listener","key","options"],"sources":["../src/ripple.ts"],"sourcesContent":["import { fromSubscribable, type Readable } from '@vielzeug/ripple';\n\nimport type { I18n } from './i18n';\nimport type { Catalog, Locale, MessageKey, PluralOptions, TranslateOptions } from './types';\n\n/** A lingua instance mirrored into ripple readables so templates react to locale changes. */\nexport interface ReactiveI18n<C extends Catalog> {\n /** The underlying instance for imperative work (`setLocale`, `load`, disposal). */\n readonly i18n: I18n<C>;\n /** Reactive locale: reading it inside a computed/template registers the dependency. */\n readonly locale: Readable<Locale>;\n /** Translate a text or plural key; re-evaluates whenever the locale changes. */\n translate(key: MessageKey<C>, options?: TranslateOptions | PluralOptions): string;\n /** Translate a runtime-assembled key; re-evaluates whenever the locale changes. */\n translateDynamic(key: string, options?: TranslateOptions | PluralOptions): string;\n}\n\n/**\n * Bridges a lingua instance into ripple so translated strings are reactive.\n *\n * `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()`\n * computes once and never re-runs, since it registers no tracked dependency. Both translate\n * methods here first read the reactive {@link ReactiveI18n.locale}, so any binding built on them\n * re-evaluates the instant `setLocale()` resolves.\n */\nexport function createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C> {\n const locale = fromSubscribable<Locale>({\n getSnapshot: () => i18n.locale,\n subscribe: (listener) => i18n.subscribe(() => listener()),\n });\n\n return {\n i18n,\n locale,\n translate: (key, options) => {\n void locale.value;\n return i18n.translateDynamic(key, options);\n },\n translateDynamic: (key, options) => {\n void locale.value;\n return i18n.translateDynamic(key, options);\n },\n };\n}\n"],"mappings":";;AAyBA,SAAgB,mBAAsC,GAAgC;CACpF,IAAMA,IAASC,EAAyB;EACtC,mBAAmBC,EAAK;EACxB,YAAY,MAAaA,EAAK,gBAAgBC,EAAS,CAAC;CAC1D,CAAC;CAED,OAAO;EACL;EACA;EACA,YAAY,GAAK,OACfH,EAAY,OACLE,EAAK,iBAAiBE,GAAKC,CAAO;EAE3C,mBAAmB,GAAK,OACtBL,EAAY,OACLE,EAAK,iBAAiBE,GAAKC,CAAO;CAE7C;AACF"}
1
+ {"version":3,"file":"ripple.js","names":["locale","fromSubscribable","i18n","listener","key","options"],"sources":["../src/ripple.ts"],"sourcesContent":["import { fromSubscribable, type Readable } from '@vielzeug/ripple';\n\nimport type { I18n } from './i18n';\nimport type { Translator } from './translator';\nimport type { Catalog, Locale, PluralOptions, TranslateOptions } from './types';\n\n/** A lingua instance mirrored into ripple readables so templates react to locale changes. */\nexport interface ReactiveI18n<C extends Catalog> {\n /** The underlying instance for imperative work (`setLocale`, `load`, disposal). */\n readonly i18n: I18n<C>;\n /** Reactive locale: reading it inside a computed/template registers the dependency. */\n readonly locale: Readable<Locale>;\n /** Translate a text or plural key; re-evaluates whenever the locale changes. */\n readonly translate: Translator<C>['translate'];\n}\n\n/**\n * Bridges a lingua instance into ripple so translated strings are reactive.\n *\n * `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()`\n * computes once and never re-runs, since it registers no tracked dependency. The bridge's\n * `translate` reads the reactive {@link ReactiveI18n.locale} first, so any binding built on\n * it re-evaluates the instant `setLocale()` resolves.\n */\nexport function createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C> {\n const locale = fromSubscribable<Locale>({\n getSnapshot: () => i18n.getSnapshot(),\n subscribe: (listener) => i18n.subscribe(() => listener()),\n });\n\n const translate = (key: string, options?: TranslateOptions | PluralOptions): string => {\n void locale.value;\n return i18n.translate(key as never, options as never);\n };\n\n return { i18n, locale, translate: translate as ReactiveI18n<C>['translate'] };\n}\n"],"mappings":";;AAwBA,SAAgB,mBAAsC,GAAgC;CACpF,IAAMA,IAASC,EAAyB;EACtC,mBAAmBC,EAAK,YAAY;EACpC,YAAY,MAAaA,EAAK,gBAAgBC,EAAS,CAAC;CAC1D,CAAC,GAEK,aAAa,GAAa,OAC9BH,EAAY,OACLE,EAAK,UAAUE,GAAcC,CAAgB;CAGtD,OAAO;EAAE;EAAM;EAAmB;CAA0C;AAC9E"}
@@ -1,2 +1,2 @@
1
- const e=require("./_catalog.cjs");require("./_dev.cjs");const t=require("./_locale.cjs"),n=require("./_template.cjs"),r=require("./errors.cjs");function resolveMissing(e,t){if(e===`throw`)throw t.name?new r.LinguaMissingValueError(`Missing interpolation value "${t.name}" for key "${t.key}" in locale "${t.locale}".`):new r.LinguaMissingKeyError(`Missing translation key "${t.key}" in locale "${t.locale}".`);return typeof e==`function`?e(t):t.name?`{${t.name}}`:t.key}function createTranslatorFromCompiled(e,i={}){let a=t.canonicalLocale(i.locale??`en`),o=(Array.isArray(i.fallback)?i.fallback:i.fallback?[i.fallback]:[]).map(t.canonicalLocale),s=t.localeChain(a,o),c=i.missing,missingKey=e=>resolveMissing(c,{key:e,locale:a}),missingValue=(e,t)=>resolveMissing(c,{key:t,locale:a,name:e}),resolve=t=>{for(let n of s){let r=e.get(n)?.get(t);if(r)return{locale:n,message:r}}},templateFor=(e,n)=>{let i=resolve(e);if(!i)return;if(i.message.kind===`text`)return`count`in n?void 0:{key:e,template:i.message.template};if(!(`count`in n)||!Number.isFinite(n.count)){if(`count`in n)throw new r.LinguaInvalidPluralCountError("`count` must be a finite number.");return}let a=n.count===0&&!n.ordinal?`zero`:t.pluralCategory(i.locale,n.count,n.ordinal??!1),o=i.message.forms.get(a)??i.message.forms.get(`other`);return o?{key:e,template:o}:void 0},valuesFor=e=>`count`in e?{count:e.count,...e.values}:e.values??{},partsDynamic=(e,t)=>{let r=templateFor(e,t);return r?n.renderParts(r.template,valuesFor(t),e=>missingValue(e,r.key)):[{type:`text`,value:missingKey(e)}]},translateDynamic=(e,t={})=>{let r=templateFor(e,t);return r?n.renderText(r.template,valuesFor(t),e=>missingValue(e,r.key)):missingKey(e)};return{locale:a,parts(e,t){return partsDynamic(e,t)},partsDynamic,translate(e,t={}){return translateDynamic(e,t)},translateDynamic}}function createTranslator(n,r){let i=t.canonicalLocale(r?.locale??`en`);return createTranslatorFromCompiled(new Map([[i,e.compileCatalog(n)]]),{...r,locale:i})}exports.createTranslator=createTranslator,exports.createTranslatorFromCompiled=createTranslatorFromCompiled;
1
+ const e=require("./_catalog.cjs");require("./_dev.cjs");const t=require("./_locale.cjs"),n=require("./_template.cjs"),r=require("./errors.cjs");function resolveMissing(e,t){if(e===`throw`)throw t.name?new r.LinguaMissingValueError(`Missing interpolation value "${t.name}" for key "${t.key}" in locale "${t.locale}".`):new r.LinguaMissingKeyError(`Missing translation key "${t.key}" in locale "${t.locale}".`);return typeof e==`function`?e(t):t.name?`{${t.name}}`:t.key}function createTranslateEngine(e,i={}){let a=t.canonicalLocale(i.locale??`en`),o=(Array.isArray(i.fallback)?i.fallback:i.fallback?[i.fallback]:[]).map(t.canonicalLocale),s=t.localeChain(a,o),c=i.missing,missingKey=e=>resolveMissing(c,{key:e,locale:a}),missingValue=(e,t)=>resolveMissing(c,{key:t,locale:a,name:e}),resolve=t=>{for(let n of s){let r=e.get(n)?.get(t);if(r)return{locale:n,message:r}}},templateFor=(e,n)=>{let i=resolve(e);if(!i)return;if(i.message.kind===`text`)return`count`in n?void 0:i.message.template;if(!(`count`in n)||!Number.isFinite(n.count)){if(`count`in n)throw new r.LinguaInvalidPluralCountError("`count` must be a finite number.");return}let a=t.pluralCategory(i.locale,n.count,n.ordinal??!1);return i.message.forms.get(a)??i.message.forms.get(`other`)},translate=(e,t={})=>{let r=templateFor(e,t);if(!r)return missingKey(e);let i=`count`in t?{count:t.count,...t.values}:t.values??{};return n.renderText(r,i,t=>missingValue(t,e))};return{locale:a,translate}}function createTranslator(n,r){let i=createTranslateEngine(new Map([[t.canonicalLocale(r?.locale??`en`),e.compileCatalog(n)]]),r);return{locale:i.locale,translate:i.translate}}exports.createTranslateEngine=createTranslateEngine,exports.createTranslator=createTranslator;
2
2
  //# sourceMappingURL=translator.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"translator.cjs","names":["LinguaMissingValueError","LinguaMissingKeyError","canonicalLocale","localeChain","LinguaInvalidPluralCountError","pluralCategory","renderParts","renderText","compileCatalog","require__catalog","require__locale","require__template","require_errors","strategy","info","locale","options","fallback","chain","missing","candidate","message","catalogs","key","found","category","template","name","catalog"],"sources":["../src/translator.ts"],"sourcesContent":["import { type CompiledCatalog, type CompiledMessage, compileCatalog } from './_catalog';\nimport { isDev, warn } from './_dev';\nimport { canonicalLocale, localeChain, pluralCategory } from './_locale';\nimport { renderParts, renderText, type Template } from './_template';\nimport { LinguaInvalidPluralCountError, LinguaMissingKeyError, LinguaMissingValueError } from './errors';\nimport type {\n Catalog,\n Locale,\n MissingInfo,\n MissingStrategy,\n Part,\n PluralKey,\n PluralOptions,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n} from './types';\n\nexport type Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n parts<V>(key: TextKey<C>, options: TranslateOptions & { values: Record<string, V> }): Array<Part<V>>;\n parts<V>(key: PluralKey<C>, options: PluralOptions & { values?: Record<string, V> }): Array<Part<number | V>>;\n partsDynamic<V>(\n key: string,\n options: (TranslateOptions | PluralOptions) & { values?: Record<string, V> },\n ): Array<Part<number | V>>;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n translateDynamic(key: string, options?: TranslateOptions | PluralOptions): string;\n};\n\ntype InternalOptions = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n};\n\nfunction resolveMissing(strategy: MissingStrategy | undefined, info: MissingInfo): string {\n if (strategy === 'throw') {\n throw info.name\n ? new LinguaMissingValueError(\n `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`,\n )\n : new LinguaMissingKeyError(`Missing translation key \"${info.key}\" in locale \"${info.locale}\".`);\n }\n\n if (typeof strategy === 'function') return strategy(info);\n\n // 'key' or undefined (default)\n if (strategy === undefined && isDev) {\n warn(\n info.name\n ? `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`\n : `Missing translation key \"${info.key}\" in locale \"${info.locale}\".`,\n );\n }\n\n return info.name ? `{${info.name}}` : info.key;\n}\n\ntype ResolvedMessage = { readonly locale: Locale; readonly message: CompiledMessage };\n\nexport function createTranslatorFromCompiled<C extends Catalog>(\n catalogs: ReadonlyMap<Locale, CompiledCatalog>,\n options: InternalOptions = {},\n): Translator<C> {\n const locale = canonicalLocale(options.locale ?? 'en');\n const fallback = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const chain = localeChain(locale, fallback);\n const missing = options.missing;\n\n const missingKey = (key: string): string => resolveMissing(missing, { key, locale });\n const missingValue = (name: string, key: string): string => resolveMissing(missing, { key, locale, name });\n\n const resolve = (key: string): ResolvedMessage | undefined => {\n for (const candidate of chain) {\n const message = catalogs.get(candidate)?.get(key);\n\n if (message) return { locale: candidate, message };\n }\n\n return undefined;\n };\n\n const templateFor = (\n key: string,\n options: TranslateOptions | PluralOptions,\n ): { key: string; template: Template } | undefined => {\n const found = resolve(key);\n\n if (!found) return undefined;\n\n if (found.message.kind === 'text') {\n if ('count' in options) return undefined;\n\n return { key, template: found.message.template };\n }\n\n if (!('count' in options) || !Number.isFinite(options.count)) {\n if ('count' in options) throw new LinguaInvalidPluralCountError('`count` must be a finite number.');\n\n return undefined;\n }\n\n const category =\n options.count === 0 && !options.ordinal\n ? 'zero'\n : pluralCategory(found.locale, options.count, options.ordinal ?? false);\n const template = found.message.forms.get(category) ?? found.message.forms.get('other');\n\n return template ? { key, template } : undefined;\n };\n\n const valuesFor = (options: TranslateOptions | PluralOptions): Record<string, unknown> =>\n 'count' in options ? { count: options.count, ...options.values } : (options.values ?? {});\n\n const partsDynamic = <V>(\n key: string,\n options: (TranslateOptions | PluralOptions) & { values?: Record<string, V> },\n ): Array<Part<number | V>> => {\n const found = templateFor(key, options);\n\n if (!found) return [{ type: 'text', value: missingKey(key) }];\n\n return renderParts(found.template, valuesFor(options) as Record<string, V | number>, (name) =>\n missingValue(name, found.key),\n );\n };\n\n const translateDynamic = (key: string, options: TranslateOptions | PluralOptions = {}): string => {\n const found = templateFor(key, options);\n\n if (!found) return missingKey(key);\n\n return renderText(found.template, valuesFor(options), (name) => missingValue(name, found.key));\n };\n\n return {\n locale,\n parts(key: string, options: (TranslateOptions | PluralOptions) & { values?: Record<string, unknown> }) {\n return partsDynamic(key, options);\n },\n partsDynamic,\n translate(key: string, options: TranslateOptions | PluralOptions = {}) {\n return translateDynamic(key, options);\n },\n translateDynamic,\n } as Translator<C>;\n}\n\n/** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */\nexport function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C> {\n const locale = canonicalLocale(options?.locale ?? 'en');\n const compiled = new Map<Locale, CompiledCatalog>([[locale, compileCatalog(catalog)]]);\n\n return createTranslatorFromCompiled<C>(compiled, { ...options, locale });\n}\n"],"mappings":"A,gJAqCA,SAAS,eAAe,EAAuC,EAA2B,CACxF,GAAIa,IAAa,QACf,MAAMC,EAAK,KACP,IAAId,EAAAA,wBACF,gCAAgCc,EAAK,KAAK,aAAaA,EAAK,IAAI,eAAeA,EAAK,OAAO,GAC7F,EACA,IAAIb,EAAAA,sBAAsB,4BAA4Ba,EAAK,IAAI,eAAeA,EAAK,OAAO,GAAG,EAcnG,OAXI,OAAOD,GAAa,WAAmBA,EAASC,CAAI,EAWjDA,EAAK,KAAO,IAAIA,EAAK,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AI,IAAA,EACxC,EAEM,UAAa,GACjB,UAAWV,EAAU,CAAE,MAAOA,EAAQ,MAAO,GAAGA,EAAQ,MAAO,EAAKA,EAAQ,QAAU,CAAC,EAEnF,cACJ,EACA,IAC4B,CAC5B,IAAMQ,EAAQ,YAAYD,EAAKP,CAAO,EAItC,OAFKQ,EAEElB,EAAAA,YAAYkB,EAAM,SAAU,UAAUR,CAAO,EAAkC,GACpF,aAAaW,EAAMH,EAAM,GAAG,CAC9B,EAJmB,CAAC,CAAE,KAAM,OAAQ,MAAO,WAAWD,CAAG,CAAE,CAAC,CAK9D,EAEM,kBAAoB,EAAa,EAA4C,CAAC,IAAc,CAChG,IAAMC,EAAQ,YAAYD,EAAKP,CAAO,EAItC,OAFKQ,EAEEjB,EAAAA,WAAWiB,EAAM,SAAU,UAAUR,CAAO,EAAI,GAAS,aAAaW,EAAMH,EAAM,GAAG,CAAC,EAF1E,WAAWD,CAAG,CAGnC,EAEA,MAAO,CACL,SACA,MAAM,EAAa,EAAoF,CACrG,OAAO,aAAaA,EAAKP,CAAO,CAClC,EACA,aACA,UAAU,EAAa,EAA4C,CAAC,EAAG,CACrE,OAAO,iBAAiBO,EAAKP,CAAO,CACtC,EACA,gBACF,CACF,CAGA,SAAgB,iBAAoC,EAAY,EAA4C,CAC1G,IAAMD,EAASb,EAAAA,gBAAgBc,GAAS,QAAU,IAAI,EAGtD,OAAO,6BAAgC,IAFlB,IAA6B,CAAC,CAACD,EAAQP,EAAAA,eAAeoB,CAAO,CAAC,CAAC,CAE7C,EAAU,CAAE,GAAGZ,EAAS,QAAO,CAAC,CACzE,C"}
1
+ {"version":3,"file":"translator.cjs","names":["LinguaMissingValueError","LinguaMissingKeyError","canonicalLocale","localeChain","LinguaInvalidPluralCountError","pluralCategory","renderText","compileCatalog","require__catalog","require__locale","require__template","require_errors","strategy","info","locale","options","fallback","chain","missing","candidate","message","catalogs","key","found","category","template","values","name","engine","catalog"],"sources":["../src/translator.ts"],"sourcesContent":["import { type CompiledCatalog, type CompiledMessage, compileCatalog } from './_catalog';\nimport { isDev, warn } from './_dev';\nimport { canonicalLocale, localeChain, pluralCategory } from './_locale';\nimport { renderText, type Template } from './_template';\nimport { LinguaInvalidPluralCountError, LinguaMissingKeyError, LinguaMissingValueError } from './errors';\nimport type {\n Catalog,\n Locale,\n MissingInfo,\n MissingStrategy,\n PluralKey,\n PluralOptions,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n} from './types';\n\nexport type Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n};\n\n/** Loose translate signature implemented by the engine; public overloads restrict keys per catalog type. */\nexport type LooseTranslate = (key: string, options?: TranslateOptions | PluralOptions) => string;\n\nfunction resolveMissing(strategy: MissingStrategy | undefined, info: MissingInfo): string {\n if (strategy === 'throw') {\n throw info.name\n ? new LinguaMissingValueError(\n `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`,\n )\n : new LinguaMissingKeyError(`Missing translation key \"${info.key}\" in locale \"${info.locale}\".`);\n }\n\n if (typeof strategy === 'function') return strategy(info);\n\n // 'key' or undefined (default)\n if (strategy === undefined && isDev) {\n warn(\n info.name\n ? `Missing interpolation value \"${info.name}\" for key \"${info.key}\" in locale \"${info.locale}\".`\n : `Missing translation key \"${info.key}\" in locale \"${info.locale}\".`,\n );\n }\n\n return info.name ? `{${info.name}}` : info.key;\n}\n\n/** Internal engine: resolves and renders any string key against compiled catalogs for a fixed locale. */\nexport function createTranslateEngine(\n catalogs: ReadonlyMap<Locale, CompiledCatalog>,\n options: InternalOptions = {},\n): { readonly locale: Locale; readonly translate: LooseTranslate } {\n const locale = canonicalLocale(options.locale ?? 'en');\n const fallback = (\n Array.isArray(options.fallback) ? options.fallback : options.fallback ? [options.fallback] : []\n ).map(canonicalLocale);\n const chain = localeChain(locale, fallback);\n const missing = options.missing;\n\n const missingKey = (key: string): string => resolveMissing(missing, { key, locale });\n const missingValue = (name: string, key: string): string => resolveMissing(missing, { key, locale, name });\n\n const resolve = (key: string): { readonly locale: Locale; readonly message: CompiledMessage } | undefined => {\n for (const candidate of chain) {\n const message = catalogs.get(candidate)?.get(key);\n\n if (message) return { locale: candidate, message };\n }\n\n return undefined;\n };\n\n const templateFor = (key: string, options: TranslateOptions | PluralOptions): Template | undefined => {\n const found = resolve(key);\n\n if (!found) return undefined;\n\n if (found.message.kind === 'text') {\n if ('count' in options) return undefined;\n\n return found.message.template;\n }\n\n if (!('count' in options) || !Number.isFinite(options.count)) {\n if ('count' in options) throw new LinguaInvalidPluralCountError('`count` must be a finite number.');\n\n return undefined;\n }\n\n const category = pluralCategory(found.locale, options.count, options.ordinal ?? false);\n\n return found.message.forms.get(category) ?? found.message.forms.get('other');\n };\n\n const translate = (key: string, options: TranslateOptions | PluralOptions = {}): string => {\n const template = templateFor(key, options);\n\n if (!template) return missingKey(key);\n\n const values: Record<string, unknown> =\n 'count' in options ? { count: options.count, ...options.values } : (options.values ?? {});\n\n return renderText(template, values, (name) => missingValue(name, key));\n };\n\n return { locale, translate };\n}\n\ntype InternalOptions = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n};\n\n/** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */\nexport function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C> {\n const engine = createTranslateEngine(\n new Map([[canonicalLocale(options?.locale ?? 'en'), compileCatalog(catalog)]]),\n options,\n );\n\n return { locale: engine.locale, translate: engine.translate };\n}\n"],"mappings":"A,gJA0BA,SAAS,eAAe,EAAuC,EAA2B,CACxF,GAAIY,IAAa,QACf,MAAMC,EAAK,KACP,IAAIb,EAAAA,wBACF,gCAAgCa,EAAK,KAAK,aAAaA,EAAK,IAAI,eAAeA,EAAK,OAAO,GAC7F,EACA,IAAIZ,EAAAA,sBAAsB,4BAA4BY,EAAK,IAAI,eAA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CAC7E,EAEM,WAAa,EAAa,EAA4C,CAAC,IAAc,CACzF,IAAME,EAAW,YAAYH,EAAKP,CAAO,EAEzC,GAAI,CAACU,EAAU,OAAO,WAAWH,CAAG,EAEpC,IAAMI,EACJ,UAAWX,EAAU,CAAE,MAAOA,EAAQ,MAAO,GAAGA,EAAQ,MAAO,EAAKA,EAAQ,QAAU,CAAC,EAEzF,OAAOT,EAAAA,WAAWmB,EAAUC,EAAS,GAAS,aAAaC,EAAML,CAAG,CAAC,CACvE,EAEA,MAAO,CAAE,SAAQ,SAAU,CAC7B,CASA,SAAgB,iBAAoC,EAAY,EAA4C,CAC1G,IAAMM,EAAS,sBACb,IAAI,IAAI,CAAC,CAAC1B,EAAAA,gBAAgBa,GAAS,QAAU,IAAI,EAAGR,EAAAA,eAAesB,CAAO,CAAC,CAAC,CAAC,EAC7Ed,CACF,EAEA,MAAO,CAAE,OAAQa,EAAO,OAAQ,UAAWA,EAAO,SAAU,CAC9D,C"}
@@ -1,26 +1,22 @@
1
1
  import { type CompiledCatalog } from './_catalog';
2
- import type { Catalog, Locale, MissingStrategy, Part, PluralKey, PluralOptions, TextKey, TranslateOptions, TranslatorOptions } from './types';
2
+ import type { Catalog, Locale, MissingStrategy, PluralKey, PluralOptions, TextKey, TranslateOptions, TranslatorOptions } from './types';
3
3
  export type Translator<C extends Catalog = Catalog> = {
4
4
  readonly locale: Locale;
5
- parts<V>(key: TextKey<C>, options: TranslateOptions & {
6
- values: Record<string, V>;
7
- }): Array<Part<V>>;
8
- parts<V>(key: PluralKey<C>, options: PluralOptions & {
9
- values?: Record<string, V>;
10
- }): Array<Part<number | V>>;
11
- partsDynamic<V>(key: string, options: (TranslateOptions | PluralOptions) & {
12
- values?: Record<string, V>;
13
- }): Array<Part<number | V>>;
14
5
  translate(key: TextKey<C>, options?: TranslateOptions): string;
15
6
  translate(key: PluralKey<C>, options: PluralOptions): string;
16
- translateDynamic(key: string, options?: TranslateOptions | PluralOptions): string;
7
+ };
8
+ /** Loose translate signature implemented by the engine; public overloads restrict keys per catalog type. */
9
+ export type LooseTranslate = (key: string, options?: TranslateOptions | PluralOptions) => string;
10
+ /** Internal engine: resolves and renders any string key against compiled catalogs for a fixed locale. */
11
+ export declare function createTranslateEngine(catalogs: ReadonlyMap<Locale, CompiledCatalog>, options?: InternalOptions): {
12
+ readonly locale: Locale;
13
+ readonly translate: LooseTranslate;
17
14
  };
18
15
  type InternalOptions = {
19
16
  readonly fallback?: Locale | readonly Locale[];
20
17
  readonly locale?: Locale;
21
18
  readonly missing?: MissingStrategy;
22
19
  };
23
- export declare function createTranslatorFromCompiled<C extends Catalog>(catalogs: ReadonlyMap<Locale, CompiledCatalog>, options?: InternalOptions): Translator<C>;
24
20
  /** Creates a fixed-locale translator from one catalog. Lingua snapshots catalog messages during construction. */
25
21
  export declare function createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C>;
26
22
  export {};