@menapo/vi18n 0.1.1 → 0.2.0

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 (121) hide show
  1. package/README.md +19 -0
  2. package/dist/{apply-Bre-lY9J.js → apply-Bg-3rB2m.js} +69 -89
  3. package/dist/{captured-Bj8bO6vd.js → captured-DfLk50Ji.js} +196 -217
  4. package/dist/{check-BIKEuu6B.js → check-CunekuYs.js} +76 -85
  5. package/dist/cli.js +2 -3
  6. package/dist/{collect-Cx4_SKOe.js → collect-CYATDjdo.js} +1 -2
  7. package/dist/collisions-CDSdtLQm.js +215 -0
  8. package/dist/{compile-Cc97JaW2.js → compile-DqkofbiO.js} +376 -331
  9. package/dist/compile-hva0qjhZ.js +240 -0
  10. package/dist/concurrency-BCY_4zcr.js +1 -0
  11. package/dist/concurrency-Dy2ny50V.js +107 -0
  12. package/dist/config.d.ts +1 -5
  13. package/dist/config.js +4 -5
  14. package/dist/{types-D3QGM8XO.js → diagnostics-LgIWyeSp.js} +28 -27
  15. package/dist/{dir-zw6bGMKQ.js → dir-TGLYuOZb.js} +34 -37
  16. package/dist/{duplicates-yuRljQ6h.js → duplicates-8cudcHNj.js} +10 -27
  17. package/dist/engine-ecRD8-IE.js +556 -0
  18. package/dist/engine.d.ts +1 -5
  19. package/dist/engine.js +297 -168
  20. package/dist/exchange-DjwlrTQ9.js +41 -0
  21. package/dist/{exclude-Du-Zd_qI.js → exclude-BFETmvde.js} +2 -3
  22. package/dist/{export-C9Sy6UWv.js → export-D2tsqWIr.js} +17 -38
  23. package/dist/{extract-C3S8btx0.js → extract-BxYchVmY.js} +114 -82
  24. package/dist/{formats-9unqj_fZ.js → formats-BaryZ2N7.js} +352 -276
  25. package/dist/fs-ezCMZeDV.js +52 -0
  26. package/dist/i18next-COO6o0tX.js +1907 -0
  27. package/dist/i18next-Dr7DCQlQ.js +1 -0
  28. package/dist/{import-nANvQutw.js → import-vSC29Cn4.js} +81 -75
  29. package/dist/index.d.ts +1 -13
  30. package/dist/index.js +14 -16
  31. package/dist/{init-C2ScuW6a.js → init-Cc7A-8VX.js} +466 -501
  32. package/dist/{library-D5CWvTQs.js → library-tp_xqzSY.js} +975 -451
  33. package/dist/lingui-BnnlqGXT.js +902 -0
  34. package/dist/lint.d.ts +0 -4
  35. package/dist/lint.js +70 -82
  36. package/dist/{load-gW-oJt1Q.js → load-BSIeGJ5v.js} +275 -148
  37. package/dist/{load-CQRz4PpM.js → load-SSrAeJVB.js} +1214 -1116
  38. package/dist/{locales-DX4MOBFE.js → locales-D0U-yVRm.js} +271 -237
  39. package/dist/{lsp-RMMMc88P.js → lsp-DvC11pBZ.js} +4 -5
  40. package/dist/{match-BGr8EXB3.js → match-BLDcj610.js} +11 -4
  41. package/dist/{mcp-CHVwBoRP.js → mcp-D2zzOTBy.js} +4 -5
  42. package/dist/{merge-driver-BTX87aVm.js → merge-driver-BLI8OtAc.js} +138 -122
  43. package/dist/migrate-1r43OBfe.js +1 -0
  44. package/dist/migrate-ChDGhlC-.js +2169 -0
  45. package/dist/{openai-CTaMDcl-.js → openai-CLn4puY8.js} +128 -87
  46. package/dist/{output-DWE3SIUA.js → output-D5tAt8q4.js} +15 -9
  47. package/dist/parse.d.ts +1 -3
  48. package/dist/parse.js +7 -8
  49. package/dist/{pipeline-C9Dbotkh.js → pipeline-BJSkkRYC.js} +387 -359
  50. package/dist/{pipeline-DbX6rlo5.js → pipeline-BeCc441z.js} +1 -1
  51. package/dist/project-B5KIO0q-.js +544 -0
  52. package/dist/{pseudo-DRv30iN5.js → pseudo-B2DUpoLu.js} +126 -3
  53. package/dist/{raw-C4Y6vyGY.js → raw-YsYZMS9n.js} +52 -29
  54. package/dist/react-intl-C8JehBBL.js +634 -0
  55. package/dist/rename-ZVGq9ZG1.js +577 -0
  56. package/dist/repeated-uuI1tUGg.js +85 -0
  57. package/dist/restore-xlBIrtRt.js +199 -0
  58. package/dist/rewrite-BwzXoBiA.js +415 -0
  59. package/dist/{rich-DCUKl5HM.js → rich-ApY1Dm4S.js} +35 -28
  60. package/dist/rolldown-runtime-C1I3wEg2.js +43 -0
  61. package/dist/{rolldown-runtime-D7D4PA-g.js → rolldown-runtime-D8jQpDG7.js} +1 -2
  62. package/dist/run-CQ9pDLSa.js +674 -0
  63. package/dist/scan-worker.d.ts +2 -4
  64. package/dist/scan-worker.js +1 -1
  65. package/dist/{scoped-BMYpSthj.js → scoped-h3KE8XWW.js} +3 -4
  66. package/dist/{server-Da1Ot9IN.js → server-Br8tAuG2.js} +312 -386
  67. package/dist/{server-deBOq2vq.js → server-DJRpUQVZ.js} +1059 -333
  68. package/dist/server.d.ts +1 -17
  69. package/dist/server.js +419 -379
  70. package/dist/{sitemap-DJXzKoza.js → sitemap-CSAkm6oi.js} +21 -33
  71. package/dist/{sources-D19czDSA.js → sources-DNVbYsgs.js} +713 -373
  72. package/dist/{status-zr4jY59Y.js → status-q6M3rBrh.js} +30 -30
  73. package/dist/{stdio-FPOKQAgu.js → stdio-D9kTzyqB.js} +2 -4
  74. package/dist/{stdio-CVaJfxA7.js → stdio-FWIVU3P4.js} +1 -2
  75. package/dist/sync-BNIAwMhR.js +1352 -0
  76. package/dist/{t-DC-c9zE5.js → t-gvEXx25s.js} +76 -53
  77. package/dist/test.d.ts +5 -16
  78. package/dist/test.js +126 -56
  79. package/dist/translate-BP4iVhOR.js +336 -0
  80. package/dist/{ts-BaU5yOf0.js → ts-BX6kwig5.js} +25 -14
  81. package/dist/{types-DtvQ7UdD.js → types-3kwyaCAm.js} +1 -2
  82. package/dist/{types-DsdWBG0b.d.ts → types-B4wNX6PA.d.ts} +6 -8
  83. package/dist/{types-CgUCkFU1.d.ts → types-_4UdFhR9.d.ts} +24 -21
  84. package/dist/types-xR2exI3L.js +42 -0
  85. package/dist/{units-CQ5Q99RC.js → units-DPPfCN7j.js} +7 -16
  86. package/dist/{url-CRfCOhUI.js → url-Bpc6wLea.js} +24 -11
  87. package/dist/{url-CsBkRaJy.js → url-D2_VlEeH.js} +25 -12
  88. package/dist/{validate-BxpupdAf.js → validate-CgzaDdOY.js} +690 -377
  89. package/dist/{validate-D6DJepZv.js → validate-PGgMsasz.js} +3 -5
  90. package/dist/{version-Byqi2guX.js → version-DC-J5WvV.js} +3 -5
  91. package/dist/{vite-scan-CT_vsp4g.js → vite-scan-kM8Ta3rO.js} +87 -92
  92. package/dist/vite.d.ts +2 -6
  93. package/dist/vite.js +6500 -6032
  94. package/dist/vue-i18n-_uIXlFVh.js +806 -0
  95. package/dist/{which-BOemZ5Q8.js → which-DFWk_KwN.js} +44 -37
  96. package/dist/{worker-84U6uYB3.js → worker-zlhNj4y3.js} +454 -608
  97. package/package.json +5 -5
  98. package/dist/check-HsmmpJZg.js +0 -1
  99. package/dist/codec-DuvU2VQy.js +0 -207
  100. package/dist/collisions-CfpZU8e4.js +0 -217
  101. package/dist/compile-BaDh0cHG.js +0 -245
  102. package/dist/concurrency-C9UUWuDC.js +0 -96
  103. package/dist/concurrency-DONL7t4V.js +0 -1
  104. package/dist/engine-C2ENBRJe.js +0 -531
  105. package/dist/i18next-9HAoxwUI.js +0 -1
  106. package/dist/i18next-BEJgv_S8.js +0 -1596
  107. package/dist/lingui-zUiCl9Um.js +0 -833
  108. package/dist/messages-BfjIExyB.js +0 -166
  109. package/dist/migrate-IpLDMXmq.js +0 -1484
  110. package/dist/migrate-rCQuOGsf.js +0 -1
  111. package/dist/project-Bw9UPIdx.js +0 -1046
  112. package/dist/project-C4GpaN-n.js +0 -381
  113. package/dist/react-intl-BP0u-D5m.js +0 -519
  114. package/dist/restore-CiYv-jxS.js +0 -175
  115. package/dist/rewrite-EsIw_lsq.js +0 -803
  116. package/dist/run-BEcnBbu-.js +0 -694
  117. package/dist/runtime-DTMmliT1.js +0 -64
  118. package/dist/sync-B9V2KFwb.js +0 -658
  119. package/dist/translate-CQnJfLjO.js +0 -299
  120. package/dist/types-wSh9fCBY.js +0 -11
  121. package/dist/vue-i18n-g0iGy6CZ.js +0 -651
@@ -1,13 +1,217 @@
1
- import { a as printICU, d as diagnosticError, f as isDiagnosticError, i as normalizeSource, r as isPlainText, s as parseSource, t as compileMessage } from "./compile-Cc97JaW2.js";
2
- import { n as validateTranslation } from "./validate-D6DJepZv.js";
3
- import { t as pseudoLocalize } from "./pseudo-DRv30iN5.js";
1
+ import { a as ID_LENGTH, i as DEFAULT_IMPORT_SOURCES, n as CONFIG_FILE, o as PSEUDO_LOCALES, r as DEFAULT_CONFIG, t as pseudoLocalize } from "./pseudo-B2DUpoLu.js";
2
+ import { a as printICU, d as diagnosticError, f as isDiagnosticError, i as normalizeSource, r as isPlainText, s as parseSource, t as compileMessage } from "./compile-DqkofbiO.js";
3
+ import { n as validateTranslation } from "./validate-PGgMsasz.js";
4
4
  import { hash } from "node:crypto";
5
5
  import { readFile, stat } from "node:fs/promises";
6
6
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
7
  import { existsSync, readFileSync, realpathSync } from "node:fs";
8
8
  import { pathToFileURL } from "node:url";
9
9
  import { z } from "zod";
10
- //#region src/core/catalog/validity.ts
10
+ // src/core/extract/paths.ts
11
+ /**
12
+ * Path and file-system helpers the file walk, the opted-in packages, the
13
+ * project scan and wrapper resolution share, so they agree on what a module
14
+ * id names and which files are scanned.
15
+ */
16
+ /** Posix form of a native path; `\` never occurs in posix names worth keeping. */
17
+ function toPosix(path) {
18
+ return sep === "/" ? path : path.replaceAll("\\", "/");
19
+ }
20
+ /** A file or directory that is not there. */
21
+ const MISSING = /* @__PURE__ */ new Set(["ENOENT", "ENOTDIR"]);
22
+ // src/core/extract/dependencies.ts
23
+ /**
24
+ * `extraction.dependencies` (PLAN §4.5, §5.24; INTERNALS §2.5.7): published
25
+ * packages the app opts in. Each name resolves from the config root the way
26
+ * Node resolves a package directory (`node_modules/<name>` in the root or a
27
+ * directory above it), by realpath, which is what Vite hands the plugin under
28
+ * pnpm's links. Their files are extracted and rewritten like the app's,
29
+ * except the package's own `node_modules`, tests and declarations, and their
30
+ * catalog references read `<name>/<path in the package>`, the same on every
31
+ * machine and package manager and across the package's versions.
32
+ */
33
+ const resolved = /* @__PURE__ */ new WeakMap();
34
+ /**
35
+ * Every `extraction.dependencies` package, resolved once per config. A
36
+ * name that does not resolve is a `config-invalid` error: its strings would
37
+ * otherwise ship untranslated and unreported.
38
+ */
39
+ function dependenciesOf(config) {
40
+ let list = resolved.get(config.extraction);
41
+ if (list !== void 0) return list;
42
+ list = [];
43
+ for (const name of config.extraction.dependencies) {
44
+ const dir = packageDir(config.root, name);
45
+ if (dir === null) throw diagnosticError({
46
+ code: "config-invalid",
47
+ severity: "error",
48
+ message: `extraction.dependencies: ${name} is not installed (no node_modules/${name} from ${toPosix(config.root)} up); add it to the app's dependencies`
49
+ });
50
+ list.push({
51
+ name,
52
+ dir,
53
+ messages: messagesFile(dir)
54
+ });
55
+ }
56
+ resolved.set(config.extraction, list);
57
+ return list;
58
+ }
59
+ /** The package directory as Node finds it from `root`, by realpath; null when not installed. */
60
+ function packageDir(root, name) {
61
+ let dir = resolve(root);
62
+ for (;;) {
63
+ const candidate = join(dir, "node_modules", name);
64
+ if (existsSync(join(candidate, "package.json"))) return toPosix(realpathSync(candidate)).replace(/\/+$/, "");
65
+ const parent = dirname(dir);
66
+ if (parent === dir) return null;
67
+ dir = parent;
68
+ }
69
+ }
70
+ /** `package.json#vi18n.messages`, absolute; null without one (or an unreadable manifest). */
71
+ function messagesFile(dir) {
72
+ try {
73
+ const path = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).vi18n?.messages;
74
+ return typeof path === "string" && path !== "" ? toPosix(resolve(dir, path)) : null;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+ // src/core/extract/files.ts
80
+ /** `file` relative to `root` in posix form for messages, or the whole path when it lies outside `root`. */
81
+ function displayPath(root, file) {
82
+ const rel = relative(root, file);
83
+ return toPosix(rel === "" || rel.startsWith("..") || isAbsolute(rel) ? file : rel);
84
+ }
85
+ [...MISSING];
86
+ // src/core/id/hash.ts
87
+ /**
88
+ * Ids (INTERNALS §2.2.1, §2.2.3, PLAN §5.5). An id depends only on its own
89
+ * canonical text and `ids.length`, so every process computes it alone and
90
+ * nothing is ever recorded. Frozen by the golden vectors: changing anything
91
+ * here re-keys every catalog.
92
+ */
93
+ /**
94
+ * Lingui's construction with an empty context (`text + "\u001F"`), so a Lingui
95
+ * 6 id of the same canonical text is a prefix of the vi18n id.
96
+ */
97
+ function sourceHash(canonical) {
98
+ return hash("sha256", canonical + "", "base64url");
99
+ }
100
+ function idScheme(length) {
101
+ return `sha256-b64u-${length}-v2`;
102
+ }
103
+ const SCHEME = /^sha256-b64u-(8|9|1[0-6])-v2$/;
104
+ /** The id length a catalog header records, or null for anything vi18n did not write. */
105
+ function parseIdScheme(tag) {
106
+ const match = SCHEME.exec(tag);
107
+ return match === null ? null : {
108
+ length: Number(match[1]),
109
+ version: 2
110
+ };
111
+ }
112
+ /** The base64url alphabet has no `.`, so a `.` is what marks a manual id. */
113
+ function isManualId(id) {
114
+ return id.includes(".");
115
+ }
116
+ /** Characters that need no escaping in JS, JSON, PO, file names or URLs, with at least one `.`. */
117
+ const MANUAL_ID = /^[A-Za-z0-9_:-]+(\.[A-Za-z0-9_:-]+)+$/;
118
+ function isValidManualId(id) {
119
+ return MANUAL_ID.test(id);
120
+ }
121
+ // src/core/codec.ts
122
+ /**
123
+ * The one place that turns source text into ids (INTERNALS §2.2). Extract,
124
+ * catalogs and compilation see the same message many times per run, so parses,
125
+ * canonical forms and hashes are memoised per string.
126
+ */
127
+ /**
128
+ * Memo entries past this count are dropped all at once: a long dev session
129
+ * sees every edit of every message, while one scan of a large project needs
130
+ * the whole set warm.
131
+ */
132
+ const MEMO_LIMIT = 2e5;
133
+ /**
134
+ * What `parseICU` returns for text without syntax characters: no node for
135
+ * "", else one literal (most sources and translations). An MF2 complex
136
+ * message is lowered to the same AST (INTERNALS §2.1.4), so its canonical
137
+ * form, id and catalog entry are ICU.
138
+ */
139
+ function parseNormalized(normalized) {
140
+ if (!isPlainText(normalized)) return parseSource(normalized);
141
+ return normalized === "" ? [] : [{
142
+ type: "literal",
143
+ value: normalized
144
+ }];
145
+ }
146
+ function createCodec(idLength) {
147
+ if (!Number.isInteger(idLength) || idLength < ID_LENGTH.min || idLength > ID_LENGTH.max) throw diagnosticError({
148
+ code: "config-invalid",
149
+ severity: "error",
150
+ message: `ids.length must be an integer from ${ID_LENGTH.min} to ${ID_LENGTH.max}, not ${String(idLength)}`
151
+ });
152
+ const parsed = /* @__PURE__ */ new Map();
153
+ const hashes = /* @__PURE__ */ new Map();
154
+ /** `normalized` is passed when the caller already normalised `source`. */
155
+ const entry = (source, normalized) => {
156
+ let found = parsed.get(source);
157
+ if (found === void 0) {
158
+ try {
159
+ found = {
160
+ ast: parseNormalized(normalized ?? normalizeSource(source)),
161
+ canonical: null
162
+ };
163
+ } catch (error) {
164
+ if (!isDiagnosticError(error)) throw error;
165
+ found = { error };
166
+ }
167
+ if (parsed.size >= MEMO_LIMIT) parsed.clear();
168
+ parsed.set(source, found);
169
+ }
170
+ return found;
171
+ };
172
+ const hashOf = (canonical) => {
173
+ let found = hashes.get(canonical);
174
+ if (found === void 0) {
175
+ found = sourceHash(canonical);
176
+ if (hashes.size >= MEMO_LIMIT) hashes.clear();
177
+ hashes.set(canonical, found);
178
+ }
179
+ return found;
180
+ };
181
+ return {
182
+ idLength,
183
+ idScheme: idScheme(idLength),
184
+ canonicalize(source) {
185
+ let memo = parsed.get(source);
186
+ if (memo === void 0) {
187
+ const normalized = normalizeSource(source);
188
+ if (isPlainText(normalized)) return normalized;
189
+ memo = entry(source, normalized);
190
+ }
191
+ if ("error" in memo) throw memo.error;
192
+ return memo.canonical ??= printICU(memo.ast);
193
+ },
194
+ parse(source) {
195
+ const memo = entry(source);
196
+ if ("error" in memo) throw memo.error;
197
+ return memo.ast;
198
+ },
199
+ sourceHash: hashOf,
200
+ label(canonical) {
201
+ return hashOf(canonical).slice(0, idLength);
202
+ }
203
+ };
204
+ }
205
+ /** `codec.canonicalize(text)`, or null when `text` is not valid ICU; any other error is a bug and is rethrown. */
206
+ function tryCanonicalize(codec, text) {
207
+ try {
208
+ return codec.canonicalize(text);
209
+ } catch (error) {
210
+ if (isDiagnosticError(error)) return null;
211
+ throw error;
212
+ }
213
+ }
214
+ // src/core/catalog/validity.ts
11
215
  function sourceMatches(entry, layout, message, codec) {
12
216
  if (layout === "id") return entry.label !== null && entry.label === message.label;
13
217
  const source = entry.source;
@@ -15,14 +219,24 @@ function sourceMatches(entry, layout, message, codec) {
15
219
  if (source === message.canonical) return true;
16
220
  return entryCanonical(entry, codec) === message.canonical;
17
221
  }
18
- //#endregion
19
- //#region src/core/catalog/model.ts
222
+ // src/core/catalog/model.ts
20
223
  /**
21
224
  * The catalog model shared by every reader, writer and consumer (INTERNALS
22
225
  * §2.6.2, §2.6.5, §2.6.7): how an entry is keyed, how entries sort, and when
23
226
  * a translation may ship. Formats (`po.ts`, `json.ts`) and files (`io.ts`)
24
227
  * build on these; nothing here touches the file system.
25
228
  */
229
+ /** A header with every field present, as `createEntry` is for entries. */
230
+ function emptyHeader(locale, fields = {}) {
231
+ return {
232
+ language: locale,
233
+ idScheme: null,
234
+ sourceLocale: null,
235
+ aiModel: null,
236
+ extra: [],
237
+ ...fields
238
+ };
239
+ }
26
240
  const canonicals = /* @__PURE__ */ new WeakMap();
27
241
  /**
28
242
  * `codec.canonicalize(entry.source)`, memoised on the entry (catalog load,
@@ -35,13 +249,7 @@ function entryCanonical(entry, codec) {
35
249
  if (source === null) return null;
36
250
  const memo = canonicals.get(entry);
37
251
  if (memo !== void 0 && memo.source === source) return memo.canonical;
38
- let canonical;
39
- try {
40
- canonical = codec.canonicalize(source);
41
- } catch (error) {
42
- if (!isDiagnosticError(error)) throw error;
43
- canonical = null;
44
- }
252
+ const canonical = tryCanonicalize(codec, source);
45
253
  canonicals.set(entry, {
46
254
  source,
47
255
  canonical
@@ -49,6 +257,51 @@ function entryCanonical(entry, codec) {
49
257
  return canonical;
50
258
  }
51
259
  /**
260
+ * An empty translation is untranslated whatever the file says; a filled one
261
+ * is `ai` only when marked so, which also covers one typed by someone who
262
+ * left an `untranslated` marker alone.
263
+ */
264
+ function entryStateOf(translation, ai) {
265
+ if (translation === "") return "untranslated";
266
+ return ai ? "ai" : "translated";
267
+ }
268
+ /** Which copy of an entry wins when two disagree: `translated` over `ai` over `untranslated`. */
269
+ const STATE_RANK = {
270
+ translated: 2,
271
+ ai: 1,
272
+ untranslated: 0
273
+ };
274
+ /** The stricter of two `maxLength` limits, null meaning none: safe whichever one a translator honoured. */
275
+ function stricterLimit(a, b) {
276
+ if (a === null) return b;
277
+ if (b === null) return a;
278
+ return Math.min(a, b);
279
+ }
280
+ /** A flag's identity: both line kinds have two characters, so the key names one flag. */
281
+ function flagKey(flag) {
282
+ return flag.line + flag.name;
283
+ }
284
+ /**
285
+ * `values` sorted (UTF-16 order, as `compareText`) without repeats; the input
286
+ * itself when it has fewer than two values, so the common case allocates nothing.
287
+ */
288
+ function sortedUnique(values) {
289
+ if (values.length < 2) return values;
290
+ const sorted = values.slice().sort();
291
+ let kept = 1;
292
+ for (let read = 1; read < sorted.length; read++) if (sorted[read] !== sorted[kept - 1]) sorted[kept++] = sorted[read];
293
+ sorted.length = kept;
294
+ return sorted;
295
+ }
296
+ function defineField(into, field, value) {
297
+ Object.defineProperty(into, field, {
298
+ value,
299
+ enumerable: true,
300
+ writable: true,
301
+ configurable: true
302
+ });
303
+ }
304
+ /**
52
305
  * The key that joins an entry to code. Null for foreign contexts (never
53
306
  * matched) and for `"source"`-layout entries whose source does not parse,
54
307
  * which consumers report on the source instead.
@@ -87,31 +340,30 @@ function usableTranslation(entry, layout, message, codec, locale) {
87
340
  reason: "fuzzy",
88
341
  diagnostics: []
89
342
  };
343
+ const errors = translationErrors(entry.translation, message.canonical, codec, locale);
344
+ if (errors.length > 0) return {
345
+ ok: false,
346
+ reason: "invalid",
347
+ diagnostics: errors.map((error) => withSubject(error, locale, message.id, entry.line))
348
+ };
349
+ return {
350
+ ok: true,
351
+ parsed: codec.parse(entry.translation)
352
+ };
353
+ }
354
+ /** The ICU errors that keep `translation` of `canonical` from shipping: a parse error, or what validation finds. */
355
+ function translationErrors(translation, canonical, codec, locale) {
90
356
  let parsed;
91
357
  try {
92
- parsed = codec.parse(entry.translation);
358
+ parsed = codec.parse(translation);
93
359
  } catch (error) {
94
360
  if (!isDiagnosticError(error)) throw error;
95
- return {
96
- ok: false,
97
- reason: "invalid",
98
- diagnostics: [withSubject(error.diagnostic, locale, message.id, entry.line)]
99
- };
361
+ return [error.diagnostic];
100
362
  }
101
- const found = validateTranslation(parsed, codec.parse(message.canonical), {
363
+ return validateTranslation(parsed, codec.parse(canonical), {
102
364
  locale,
103
- text: entry.translation
104
- });
105
- let errors = null;
106
- for (const diagnostic of found) if (diagnostic.severity === "error") (errors ??= []).push(withSubject(diagnostic, locale, message.id, entry.line));
107
- return errors === null ? {
108
- ok: true,
109
- parsed
110
- } : {
111
- ok: false,
112
- reason: "invalid",
113
- diagnostics: errors
114
- };
365
+ text: translation
366
+ }).filter((diagnostic) => diagnostic.severity === "error");
115
367
  }
116
368
  /**
117
369
  * ICU diagnostics locate problems inside the message text; for a catalog the
@@ -128,17 +380,15 @@ function withSubject(diagnostic, locale, id, line) {
128
380
  if (line > 0) located.line = line;
129
381
  return located;
130
382
  }
131
- //#endregion
132
- //#region src/core/catalog/json.ts
133
- /** Top-level keys the reader maps onto the header; anything else is preserved in `extra`. */
134
- const OWNED_KEYS = /* @__PURE__ */ new Set([
135
- "$schema",
136
- "locale",
137
- "sourceLocale",
138
- "idScheme",
139
- "aiModel",
140
- "messages"
141
- ]);
383
+ // src/core/catalog/json.ts
384
+ /**
385
+ * JSON catalogs (INTERNALS §2.6.4, PLAN §5.6). The writer controls every byte
386
+ * (key order, two-space indent, inline string arrays) so output is
387
+ * deterministic and `source` always sits on the line before `translation`.
388
+ * The reader finds duplicate message keys by scanning the text, because
389
+ * `JSON.parse` silently keeps the last one and would hide a git-merge
390
+ * duplicate.
391
+ */
142
392
  /** Per-message fields with a model field; anything else is preserved in `extra`. */
143
393
  const MESSAGE_FIELDS = /* @__PURE__ */ new Set([
144
394
  "context",
@@ -249,15 +499,12 @@ function scanMessages(text) {
249
499
  }
250
500
  return null;
251
501
  }
252
- function isRecord(value) {
502
+ function isRecord$1(value) {
253
503
  return typeof value === "object" && value !== null && !Array.isArray(value);
254
504
  }
255
505
  function isStringArray(value) {
256
506
  return Array.isArray(value) && value.every((item) => typeof item === "string");
257
507
  }
258
- function sortedUnique$1(values) {
259
- return [...new Set(values)].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
260
- }
261
508
  /** Line and column of a `JSON.parse` error, when V8 names a position. */
262
509
  function errorPosition(text, error) {
263
510
  const match = /position (\d+)/.exec(error instanceof Error ? error.message : "");
@@ -274,39 +521,78 @@ function errorPosition(text, error) {
274
521
  column: offset - lineStart + 1
275
522
  };
276
523
  }
524
+ /** Each model field's check and the error naming its shape, in the order they are reported. */
525
+ const FIELD_CHECKS = [
526
+ [
527
+ "context",
528
+ (value) => typeof value === "string",
529
+ "context must be a string"
530
+ ],
531
+ [
532
+ "fuzzy",
533
+ (value) => typeof value === "boolean",
534
+ "fuzzy must be true or absent"
535
+ ],
536
+ [
537
+ "maxLength",
538
+ (value) => typeof value === "number" && Number.isInteger(value) && value > 0,
539
+ "maxLength must be a positive integer"
540
+ ],
541
+ [
542
+ "flags",
543
+ isStringArray,
544
+ "flags must be an array of strings"
545
+ ],
546
+ [
547
+ "refs",
548
+ isStringArray,
549
+ "refs must be an array of strings"
550
+ ],
551
+ [
552
+ "state",
553
+ (value) => typeof value === "string" && STATES.has(value),
554
+ "state must be \"untranslated\", \"ai\" or \"translated\""
555
+ ],
556
+ [
557
+ "source",
558
+ (value) => value === null || typeof value === "string",
559
+ "source must be a string"
560
+ ],
561
+ [
562
+ "translation",
563
+ (value) => typeof value === "string",
564
+ "translation must be a string"
565
+ ]
566
+ ];
567
+ function readFields(key, value) {
568
+ for (const [field, valid, error] of FIELD_CHECKS) if (value[field] !== void 0 && !valid(value[field])) return `${key}: ${error}`;
569
+ return value;
570
+ }
571
+ /** The fields of other tools, kept for the writer; undefined when there are none. */
572
+ function extraFields(value) {
573
+ let extra;
574
+ for (const field of Object.keys(value)) if (!MESSAGE_FIELDS.has(field)) defineField(extra ??= {}, field, value[field]);
575
+ return extra;
576
+ }
277
577
  function readEntry(key, value, line, isSourceLocale) {
278
- if (!isRecord(value)) return { error: `message ${JSON.stringify(key)} must be an object` };
279
- const { context, fuzzy, maxLength, flags, refs, state, source, translation } = value;
280
- if (context !== void 0 && typeof context !== "string") return { error: `${key}: context must be a string` };
281
- if (fuzzy !== void 0 && typeof fuzzy !== "boolean") return { error: `${key}: fuzzy must be true or absent` };
282
- if (maxLength !== void 0 && !(Number.isInteger(maxLength) && maxLength > 0)) return { error: `${key}: maxLength must be a positive integer` };
283
- if (flags !== void 0 && !isStringArray(flags)) return { error: `${key}: flags must be an array of strings` };
284
- if (refs !== void 0 && !isStringArray(refs)) return { error: `${key}: refs must be an array of strings` };
285
- if (state !== void 0 && (typeof state !== "string" || !STATES.has(state))) return { error: `${key}: state must be "untranslated", "ai" or "translated"` };
286
- if (source !== void 0 && source !== null && typeof source !== "string") return { error: `${key}: source must be a string` };
287
- if (translation !== void 0 && typeof translation !== "string") return { error: `${key}: translation must be a string` };
578
+ if (!isRecord$1(value)) return { error: `message ${JSON.stringify(key)} must be an object` };
579
+ const fields = readFields(key, value);
580
+ if (typeof fields === "string") return { error: fields };
581
+ const { context, fuzzy, maxLength, flags, refs, state, source, translation } = fields;
288
582
  const text = isSourceLocale ? "" : translation ?? "";
289
- const entryState = text === "" ? "untranslated" : state === "ai" ? "ai" : "translated";
290
- let extra;
291
- for (const field of Object.keys(value)) if (!MESSAGE_FIELDS.has(field)) Object.defineProperty(extra ??= {}, field, {
292
- value: value[field],
293
- enumerable: true,
294
- writable: true,
295
- configurable: true
296
- });
297
- const manual = key.includes(".");
583
+ const manual = isManualId(key);
298
584
  const entry = {
299
585
  manualId: manual ? key : null,
300
586
  foreignContext: null,
301
587
  label: manual ? null : key,
302
588
  source: typeof source === "string" ? source : null,
303
589
  translation: text,
304
- state: entryState,
590
+ state: entryStateOf(text, state === "ai"),
305
591
  fuzzy: fuzzy === true,
306
- contexts: typeof context === "string" ? splitContexts(context) : [],
592
+ contexts: context === void 0 ? [] : splitContexts(context),
307
593
  comments: [],
308
- refs: refs === void 0 ? [] : sortedUnique$1(refs),
309
- maxLength: maxLength === void 0 ? null : maxLength,
594
+ refs: refs === void 0 ? [] : sortedUnique(refs),
595
+ maxLength: maxLength ?? null,
310
596
  flags: flags === void 0 ? [] : [...new Set(flags)].map((name) => ({
311
597
  name,
312
598
  line: "#,"
@@ -314,19 +600,46 @@ function readEntry(key, value, line, isSourceLocale) {
314
600
  line,
315
601
  wrapped: false
316
602
  };
603
+ const extra = extraFields(value);
317
604
  if (extra !== void 0) entry.extra = extra;
318
605
  return { entry };
319
606
  }
607
+ /** The top-level keys onto the header; keys of other tools go to `extra`. */
608
+ function readTopLevel(root, header, fail) {
609
+ for (const [key, value] of Object.entries(root)) switch (key) {
610
+ case "$schema":
611
+ case "messages": break;
612
+ case "locale":
613
+ if (typeof value === "string" && value !== "") header.language = value;
614
+ else fail("locale must be a string");
615
+ break;
616
+ case "sourceLocale":
617
+ case "idScheme":
618
+ case "aiModel":
619
+ if (typeof value === "string") header[key] = value;
620
+ else if (value !== null) fail(`${key} must be a string`);
621
+ break;
622
+ default: header.extra.push([key, value]);
623
+ }
624
+ }
625
+ /** The entries of `messages` in text order, duplicate keys included (they are read from the text). */
626
+ function readMessages(text, messages, isSourceLocale, catalog, fail) {
627
+ const members = scanMessages(text) ?? [];
628
+ const seen = /* @__PURE__ */ new Set();
629
+ let duplicates = null;
630
+ for (const member of members) if (seen.has(member.key)) (duplicates ??= /* @__PURE__ */ new Set()).add(member.key);
631
+ else seen.add(member.key);
632
+ for (const member of members) {
633
+ const value = duplicates !== null && duplicates.has(member.key) ? JSON.parse(text.slice(member.start, member.end)) : messages[member.key];
634
+ const read = readEntry(member.key, value, member.line, isSourceLocale);
635
+ if ("error" in read) fail(read.error, member.line);
636
+ else catalog.entries.push(read.entry);
637
+ }
638
+ }
320
639
  function parseJsonCatalog(text, options) {
321
640
  const { locale, isSourceLocale } = options;
322
641
  const diagnostics = [];
323
- const header = {
324
- language: locale,
325
- idScheme: null,
326
- sourceLocale: null,
327
- aiModel: null,
328
- extra: []
329
- };
642
+ const header = emptyHeader(locale);
330
643
  const catalog = {
331
644
  locale,
332
645
  layout: "json",
@@ -360,118 +673,27 @@ function parseJsonCatalog(text, options) {
360
673
  diagnostics
361
674
  };
362
675
  }
363
- if (!isRecord(root)) {
676
+ if (!isRecord$1(root)) {
364
677
  fail("a JSON catalog must be an object", 1);
365
678
  return {
366
679
  catalog,
367
680
  diagnostics
368
681
  };
369
682
  }
370
- for (const [key, value] of Object.entries(root)) switch (key) {
371
- case "$schema":
372
- case "messages": break;
373
- case "locale":
374
- if (typeof value === "string" && value !== "") header.language = value;
375
- else fail("locale must be a string");
376
- break;
377
- case "sourceLocale":
378
- case "idScheme":
379
- case "aiModel":
380
- if (typeof value === "string") header[key] = value;
381
- else if (value !== null) fail(`${key} must be a string`);
382
- break;
383
- default: if (!OWNED_KEYS.has(key)) header.extra.push([key, value]);
384
- }
683
+ readTopLevel(root, header, fail);
385
684
  const messages = root.messages;
386
685
  if (messages === void 0) return {
387
686
  catalog,
388
687
  diagnostics
389
688
  };
390
- if (!isRecord(messages)) {
391
- fail("messages must be an object");
392
- return {
393
- catalog,
394
- diagnostics
395
- };
396
- }
397
- const members = scanMessages(text) ?? [];
398
- const seen = /* @__PURE__ */ new Set();
399
- let duplicates = null;
400
- for (const member of members) if (seen.has(member.key)) (duplicates ??= /* @__PURE__ */ new Set()).add(member.key);
401
- else seen.add(member.key);
402
- for (const member of members) {
403
- const value = duplicates !== null && duplicates.has(member.key) ? JSON.parse(text.slice(member.start, member.end)) : messages[member.key];
404
- const read = readEntry(member.key, value, member.line, isSourceLocale);
405
- if ("error" in read) fail(read.error, member.line);
406
- else catalog.entries.push(read.entry);
407
- }
689
+ if (!isRecord$1(messages)) fail("messages must be an object");
690
+ else readMessages(text, messages, isSourceLocale, catalog, fail);
408
691
  return {
409
692
  catalog,
410
693
  diagnostics
411
694
  };
412
695
  }
413
- //#endregion
414
- //#region src/core/extract/dependencies.ts
415
- /**
416
- * `extraction.dependencies` (PLAN §4.5, §5.24; INTERNALS §2.5.7): published
417
- * packages the app opts in. Each name resolves from the config root the way
418
- * Node resolves a package directory (`node_modules/<name>` in the root or a
419
- * directory above it), by realpath, which is what Vite hands the plugin under
420
- * pnpm's links. Their files are extracted and rewritten like the app's,
421
- * except the package's own `node_modules`, tests and declarations, and their
422
- * catalog references read `<name>/<path in the package>`, the same on every
423
- * machine and package manager and across the package's versions.
424
- */
425
- /** As `files.ts` has it (which imports this module). */
426
- const toPosix$1 = (path) => sep === "/" ? path : path.replaceAll("\\", "/");
427
- const resolved = /* @__PURE__ */ new WeakMap();
428
- /**
429
- * Every `extraction.dependencies` package, resolved once per config. A
430
- * name that does not resolve is a `config-invalid` error: its strings would
431
- * otherwise ship untranslated and unreported.
432
- */
433
- function dependenciesOf(config) {
434
- let list = resolved.get(config.extraction);
435
- if (list !== void 0) return list;
436
- list = [];
437
- for (const name of config.extraction.dependencies) {
438
- const dir = packageDir(config.root, name);
439
- if (dir === null) throw diagnosticError({
440
- code: "config-invalid",
441
- severity: "error",
442
- message: `extraction.dependencies: ${name} is not installed (no node_modules/${name} from ${toPosix$1(config.root)} up); add it to the app's dependencies`
443
- });
444
- list.push({
445
- name,
446
- dir,
447
- messages: messagesFile(dir)
448
- });
449
- }
450
- resolved.set(config.extraction, list);
451
- return list;
452
- }
453
- /** The package directory as Node finds it from `root`, by realpath; null when not installed. */
454
- function packageDir(root, name) {
455
- let dir = resolve(root);
456
- for (;;) {
457
- const candidate = join(dir, "node_modules", name);
458
- if (existsSync(join(candidate, "package.json"))) return toPosix$1(realpathSync(candidate)).replace(/\/+$/, "");
459
- const parent = dirname(dir);
460
- if (parent === dir) return null;
461
- dir = parent;
462
- }
463
- }
464
- /** `package.json#vi18n.messages`, absolute; null without one (or an unreadable manifest). */
465
- function messagesFile(dir) {
466
- try {
467
- const path = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).vi18n?.messages;
468
- return typeof path === "string" && path !== "" ? toPosix$1(resolve(dir, path)) : null;
469
- } catch {
470
- return null;
471
- }
472
- }
473
- //#endregion
474
- //#region src/core/catalog/library.ts
696
+ // src/core/catalog/library.ts
475
697
  /**
476
698
  * Library mode, the app's side (PLAN §4.7, §5.24; INTERNALS §2.6.11): what an
477
699
  * opted-in package ships next to its code. Its `vi18n.messages.json` (written
@@ -502,36 +724,55 @@ function libraryManifests(config) {
502
724
  return list;
503
725
  }
504
726
  function readManifest(file, root) {
505
- const shown = displayPath$2(root, file);
506
- let data;
507
- try {
508
- data = JSON.parse(readFileSync(file, "utf8"));
509
- } catch (error) {
510
- return {
511
- manifest: null,
512
- diagnostic: {
513
- code: "catalog-parse",
514
- severity: "warning",
515
- message: `${shown} cannot be read (${error.message}); the package's translations are left out`,
516
- file: shown
517
- }
518
- };
519
- }
520
- const manifest = data;
521
- if (manifest === null || typeof manifest !== "object" || manifest.vi18n !== 1 || !Array.isArray(manifest.messages)) return {
727
+ const shown = displayPath(root, file);
728
+ const unusable = (problem) => ({
522
729
  manifest: null,
523
730
  diagnostic: {
524
731
  code: "catalog-parse",
525
732
  severity: "warning",
526
- message: `${shown} is not a vi18n.messages.json of version 1; the package's translations are left out`,
733
+ message: `${shown} ${problem}; the package's translations are left out`,
527
734
  file: shown
528
735
  }
529
- };
736
+ });
737
+ let data;
738
+ try {
739
+ data = JSON.parse(readFileSync(file, "utf8"));
740
+ } catch (error) {
741
+ return unusable(`cannot be read (${error instanceof Error ? error.message : String(error)})`);
742
+ }
743
+ if (!isRecord(data) || data.vi18n !== 1 || !Array.isArray(data.messages)) return unusable("is not a vi18n.messages.json of version 1");
530
744
  return {
531
- manifest,
745
+ manifest: usableManifest(data, data.messages),
532
746
  diagnostic: null
533
747
  };
534
748
  }
749
+ function isRecord(value) {
750
+ return typeof value === "object" && value !== null && !Array.isArray(value);
751
+ }
752
+ function isMessage(value) {
753
+ return isRecord(value) && typeof value.message === "string" && (value.id === void 0 || typeof value.id === "string");
754
+ }
755
+ /**
756
+ * The parts of a version 1 manifest the app can use, so later code can trust
757
+ * the type: a malformed message is skipped, a malformed catalog list counts as
758
+ * none, and a missing `sourceLocale` as the app's own. One bad field never
759
+ * drops the rest of the package.
760
+ */
761
+ function usableManifest(data, messages) {
762
+ return {
763
+ sourceLocale: typeof data.sourceLocale === "string" ? data.sourceLocale : null,
764
+ catalogs: usableCatalogs(data.catalogs),
765
+ messages: messages.filter(isMessage)
766
+ };
767
+ }
768
+ function usableCatalogs(value) {
769
+ if (!isRecord(value) || !isRecord(value.files)) return null;
770
+ return {
771
+ format: value.format === "json" ? "json" : "po",
772
+ msgid: value.msgid === "id" ? "id" : "source",
773
+ files: value.files
774
+ };
775
+ }
535
776
  /**
536
777
  * Loads the opted-in packages' catalogs for `locales` under the app's
537
778
  * (`LoadedCatalog.libraries`), normalised for joining (below). The source
@@ -539,72 +780,89 @@ function readManifest(file, root) {
539
780
  * package written in another language: its texts are not the app's source
540
781
  * language, and its catalog for that language is what those pages show.
541
782
  */
542
- async function attachLibraryCatalogs(set, config, codec, locales) {
543
- const diagnostics = [];
544
- if (config.extraction.dependencies.length === 0) return diagnostics;
545
- const layout = catalogLayout(config);
546
- for (const loaded of libraryManifests(config)) {
547
- if (loaded.diagnostic !== null) diagnostics.push(loaded.diagnostic);
548
- const catalogs = loaded.manifest?.catalogs;
549
- if (catalogs == null || typeof catalogs.files !== "object") continue;
550
- const from = catalogs.format === "json" ? "json" : catalogs.msgid === "id" ? "id" : "source";
551
- const foreign = typeof loaded.manifest?.sourceLocale === "string" && loaded.manifest.sourceLocale !== config.sourceLocale;
552
- for (const locale of locales) {
553
- if (locale === config.sourceLocale && !foreign) continue;
554
- const own = set.get(locale);
555
- const relativePath = Object.hasOwn(catalogs.files, locale) ? catalogs.files[locale] : void 0;
556
- if (locale === config.sourceLocale && typeof relativePath !== "string") {
557
- diagnostics.push({
558
- code: "catalog-parse",
559
- severity: "warning",
560
- message: `${loaded.name} is written in ${loaded.manifest?.sourceLocale} and ships no ${locale} catalog; its messages show in ${loaded.manifest?.sourceLocale} on ${locale} pages`,
561
- file: displayPath$2(config.root, loaded.file),
562
- locale
563
- });
564
- continue;
565
- }
566
- if (own === void 0 || typeof relativePath !== "string") continue;
567
- const path = resolve(dirname(loaded.file), relativePath);
568
- let text;
569
- try {
570
- text = await readFile(path, "utf8");
571
- } catch {
572
- diagnostics.push({
573
- code: "catalog-parse",
574
- severity: "warning",
575
- message: `${loaded.name} lists a ${locale} catalog it does not ship (${relativePath}); its ${locale} translations are left out`,
576
- file: displayPath$2(config.root, loaded.file),
577
- locale
578
- });
579
- continue;
580
- }
581
- const read = parseCatalog(text, {
582
- locale,
583
- layout: from,
584
- isSourceLocale: false
585
- });
586
- for (const diagnostic of read.diagnostics) diagnostics.push({
587
- ...diagnostic,
588
- severity: diagnostic.severity === "error" ? "warning" : diagnostic.severity,
589
- file: diagnostic.file ?? displayPath$2(config.root, path),
590
- locale
783
+ async function attachLibraryCatalogs(set, config, codec, locales) {
784
+ const diagnostics = [];
785
+ if (config.extraction.dependencies.length === 0) return diagnostics;
786
+ for (const loaded of libraryManifests(config)) {
787
+ if (loaded.diagnostic !== null) diagnostics.push(loaded.diagnostic);
788
+ const manifest = loaded.manifest;
789
+ if (manifest === null || manifest.catalogs === null) continue;
790
+ const library = {
791
+ name: loaded.name,
792
+ file: loaded.file,
793
+ manifest,
794
+ catalogs: manifest.catalogs
795
+ };
796
+ for (const locale of locales) {
797
+ const own = set.get(locale);
798
+ const attached = await libraryCatalog(library, locale, own, {
799
+ config,
800
+ codec,
801
+ diagnostics
591
802
  });
592
- const library = {
593
- locale,
594
- path,
595
- catalog: joined(read.catalog, layout, codec),
596
- hash: contentHash(text),
597
- library: true,
598
- ...foreign ? { librarySource: loaded.manifest?.sourceLocale } : {}
599
- };
600
- set.set(locale, {
803
+ if (own !== void 0 && attached !== null) set.set(locale, {
601
804
  ...own,
602
- libraries: [...own.libraries ?? [], library]
805
+ libraries: [...own.libraries ?? [], attached]
603
806
  });
604
807
  }
605
808
  }
606
809
  return diagnostics;
607
810
  }
811
+ /** One package's catalog for `locale`, read and joined; null (with a warning when it should exist) otherwise. */
812
+ async function libraryCatalog(library, locale, own, app) {
813
+ const { config, codec, diagnostics } = app;
814
+ const { name, manifest, catalogs } = library;
815
+ const librarySource = manifest.sourceLocale ?? config.sourceLocale;
816
+ const foreign = librarySource !== config.sourceLocale;
817
+ if (locale === config.sourceLocale && !foreign) return null;
818
+ const relativePath = Object.hasOwn(catalogs.files, locale) ? catalogs.files[locale] : void 0;
819
+ const shown = displayPath(config.root, library.file);
820
+ if (locale === config.sourceLocale && typeof relativePath !== "string") {
821
+ diagnostics.push({
822
+ code: "catalog-parse",
823
+ severity: "warning",
824
+ message: `${name} is written in ${librarySource} and ships no ${locale} catalog; its messages show in ${librarySource} on ${locale} pages`,
825
+ file: shown,
826
+ locale
827
+ });
828
+ return null;
829
+ }
830
+ if (own === void 0 || typeof relativePath !== "string") return null;
831
+ const path = resolve(dirname(library.file), relativePath);
832
+ let text;
833
+ try {
834
+ text = await readFile(path, "utf8");
835
+ } catch {
836
+ diagnostics.push({
837
+ code: "catalog-parse",
838
+ severity: "warning",
839
+ message: `${name} lists a ${locale} catalog it does not ship (${relativePath}); its ${locale} translations are left out`,
840
+ file: shown,
841
+ locale
842
+ });
843
+ return null;
844
+ }
845
+ const from = catalogLayout({ catalogs });
846
+ const read = parseCatalog(text, {
847
+ locale,
848
+ layout: from,
849
+ isSourceLocale: false
850
+ });
851
+ for (const diagnostic of read.diagnostics) diagnostics.push({
852
+ ...diagnostic,
853
+ severity: diagnostic.severity === "error" ? "warning" : diagnostic.severity,
854
+ file: diagnostic.file ?? displayPath(config.root, path),
855
+ locale
856
+ });
857
+ return {
858
+ locale,
859
+ path,
860
+ catalog: joined(read.catalog, catalogLayout(config), codec),
861
+ hash: contentHash(text),
862
+ library: true,
863
+ ...foreign ? { librarySource } : {}
864
+ };
865
+ }
608
866
  /**
609
867
  * A library catalog in the app's terms: the app's layout, no recorded
610
868
  * scheme, and every entry's `label` computed from its source by the app's
@@ -637,13 +895,7 @@ function joined(catalog, layout, codec) {
637
895
  droppedObsolete: 0
638
896
  };
639
897
  }
640
- function displayPath$2(root, file) {
641
- const rel = relative(root, file);
642
- if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) return file.split(sep).join("/");
643
- return rel.split(sep).join("/");
644
- }
645
- //#endregion
646
- //#region src/core/catalog/plural-forms.ts
898
+ // src/core/catalog/plural-forms.ts
647
899
  /**
648
900
  * The PO `Plural-Forms` header (PLAN §4.4 P1, INTERNALS §2.6.3). vi18n never
649
901
  * evaluates it: an ICU message carries its own plural cases, and vi18n never
@@ -711,8 +963,7 @@ function pluralFormsFor(language) {
711
963
  }
712
964
  return null;
713
965
  }
714
- //#endregion
715
- //#region src/core/catalog/po.ts
966
+ // src/core/catalog/po.ts
716
967
  /**
717
968
  * Header fields the writer always emits itself; keeping them in `extra` would
718
969
  * write them twice.
@@ -888,38 +1139,23 @@ function readFlags(text, line, draft) {
888
1139
  if (name === "") continue;
889
1140
  if (name === "fuzzy") draft.fuzzy = true;
890
1141
  else if (name === "ai") draft.ai = true;
891
- else if (name.startsWith("max-length:") && /^max-length:[1-9]\d*$/.test(name)) {
892
- const value = Number(name.slice(11));
893
- draft.maxLength = draft.maxLength === null ? value : Math.min(draft.maxLength, value);
894
- } else {
895
- const key = line + name;
1142
+ else if (name.startsWith("max-length:") && /^max-length:[1-9]\d*$/.test(name)) draft.maxLength = stricterLimit(draft.maxLength, Number(name.slice(11)));
1143
+ else {
1144
+ const flag = {
1145
+ name,
1146
+ line
1147
+ };
1148
+ const key = flagKey(flag);
896
1149
  const keys = draft.flagKeys ??= /* @__PURE__ */ new Set();
897
1150
  if (!keys.has(key)) {
898
1151
  keys.add(key);
899
- draft.flags.push({
900
- name,
901
- line
902
- });
1152
+ draft.flags.push(flag);
903
1153
  }
904
1154
  }
905
1155
  }
906
1156
  }
907
- function sortedUnique(values) {
908
- if (values.length < 2) return values;
909
- const sorted = values.slice().sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
910
- let w = 1;
911
- for (let r = 1; r < sorted.length; r++) if (sorted[r] !== sorted[w - 1]) sorted[w++] = sorted[r];
912
- sorted.length = w;
913
- return sorted;
914
- }
915
1157
  function readHeader(msgstr, locale) {
916
- const header = {
917
- language: locale,
918
- idScheme: null,
919
- sourceLocale: null,
920
- aiModel: null,
921
- extra: []
922
- };
1158
+ const header = emptyHeader(locale);
923
1159
  for (const field of msgstr.split("\n")) {
924
1160
  const colon = field.indexOf(":");
925
1161
  if (colon <= 0) continue;
@@ -937,183 +1173,187 @@ function readHeader(msgstr, locale) {
937
1173
  return header;
938
1174
  }
939
1175
  function parsePo(text, options) {
940
- const { locale, layout, isSourceLocale } = options;
941
- const diagnostics = [];
942
- const entries = [];
943
- const obsolete = [];
944
- let header = null;
945
- let draft = newDraft();
946
- let block = null;
947
- let blockHasMsgstr = false;
948
- const closeBlock = () => {
949
- if (block !== null) {
950
- obsolete.push(block.join("\n"));
951
- block = null;
952
- blockHasMsgstr = false;
953
- }
954
- };
955
- const finish = () => {
956
- const done = draft;
957
- if (!hasKeywords(done)) return;
958
- draft = newDraft();
959
- if (done.error !== null) {
960
- diagnostics.push(done.error);
961
- return;
962
- }
963
- if (done.msgid === null) {
964
- diagnostics.push(parseError(done.firstLine, "entry without msgid"));
965
- return;
966
- }
967
- if (done.plural) {
968
- diagnostics.push(parseError(done.line, "gettext plural entries (msgid_plural) are not supported: write the plural as ICU in the source text"));
969
- return;
970
- }
971
- if (done.msgstr === null) {
972
- diagnostics.push(parseError(done.line, "msgid without msgstr"));
973
- return;
974
- }
975
- if (done.msgid === "" && done.msgctxt === null && header === null && entries.length === 0) {
976
- header = readHeader(done.msgstr, locale);
977
- return;
978
- }
979
- const manual = done.msgctxt !== null && done.msgctxt.includes(".");
980
- const translation = isSourceLocale ? "" : done.msgstr;
981
- let source;
982
- let label = null;
983
- if (layout === "source") source = done.msgid;
984
- else {
985
- label = done.msgid;
986
- source = isSourceLocale ? done.msgstr : done.sourceNote;
987
- }
988
- const state = translation === "" ? "untranslated" : done.ai ? "ai" : "translated";
989
- entries.push({
990
- manualId: manual ? done.msgctxt : null,
991
- foreignContext: manual ? null : done.msgctxt,
992
- label,
993
- source,
994
- translation,
995
- state,
996
- fuzzy: done.fuzzy,
997
- contexts: done.contexts,
998
- comments: done.comments,
999
- refs: sortedUnique(done.refs),
1000
- maxLength: done.maxLength,
1001
- flags: done.flags,
1002
- line: done.line,
1003
- wrapped: done.wrapped
1004
- });
1005
- };
1006
- const fail = (line, message) => {
1007
- draft.error ??= parseError(line, message);
1008
- };
1176
+ const reader = new PoReader(options);
1009
1177
  const start = text.charCodeAt(0) === 65279 ? 1 : 0;
1010
1178
  const lines = (start === 0 ? text : text.slice(start)).split("\n");
1011
1179
  for (let index = 0; index < lines.length; index++) {
1012
- const lineNo = index + 1;
1013
- let raw = lines[index];
1014
- if (raw.endsWith("\r")) raw = raw.slice(0, -1);
1180
+ const raw = lines[index];
1181
+ reader.readLine(raw.endsWith("\r") ? raw.slice(0, -1) : raw, index + 1);
1182
+ }
1183
+ return reader.end();
1184
+ }
1185
+ /** The reader's state between lines: the entry being read, and the `#~` block being collected. */
1186
+ var PoReader = class {
1187
+ #options;
1188
+ #diagnostics = [];
1189
+ #entries = [];
1190
+ #obsolete = [];
1191
+ #header = null;
1192
+ #draft = newDraft();
1193
+ #block = null;
1194
+ #blockHasMsgstr = false;
1195
+ constructor(options) {
1196
+ this.#options = options;
1197
+ }
1198
+ readLine(raw, lineNo) {
1015
1199
  let s = 0;
1016
1200
  while (s < raw.length && (raw[s] === " " || raw[s] === " ")) s++;
1017
1201
  if (s === raw.length) {
1018
- finish();
1019
- closeBlock();
1020
- continue;
1202
+ this.#finish();
1203
+ this.#closeBlock();
1204
+ return;
1021
1205
  }
1022
1206
  const line = s === 0 ? raw : raw.slice(s);
1023
1207
  if (line.startsWith("#~")) {
1024
- finish();
1025
- const body = line.slice(2).trimStart();
1026
- const startsEntry = body.startsWith("msgid") || body.startsWith("msgctxt");
1027
- if (block !== null && blockHasMsgstr && startsEntry) closeBlock();
1028
- if (block === null) {
1029
- block = draft.raw;
1030
- draft = newDraft();
1031
- }
1032
- block.push(raw);
1033
- if (body.startsWith("msgstr")) blockHasMsgstr = true;
1034
- continue;
1208
+ this.#readObsolete(line, raw);
1209
+ return;
1210
+ }
1211
+ this.#closeBlock();
1212
+ const first = line.charCodeAt(0);
1213
+ if (first === 35) this.#readComment(line, raw, lineNo);
1214
+ else if (first === 34) this.#readContinuation(line, lineNo);
1215
+ else this.#readKeyword(line, lineNo);
1216
+ }
1217
+ end() {
1218
+ this.#finish();
1219
+ this.#closeBlock();
1220
+ const { locale, layout } = this.#options;
1221
+ return {
1222
+ catalog: {
1223
+ locale,
1224
+ layout,
1225
+ header: this.#header ?? emptyHeader(locale),
1226
+ entries: this.#entries,
1227
+ obsolete: this.#obsolete,
1228
+ droppedObsolete: this.#obsolete.length
1229
+ },
1230
+ diagnostics: this.#diagnostics
1231
+ };
1232
+ }
1233
+ #closeBlock() {
1234
+ if (this.#block === null) return;
1235
+ this.#obsolete.push(this.#block.join("\n"));
1236
+ this.#block = null;
1237
+ this.#blockHasMsgstr = false;
1238
+ }
1239
+ #fail(line, message) {
1240
+ this.#draft.error ??= parseError(line, message);
1241
+ }
1242
+ #readObsolete(line, raw) {
1243
+ this.#finish();
1244
+ const body = line.slice(2).trimStart();
1245
+ const startsEntry = body.startsWith("msgid") || body.startsWith("msgctxt");
1246
+ if (this.#block !== null && this.#blockHasMsgstr && startsEntry) this.#closeBlock();
1247
+ if (this.#block === null) {
1248
+ this.#block = this.#draft.raw;
1249
+ this.#draft = newDraft();
1035
1250
  }
1036
- closeBlock();
1037
- if (line.charCodeAt(0) === 35) {
1038
- if (hasKeywords(draft)) finish();
1039
- if (draft.firstLine === 0) draft.firstLine = lineNo;
1040
- draft.raw.push(raw);
1041
- const kind = line[1];
1042
- const rest = line.slice(2);
1043
- const content = rest.startsWith(" ") ? rest.slice(1) : rest;
1044
- if (kind === ".") {
1045
- if (layout === "id" && content.startsWith("source:")) {
1046
- if (!isSourceLocale) {
1047
- const body = content.slice(content.startsWith("source: ") ? 8 : 7);
1048
- const note = unescapePo(body);
1049
- if (note === null) diagnostics.push({
1050
- code: "catalog-parse",
1051
- severity: "warning",
1052
- message: "invalid escape in #. source:; the note is kept as written",
1053
- line: lineNo
1054
- });
1055
- draft.sourceNote = note ?? body;
1056
- }
1057
- } else draft.contexts.push(layout === "id" && ESCAPED_SOURCE_LIKE.test(content) ? content.slice(1) : content);
1058
- } else if (kind === ":") readRefs(content, draft.refs);
1059
- else if (kind === ",") readFlags(content, "#,", draft);
1060
- else if (kind === "=") readFlags(content, "#=", draft);
1061
- else if (kind === "|") {} else {
1251
+ this.#block.push(raw);
1252
+ if (body.startsWith("msgstr")) this.#blockHasMsgstr = true;
1253
+ }
1254
+ #readComment(line, raw, lineNo) {
1255
+ if (hasKeywords(this.#draft)) this.#finish();
1256
+ const into = this.#draft;
1257
+ if (into.firstLine === 0) into.firstLine = lineNo;
1258
+ into.raw.push(raw);
1259
+ const kind = line[1];
1260
+ const rest = line.slice(2);
1261
+ const content = rest.startsWith(" ") ? rest.slice(1) : rest;
1262
+ switch (kind) {
1263
+ case ".":
1264
+ this.#readNote(content, lineNo);
1265
+ break;
1266
+ case ":":
1267
+ readRefs(content, into.refs);
1268
+ break;
1269
+ case ",":
1270
+ readFlags(content, "#,", into);
1271
+ break;
1272
+ case "=":
1273
+ readFlags(content, "#=", into);
1274
+ break;
1275
+ case "|": break;
1276
+ default: {
1062
1277
  const body = line.slice(1);
1063
- draft.comments.push(body.startsWith(" ") ? body.slice(1) : body);
1278
+ into.comments.push(body.startsWith(" ") ? body.slice(1) : body);
1064
1279
  }
1065
- continue;
1066
1280
  }
1067
- if (line.charCodeAt(0) === 34) {
1068
- const value = readString(line, 0);
1069
- if (draft.field === null) {
1070
- fail(lineNo, "string continuation without a keyword");
1071
- draft.firstLine ||= lineNo;
1072
- draft.field = "msgstr";
1073
- continue;
1074
- }
1075
- if (value === null) {
1076
- fail(lineNo, "malformed string");
1077
- continue;
1078
- }
1079
- switch (draft.field) {
1080
- case "msgctxt":
1081
- draft.msgctxt = (draft.msgctxt ?? "") + value;
1082
- break;
1083
- case "msgid":
1084
- draft.msgid = (draft.msgid ?? "") + value;
1085
- draft.wrapped = true;
1086
- break;
1087
- case "msgstr":
1088
- draft.msgstr = (draft.msgstr ?? "") + value;
1089
- draft.wrapped = true;
1090
- }
1091
- continue;
1281
+ }
1282
+ /** A `#.` line: a developer note, or in the `"id"` layout possibly the `source:` note. */
1283
+ #readNote(content, lineNo) {
1284
+ const { layout, isSourceLocale } = this.#options;
1285
+ if (layout !== "id" || !content.startsWith("source:")) {
1286
+ this.#draft.contexts.push(layout === "id" && ESCAPED_SOURCE_LIKE.test(content) ? content.slice(1) : content);
1287
+ return;
1288
+ }
1289
+ if (isSourceLocale) return;
1290
+ const body = content.slice(content.startsWith("source: ") ? 8 : 7);
1291
+ const note = unescapePo(body);
1292
+ if (note === null) this.#diagnostics.push({
1293
+ code: "catalog-parse",
1294
+ severity: "warning",
1295
+ message: "invalid escape in #. source:; the note is kept as written",
1296
+ line: lineNo
1297
+ });
1298
+ this.#draft.sourceNote = note ?? body;
1299
+ }
1300
+ #readContinuation(line, lineNo) {
1301
+ const draft = this.#draft;
1302
+ const value = readString(line, 0);
1303
+ if (draft.field === null) {
1304
+ this.#fail(lineNo, "string continuation without a keyword");
1305
+ draft.firstLine ||= lineNo;
1306
+ draft.field = "msgstr";
1307
+ return;
1308
+ }
1309
+ if (value === null) {
1310
+ this.#fail(lineNo, "malformed string");
1311
+ return;
1312
+ }
1313
+ switch (draft.field) {
1314
+ case "msgctxt":
1315
+ draft.msgctxt = (draft.msgctxt ?? "") + value;
1316
+ break;
1317
+ case "msgid":
1318
+ draft.msgid = (draft.msgid ?? "") + value;
1319
+ draft.wrapped = true;
1320
+ break;
1321
+ case "msgstr":
1322
+ draft.msgstr = (draft.msgstr ?? "") + value;
1323
+ draft.wrapped = true;
1092
1324
  }
1325
+ }
1326
+ #readKeyword(line, lineNo) {
1093
1327
  const keyword = /^(msgctxt|msgid_plural|msgid|msgstr\[\d+\]|msgstr)(?=[\s"])/.exec(line);
1094
1328
  if (keyword === null) {
1329
+ const draft = this.#draft;
1095
1330
  if (!hasKeywords(draft)) draft.firstLine ||= lineNo;
1096
1331
  draft.field ??= "msgstr";
1097
- fail(lineNo, `unexpected line: ${line.length > 40 ? `${line.slice(0, 40)}…` : line}`);
1098
- continue;
1332
+ this.#fail(lineNo, `unexpected line: ${line.length > 40 ? `${line.slice(0, 40)}…` : line}`);
1333
+ return;
1099
1334
  }
1100
1335
  const word = keyword[1];
1101
1336
  const field = word.startsWith("msgstr[") ? "msgstr[]" : word;
1102
- if ((field === "msgctxt" || field === "msgid") && (draft.msgstr !== null || draft.plural)) finish();
1337
+ if ((field === "msgctxt" || field === "msgid") && (this.#draft.msgstr !== null || this.#draft.plural)) this.#finish();
1338
+ const draft = this.#draft;
1103
1339
  if (draft.firstLine === 0) draft.firstLine = lineNo;
1104
1340
  const value = readString(line, word.length);
1105
1341
  draft.field = field;
1106
1342
  if (value === null) {
1107
- fail(lineNo, `malformed ${word} string`);
1108
- continue;
1343
+ this.#fail(lineNo, `malformed ${word} string`);
1344
+ return;
1109
1345
  }
1346
+ this.#setField(field, word, value, lineNo);
1347
+ }
1348
+ #setField(field, word, value, lineNo) {
1349
+ const draft = this.#draft;
1110
1350
  switch (field) {
1111
1351
  case "msgctxt":
1112
- if (draft.msgctxt !== null || draft.msgid !== null) fail(lineNo, "msgctxt must come first, once");
1352
+ if (draft.msgctxt !== null || draft.msgid !== null) this.#fail(lineNo, "msgctxt must come first, once");
1113
1353
  draft.msgctxt = value;
1114
1354
  break;
1115
1355
  case "msgid":
1116
- if (draft.msgid !== null) fail(lineNo, "duplicate msgid");
1356
+ if (draft.msgid !== null) this.#fail(lineNo, "duplicate msgid");
1117
1357
  draft.msgid = value;
1118
1358
  draft.line = lineNo;
1119
1359
  break;
@@ -1121,35 +1361,69 @@ function parsePo(text, options) {
1121
1361
  draft.plural = true;
1122
1362
  break;
1123
1363
  case "msgstr":
1124
- if (draft.msgid === null) fail(lineNo, "msgstr without msgid");
1125
- if (draft.msgstr !== null) fail(lineNo, "duplicate msgstr");
1364
+ if (draft.msgid === null) this.#fail(lineNo, "msgstr without msgid");
1365
+ if (draft.msgstr !== null) this.#fail(lineNo, "duplicate msgstr");
1126
1366
  draft.msgstr = value;
1127
1367
  break;
1128
- case "msgstr[]": if (!draft.plural) fail(lineNo, `${word} without msgid_plural`);
1368
+ case "msgstr[]": if (!draft.plural) this.#fail(lineNo, `${word} without msgid_plural`);
1369
+ }
1370
+ }
1371
+ /** Ends the draft entry: an entry, the header, or a diagnostic for what it lacks. */
1372
+ #finish() {
1373
+ const done = this.#draft;
1374
+ if (!hasKeywords(done)) return;
1375
+ this.#draft = newDraft();
1376
+ const problem = draftProblem(done);
1377
+ if (problem !== null) {
1378
+ this.#diagnostics.push(problem);
1379
+ return;
1380
+ }
1381
+ const msgid = done.msgid;
1382
+ const msgstr = done.msgstr;
1383
+ if (msgid === "" && done.msgctxt === null && this.#header === null && this.#entries.length === 0) {
1384
+ this.#header = readHeader(msgstr, this.#options.locale);
1385
+ return;
1129
1386
  }
1387
+ this.#entries.push(entryOf(done, msgid, msgstr, this.#options));
1388
+ }
1389
+ };
1390
+ /** Why a finished draft is not an entry, or null when it is one. */
1391
+ function draftProblem(done) {
1392
+ if (done.error !== null) return done.error;
1393
+ if (done.msgid === null) return parseError(done.firstLine, "entry without msgid");
1394
+ if (done.plural) return parseError(done.line, "gettext plural entries (msgid_plural) are not supported: write the plural as ICU in the source text");
1395
+ if (done.msgstr === null) return parseError(done.line, "msgid without msgstr");
1396
+ return null;
1397
+ }
1398
+ function entryOf(done, msgid, msgstr, options) {
1399
+ const { layout, isSourceLocale } = options;
1400
+ const manual = done.msgctxt !== null && isManualId(done.msgctxt);
1401
+ const translation = isSourceLocale ? "" : msgstr;
1402
+ let source;
1403
+ let label = null;
1404
+ if (layout === "source") source = msgid;
1405
+ else {
1406
+ label = msgid;
1407
+ source = isSourceLocale ? msgstr : done.sourceNote;
1130
1408
  }
1131
- finish();
1132
- closeBlock();
1133
1409
  return {
1134
- catalog: {
1135
- locale,
1136
- layout,
1137
- header: header ?? {
1138
- language: locale,
1139
- idScheme: null,
1140
- sourceLocale: null,
1141
- aiModel: null,
1142
- extra: []
1143
- },
1144
- entries,
1145
- obsolete,
1146
- droppedObsolete: obsolete.length
1147
- },
1148
- diagnostics
1410
+ manualId: manual ? done.msgctxt : null,
1411
+ foreignContext: manual ? null : done.msgctxt,
1412
+ label,
1413
+ source,
1414
+ translation,
1415
+ state: entryStateOf(translation, done.ai),
1416
+ fuzzy: done.fuzzy,
1417
+ contexts: done.contexts,
1418
+ comments: done.comments,
1419
+ refs: sortedUnique(done.refs),
1420
+ maxLength: done.maxLength,
1421
+ flags: done.flags,
1422
+ line: done.line,
1423
+ wrapped: done.wrapped
1149
1424
  };
1150
1425
  }
1151
- //#endregion
1152
- //#region src/core/catalog/io.ts
1426
+ // src/core/catalog/io.ts
1153
1427
  /**
1154
1428
  * Catalog files (INTERNALS §2.6.1, §2.6.6, PLAN §5.6): one per locale,
1155
1429
  * source locale included. Every writer (dev, extract, translate, import,
@@ -1176,11 +1450,6 @@ function parseCatalog(text, options) {
1176
1450
  function contentHash(data) {
1177
1451
  return hash("sha256", data, "hex");
1178
1452
  }
1179
- function displayPath$1(root, file) {
1180
- const rel = relative(root, file);
1181
- if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) return file.split(sep).join("/");
1182
- return rel.split(sep).join("/");
1183
- }
1184
1453
  function isMissing(error) {
1185
1454
  return error?.code === "ENOENT";
1186
1455
  }
@@ -1238,35 +1507,28 @@ function firstInvalidLine(bytes) {
1238
1507
  */
1239
1508
  function decodeCatalog(bytes, layout) {
1240
1509
  const charset = layout === "json" ? null : poCharset(bytes);
1241
- const lossy = () => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.length).toString("utf8");
1510
+ const undecodable = (message, line) => ({
1511
+ text: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.length).toString("utf8"),
1512
+ diagnostic: {
1513
+ code: "catalog-parse",
1514
+ severity: "error",
1515
+ message,
1516
+ ...line === void 0 ? {} : { line }
1517
+ }
1518
+ });
1242
1519
  if (charset === null || UTF8_LABELS.has(charset.toLowerCase())) try {
1243
1520
  return {
1244
1521
  text: UTF8.decode(bytes),
1245
1522
  diagnostic: null
1246
1523
  };
1247
1524
  } catch {
1248
- return {
1249
- text: lossy(),
1250
- diagnostic: {
1251
- code: "catalog-parse",
1252
- severity: "error",
1253
- message: "the file is not valid UTF-8; re-save it as UTF-8",
1254
- line: firstInvalidLine(bytes)
1255
- }
1256
- };
1525
+ return undecodable("the file is not valid UTF-8; re-save it as UTF-8", firstInvalidLine(bytes));
1257
1526
  }
1258
1527
  let decoder;
1259
1528
  try {
1260
1529
  decoder = new TextDecoder(charset, { fatal: true });
1261
1530
  } catch {
1262
- return {
1263
- text: lossy(),
1264
- diagnostic: {
1265
- code: "catalog-parse",
1266
- severity: "error",
1267
- message: `unsupported charset ${charset} in Content-Type; convert the file to UTF-8`
1268
- }
1269
- };
1531
+ return undecodable(`unsupported charset ${charset} in Content-Type; convert the file to UTF-8`);
1270
1532
  }
1271
1533
  try {
1272
1534
  return {
@@ -1274,18 +1536,17 @@ function decodeCatalog(bytes, layout) {
1274
1536
  diagnostic: null
1275
1537
  };
1276
1538
  } catch {
1277
- return {
1278
- text: lossy(),
1279
- diagnostic: {
1280
- code: "catalog-parse",
1281
- severity: "error",
1282
- message: `the file is not valid ${charset} as its Content-Type declares; fix its encoding`
1283
- }
1284
- };
1539
+ return undecodable(`the file is not valid ${charset} as its Content-Type declares; fix its encoding`);
1285
1540
  }
1286
1541
  }
1287
- function severityOf$1(level) {
1288
- return level === "off" ? null : level === "warn" ? "warning" : "error";
1542
+ const SEVERITY = {
1543
+ off: null,
1544
+ warn: "warning",
1545
+ error: "error"
1546
+ };
1547
+ /** The severity a `strict` level reports at; null for `"off"`, which reports nothing. */
1548
+ function severityOf(level) {
1549
+ return SEVERITY[level];
1289
1550
  }
1290
1551
  /**
1291
1552
  * Sources that do not parse leave their entry without a key (INTERNALS
@@ -1324,7 +1585,7 @@ function invalidSources(catalog, codec, isSourceLocale, severity) {
1324
1585
  async function loadCatalogSet(config, codec, locales) {
1325
1586
  const layout = catalogLayout(config);
1326
1587
  const wanted = locales ?? config.locales;
1327
- const invalid = severityOf$1(config.strict.invalid);
1588
+ const invalid = severityOf(config.strict.invalid);
1328
1589
  const loaded = await Promise.all(wanted.map(async (locale) => {
1329
1590
  const path = catalogPath(config, locale);
1330
1591
  const bytes = await readOptional(path);
@@ -1347,7 +1608,7 @@ async function loadCatalogSet(config, codec, locales) {
1347
1608
  const diagnostics = read.diagnostics;
1348
1609
  if (decoded.diagnostic !== null) diagnostics.unshift(decoded.diagnostic);
1349
1610
  if (invalid !== null) diagnostics.push(...invalidSources(read.catalog, codec, isSourceLocale, invalid));
1350
- const file = displayPath$1(config.root, path);
1611
+ const file = displayPath(config.root, path);
1351
1612
  for (const diagnostic of diagnostics) {
1352
1613
  diagnostic.file ??= file;
1353
1614
  diagnostic.locale ??= locale;
@@ -1360,140 +1621,21 @@ async function loadCatalogSet(config, codec, locales) {
1360
1621
  hash: contentHash(bytes)
1361
1622
  },
1362
1623
  diagnostics
1363
- };
1364
- }));
1365
- const set = /* @__PURE__ */ new Map();
1366
- const diagnostics = [];
1367
- for (const item of loaded) {
1368
- set.set(item.catalog.locale, item.catalog);
1369
- diagnostics.push(...item.diagnostics);
1370
- }
1371
- if (config.extraction.dependencies.length > 0) diagnostics.push(...await attachLibraryCatalogs(set, config, codec, wanted));
1372
- return {
1373
- set,
1374
- diagnostics
1375
- };
1376
- }
1377
- //#endregion
1378
- //#region src/core/id/hash.ts
1379
- /**
1380
- * Ids (INTERNALS §2.2.1, §2.2.3, PLAN §5.5). An id depends only on its own
1381
- * canonical text and `ids.length`, so every process computes it alone and
1382
- * nothing is ever recorded. Frozen by the golden vectors: changing anything
1383
- * here re-keys every catalog.
1384
- */
1385
- /**
1386
- * Lingui's construction with an empty context (`text + "\u001F"`), so a Lingui
1387
- * 6 id of the same canonical text is a prefix of the vi18n id.
1388
- */
1389
- function sourceHash(canonical) {
1390
- return hash("sha256", canonical + "", "base64url");
1391
- }
1392
- function idScheme(length) {
1393
- return `sha256-b64u-${length}-v2`;
1394
- }
1395
- const SCHEME = /^sha256-b64u-(8|9|1[0-6])-v2$/;
1396
- /** The id length a catalog header records, or null for anything vi18n did not write. */
1397
- function parseIdScheme(tag) {
1398
- const match = SCHEME.exec(tag);
1399
- return match === null ? null : {
1400
- length: Number(match[1]),
1401
- version: 2
1402
- };
1403
- }
1404
- /** The base64url alphabet has no `.`, so a `.` is what marks a manual id. */
1405
- function isManualId(id) {
1406
- return id.includes(".");
1407
- }
1408
- /** Characters that need no escaping in JS, JSON, PO, file names or URLs, with at least one `.`. */
1409
- const MANUAL_ID = /^[A-Za-z0-9_:-]+(\.[A-Za-z0-9_:-]+)+$/;
1410
- function isValidManualId(id) {
1411
- return MANUAL_ID.test(id);
1412
- }
1413
- //#endregion
1414
- //#region src/core/codec.ts
1415
- /**
1416
- * The one place that turns source text into ids (INTERNALS §2.2). Extract,
1417
- * catalogs and compilation see the same message many times per run, so parses,
1418
- * canonical forms and hashes are memoised per string.
1419
- */
1420
- /**
1421
- * Memo entries past this count are dropped all at once: a long dev session
1422
- * sees every edit of every message, while one scan of a large project needs
1423
- * the whole set warm.
1424
- */
1425
- const MEMO_LIMIT = 2e5;
1426
- function createCodec(idLength) {
1427
- if (!Number.isInteger(idLength) || idLength < 8 || idLength > 16) throw diagnosticError({
1428
- code: "config-invalid",
1429
- severity: "error",
1430
- message: `ids.length must be an integer from 8 to 16, not ${String(idLength)}`
1431
- });
1432
- const parsed = /* @__PURE__ */ new Map();
1433
- const hashes = /* @__PURE__ */ new Map();
1434
- const entry = (source) => {
1435
- let found = parsed.get(source);
1436
- if (found === void 0) {
1437
- found = {
1438
- ast: null,
1439
- error: null,
1440
- canonical: null
1441
- };
1442
- try {
1443
- const normalized = normalizeSource(source);
1444
- found.ast = isPlainText(normalized) ? normalized === "" ? [] : [{
1445
- type: "literal",
1446
- value: normalized
1447
- }] : parseSource(normalized);
1448
- } catch (error) {
1449
- if (!isDiagnosticError(error)) throw error;
1450
- found.error = error;
1451
- }
1452
- if (parsed.size >= MEMO_LIMIT) parsed.clear();
1453
- parsed.set(source, found);
1454
- }
1455
- return found;
1456
- };
1457
- const hashOf = (canonical) => {
1458
- let found = hashes.get(canonical);
1459
- if (found === void 0) {
1460
- found = sourceHash(canonical);
1461
- if (hashes.size >= MEMO_LIMIT) hashes.clear();
1462
- hashes.set(canonical, found);
1463
- }
1464
- return found;
1465
- };
1466
- return {
1467
- idLength,
1468
- idScheme: idScheme(idLength),
1469
- canonicalize(source) {
1470
- const found = parsed.get(source);
1471
- if (found === void 0) {
1472
- const normalized = normalizeSource(source);
1473
- if (isPlainText(normalized)) return normalized;
1474
- }
1475
- const memo = found ?? entry(source);
1476
- if (memo.error !== null) throw memo.error;
1477
- return memo.canonical ??= printICU(memo.ast);
1478
- },
1479
- parse(source) {
1480
- const memo = entry(source);
1481
- if (memo.error !== null) throw memo.error;
1482
- return memo.ast;
1483
- },
1484
- sourceHash: hashOf,
1485
- label(canonical) {
1486
- return hashOf(canonical).slice(0, idLength);
1487
- }
1624
+ };
1625
+ }));
1626
+ const set = /* @__PURE__ */ new Map();
1627
+ const diagnostics = [];
1628
+ for (const item of loaded) {
1629
+ set.set(item.catalog.locale, item.catalog);
1630
+ diagnostics.push(...item.diagnostics);
1631
+ }
1632
+ if (config.extraction.dependencies.length > 0) diagnostics.push(...await attachLibraryCatalogs(set, config, codec, wanted));
1633
+ return {
1634
+ set,
1635
+ diagnostics
1488
1636
  };
1489
1637
  }
1490
- //#endregion
1491
- //#region src/core/catalog/duplicates.ts
1492
- const RANK = {
1493
- translated: 2,
1494
- ai: 1,
1495
- untranslated: 0
1496
- };
1638
+ // src/core/catalog/duplicates.ts
1497
1639
  /** Entries grouped by key; only keys seen more than once. Null when there are none. */
1498
1640
  function duplicateGroups(catalog, codec) {
1499
1641
  const first = /* @__PURE__ */ new Map();
@@ -1517,7 +1659,10 @@ function duplicateGroups(catalog, codec) {
1517
1659
  /** `translated` over `ai` over `untranslated`, then the first in the file. */
1518
1660
  function winnerOf(entries, indexes) {
1519
1661
  let best = indexes[0];
1520
- for (const index of indexes) if (RANK[entries[index].state] > RANK[entries[best].state]) best = index;
1662
+ for (const index of indexes) {
1663
+ const state = entries[index].state;
1664
+ if (STATE_RANK[state] > STATE_RANK[entries[best].state]) best = index;
1665
+ }
1521
1666
  return best;
1522
1667
  }
1523
1668
  /**
@@ -1575,9 +1720,11 @@ function duplicateDiagnostics(duplicates, file) {
1575
1720
  return diagnostic;
1576
1721
  });
1577
1722
  }
1578
- //#endregion
1579
- //#region src/core/compile/fallback.ts
1580
- const PSEUDO_LOCALES$1 = /* @__PURE__ */ new Set(["en-XA", "ar-XB"]);
1723
+ // src/core/compile/fallback.ts
1724
+ const PSEUDO = new Set(PSEUDO_LOCALES);
1725
+ function isPseudoLocale(locale) {
1726
+ return PSEUDO.has(locale);
1727
+ }
1581
1728
  /**
1582
1729
  * The locales whose catalogs supply `locale`'s messages, most specific first
1583
1730
  * and always ending with `sourceLocale` (INTERNALS §2.8.1).
@@ -1596,7 +1743,7 @@ const PSEUDO_LOCALES$1 = /* @__PURE__ */ new Set(["en-XA", "ar-XB"]);
1596
1743
  function fallbackChain(locale, config) {
1597
1744
  const source = config.sourceLocale;
1598
1745
  if (locale === source) return [locale];
1599
- if (PSEUDO_LOCALES$1.has(locale)) return [locale, source];
1746
+ if (isPseudoLocale(locale)) return [locale, source];
1600
1747
  const chain = [locale];
1601
1748
  for (let end = locale.lastIndexOf("-"); end > 0; end = locale.lastIndexOf("-", end - 1)) {
1602
1749
  const ancestor = locale.slice(0, end);
@@ -1611,16 +1758,7 @@ function fallbackChain(locale, config) {
1611
1758
  chain.push(source);
1612
1759
  return chain;
1613
1760
  }
1614
- //#endregion
1615
- //#region src/core/compile/locales.ts
1616
- /**
1617
- * Locale compilation (INTERNALS §2.8.2, PLAN §5.5 D10, §5.9): catalogs and
1618
- * code messages become one IR map per locale, fallbacks applied, with the
1619
- * reason every untranslated id fell back. The build, `vi18n compile`, dev
1620
- * catalog modules, `check` and `status` all read translations through here,
1621
- * so "what ships" has one definition.
1622
- */
1623
- const PSEUDO_LOCALES = /* @__PURE__ */ new Set(["en-XA", "ar-XB"]);
1761
+ // src/core/compile/locales.ts
1624
1762
  /** Ids listed in `catalog-missing-translation`; the rest are only counted. */
1625
1763
  const MISSING_LISTED = 20;
1626
1764
  const NO_ENTRY = {
@@ -1632,157 +1770,99 @@ const SCHEME_MISMATCH = {
1632
1770
  reason: "scheme-mismatch"
1633
1771
  };
1634
1772
  function compileLocales(input) {
1635
- const { config, codec, messages, catalogs } = input;
1636
- const sourceFallback = input.sourceFallback ?? true;
1637
- const layout = catalogLayout(config);
1638
- const sourceLocale = config.sourceLocale;
1639
- const invalidSeverity = severityOf(config.strict.invalid);
1640
- const missingSeverity = severityOf(config.strict.missing);
1641
- const prepared = /* @__PURE__ */ new Map();
1642
- const prepare = (locale) => {
1643
- let found = prepared.get(locale);
1644
- if (found === void 0) {
1645
- found = prepareCatalog(catalogs, locale, layout, codec, config.root);
1646
- prepared.set(locale, found);
1647
- }
1648
- return found;
1649
- };
1650
- let sink = [];
1651
- const report = (catalog) => {
1652
- if (catalog !== null && catalog.pending !== null) {
1653
- for (const diagnostic of catalog.pending) sink.push(diagnostic);
1654
- catalog.pending = null;
1655
- }
1656
- return catalog;
1657
- };
1658
- const lookup = (catalog, id, message) => {
1659
- if (catalog === null) return NO_ENTRY;
1660
- const cached = catalog.lookups.get(id);
1661
- if (cached !== void 0) return cached;
1662
- const result = evaluate(catalog, id, message);
1663
- catalog.lookups.set(id, result);
1664
- return result;
1665
- };
1666
- const libraries = /* @__PURE__ */ new Map();
1667
- /** A package's language, for its catalogs that differ from the app's (§2.6.11). */
1668
- const librarySource = /* @__PURE__ */ new Map();
1669
- const librariesOf = (locale) => {
1670
- let found = libraries.get(locale);
1671
- if (found === void 0) {
1672
- found = [];
1673
- for (const loaded of catalogs.get(locale)?.libraries ?? []) {
1674
- const one = prepareCatalog(/* @__PURE__ */ new Map([[locale, loaded]]), locale, layout, codec, config.root);
1675
- if (one === null) continue;
1676
- const prepared = {
1677
- ...one,
1678
- pending: null,
1679
- library: true
1680
- };
1681
- if (loaded.librarySource !== void 0) librarySource.set(prepared, loaded.librarySource);
1682
- found.push(prepared);
1683
- }
1684
- libraries.set(locale, found);
1685
- }
1686
- return found;
1687
- };
1688
- /** A chain step: the app's catalog, then each library's for the same locale. */
1689
- const step = (catalog, locale, id, message) => {
1690
- const own = lookup(catalog, id, message);
1691
- if (own.ok) return own;
1692
- for (const library of librariesOf(locale)) {
1693
- const found = lookup(library, id, message);
1694
- if (found.ok) return found;
1695
- }
1696
- return own;
1697
- };
1698
- const evaluate = (catalog, id, message) => {
1699
- if (catalog.schemeMismatch && (layout === "id" || !message.manual)) return SCHEME_MISMATCH;
1700
- const entry = catalog.index.get(id);
1701
- if (entry === void 0) return NO_ENTRY;
1702
- const usable = usableTranslation(entry, layout, message, codec, catalog.locale);
1703
- if (usable.ok) return {
1704
- ok: true,
1705
- ir: compileMessage(usable.parsed),
1706
- state: entry.state === "ai" ? "ai" : "translated"
1707
- };
1708
- if (catalog.library) return {
1709
- ok: false,
1710
- reason: usable.reason
1711
- };
1712
- if (usable.reason === "invalid" && invalidSeverity !== null) sink.push(invalidDiagnostic(catalog, entry, id, usable.diagnostics, invalidSeverity));
1713
- else if (usable.reason === "source-mismatch" && entry.manualId !== null) sink.push(sourceMismatchDiagnostic(catalog, entry, id, message, layout));
1714
- return {
1715
- ok: false,
1716
- reason: usable.reason
1717
- };
1718
- };
1719
- const sourceIRs = /* @__PURE__ */ new Map();
1720
- const sourceIR = (id, message) => {
1721
- let ir = sourceIRs.get(id);
1722
- if (ir === void 0) {
1723
- ir = parseOrReport(codec, message, sink, (ast) => compileMessage(ast));
1724
- sourceIRs.set(id, ir);
1725
- }
1726
- return ir;
1727
- };
1728
- const all = withKeep(messages, input.keep ?? config.extraction.keep, {
1773
+ const { config, codec, catalogs } = input;
1774
+ const compiler = new LocaleCompiler(config, codec, catalogs);
1775
+ const keep = input.keep ?? config.extraction.keep;
1776
+ const preamble = [];
1777
+ compiler.reportTo(preamble);
1778
+ const all = withKeep(input.messages, keep, {
1729
1779
  config,
1730
1780
  codec,
1731
- layout,
1732
1781
  catalogs,
1733
- prepare,
1734
- sink: (diagnostic) => sink.push(diagnostic)
1782
+ prepare: (locale) => compiler.prepare(locale),
1783
+ sink: (diagnostic) => preamble.push(diagnostic)
1735
1784
  });
1736
- const keepSet = new Set(input.keep ?? config.extraction.keep);
1737
- const preamble = sink;
1785
+ const target = {
1786
+ sourceFallback: input.sourceFallback ?? true,
1787
+ keep: new Set(keep),
1788
+ missingSeverity: severityOf(config.strict.missing)
1789
+ };
1738
1790
  const result = /* @__PURE__ */ new Map();
1739
1791
  for (const locale of input.locales) {
1740
- const chain = fallbackChain(locale, config);
1741
1792
  const compiled = {
1742
1793
  locale,
1743
- chain,
1794
+ chain: fallbackChain(locale, config),
1744
1795
  messages: /* @__PURE__ */ new Map(),
1745
1796
  status: /* @__PURE__ */ new Map(),
1746
1797
  labels: /* @__PURE__ */ new Map(),
1747
1798
  diagnostics: result.size === 0 ? preamble : []
1748
1799
  };
1749
- sink = compiled.diagnostics;
1750
1800
  result.set(locale, compiled);
1751
- if (PSEUDO_LOCALES.has(locale)) {
1752
- compilePseudo(compiled, locale, all, codec);
1753
- continue;
1754
- }
1755
- if (locale === sourceLocale) {
1756
- report(prepare(locale));
1757
- const status = {
1758
- state: "translated",
1759
- from: sourceLocale
1760
- };
1761
- const foreign = librariesOf(locale);
1762
- for (const [id, message] of all) {
1763
- let ir = null;
1764
- for (const library of foreign) {
1765
- const found = lookup(library, id, message);
1766
- if (found.ok) {
1767
- ir = found.ir;
1768
- break;
1769
- }
1770
- }
1771
- ir ??= sourceIR(id, message);
1772
- if (ir === null) continue;
1773
- compiled.messages.set(id, ir);
1774
- compiled.status.set(id, status);
1775
- if (message.manual) compiled.labels.set(id, message.label);
1776
- }
1777
- continue;
1801
+ compiler.reportTo(compiled.diagnostics);
1802
+ if (isPseudoLocale(locale)) compilePseudo(compiled, locale, all, codec);
1803
+ else if (locale === config.sourceLocale) compiler.compileSource(compiled, all);
1804
+ else compiler.compileTarget(compiled, all, target);
1805
+ }
1806
+ return result;
1807
+ }
1808
+ /**
1809
+ * One compilation's catalogs, prepared once and shared by every locale whose
1810
+ * chain reaches them: lookups are memoised per catalog, source IR per id.
1811
+ */
1812
+ var LocaleCompiler = class {
1813
+ #config;
1814
+ #codec;
1815
+ #catalogs;
1816
+ #layout;
1817
+ #invalidSeverity;
1818
+ #prepared = /* @__PURE__ */ new Map();
1819
+ /** Opted-in packages' catalogs of each locale (§2.6.11). */
1820
+ #libraries = /* @__PURE__ */ new Map();
1821
+ /** Source IR is the same for every locale that falls back to it. */
1822
+ #sourceIRs = /* @__PURE__ */ new Map();
1823
+ /**
1824
+ * Where findings land: the locale being compiled. A memoised lookup reports
1825
+ * once, into the locale that first made it, so each finding appears once.
1826
+ */
1827
+ #diagnostics = [];
1828
+ constructor(config, codec, catalogs) {
1829
+ this.#config = config;
1830
+ this.#codec = codec;
1831
+ this.#catalogs = catalogs;
1832
+ this.#layout = catalogLayout(config);
1833
+ this.#invalidSeverity = severityOf(config.strict.invalid);
1834
+ }
1835
+ reportTo(diagnostics) {
1836
+ this.#diagnostics = diagnostics;
1837
+ }
1838
+ prepare(locale) {
1839
+ let found = this.#prepared.get(locale);
1840
+ if (found === void 0) {
1841
+ found = prepareCatalog(this.#catalogs, locale, this.#layout, this.#codec, this.#config.root);
1842
+ this.#prepared.set(locale, found);
1778
1843
  }
1779
- const own = report(prepare(locale));
1780
- const walk = [];
1781
- for (let i = 1; i < chain.length; i++) {
1782
- const member = chain[i];
1783
- if (member !== sourceLocale) walk.push(report(prepare(member)));
1844
+ return found;
1845
+ }
1846
+ /** The source locale: code text, or a foreign package's catalog for it (§2.6.11). */
1847
+ compileSource(compiled, all) {
1848
+ const { locale } = compiled;
1849
+ this.#report(this.prepare(locale));
1850
+ const status = {
1851
+ state: "translated",
1852
+ from: locale
1853
+ };
1854
+ for (const [id, message] of all) {
1855
+ const ir = this.#libraryHit(locale, id, message) ?? this.#sourceIR(id, message);
1856
+ if (ir === null) continue;
1857
+ compiled.messages.set(id, ir);
1858
+ compiled.status.set(id, status);
1859
+ if (message.manual) compiled.labels.set(id, message.label);
1784
1860
  }
1785
- const walkLocales = chain.slice(1).filter((member) => member !== sourceLocale);
1861
+ }
1862
+ compileTarget(compiled, all, options) {
1863
+ const { locale } = compiled;
1864
+ const own = this.#report(this.prepare(locale));
1865
+ const walk = this.#walk(compiled.chain);
1786
1866
  const translated = {
1787
1867
  state: "translated",
1788
1868
  from: locale
@@ -1792,10 +1872,10 @@ function compileLocales(input) {
1792
1872
  from: locale
1793
1873
  };
1794
1874
  const missing = /* @__PURE__ */ new Map();
1795
- let missingCount = 0;
1796
1875
  const missingIds = [];
1876
+ let missingCount = 0;
1797
1877
  for (const [id, message] of all) {
1798
- const mine = step(own, locale, id, message);
1878
+ const mine = this.#step(own, locale, id, message);
1799
1879
  if (mine.ok) {
1800
1880
  compiled.messages.set(id, mine.ir);
1801
1881
  compiled.status.set(id, mine.state === "ai" ? ai : translated);
@@ -1804,56 +1884,158 @@ function compileLocales(input) {
1804
1884
  }
1805
1885
  missingCount++;
1806
1886
  if (missingIds.length < MISSING_LISTED) missingIds.push(id);
1807
- let from = sourceLocale;
1808
- let ir = null;
1809
- for (let i = 0; i < walk.length; i++) {
1810
- const found = step(walk[i], walkLocales[i], id, message);
1811
- if (found.ok) {
1812
- ir = found.ir;
1813
- from = walkLocales[i];
1814
- break;
1815
- }
1816
- }
1817
- if (ir === null) for (const library of librariesOf(sourceLocale)) {
1818
- if (librarySource.get(library) === locale) continue;
1819
- const found = lookup(library, id, message);
1820
- if (found.ok) {
1821
- ir = found.ir;
1822
- break;
1823
- }
1824
- }
1825
- const suppliedByEntry = ir !== null;
1826
- if (ir === null && (sourceFallback || keepSet.has(id))) ir = sourceIR(id, message);
1887
+ const fallback = this.#fallback(walk, locale, id, message);
1888
+ const suppliedByEntry = fallback.ir !== null;
1889
+ let ir = fallback.ir;
1890
+ if (ir === null && (options.sourceFallback || options.keep.has(id))) ir = this.#sourceIR(id, message);
1827
1891
  if (ir !== null) compiled.messages.set(id, ir);
1828
- const statusKey = `${from}\0${mine.reason}`;
1892
+ const statusKey = `${fallback.from}\0${mine.reason}`;
1829
1893
  let status = missing.get(statusKey);
1830
1894
  if (status === void 0) {
1831
1895
  status = {
1832
1896
  state: "missing",
1833
- from,
1897
+ from: fallback.from,
1834
1898
  reason: mine.reason
1835
1899
  };
1836
1900
  missing.set(statusKey, status);
1837
1901
  }
1838
1902
  compiled.status.set(id, status);
1839
1903
  if (message.manual) {
1840
- const label = suppliedByEntry ? message.label : ownLabel(own, id, layout, codec);
1904
+ const label = suppliedByEntry ? message.label : this.#ownLabel(own, id);
1841
1905
  if (label !== null) compiled.labels.set(id, label);
1842
1906
  else if (ir !== null) compiled.labels.set(id, message.label);
1843
1907
  }
1844
1908
  }
1845
- if (missingCount > 0 && missingSeverity !== null) {
1846
- const more = missingCount > missingIds.length ? ", …" : "";
1847
- compiled.diagnostics.push({
1848
- code: "catalog-missing-translation",
1849
- severity: missingSeverity,
1850
- message: `${missingCount} ${missingCount === 1 ? "message has" : "messages have"} no usable ${locale} translation (${missingIds.join(", ")}${more}); ${missingCount === 1 ? "it falls" : "they fall"} back along ${chain.join(" → ")}`,
1851
- locale,
1852
- ...own === null ? {} : { file: own.file }
1853
- });
1909
+ if (missingCount > 0 && options.missingSeverity !== null) compiled.diagnostics.push(missingDiagnostic(compiled, missingCount, missingIds, options.missingSeverity, own));
1910
+ }
1911
+ /** The chain after the locale itself, without the source locale, which `#fallback` handles last. */
1912
+ #walk(chain) {
1913
+ const walk = [];
1914
+ for (const member of chain.slice(1)) if (member !== this.#config.sourceLocale) walk.push({
1915
+ locale: member,
1916
+ catalog: this.#report(this.prepare(member))
1917
+ });
1918
+ return walk;
1919
+ }
1920
+ /** The first fallback that translates `id`, and where it came from (the source locale when none does). */
1921
+ #fallback(walk, locale, id, message) {
1922
+ for (const member of walk) {
1923
+ const found = this.#step(member.catalog, member.locale, id, message);
1924
+ if (found.ok) return {
1925
+ ir: found.ir,
1926
+ from: member.locale
1927
+ };
1928
+ }
1929
+ const sourceLocale = this.#config.sourceLocale;
1930
+ return {
1931
+ ir: this.#libraryHit(sourceLocale, id, message, (library) => library.librarySource === locale),
1932
+ from: sourceLocale
1933
+ };
1934
+ }
1935
+ /** Hands a catalog's file-level findings to the current locale, once. */
1936
+ #report(catalog) {
1937
+ if (catalog !== null && catalog.pending !== null) {
1938
+ for (const diagnostic of catalog.pending) this.#diagnostics.push(diagnostic);
1939
+ catalog.pending = null;
1854
1940
  }
1941
+ return catalog;
1855
1942
  }
1856
- return result;
1943
+ #librariesOf(locale) {
1944
+ let found = this.#libraries.get(locale);
1945
+ if (found !== void 0) return found;
1946
+ found = [];
1947
+ for (const loaded of this.#catalogs.get(locale)?.libraries ?? []) {
1948
+ const one = prepareCatalog(/* @__PURE__ */ new Map([[locale, loaded]]), locale, this.#layout, this.#codec, this.#config.root);
1949
+ if (one === null) continue;
1950
+ const prepared = {
1951
+ ...one,
1952
+ pending: null,
1953
+ library: true
1954
+ };
1955
+ if (loaded.librarySource !== void 0) prepared.librarySource = loaded.librarySource;
1956
+ found.push(prepared);
1957
+ }
1958
+ this.#libraries.set(locale, found);
1959
+ return found;
1960
+ }
1961
+ /** The IR of the first library catalog of `locale` that translates `id` usably. */
1962
+ #libraryHit(locale, id, message, skip) {
1963
+ for (const library of this.#librariesOf(locale)) {
1964
+ if (skip?.(library) === true) continue;
1965
+ const found = this.#lookup(library, id, message);
1966
+ if (found.ok) return found.ir;
1967
+ }
1968
+ return null;
1969
+ }
1970
+ /** A chain step: the app's catalog, then each library's for the same locale. */
1971
+ #step(catalog, locale, id, message) {
1972
+ const own = this.#lookup(catalog, id, message);
1973
+ if (own.ok) return own;
1974
+ for (const library of this.#librariesOf(locale)) {
1975
+ const found = this.#lookup(library, id, message);
1976
+ if (found.ok) return found;
1977
+ }
1978
+ return own;
1979
+ }
1980
+ #lookup(catalog, id, message) {
1981
+ if (catalog === null) return NO_ENTRY;
1982
+ const cached = catalog.lookups.get(id);
1983
+ if (cached !== void 0) return cached;
1984
+ const result = this.#evaluate(catalog, id, message);
1985
+ catalog.lookups.set(id, result);
1986
+ return result;
1987
+ }
1988
+ #evaluate(catalog, id, message) {
1989
+ const layout = this.#layout;
1990
+ if (catalog.schemeMismatch && (layout === "id" || !message.manual)) return SCHEME_MISMATCH;
1991
+ const entry = catalog.index.get(id);
1992
+ if (entry === void 0) return NO_ENTRY;
1993
+ const usable = usableTranslation(entry, layout, message, this.#codec, catalog.locale);
1994
+ if (usable.ok) return {
1995
+ ok: true,
1996
+ ir: compileMessage(usable.parsed),
1997
+ state: entry.state === "ai" ? "ai" : "translated"
1998
+ };
1999
+ if (catalog.library) return {
2000
+ ok: false,
2001
+ reason: usable.reason
2002
+ };
2003
+ const severity = this.#invalidSeverity;
2004
+ if (usable.reason === "invalid" && severity !== null) this.#diagnostics.push(invalidDiagnostic(catalog, entry, id, usable.diagnostics, severity));
2005
+ else if (usable.reason === "source-mismatch" && entry.manualId !== null) this.#diagnostics.push(sourceMismatchDiagnostic(catalog, entry, id, message, layout));
2006
+ return {
2007
+ ok: false,
2008
+ reason: usable.reason
2009
+ };
2010
+ }
2011
+ #sourceIR(id, message) {
2012
+ let ir = this.#sourceIRs.get(id);
2013
+ if (ir === void 0) {
2014
+ ir = parseOrReport(this.#codec, message, this.#diagnostics, (ast) => compileMessage(ast));
2015
+ this.#sourceIRs.set(id, ir);
2016
+ }
2017
+ return ir;
2018
+ }
2019
+ /** The label of the source a locale's own manual entry was made from, valid or not. */
2020
+ #ownLabel(own, id) {
2021
+ const entry = own?.index.get(id);
2022
+ if (entry === void 0) return null;
2023
+ if (this.#layout === "id") return entry.label;
2024
+ const canonical = entryCanonical(entry, this.#codec);
2025
+ return canonical === null ? null : this.#codec.label(canonical);
2026
+ }
2027
+ };
2028
+ /** The one `catalog-missing-translation` of a locale: how many fall back, the first ids, and along what. */
2029
+ function missingDiagnostic(compiled, count, ids, severity, own) {
2030
+ const { locale, chain } = compiled;
2031
+ const more = count > ids.length ? ", …" : "";
2032
+ return {
2033
+ code: "catalog-missing-translation",
2034
+ severity,
2035
+ message: `${count} ${count === 1 ? "message has" : "messages have"} no usable ${locale} translation (${ids.join(", ")}${more}); ${count === 1 ? "it falls" : "they fall"} back along ${chain.join(" → ")}`,
2036
+ locale,
2037
+ ...own === null ? {} : { file: own.file }
2038
+ };
1857
2039
  }
1858
2040
  function compilePseudo(compiled, locale, messages, codec) {
1859
2041
  const status = {
@@ -1880,14 +2062,6 @@ function parseOrReport(codec, message, sink, build) {
1880
2062
  return null;
1881
2063
  }
1882
2064
  }
1883
- function severityOf(level) {
1884
- return level === "off" ? null : level === "warn" ? "warning" : "error";
1885
- }
1886
- function displayPath(root, file) {
1887
- const rel = relative(root, file);
1888
- if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) return file.split(sep).join("/");
1889
- return rel.split(sep).join("/");
1890
- }
1891
2065
  function prepareCatalog(catalogs, locale, layout, codec, root) {
1892
2066
  const loaded = catalogs.get(locale);
1893
2067
  if (loaded === void 0 || loaded.catalog === null) return null;
@@ -1923,12 +2097,10 @@ function schemeDiagnostic(recorded, codec, layout, locale, file) {
1923
2097
  };
1924
2098
  }
1925
2099
  function invalidDiagnostic(catalog, entry, id, found, severity) {
1926
- const first = found[0];
1927
- const reason = first === void 0 ? "it does not validate" : found.length === 1 ? first.message : `${first.message}, and ${found.length - 1} more`;
1928
2100
  const diagnostic = {
1929
2101
  code: "catalog-invalid-translation",
1930
2102
  severity,
1931
- message: `${id}: the ${catalog.locale} translation is not used (${reason}); fix it or clear it`,
2103
+ message: `${id}: the ${catalog.locale} translation is not used (${invalidReason(found)}); fix it or clear it`,
1932
2104
  file: catalog.file,
1933
2105
  locale: catalog.locale,
1934
2106
  id
@@ -1941,6 +2113,11 @@ function invalidDiagnostic(catalog, entry, id, found, severity) {
1941
2113
  }));
1942
2114
  return diagnostic;
1943
2115
  }
2116
+ function invalidReason(found) {
2117
+ const first = found[0];
2118
+ if (first === void 0) return "it does not validate";
2119
+ return found.length === 1 ? first.message : `${first.message}, and ${found.length - 1} more`;
2120
+ }
1944
2121
  function sourceMismatchDiagnostic(catalog, entry, id, message, layout) {
1945
2122
  const old = entry.source ?? (layout === "id" ? entry.label : null);
1946
2123
  const was = old === null ? "" : ` is for ${JSON.stringify(old)}`;
@@ -1955,19 +2132,6 @@ function sourceMismatchDiagnostic(catalog, entry, id, message, layout) {
1955
2132
  if (entry.line > 0) diagnostic.line = entry.line;
1956
2133
  return diagnostic;
1957
2134
  }
1958
- /** The label of the source a locale's own manual entry was made from, valid or not. */
1959
- function ownLabel(own, id, layout, codec) {
1960
- const entry = own?.index.get(id);
1961
- if (entry === void 0) return null;
1962
- if (layout === "id") return entry.label;
1963
- if (entry.source === null) return null;
1964
- try {
1965
- return codec.label(codec.canonicalize(entry.source));
1966
- } catch (error) {
1967
- if (isDiagnosticError(error)) return null;
1968
- throw error;
1969
- }
1970
- }
1971
2135
  /**
1972
2136
  * The messages plus `keep` ids no message declares, whose identity comes from
1973
2137
  * their catalog entries (INTERNALS §2.8.2): the source locale's entry first
@@ -1991,7 +2155,7 @@ function withKeep(messages, keep, context) {
1991
2155
  if (entry === void 0) continue;
1992
2156
  found = true;
1993
2157
  if (entry.source === null) continue;
1994
- identity = keepIdentity(id, entry.source, codec);
2158
+ identity = keepIdentity(id, entry, codec);
1995
2159
  if (identity !== null) break;
1996
2160
  }
1997
2161
  if (identity !== null) {
@@ -2008,147 +2172,18 @@ function withKeep(messages, keep, context) {
2008
2172
  }
2009
2173
  return all;
2010
2174
  }
2011
- function keepIdentity(id, source, codec) {
2012
- let canonical;
2013
- try {
2014
- canonical = codec.canonicalize(source);
2015
- } catch (error) {
2016
- if (isDiagnosticError(error)) return null;
2017
- throw error;
2018
- }
2019
- const sourceHash = codec.sourceHash(canonical);
2175
+ function keepIdentity(id, entry, codec) {
2176
+ const canonical = entryCanonical(entry, codec);
2177
+ if (canonical === null) return null;
2020
2178
  return {
2021
2179
  id,
2022
2180
  manual: isManualId(id),
2023
2181
  canonical,
2024
- sourceHash,
2025
- label: sourceHash.slice(0, codec.idLength)
2182
+ sourceHash: codec.sourceHash(canonical),
2183
+ label: codec.label(canonical)
2026
2184
  };
2027
2185
  }
2028
- //#endregion
2029
- //#region src/config/types.ts
2030
- /** The only config file name (revision 4.2). */
2031
- const CONFIG_FILE = "vi18n.config.ts";
2032
- /** Import sources that always apply; `extraction.importSources` is appended to them. */
2033
- const DEFAULT_IMPORT_SOURCES = ["@menapo/vi18n", "@menapo/vi18n/server"];
2034
- /** Valid range of `ids.length`. */
2035
- const ID_LENGTH = {
2036
- min: 8,
2037
- max: 16,
2038
- default: 12
2039
- };
2040
- /**
2041
- * Defaults (PLAN §5.7). Relative paths here are resolved against the config
2042
- * directory; `catalogs.path` becomes `locales/{locale}.json` when only
2043
- * `format: "json"` is given.
2044
- */
2045
- const DEFAULT_CONFIG = {
2046
- sourceLocale: "en",
2047
- locales: ["en"],
2048
- pseudoLocales: [],
2049
- fallbacks: {},
2050
- project: {
2051
- include: ["src"],
2052
- extensions: [
2053
- ".js",
2054
- ".jsx",
2055
- ".mjs",
2056
- ".ts",
2057
- ".tsx",
2058
- ".mts",
2059
- ".svelte",
2060
- ".vue",
2061
- ".astro",
2062
- ".mdx"
2063
- ],
2064
- exclude: [
2065
- "node_modules",
2066
- "/dist",
2067
- "/build",
2068
- "**/*.test.*",
2069
- "**/*.spec.*",
2070
- "**/__tests__/**"
2071
- ]
2072
- },
2073
- extraction: {
2074
- importSources: [...DEFAULT_IMPORT_SOURCES],
2075
- aliases: [],
2076
- globals: [],
2077
- keep: [],
2078
- dependencies: []
2079
- },
2080
- ids: { length: ID_LENGTH.default },
2081
- catalogs: {
2082
- format: "po",
2083
- path: "locales/{locale}.po",
2084
- msgid: "source",
2085
- icuFlag: false
2086
- },
2087
- output: {
2088
- split: {
2089
- shared: "per-set",
2090
- dupBelow: 1024,
2091
- minBytes: 1024,
2092
- maxBundlesPerRoot: null
2093
- },
2094
- guard: "auto",
2095
- manifestPath: "vi18n/{locale}/manifest.json",
2096
- manifest: "data",
2097
- baseEntries: [],
2098
- compactIds: false,
2099
- perLocale: false
2100
- },
2101
- routing: {
2102
- strategy: [
2103
- "url",
2104
- "cookie",
2105
- "header",
2106
- "default"
2107
- ],
2108
- routeStrategies: {},
2109
- url: "prefix_except_default",
2110
- redirectRoot: false,
2111
- propagate: "header",
2112
- switch: "in-place",
2113
- cookie: {
2114
- name: "vi18n_locale",
2115
- maxAge: 31536e3
2116
- },
2117
- base: null,
2118
- paths: {},
2119
- domains: {}
2120
- },
2121
- ssr: {
2122
- timeZone: "UTC",
2123
- timeZoneFrom: {},
2124
- payload: "bundles",
2125
- catalogs: "auto",
2126
- maxLoadedLocales: 8,
2127
- normalizeSpaces: true
2128
- },
2129
- ai: {
2130
- provider: "gemini",
2131
- model: "gemini-3.8-flash",
2132
- exclude: [],
2133
- glossary: {},
2134
- doNotTranslate: [],
2135
- tone: {},
2136
- description: null,
2137
- apiKeyEnv: "GEMINI_API_KEY",
2138
- batchSize: 60,
2139
- concurrency: 4,
2140
- dev: false
2141
- },
2142
- defaults: { tags: {} },
2143
- devtools: false,
2144
- strict: {
2145
- missing: "warn",
2146
- invalid: "error",
2147
- moduleScope: "warn"
2148
- }
2149
- };
2150
- //#endregion
2151
- //#region src/core/config/exclude.ts
2186
+ // src/core/config/exclude.ts
2152
2187
  /**
2153
2188
  * `ai.exclude` entries (PLAN §4.6, §5.20; INTERNALS §2.15): a configured
2154
2189
  * locale, a message id, or a glob over the config-relative files that use a
@@ -2171,8 +2206,7 @@ function excludeKind(entry, locales, idLength) {
2171
2206
  if (isValidManualId(entry)) return "id";
2172
2207
  return entry.length === idLength && BASE64URL.test(entry) ? "id" : null;
2173
2208
  }
2174
- //#endregion
2175
- //#region src/core/config/schema.ts
2209
+ // src/core/config/schema.ts
2176
2210
  /**
2177
2211
  * The zod 4 schema of `vi18n.config.ts` (PLAN §5.7, INTERNALS §2.7.1). It
2178
2212
  * checks shapes and per-field rules only; rules that relate two keys
@@ -2242,8 +2276,6 @@ const RAW_TEXT = /* @__PURE__ */ new Set([
2242
2276
  "xmp"
2243
2277
  ]);
2244
2278
  const element = z.string().regex(/^[a-z][a-z\d-]*$/, { error: "an HTML element name in lower case" }).refine((name) => !RAW_TEXT.has(name), { error: "must render its children as text (not script, style, iframe or noscript)" });
2245
- /** PLAN §5.20: batches of 40–80 items. */
2246
- const BATCH_SIZE_RANGE = "must be an integer from 40 to 80";
2247
2279
  const text = z.string().min(1, { error: "must be a non-empty string" });
2248
2280
  const locale = z.string().superRefine((value, ctx) => {
2249
2281
  const problem = localeProblem(value);
@@ -2253,6 +2285,11 @@ const locale = z.string().superRefine((value, ctx) => {
2253
2285
  });
2254
2286
  });
2255
2287
  const positiveInt = z.number({ error: "must be a positive integer" }).int({ error: "must be a positive integer" }).positive({ error: "must be a positive integer" });
2288
+ /** An integer from `min` to `max`, every failure reported with the one message naming the range. */
2289
+ function intIn(min, max) {
2290
+ const error = `must be an integer from ${min} to ${max}`;
2291
+ return z.number({ error }).int({ error }).min(min, { error }).max(max, { error });
2292
+ }
2256
2293
  const withLocale = z.string().includes("{locale}", { error: "must contain {locale}" });
2257
2294
  const manifestPath = withLocale.refine((path) => path.indexOf("{locale}", path.indexOf("{locale}") + 1) < 0, { error: "must contain {locale} exactly once" });
2258
2295
  const routePattern = z.string().startsWith("/", { error: "route patterns start with /" });
@@ -2289,7 +2326,7 @@ const outputSchema = z.strictObject({
2289
2326
  const configSchema = z.strictObject({
2290
2327
  sourceLocale: locale.optional(),
2291
2328
  locales: z.array(locale).min(1, { error: "must list at least one locale" }).optional(),
2292
- pseudoLocales: z.array(z.enum(["en-XA", "ar-XB"])).optional(),
2329
+ pseudoLocales: z.array(z.enum(PSEUDO_LOCALES)).optional(),
2293
2330
  fallbacks: z.record(locale, z.array(locale)).optional(),
2294
2331
  project: z.strictObject({
2295
2332
  include: z.array(text).optional(),
@@ -2301,9 +2338,10 @@ const configSchema = z.strictObject({
2301
2338
  aliases: z.array(text).optional(),
2302
2339
  globals: z.array(text).optional(),
2303
2340
  keep: z.array(text).optional(),
2304
- dependencies: z.array(z.string().regex(/^(?:@[a-z0-9][\w.~-]*\/)?[a-z0-9][\w.~-]*$/, { error: "must be a package name, like \"@acme/ui\"" })).refine((names) => new Set(names).size === names.length, { error: "lists a package twice" }).optional()
2341
+ dependencies: z.array(z.string().regex(/^(?:@[a-z0-9][\w.~-]*\/)?[a-z0-9][\w.~-]*$/, { error: "must be a package name, like \"@acme/ui\"" })).refine((names) => new Set(names).size === names.length, { error: "lists a package twice" }).optional(),
2342
+ repeatedText: z.union([z.literal(false), intIn(2, 1e3)]).optional()
2305
2343
  }).optional(),
2306
- ids: z.strictObject({ length: z.number({ error: `must be an integer from ${ID_LENGTH.min} to ${ID_LENGTH.max}` }).int({ error: `must be an integer from ${ID_LENGTH.min} to ${ID_LENGTH.max}` }).min(ID_LENGTH.min, { error: `must be an integer from ${ID_LENGTH.min} to ${ID_LENGTH.max}` }).max(ID_LENGTH.max, { error: `must be an integer from ${ID_LENGTH.min} to ${ID_LENGTH.max}` }).optional() }).optional(),
2344
+ ids: z.strictObject({ length: intIn(ID_LENGTH.min, ID_LENGTH.max).optional() }).optional(),
2307
2345
  catalogs: z.strictObject({
2308
2346
  format: z.enum(["po", "json"]).optional(),
2309
2347
  path: withLocale.optional(),
@@ -2361,7 +2399,7 @@ const configSchema = z.strictObject({
2361
2399
  tone: z.record(z.string(), z.string()).optional(),
2362
2400
  description: z.string().optional(),
2363
2401
  apiKeyEnv: z.string().regex(/^[A-Za-z_]\w*$/, { error: "must be an environment variable name" }).optional(),
2364
- batchSize: z.number({ error: BATCH_SIZE_RANGE }).int({ error: BATCH_SIZE_RANGE }).min(40, { error: BATCH_SIZE_RANGE }).max(80, { error: BATCH_SIZE_RANGE }).optional(),
2402
+ batchSize: intIn(40, 80).optional(),
2365
2403
  concurrency: positiveInt.optional(),
2366
2404
  dev: z.boolean().optional()
2367
2405
  }).optional(),
@@ -2384,6 +2422,12 @@ function formatPath(path) {
2384
2422
  else out += `[${JSON.stringify(String(key))}]`;
2385
2423
  return out;
2386
2424
  }
2425
+ /** What an issue line names: the key path under `label`, the label alone, or `config` for the root. */
2426
+ function issueSubject(label, key) {
2427
+ if (label === "") return key || "config";
2428
+ if (key === "") return label;
2429
+ return `${label}${key.startsWith("[") ? "" : "."}${key}`;
2430
+ }
2387
2431
  /**
2388
2432
  * One `<key path>: <problem>` line per zod issue, nested union and key
2389
2433
  * issues flattened. `label` names the object the paths start from.
@@ -2391,9 +2435,7 @@ function formatPath(path) {
2391
2435
  function issueLines(issues, prefix = [], label = "") {
2392
2436
  const lines = [];
2393
2437
  const line = (path, message) => {
2394
- const key = formatPath(path);
2395
- const at = label === "" ? key || "config" : key === "" ? label : `${label}${key.startsWith("[") ? "" : "."}${key}`;
2396
- lines.push(`${at}: ${message}`);
2438
+ lines.push(`${issueSubject(label, formatPath(path))}: ${message}`);
2397
2439
  };
2398
2440
  for (const issue of issues) {
2399
2441
  const path = [...prefix, ...issue.path];
@@ -2415,8 +2457,17 @@ function issueLines(issues, prefix = [], label = "") {
2415
2457
  }
2416
2458
  return lines;
2417
2459
  }
2418
- //#endregion
2419
- //#region src/core/config/routing.ts
2460
+ // src/core/config/routing.ts
2461
+ /**
2462
+ * `routing.paths` and `routing.domains` (PLAN §4.11, §5.14; INTERNALS §2.7.1,
2463
+ * §6 D132, D135): the rules between their entries and the rest of the
2464
+ * config, checked once the locale list is known, and the domain keys in the
2465
+ * one form the runtime compares (`https://example.de`).
2466
+ *
2467
+ * The URL codec (`src/runtime/url.ts`) trusts what passes here: a path is
2468
+ * either a route path or one locale's form of one, so translating it back
2469
+ * and forth never depends on which entry is read first.
2470
+ */
2420
2471
  /** Segments of a validated path as a pathname spells them (`*` and `**` stay). */
2421
2472
  const segmentsOf = (path) => new URL(path, "http://h").pathname.split("/").slice(1);
2422
2473
  /**
@@ -2468,24 +2519,40 @@ function domainOrigin(key) {
2468
2519
  /** `routing.domains` with every key as `https://host[:port]` (or its `http:` origin). */
2469
2520
  function resolveDomains(domains) {
2470
2521
  const out = {};
2471
- for (const [key, locale] of Object.entries(domains)) out[domainOrigin(key)] = locale;
2522
+ for (const [key, locale] of Object.entries(domains)) {
2523
+ const origin = domainOrigin(key);
2524
+ if (origin === null) throw new Error(`routing.domains: ${JSON.stringify(key)} is not a host; check the config with routingProblems before resolving it`);
2525
+ out[origin] = locale;
2526
+ }
2472
2527
  return out;
2473
2528
  }
2529
+ const at = (...keys) => formatPath(["routing", ...keys]);
2474
2530
  /**
2475
2531
  * Rules between `routing.paths`, `routing.domains` and the other keys. Only
2476
2532
  * configured locales (never pseudo-locales, which are not advertised) may
2477
2533
  * have a path or a host.
2478
2534
  */
2479
2535
  function routingProblems(routing, sourceLocale, locales) {
2480
- const problems = [];
2481
- const url = routing?.url ?? "prefix_except_default";
2536
+ const url = routing?.url ?? DEFAULT_CONFIG.routing.url;
2482
2537
  const paths = routing?.paths ?? {};
2483
2538
  const domains = routing?.domains ?? {};
2484
2539
  const hasDomains = Object.keys(domains).length > 0;
2485
- const at = (...keys) => formatPath(["routing", ...keys]);
2486
- if (hasDomains && url !== "prefix_except_default") problems.push(`${at("domains")}: needs routing.url "prefix_except_default" (a host's locale is its unprefixed one, every other host's prefix is redirected to that host)`);
2540
+ const problems = domainProblems(domains, url, locales);
2541
+ const { valid, problems: entries } = pathEntryProblems(paths, url, locales);
2542
+ problems.push(...entries);
2543
+ let unprefixed = [sourceLocale];
2544
+ if (url === "prefix" || url === "no_prefix") unprefixed = [];
2545
+ else if (hasDomains) unprefixed = locales;
2546
+ problems.push(...pathConflictProblems(valid, paths, locales, unprefixed));
2547
+ return problems;
2548
+ }
2549
+ function domainProblems(domains, url, locales) {
2550
+ const problems = [];
2551
+ const hosts = Object.entries(domains);
2552
+ if (hosts.length === 0) return problems;
2553
+ if (url !== "prefix_except_default") problems.push(`${at("domains")}: needs routing.url "prefix_except_default" (a host's locale is its unprefixed one, every other host's prefix is redirected to that host)`);
2487
2554
  const seen = /* @__PURE__ */ new Map();
2488
- for (const [key, locale] of Object.entries(domains)) {
2555
+ for (const [key, locale] of hosts) {
2489
2556
  const origin = domainOrigin(key);
2490
2557
  if (origin === null) {
2491
2558
  problems.push(`${at("domains", key)}: must be a host such as "example.de" or an origin such as "http://localhost:5173"`);
@@ -2496,63 +2563,77 @@ function routingProblems(routing, sourceLocale, locales) {
2496
2563
  seen.set(origin, key);
2497
2564
  if (!locales.includes(locale)) problems.push(`${at("domains", key)}: ${JSON.stringify(locale)} is not in locales`);
2498
2565
  }
2499
- if (hasDomains) {
2500
- const served = new Set(Object.values(domains));
2501
- for (const l of locales) if (!served.has(l)) problems.push(`${at("domains")}: no host serves ${JSON.stringify(l)} (every locale needs one)`);
2502
- }
2503
- const keys = Object.keys(paths);
2504
- if (keys.length > 0 && url === "no_prefix") problems.push(`${at("paths")}: needs URLs that name their locale (a routing.url other than "no_prefix")`);
2566
+ const served = new Set(Object.values(domains));
2567
+ for (const locale of locales) if (!served.has(locale)) problems.push(`${at("domains")}: no host serves ${JSON.stringify(locale)} (every locale needs one)`);
2568
+ return problems;
2569
+ }
2570
+ /** Each `routing.paths` entry on its own; `valid` lists the keys whose entry has no problem. */
2571
+ function pathEntryProblems(paths, url, locales) {
2572
+ const problems = [];
2573
+ if (Object.keys(paths).length > 0 && url === "no_prefix") problems.push(`${at("paths")}: needs URLs that name their locale (a routing.url other than "no_prefix")`);
2505
2574
  const valid = [];
2506
- for (const key of keys) {
2575
+ for (const [key, forms] of Object.entries(paths)) {
2507
2576
  const problem = pathProblem(key);
2508
2577
  if (problem !== null) {
2509
2578
  problems.push(`${at("paths", key)}: ${problem}`);
2510
2579
  continue;
2511
2580
  }
2512
- let ok = true;
2513
- for (const [locale, value] of Object.entries(paths[key])) {
2581
+ const before = problems.length;
2582
+ for (const [locale, value] of Object.entries(forms)) {
2514
2583
  const where = at("paths", key, locale);
2515
- if (!locales.includes(locale)) {
2516
- problems.push(`${where}: ${JSON.stringify(locale)} is not in locales`);
2517
- ok = false;
2518
- }
2519
- const p = pathProblem(value);
2520
- if (p !== null) {
2521
- problems.push(`${where}: ${p}`);
2522
- ok = false;
2523
- } else if (wildcards(value) !== wildcards(key)) {
2524
- problems.push(`${where}: must keep the wildcards of ${JSON.stringify(key)}, in order`);
2525
- ok = false;
2526
- }
2584
+ if (!locales.includes(locale)) problems.push(`${where}: ${JSON.stringify(locale)} is not in locales`);
2585
+ const valueProblem = pathProblem(value);
2586
+ if (valueProblem !== null) problems.push(`${where}: ${valueProblem}`);
2587
+ else if (wildcards(value) !== wildcards(key)) problems.push(`${where}: must keep the wildcards of ${JSON.stringify(key)}, in order`);
2527
2588
  }
2528
- if (ok) valid.push(key);
2589
+ if (problems.length === before) valid.push(key);
2529
2590
  }
2530
- const form = (key, l) => Object.hasOwn(paths[key], l) ? paths[key][l] : key;
2531
- const seg = new Map(valid.map((k) => [k, segmentsOf(k)]));
2532
- const segOf = (p) => seg.get(p) ?? segmentsOf(p);
2533
- const unprefixed = url === "prefix" || url === "no_prefix" ? [] : hasDomains ? locales : [sourceLocale];
2534
- for (const l of locales) {
2591
+ return {
2592
+ valid,
2593
+ problems
2594
+ };
2595
+ }
2596
+ /**
2597
+ * Pairs of valid routes whose forms in one locale are the same path, or
2598
+ * overlap where the route paths do not; and, where a locale is unprefixed,
2599
+ * a translated path that would read as another route's path.
2600
+ */
2601
+ function pathConflictProblems(valid, paths, locales, unprefixed) {
2602
+ const problems = [];
2603
+ const formOf = (route, locale) => Object.hasOwn(paths[route], locale) ? paths[route][locale] : route;
2604
+ const segmentsCache = new Map(valid.map((route) => [route, segmentsOf(route)]));
2605
+ const segments = (path) => segmentsCache.get(path) ?? segmentsOf(path);
2606
+ for (const locale of locales) {
2535
2607
  for (let i = 0; i < valid.length; i++) {
2536
- const a = valid[i];
2537
- const fa = form(a, l);
2608
+ const routeA = valid[i];
2609
+ const formA = formOf(routeA, locale);
2538
2610
  for (let j = i + 1; j < valid.length; j++) {
2539
- const b = valid[j];
2540
- const fb = form(b, l);
2541
- const where = at("paths", Object.hasOwn(paths[b], l) ? b : a, l);
2542
- if (fa === fb) problems.push(`${where}: ${JSON.stringify(a)} and ${JSON.stringify(b)} share the path ${JSON.stringify(fa)} in ${l}`);
2543
- else if (overlap(segOf(fa), segOf(fb)) && !overlap(segOf(a), segOf(b))) problems.push(`${where}: ${JSON.stringify(fa)} and ${JSON.stringify(fb)} overlap in ${l}, but ${JSON.stringify(a)} and ${JSON.stringify(b)} do not`);
2611
+ const routeB = valid[j];
2612
+ const formB = formOf(routeB, locale);
2613
+ const where = at("paths", Object.hasOwn(paths[routeB], locale) ? routeB : routeA, locale);
2614
+ if (formA === formB) problems.push(`${where}: ${JSON.stringify(routeA)} and ${JSON.stringify(routeB)} share the path ${JSON.stringify(formA)} in ${locale}`);
2615
+ else if (overlap(segments(formA), segments(formB)) && !overlap(segments(routeA), segments(routeB))) problems.push(`${where}: ${JSON.stringify(formA)} and ${JSON.stringify(formB)} overlap in ${locale}, but ${JSON.stringify(routeA)} and ${JSON.stringify(routeB)} do not`);
2544
2616
  }
2545
2617
  }
2546
- if (!unprefixed.includes(l)) continue;
2547
- for (const a of valid) for (const b of valid) {
2548
- if (a === b || !Object.hasOwn(paths[b], l)) continue;
2549
- if (overlap(segOf(a), segOf(paths[b][l]))) problems.push(`${at("paths", b, l)}: ${JSON.stringify(paths[b][l])} would read as the route ${JSON.stringify(a)} where ${l} is unprefixed`);
2550
- }
2618
+ if (unprefixed.includes(locale)) problems.push(...unprefixedProblems(valid, paths, locale, segments));
2619
+ }
2620
+ return problems;
2621
+ }
2622
+ /** Where `locale` is unprefixed, a translated path must not read as another route's path. */
2623
+ function unprefixedProblems(valid, paths, locale, segments) {
2624
+ const problems = [];
2625
+ for (const routeA of valid) for (const routeB of valid) {
2626
+ if (routeA === routeB || !Object.hasOwn(paths[routeB], locale)) continue;
2627
+ if (overlap(segments(routeA), segments(paths[routeB][locale]))) problems.push(`${at("paths", routeB, locale)}: ${JSON.stringify(paths[routeB][locale])} would read as the route ${JSON.stringify(routeA)} where ${locale} is unprefixed`);
2551
2628
  }
2552
2629
  return problems;
2553
2630
  }
2554
- //#endregion
2555
- //#region src/core/config/load.ts
2631
+ // src/core/config/runtime.ts
2632
+ /** A fresh record of mapped values; `fromEntries` defines properties, so a `__proto__` key stays a key. */
2633
+ function mapRecord(record, map) {
2634
+ return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(value)]));
2635
+ }
2636
+ // src/core/config/load.ts
2556
2637
  /**
2557
2638
  * Finding, loading and resolving `vi18n.config.ts` (PLAN §5.7, INTERNALS
2558
2639
  * §2.7.1, spike S8). The plugin and the CLI both come through `loadConfig`,
@@ -2739,7 +2820,7 @@ function mergeDefined(base, over) {
2739
2820
  }
2740
2821
  function resolveWith(input, root, configFile, inline) {
2741
2822
  root = resolve(root);
2742
- const file = configFile === null ? void 0 : toPosix(relativeOrAbsolute(root, configFile));
2823
+ const file = configFile === null ? void 0 : displayPath(root, resolve(configFile));
2743
2824
  const result = configSchema.safeParse(input);
2744
2825
  if (!result.success) throw invalid(file, issueLines(result.error.issues).join("; "));
2745
2826
  const user = inline === void 0 ? result.data : {
@@ -2751,73 +2832,22 @@ function resolveWith(input, root, configFile, inline) {
2751
2832
  const problems = crossFieldProblems(user, sourceLocale, locales);
2752
2833
  if (problems.length > 0) throw invalid(file, problems.join("; "));
2753
2834
  const d = DEFAULT_CONFIG;
2754
- const format = user.catalogs?.format ?? d.catalogs.format;
2755
- const catalogPath = user.catalogs?.path ?? (format === "json" ? JSON_CATALOG_PATH : d.catalogs.path);
2756
- const provider = user.ai?.provider ?? d.ai.provider;
2757
2835
  return {
2758
2836
  root,
2759
2837
  configFile: configFile === null ? null : resolve(configFile),
2760
2838
  sourceLocale,
2761
2839
  locales,
2762
2840
  pseudoLocales: [...new Set(user.pseudoLocales ?? d.pseudoLocales)],
2763
- fallbacks: copyRecord(user.fallbacks ?? d.fallbacks, (chain) => [...chain]),
2764
- project: {
2765
- include: (user.project?.include ?? d.project.include).map((entry) => resolve(root, entry)),
2766
- extensions: [...user.project?.extensions ?? d.project.extensions],
2767
- exclude: [...user.project?.exclude ?? d.project.exclude]
2768
- },
2769
- extraction: {
2770
- importSources: [.../* @__PURE__ */ new Set([...DEFAULT_IMPORT_SOURCES, ...user.extraction?.importSources ?? []])],
2771
- aliases: [...user.extraction?.aliases ?? d.extraction.aliases],
2772
- globals: [...user.extraction?.globals ?? d.extraction.globals],
2773
- keep: [...user.extraction?.keep ?? d.extraction.keep],
2774
- dependencies: [...user.extraction?.dependencies ?? d.extraction.dependencies]
2775
- },
2841
+ fallbacks: mapRecord(user.fallbacks ?? d.fallbacks, (chain) => [...chain]),
2842
+ project: resolveProject(user.project, root),
2843
+ extraction: resolveExtraction(user.extraction),
2776
2844
  ids: { length: user.ids?.length ?? d.ids.length },
2777
- catalogs: {
2778
- format,
2779
- path: resolve(root, catalogPath),
2780
- msgid: user.catalogs?.msgid ?? d.catalogs.msgid,
2781
- icuFlag: user.catalogs?.icuFlag ?? d.catalogs.icuFlag
2782
- },
2845
+ catalogs: resolveCatalogs(user.catalogs, root),
2783
2846
  output: resolveOutput(user.output),
2784
- routing: {
2785
- strategy: [...user.routing?.strategy ?? d.routing.strategy],
2786
- routeStrategies: copyRecord(user.routing?.routeStrategies ?? d.routing.routeStrategies, (chain) => [...chain]),
2787
- url: user.routing?.url ?? d.routing.url,
2788
- redirectRoot: user.routing?.redirectRoot ?? d.routing.redirectRoot,
2789
- propagate: user.routing?.propagate ?? d.routing.propagate,
2790
- switch: user.routing?.switch ?? d.routing.switch,
2791
- cookie: {
2792
- name: user.routing?.cookie?.name ?? d.routing.cookie.name,
2793
- maxAge: user.routing?.cookie?.maxAge ?? d.routing.cookie.maxAge
2794
- },
2795
- base: user.routing?.base ?? d.routing.base,
2796
- paths: copyRecord(user.routing?.paths ?? d.routing.paths, (entry) => ({ ...entry })),
2797
- domains: resolveDomains(user.routing?.domains ?? d.routing.domains)
2798
- },
2799
- ssr: {
2800
- timeZone: user.ssr?.timeZone ?? d.ssr.timeZone,
2801
- timeZoneFrom: copyRecord(user.ssr?.timeZoneFrom ?? d.ssr.timeZoneFrom, (v) => v),
2802
- payload: user.ssr?.payload ?? d.ssr.payload,
2803
- catalogs: user.ssr?.catalogs ?? d.ssr.catalogs,
2804
- maxLoadedLocales: user.ssr?.maxLoadedLocales ?? d.ssr.maxLoadedLocales,
2805
- normalizeSpaces: user.ssr?.normalizeSpaces ?? d.ssr.normalizeSpaces
2806
- },
2807
- ai: {
2808
- provider,
2809
- model: user.ai?.model ?? (typeof provider === "string" ? d.ai.model : provider.model),
2810
- exclude: [...user.ai?.exclude ?? d.ai.exclude],
2811
- glossary: copyRecord(user.ai?.glossary ?? d.ai.glossary, (targets) => copyRecord(targets, (v) => v)),
2812
- doNotTranslate: [...user.ai?.doNotTranslate ?? d.ai.doNotTranslate],
2813
- tone: copyRecord(user.ai?.tone ?? d.ai.tone, (v) => v),
2814
- description: user.ai?.description ?? d.ai.description,
2815
- apiKeyEnv: user.ai?.apiKeyEnv ?? d.ai.apiKeyEnv,
2816
- batchSize: user.ai?.batchSize ?? d.ai.batchSize,
2817
- concurrency: user.ai?.concurrency ?? d.ai.concurrency,
2818
- dev: user.ai?.dev ?? d.ai.dev
2819
- },
2820
- defaults: { tags: copyRecord(user.defaults?.tags ?? d.defaults.tags, (spec) => typeof spec === "string" ? spec : {
2847
+ routing: resolveRouting(user.routing),
2848
+ ssr: resolveSsr(user.ssr),
2849
+ ai: resolveAi(user.ai),
2850
+ defaults: { tags: mapRecord(user.defaults?.tags ?? d.defaults.tags, (spec) => typeof spec === "string" ? spec : {
2821
2851
  element: spec.element,
2822
2852
  attributes: { ...spec.attributes }
2823
2853
  }) },
@@ -2825,6 +2855,88 @@ function resolveWith(input, root, configFile, inline) {
2825
2855
  strict: resolveStrict(user.strict)
2826
2856
  };
2827
2857
  }
2858
+ function resolveProject(given, root) {
2859
+ const d = DEFAULT_CONFIG.project;
2860
+ const user = given ?? {};
2861
+ return {
2862
+ include: (user.include ?? d.include).map((entry) => resolve(root, entry)),
2863
+ extensions: [...user.extensions ?? d.extensions],
2864
+ exclude: [...user.exclude ?? d.exclude]
2865
+ };
2866
+ }
2867
+ function resolveExtraction(given) {
2868
+ const d = DEFAULT_CONFIG.extraction;
2869
+ const user = given ?? {};
2870
+ return {
2871
+ importSources: [.../* @__PURE__ */ new Set([...DEFAULT_IMPORT_SOURCES, ...user.importSources ?? []])],
2872
+ aliases: [...user.aliases ?? d.aliases],
2873
+ globals: [...user.globals ?? d.globals],
2874
+ keep: [...user.keep ?? d.keep],
2875
+ dependencies: [...user.dependencies ?? d.dependencies],
2876
+ repeatedText: user.repeatedText ?? d.repeatedText
2877
+ };
2878
+ }
2879
+ function resolveCatalogs(given, root) {
2880
+ const d = DEFAULT_CONFIG.catalogs;
2881
+ const user = given ?? {};
2882
+ const format = user.format ?? d.format;
2883
+ const path = user.path ?? (format === "json" ? JSON_CATALOG_PATH : d.path);
2884
+ return {
2885
+ format,
2886
+ path: resolve(root, path),
2887
+ msgid: user.msgid ?? d.msgid,
2888
+ icuFlag: user.icuFlag ?? d.icuFlag
2889
+ };
2890
+ }
2891
+ function resolveRouting(given) {
2892
+ const d = DEFAULT_CONFIG.routing;
2893
+ const user = given ?? {};
2894
+ return {
2895
+ strategy: [...user.strategy ?? d.strategy],
2896
+ routeStrategies: mapRecord(user.routeStrategies ?? d.routeStrategies, (chain) => [...chain]),
2897
+ url: user.url ?? d.url,
2898
+ redirectRoot: user.redirectRoot ?? d.redirectRoot,
2899
+ propagate: user.propagate ?? d.propagate,
2900
+ switch: user.switch ?? d.switch,
2901
+ cookie: {
2902
+ name: user.cookie?.name ?? d.cookie.name,
2903
+ maxAge: user.cookie?.maxAge ?? d.cookie.maxAge
2904
+ },
2905
+ base: user.base ?? d.base,
2906
+ paths: mapRecord(user.paths ?? d.paths, (entry) => ({ ...entry })),
2907
+ domains: resolveDomains(user.domains ?? d.domains)
2908
+ };
2909
+ }
2910
+ function resolveSsr(given) {
2911
+ const d = DEFAULT_CONFIG.ssr;
2912
+ const user = given ?? {};
2913
+ return {
2914
+ timeZone: user.timeZone ?? d.timeZone,
2915
+ timeZoneFrom: mapRecord(user.timeZoneFrom ?? d.timeZoneFrom, (v) => v),
2916
+ payload: user.payload ?? d.payload,
2917
+ catalogs: user.catalogs ?? d.catalogs,
2918
+ maxLoadedLocales: user.maxLoadedLocales ?? d.maxLoadedLocales,
2919
+ normalizeSpaces: user.normalizeSpaces ?? d.normalizeSpaces
2920
+ };
2921
+ }
2922
+ function resolveAi(given) {
2923
+ const d = DEFAULT_CONFIG.ai;
2924
+ const user = given ?? {};
2925
+ const provider = user.provider ?? d.provider;
2926
+ return {
2927
+ provider,
2928
+ model: user.model ?? (typeof provider === "string" ? d.model : provider.model),
2929
+ exclude: [...user.exclude ?? d.exclude],
2930
+ glossary: mapRecord(user.glossary ?? d.glossary, (targets) => mapRecord(targets, (v) => v)),
2931
+ doNotTranslate: [...user.doNotTranslate ?? d.doNotTranslate],
2932
+ tone: mapRecord(user.tone ?? d.tone, (v) => v),
2933
+ description: user.description ?? d.description,
2934
+ apiKeyEnv: user.apiKeyEnv ?? d.apiKeyEnv,
2935
+ batchSize: user.batchSize ?? d.batchSize,
2936
+ concurrency: user.concurrency ?? d.concurrency,
2937
+ dev: user.dev ?? d.dev
2938
+ };
2939
+ }
2828
2940
  /** Rules between keys, checked once the locale list is known. */
2829
2941
  function crossFieldProblems(user, sourceLocale, locales) {
2830
2942
  const problems = [];
@@ -2861,12 +2973,7 @@ function crossFieldProblems(user, sourceLocale, locales) {
2861
2973
  function resolveOutput(user) {
2862
2974
  const d = DEFAULT_CONFIG.output;
2863
2975
  return {
2864
- split: {
2865
- shared: user?.split?.shared ?? d.split.shared,
2866
- dupBelow: user?.split?.dupBelow ?? d.split.dupBelow,
2867
- minBytes: user?.split?.minBytes ?? d.split.minBytes,
2868
- maxBundlesPerRoot: user?.split?.maxBundlesPerRoot === void 0 ? d.split.maxBundlesPerRoot : user.split.maxBundlesPerRoot
2869
- },
2976
+ split: resolveSplit(user?.split),
2870
2977
  guard: user?.guard ?? d.guard,
2871
2978
  manifestPath: user?.manifestPath ?? d.manifestPath,
2872
2979
  manifest: user?.manifest ?? d.manifest,
@@ -2875,6 +2982,16 @@ function resolveOutput(user) {
2875
2982
  perLocale: user?.perLocale ?? d.perLocale
2876
2983
  };
2877
2984
  }
2985
+ function resolveSplit(given) {
2986
+ const d = DEFAULT_CONFIG.output.split;
2987
+ const user = given ?? {};
2988
+ return {
2989
+ shared: user.shared ?? d.shared,
2990
+ dupBelow: user.dupBelow ?? d.dupBelow,
2991
+ minBytes: user.minBytes ?? d.minBytes,
2992
+ maxBundlesPerRoot: user.maxBundlesPerRoot === void 0 ? d.maxBundlesPerRoot : user.maxBundlesPerRoot
2993
+ };
2994
+ }
2878
2995
  function resolveStrict(strict) {
2879
2996
  const d = DEFAULT_CONFIG.strict;
2880
2997
  if (strict === true) return {
@@ -2883,29 +3000,13 @@ function resolveStrict(strict) {
2883
3000
  moduleScope: "error"
2884
3001
  };
2885
3002
  if (strict === void 0 || strict === false) return { ...d };
2886
- const pick = (value, fallback) => value ?? fallback;
2887
3003
  return {
2888
- missing: pick(strict.missing, d.missing),
2889
- invalid: pick(strict.invalid, d.invalid),
2890
- moduleScope: pick(strict.moduleScope, d.moduleScope)
3004
+ missing: strict.missing ?? d.missing,
3005
+ invalid: strict.invalid ?? d.invalid,
3006
+ moduleScope: strict.moduleScope ?? d.moduleScope
2891
3007
  };
2892
3008
  }
2893
- /**
2894
- * A fresh copy, so resolved configs never share arrays with the input or the
2895
- * defaults. `fromEntries` defines properties, so a `__proto__` key stays a key.
2896
- */
2897
- function copyRecord(record, copy) {
2898
- return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, copy(value)]));
2899
- }
2900
- function relativeOrAbsolute(root, file) {
2901
- const rel = relative(root, resolve(file));
2902
- return rel === "" || rel.startsWith("..") || isAbsolute(rel) ? resolve(file) : rel;
2903
- }
2904
- function toPosix(path) {
2905
- return sep === "/" ? path : path.split(sep).join("/");
2906
- }
2907
- //#endregion
2908
- //#region src/test/load.ts
3009
+ // src/test/load.ts
2909
3010
  /**
2910
3011
  * The Node half of `loadCatalog`: the config and every catalog file, compiled
2911
3012
  * for one locale by `compileLocales`, the function the build, dev and
@@ -2918,17 +3019,15 @@ async function compileCatalog(locale, root, configFile) {
2918
3019
  cwd: root,
2919
3020
  configFile
2920
3021
  });
2921
- if (locale === "en-XA" || locale === "ar-XB") throw new RangeError(`vi18n: ${locale} is a pseudo-locale and has no catalog; use createTestI18n({ mode: "pseudo" })`);
3022
+ if (PSEUDO_LOCALES.includes(locale)) throw new RangeError(`vi18n: ${locale} is a pseudo-locale and has no catalog; use createTestI18n({ mode: "pseudo" })`);
2922
3023
  if (!config.locales.includes(locale)) throw new RangeError(`vi18n: ${locale} is not a configured locale (${config.locales.join(", ")}) in ${config.configFile ?? config.root}`);
2923
3024
  const codec = createCodec(config.ids.length);
2924
3025
  const { set } = await loadCatalogSet(config, codec);
2925
3026
  const layout = catalogLayout(config);
2926
3027
  const keep = /* @__PURE__ */ new Set();
2927
- for (const loaded of set.values()) for (const entry of loaded.catalog?.entries ?? []) try {
3028
+ for (const loaded of set.values()) for (const entry of loaded.catalog?.entries ?? []) {
2928
3029
  const key = entryKey(entry, layout, codec);
2929
3030
  if (key !== null) keep.add(key);
2930
- } catch (error) {
2931
- if (!isDiagnosticError(error)) throw error;
2932
3031
  }
2933
3032
  const result = compileLocales({
2934
3033
  config,
@@ -2946,5 +3045,4 @@ async function compileCatalog(locale, root, configFile) {
2946
3045
  messages
2947
3046
  };
2948
3047
  }
2949
- //#endregion
2950
3048
  export { compileCatalog };