@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
@@ -0,0 +1,1907 @@
1
+ import { n as isDiagnosticError } from "./diagnostics-LgIWyeSp.js";
2
+ import { C as langFromId, w as parseModule } from "./sources-DNVbYsgs.js";
3
+ import { b as printICU, t as pluralCategories } from "./validate-CgzaDdOY.js";
4
+ import { o as errorMessage } from "./output-D5tAt8q4.js";
5
+ import { A as isNode, B as objectProperties, C as attributeString, D as inJsxChildren, E as identifierName, F as jsxNameNodes, H as templateKeyPattern, I as keyName, M as jsxAttributes, N as jsxChildren, P as jsxName, S as attributeExpression, T as cleanJsxText, V as stringValue, W as unwrap, j as jsString, w as childEntries, x as analyzeModule, z as memberParts } from "./migrate-ChDGhlC-.js";
6
+ import { t as ModuleBuilder } from "./rewrite-BwzXoBiA.js";
7
+ import { extname } from "node:path";
8
+ import { createHash } from "node:crypto";
9
+ import { readFileSync } from "node:fs";
10
+ // src/cli/commands/migrate/formats.ts
11
+ /**
12
+ * Catalog formats of the libraries `vi18n migrate` converts from (INTERNALS
13
+ * §2.14): nested JSON flattened to keys, a YAML subset for vue-i18n (vi18n
14
+ * depends on no YAML parser, §6 D1), FormatJS's compiled message AST, and the
15
+ * id schemes of FormatJS and Lingui, so translations keyed by a generated id
16
+ * are found from the message text a call site holds. Every reader reports
17
+ * what it cannot read instead of guessing; nothing here executes a catalog.
18
+ */
19
+ /** Hex digits after a YAML double-quoted escape: `\x41`, `\u0041`, `\U00000041`. */
20
+ const ESCAPE_WIDTHS = {
21
+ x: 2,
22
+ u: 4,
23
+ U: 8
24
+ };
25
+ /** 1-based line of an offset. */
26
+ function lineAt(text, offset) {
27
+ let line = 1;
28
+ for (let i = text.indexOf("\n"); i !== -1 && i < offset; i = text.indexOf("\n", i + 1)) line++;
29
+ return line;
30
+ }
31
+ /** `JSON.parse`, with the position of a syntax error turned into a line. */
32
+ function parseJson(text) {
33
+ const body = text.charCodeAt(0) === 65279 ? text.slice(1) : text;
34
+ try {
35
+ return {
36
+ value: JSON.parse(body),
37
+ problem: null
38
+ };
39
+ } catch (error) {
40
+ const message = errorMessage(error);
41
+ const at = /position (\d+)/.exec(message);
42
+ return {
43
+ value: void 0,
44
+ problem: {
45
+ message,
46
+ line: at === null ? 0 : lineAt(body, Number(at[1]))
47
+ }
48
+ };
49
+ }
50
+ }
51
+ /** The line of each key's first occurrence in a JSON text (`"key":`), for diagnostics. */
52
+ function keyLines(text) {
53
+ const lines = /* @__PURE__ */ new Map();
54
+ const pattern = /"((?:[^"\\\n]|\\.)*)"\s*:/g;
55
+ for (let match = pattern.exec(text); match !== null; match = pattern.exec(text)) {
56
+ let key;
57
+ try {
58
+ key = JSON.parse(`"${match[1]}"`);
59
+ } catch {
60
+ continue;
61
+ }
62
+ if (!lines.has(key)) lines.set(key, lineAt(text, match.index));
63
+ }
64
+ return lines;
65
+ }
66
+ /**
67
+ * Flattens a nested catalog: objects join their keys with `separator`,
68
+ * arrays use indexes (`list.0`), as i18next and vue-i18n address them.
69
+ * Leaves that are not strings are reported, never stringified.
70
+ */
71
+ function flattenTree(tree, text, separator = ".") {
72
+ const texts = /* @__PURE__ */ new Map();
73
+ const problems = [];
74
+ const lines = keyLines(text);
75
+ const lineOf = (key) => {
76
+ const last = key.lastIndexOf(separator);
77
+ return lines.get(key) ?? lines.get(last === -1 ? key : key.slice(last + 1)) ?? 0;
78
+ };
79
+ const visit = (value, key) => {
80
+ if (typeof value === "string") {
81
+ texts.set(key, {
82
+ value,
83
+ line: lineOf(key)
84
+ });
85
+ return;
86
+ }
87
+ if (Array.isArray(value)) {
88
+ value.forEach((item, index) => visit(item, key === "" ? String(index) : `${key}${separator}${index}`));
89
+ return;
90
+ }
91
+ if (typeof value === "object" && value !== null) {
92
+ for (const [name, item] of Object.entries(value)) visit(item, key === "" ? name : `${key}${separator}${name}`);
93
+ return;
94
+ }
95
+ if (value === null) return;
96
+ problems.push({
97
+ message: `"${key}" holds ${typeof value} ${JSON.stringify(value)}, not a string; it was skipped`,
98
+ line: lineOf(key)
99
+ });
100
+ };
101
+ if (typeof tree !== "object" || tree === null || Array.isArray(tree)) {
102
+ problems.push({
103
+ message: "a catalog is an object of messages",
104
+ line: 1
105
+ });
106
+ return {
107
+ texts,
108
+ problems
109
+ };
110
+ }
111
+ visit(tree, "");
112
+ return {
113
+ texts,
114
+ problems
115
+ };
116
+ }
117
+ var YamlError = class extends Error {
118
+ line;
119
+ constructor(message, line) {
120
+ super(message);
121
+ this.line = line;
122
+ }
123
+ };
124
+ /**
125
+ * Block mappings and sequences of scalars: plain, quoted (single and double,
126
+ * also over several lines) and block scalars (`|`, `>`, with chomping and an
127
+ * indentation indicator); comments; `{}` and `[]`. Anchors, aliases, tags,
128
+ * non-empty flow collections and complex keys are errors, since guessing
129
+ * would change a message silently. Plain scalars stay strings (`404`, `yes`):
130
+ * a message catalog has nothing else.
131
+ */
132
+ function parseYaml(text) {
133
+ try {
134
+ return {
135
+ value: new YamlReader(text).document(),
136
+ problem: null
137
+ };
138
+ } catch (error) {
139
+ if (error instanceof YamlError) return {
140
+ value: void 0,
141
+ problem: {
142
+ message: error.message,
143
+ line: error.line
144
+ }
145
+ };
146
+ throw error;
147
+ }
148
+ }
149
+ const blank = (line) => line.text === "" || line.text.startsWith("#");
150
+ const fail = (message, line) => {
151
+ throw new YamlError(message, line?.no ?? 0);
152
+ };
153
+ /** A plain scalar's text with a trailing ` #comment` removed. */
154
+ function plain(value) {
155
+ const comment = /(?:^|\s)#/.exec(value);
156
+ return (comment === null ? value : value.slice(0, comment.index)).trim();
157
+ }
158
+ function checkScalarStart(value, line) {
159
+ if (/^[&*!]/.test(value)) fail(`anchors, aliases and tags are not supported (${value.split(/\s/)[0]})`, line);
160
+ if (/^[[{]/.test(value) && !/^(?:\{\s*\}|\[\s*\])\s*(?:#.*)?$/.test(value)) fail("flow collections are not supported: write the entries as a block", line);
161
+ if (/^[|>]/.test(value) === false && /^[?%@`]/.test(value)) fail(`a scalar cannot start with ${value[0]}: quote it`, line);
162
+ }
163
+ const SIMPLE_ESCAPES = {
164
+ n: "\n",
165
+ t: " ",
166
+ r: "\r",
167
+ "0": "\0",
168
+ "\"": "\"",
169
+ "\\": "\\",
170
+ "/": "/",
171
+ " ": " ",
172
+ b: "\b",
173
+ f: "\f",
174
+ e: "\x1B",
175
+ N: "…",
176
+ _: " "
177
+ };
178
+ /**
179
+ * The escape after the backslash at `source[i]`: its text and how many
180
+ * characters past the backslash it takes. `null` for a backslash ending the
181
+ * line, which joins the lines without a space.
182
+ */
183
+ function escapeAt(source, i, line) {
184
+ const next = source[i + 1];
185
+ if (next === void 0) return null;
186
+ if (next in SIMPLE_ESCAPES) return {
187
+ text: SIMPLE_ESCAPES[next],
188
+ width: 1
189
+ };
190
+ const width = ESCAPE_WIDTHS[next] ?? 0;
191
+ if (width === 0) fail(`unknown escape \\${next}`, line);
192
+ const hex = source.slice(i + 2, i + 2 + width);
193
+ if (!new RegExp(`^[0-9a-fA-F]{${width}}$`).test(hex)) fail(`malformed escape \\${next}${hex}`, line);
194
+ return {
195
+ text: String.fromCodePoint(Number.parseInt(hex, 16)),
196
+ width: 1 + width
197
+ };
198
+ }
199
+ /**
200
+ * One line of a quoted scalar: the text up to the closing quote and what
201
+ * follows it (`rest`), or, with `rest` null, the whole line's text when the
202
+ * scalar goes on. A text ending in U+0000 ended in an escaped line break.
203
+ */
204
+ function quotedLine(source, quote, line) {
205
+ let out = "";
206
+ for (let i = 0; i < source.length; i++) {
207
+ const c = source[i];
208
+ if (quote === "'" && c === "'" && source[i + 1] === "'") {
209
+ out += "'";
210
+ i++;
211
+ } else if (c === quote) return {
212
+ text: out,
213
+ rest: source.slice(i + 1)
214
+ };
215
+ else if (quote === "\"" && c === "\\") {
216
+ const escape = escapeAt(source, i, line);
217
+ if (escape === null) return {
218
+ text: out + "\0",
219
+ rest: null
220
+ };
221
+ out += escape.text;
222
+ i += escape.width;
223
+ } else out += c;
224
+ }
225
+ return {
226
+ text: out,
227
+ rest: null
228
+ };
229
+ }
230
+ /** A `>` block scalar's lines folded: an empty line is a newline, a break between text lines a space, unless one is more indented. */
231
+ function folded(content) {
232
+ let value = "";
233
+ for (let i = 0; i < content.length; i++) {
234
+ const piece = content[i];
235
+ const previous = content[i - 1];
236
+ if (i > 0 && piece === "") value += "\n";
237
+ else if (i > 0 && previous !== "") value += /^\s/.test(piece) || /^\s/.test(previous) ? "\n" : " ";
238
+ value += piece;
239
+ }
240
+ return value;
241
+ }
242
+ /** A block scalar's value from its content lines, `trailing` empty lines cut off, by its style and chomping. */
243
+ function blockValue(content, trailing, style, chomp) {
244
+ if (content.length === 0) return "";
245
+ const value = style === "|" ? content.join("\n") : folded(content);
246
+ if (chomp === "-") return value;
247
+ if (chomp === "+") return value + "\n".repeat(trailing + 1);
248
+ return value + "\n";
249
+ }
250
+ const isSequenceItem = (text) => text.startsWith("- ") || text === "-";
251
+ /** One YAML document read line by line; `at` is the line being read. */
252
+ var YamlReader = class {
253
+ lines;
254
+ at = 0;
255
+ constructor(text) {
256
+ const body = text.charCodeAt(0) === 65279 ? text.slice(1) : text;
257
+ this.lines = body.split("\n").map((raw, index) => {
258
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
259
+ const indent = /^ */.exec(line)?.[0].length ?? 0;
260
+ return {
261
+ no: index + 1,
262
+ indent,
263
+ text: line.slice(indent),
264
+ raw: line
265
+ };
266
+ });
267
+ }
268
+ document() {
269
+ this.skipBlank();
270
+ if (this.at < this.lines.length && /^---\s*(?:#.*)?$/.test(this.current().raw)) {
271
+ this.at++;
272
+ this.skipBlank();
273
+ }
274
+ if (this.at >= this.lines.length) return {};
275
+ const value = this.node(this.current().indent);
276
+ this.skipBlank();
277
+ if (this.at < this.lines.length) fail("unexpected indentation", this.lines[this.at]);
278
+ return value;
279
+ }
280
+ current() {
281
+ return this.lines[this.at];
282
+ }
283
+ skipBlank() {
284
+ while (this.at < this.lines.length && blank(this.current())) this.at++;
285
+ }
286
+ /** A quoted scalar starting at `value` on `line`, possibly continued on later lines; folds line breaks. */
287
+ quoted(value, line) {
288
+ const quote = value[0];
289
+ let source = value.slice(1);
290
+ let out = "";
291
+ let current = line;
292
+ for (;;) {
293
+ const read = quotedLine(source, quote, current);
294
+ out += read.text;
295
+ if (read.rest !== null) return {
296
+ text: out,
297
+ rest: read.rest
298
+ };
299
+ current = this.continuation(current);
300
+ out = joinBreak(out, this.breaks);
301
+ source = current.text.replace(/^\s+/, "");
302
+ }
303
+ }
304
+ /** Empty lines skipped by the last {@link continuation}. */
305
+ breaks = 0;
306
+ /** The line a quoted scalar continues on, after any empty lines (counted in {@link breaks}). */
307
+ continuation(line) {
308
+ this.at++;
309
+ this.breaks = 0;
310
+ while (this.at < this.lines.length && this.current().text === "") {
311
+ this.breaks++;
312
+ this.at++;
313
+ }
314
+ if (this.at >= this.lines.length) fail("unterminated quoted scalar", line);
315
+ return this.current();
316
+ }
317
+ /** A block scalar whose header (`|`, `>-`, `|2`…) is `header`; the content follows `line`. */
318
+ blockScalar(header, parentIndent, line) {
319
+ const m = /^([|>])([+-]?)([1-9]?)([+-]?)\s*(?:#.*)?$/.exec(header);
320
+ if (m === null) fail(`malformed block scalar header ${header}`, line);
321
+ const [, style, chompA, digit, chompB] = m;
322
+ this.at++;
323
+ const content = this.blockLines(digit === "" ? -1 : parentIndent + Number(digit), parentIndent);
324
+ let trailing = 0;
325
+ while (content.length > 0 && content[content.length - 1] === "") {
326
+ content.pop();
327
+ trailing++;
328
+ }
329
+ return blockValue(content, trailing, style, chompA || chompB);
330
+ }
331
+ /** A block scalar's content lines, at `indent` (-1: the first line's). */
332
+ blockLines(indent, parentIndent) {
333
+ const content = [];
334
+ while (this.at < this.lines.length) {
335
+ const current = this.current();
336
+ if (current.raw.trim() === "") {
337
+ content.push("");
338
+ this.at++;
339
+ continue;
340
+ }
341
+ if (indent === -1 && current.indent <= parentIndent) break;
342
+ if (indent === -1) indent = current.indent;
343
+ if (current.indent < indent) break;
344
+ content.push(current.raw.slice(indent));
345
+ this.at++;
346
+ }
347
+ return content;
348
+ }
349
+ /** A plain scalar starting on the current line, with its continuation lines (more indented than `parentIndent`). */
350
+ plainScalar(first, parentIndent) {
351
+ let value = plain(first);
352
+ this.at++;
353
+ if (/(?:^|\s)#/.test(first)) return value;
354
+ let breaks = 0;
355
+ while (this.at < this.lines.length) {
356
+ const current = this.current();
357
+ if (current.text === "") {
358
+ breaks++;
359
+ this.at++;
360
+ continue;
361
+ }
362
+ if (current.indent <= parentIndent || current.text.startsWith("#")) break;
363
+ if (/^[^"'#][^:#]*:(?:\s|$)/.test(current.text) || current.text.startsWith("- ")) break;
364
+ value += (breaks > 0 ? "\n".repeat(breaks) : " ") + plain(current.text);
365
+ breaks = 0;
366
+ this.at++;
367
+ if (/(?:^|\s)#/.test(current.text)) break;
368
+ }
369
+ return value;
370
+ }
371
+ /** The value after `key:` or `- ` (`rest`), at a node whose own indentation is `indent`. */
372
+ valueAfter(rest, indent, line) {
373
+ const value = rest.trim();
374
+ if (value === "" || value.startsWith("#")) return this.nested(indent);
375
+ checkScalarStart(value, line);
376
+ if (value.startsWith("|") || value.startsWith(">")) return this.blockScalar(value, indent, line);
377
+ if (value.startsWith("\"") || value.startsWith("'")) {
378
+ const result = this.quoted(value, line);
379
+ if (plain(result.rest) !== "") fail(`unexpected text after a quoted scalar: ${result.rest.trim()}`, this.lines[this.at]);
380
+ this.at++;
381
+ return result.text;
382
+ }
383
+ const empty = emptyValue(value);
384
+ if (empty === void 0) return this.plainScalar(value, indent);
385
+ this.at++;
386
+ return empty;
387
+ }
388
+ /** What a `key:` or `- ` with nothing after it holds: the block below, or null. */
389
+ nested(indent) {
390
+ this.at++;
391
+ this.skipBlank();
392
+ const next = this.lines[this.at];
393
+ if (next !== void 0 && next.indent > indent) return this.node(next.indent);
394
+ if (next !== void 0 && next.indent === indent && next.text.startsWith("- ")) return this.node(indent);
395
+ return null;
396
+ }
397
+ /** A mapping key at the start of `text`: its name and what follows the `:`. */
398
+ keyOf(text, line) {
399
+ if (text.startsWith("\"") || text.startsWith("'")) {
400
+ const saved = this.at;
401
+ const result = this.quoted(text, line);
402
+ if (this.at !== saved) fail("a key cannot span lines", line);
403
+ const rest = result.rest.replace(/^\s*/, "");
404
+ if (!rest.startsWith(":")) return null;
405
+ return {
406
+ key: result.text,
407
+ rest: rest.slice(1)
408
+ };
409
+ }
410
+ if (text.startsWith("? ")) fail("complex keys (? …) are not supported", line);
411
+ const m = /^([^#][^:]*?)\s*:(?:\s|$)/.exec(text);
412
+ if (m === null) return null;
413
+ return {
414
+ key: m[1],
415
+ rest: text.slice(m[0].length)
416
+ };
417
+ }
418
+ /** The next line of a block at `indent`, or undefined where the block ends. */
419
+ nextIn(indent) {
420
+ this.skipBlank();
421
+ const line = this.lines[this.at];
422
+ if (line === void 0 || line.indent < indent) return void 0;
423
+ if (line.indent > indent) fail("unexpected indentation", line);
424
+ return line;
425
+ }
426
+ /** A block node whose lines are indented by exactly `indent`. */
427
+ node(indent) {
428
+ this.skipBlank();
429
+ const first = this.lines[this.at];
430
+ if (first === void 0) return null;
431
+ return isSequenceItem(first.text) ? this.sequence(indent) : this.mapping(indent);
432
+ }
433
+ sequence(indent) {
434
+ const out = [];
435
+ for (let line = this.nextIn(indent); line && isSequenceItem(line.text); line = this.nextIn(indent)) {
436
+ const rest = line.text.slice(1);
437
+ const inner = rest.trimStart();
438
+ if (inner !== "" && !/^["'|>]/.test(inner) && this.keyOf(inner, line) !== null) {
439
+ const shift = line.indent + 1 + (rest.length - inner.length);
440
+ this.lines[this.at] = {
441
+ ...line,
442
+ indent: shift,
443
+ text: inner
444
+ };
445
+ out.push(this.node(shift));
446
+ } else out.push(this.valueAfter(rest, indent, line));
447
+ }
448
+ return out;
449
+ }
450
+ mapping(indent) {
451
+ const out = {};
452
+ for (let line = this.nextIn(indent); line; line = this.nextIn(indent)) {
453
+ if (line.text === "..." || line.text === "---") fail("only one YAML document is supported", line);
454
+ const entry = this.keyOf(line.text, line);
455
+ if (entry === null) fail(`expected "key: value", found ${line.text}`, line);
456
+ const { key, rest } = entry;
457
+ if (Object.hasOwn(out, key)) fail(`duplicate key ${key}`, line);
458
+ out[key] = this.valueAfter(rest, indent, line);
459
+ }
460
+ return out;
461
+ }
462
+ };
463
+ /** A quoted scalar's text so far, joined to its next line: an escaped break joins without a space, a break folds into a space, empty lines into newlines. */
464
+ function joinBreak(out, breaks) {
465
+ if (out.endsWith("\0")) return out.slice(0, -1);
466
+ return out.replace(/[ \t]+$/, "") + (breaks > 0 ? "\n".repeat(breaks) : " ");
467
+ }
468
+ /** `{}`, `[]`, `~` and `null` as values; undefined for anything else. */
469
+ function emptyValue(value) {
470
+ if (/^\{\s*\}/.test(value)) return {};
471
+ if (/^\[\s*\]/.test(value)) return [];
472
+ if (value === "~" || value === "null") return null;
473
+ }
474
+ /** Line numbers of YAML keys (`key:` at any depth), for diagnostics. */
475
+ function yamlKeyLines(text) {
476
+ const lines = /* @__PURE__ */ new Map();
477
+ text.split("\n").forEach((line, index) => {
478
+ const m = /^\s*(?:-\s+)?["']?([^"':#]+?)["']?\s*:(?:\s|$)/.exec(line);
479
+ if (m !== null && !lines.has(m[1])) lines.set(m[1], index + 1);
480
+ });
481
+ return lines;
482
+ }
483
+ const KEYWORD_STYLES = /* @__PURE__ */ new Set([
484
+ "integer",
485
+ "percent",
486
+ "short",
487
+ "medium",
488
+ "long",
489
+ "full"
490
+ ]);
491
+ /** `@formatjs/icu-messageformat-parser`'s TYPE enum, as `formatjs compile --ast` writes it. */
492
+ const FORMATJS = {
493
+ literal: 0,
494
+ argument: 1,
495
+ number: 2,
496
+ date: 3,
497
+ time: 4,
498
+ select: 5,
499
+ plural: 6,
500
+ pound: 7,
501
+ tag: 8
502
+ };
503
+ const FORMATTED_TYPES = {
504
+ 2: "number",
505
+ 3: "date",
506
+ 4: "time"
507
+ };
508
+ /**
509
+ * A message compiled by `formatjs compile --ast` (an array of typed
510
+ * elements) as vi18n's AST; null when an element is not one FormatJS writes.
511
+ */
512
+ function formatjsAstToIcu(elements) {
513
+ if (!Array.isArray(elements)) return null;
514
+ const out = [];
515
+ for (const element of elements) {
516
+ if (typeof element !== "object" || element === null) return null;
517
+ const value = element.value;
518
+ switch (element.type) {
519
+ case FORMATJS.literal:
520
+ if (typeof value !== "string") return null;
521
+ if (value !== "") out.push({
522
+ type: "literal",
523
+ value
524
+ });
525
+ break;
526
+ case FORMATJS.argument:
527
+ out.push({
528
+ type: "argument",
529
+ name: value
530
+ });
531
+ break;
532
+ case FORMATJS.number:
533
+ case FORMATJS.date:
534
+ case FORMATJS.time: {
535
+ const style = formatjsStyle(element.style);
536
+ if (style === void 0) return null;
537
+ out.push({
538
+ type: FORMATTED_TYPES[element.type],
539
+ name: value,
540
+ style,
541
+ options: null
542
+ });
543
+ break;
544
+ }
545
+ case FORMATJS.select:
546
+ case FORMATJS.plural: {
547
+ const options = [];
548
+ const raw = element.options;
549
+ if (typeof raw !== "object" || raw === null) return null;
550
+ for (const [key, option] of Object.entries(raw)) {
551
+ const nested = formatjsAstToIcu(option?.value);
552
+ if (nested === null) return null;
553
+ options.push({
554
+ key,
555
+ value: nested
556
+ });
557
+ }
558
+ if (element.type === 5) out.push({
559
+ type: "select",
560
+ name: value,
561
+ options
562
+ });
563
+ else out.push({
564
+ type: "plural",
565
+ pluralType: element.pluralType === "ordinal" ? "ordinal" : "cardinal",
566
+ name: value,
567
+ offset: typeof element.offset === "number" ? element.offset : 0,
568
+ options
569
+ });
570
+ break;
571
+ }
572
+ case FORMATJS.pound:
573
+ out.push({ type: "pound" });
574
+ break;
575
+ case FORMATJS.tag: {
576
+ const children = formatjsAstToIcu(element.children);
577
+ if (children === null) return null;
578
+ out.push({
579
+ type: "tag",
580
+ name: value,
581
+ children
582
+ });
583
+ break;
584
+ }
585
+ default: return null;
586
+ }
587
+ }
588
+ return out;
589
+ }
590
+ function formatjsStyle(style) {
591
+ if (style === null || style === void 0) return null;
592
+ if (typeof style === "string") {
593
+ if (style.startsWith("::")) return {
594
+ kind: "skeleton",
595
+ value: style.slice(2).trim()
596
+ };
597
+ return KEYWORD_STYLES.has(style) ? {
598
+ kind: "keyword",
599
+ value: style
600
+ } : void 0;
601
+ }
602
+ if (typeof style !== "object") return void 0;
603
+ const skeleton = style;
604
+ if (typeof skeleton.pattern === "string") return {
605
+ kind: "skeleton",
606
+ value: skeleton.pattern
607
+ };
608
+ if (Array.isArray(skeleton.tokens)) return {
609
+ kind: "skeleton",
610
+ value: skeleton.tokens.map((token) => [token.stem, ...token.options ?? []].join("/")).join(" ")
611
+ };
612
+ }
613
+ /**
614
+ * The id `babel-plugin-formatjs` / `@formatjs/ts-transformer` give a
615
+ * descriptor without one, with the default `idInterpolationPattern`
616
+ * (`[sha512:contenthash:base64:6]` over `defaultMessage#description`).
617
+ */
618
+ function formatjsId(defaultMessage, description) {
619
+ const content = description === null || description === "" ? defaultMessage : `${defaultMessage}#${description}`;
620
+ return createHash("sha512").update(content).digest("base64").slice(0, 6);
621
+ }
622
+ /** Lingui's `generateMessageId(message, context)` (v4+): sha256 over `message␟context`, base64, 6 characters. */
623
+ function linguiId(message, context) {
624
+ return createHash("sha256").update(message + "" + (context ?? "")).digest("base64").slice(0, 6);
625
+ }
626
+ /** Appends literal text, merging with a preceding literal. */
627
+ function pushLiteral(nodes, value) {
628
+ if (value === "") return;
629
+ const last = nodes[nodes.length - 1];
630
+ if (last?.type === "literal") last.value += value;
631
+ else nodes.push({
632
+ type: "literal",
633
+ value
634
+ });
635
+ }
636
+ // src/cli/commands/migrate/react.ts
637
+ function newNaming() {
638
+ return {
639
+ byPath: /* @__PURE__ */ new Map(),
640
+ sourcePaths: /* @__PURE__ */ new Set()
641
+ };
642
+ }
643
+ function baseName(element, path) {
644
+ if (element === "html") return path.replace(/^html:/, "");
645
+ if (element === null || element.type !== "JSXElement") return "c" + path.replace(/\W/g, "_");
646
+ const name = jsxName(element).split(/[.:]/).pop().replace(/^[A-Z]/, (c) => c.toLowerCase()).replace(/[^A-Za-z0-9_-]/g, "");
647
+ return /^[A-Za-z]/.test(name) ? name : `c${name}`;
648
+ }
649
+ /** Renames the tags of a message (source first, then translations) through `naming`. */
650
+ function renameTags(nodes, naming, pathOf, elementAt, source) {
651
+ const taken = new Set(naming.byPath.values());
652
+ const walk = (list, parent) => list.map((node) => {
653
+ if (node.type === "plural" || node.type === "select") return {
654
+ ...node,
655
+ options: node.options.map((o) => ({
656
+ key: o.key,
657
+ value: walk(o.value, parent)
658
+ }))
659
+ };
660
+ if (node.type !== "tag") return node;
661
+ const path = pathOf(node.name, parent);
662
+ let name = node.name;
663
+ if (path !== null) {
664
+ const known = naming.byPath.get(path);
665
+ if (known !== void 0) name = known;
666
+ else {
667
+ const base = baseName(elementAt(path), path);
668
+ name = base;
669
+ for (let n = 2; taken.has(name); n++) name = `${base}${n}`;
670
+ naming.byPath.set(path, name);
671
+ taken.add(name);
672
+ }
673
+ if (source) naming.sourcePaths.add(path);
674
+ }
675
+ return {
676
+ type: "tag",
677
+ name,
678
+ children: node.children === null ? null : walk(node.children, path ?? parent)
679
+ };
680
+ });
681
+ return walk(nodes, null);
682
+ }
683
+ /** This site's handler per tag name, or the paths it cannot map. */
684
+ function siteHandlers(naming, elementAt) {
685
+ const handlers = /* @__PURE__ */ new Map();
686
+ const missing = [];
687
+ for (const path of naming.sourcePaths) {
688
+ const name = naming.byPath.get(path);
689
+ const element = elementAt(path);
690
+ if (element === "html") handlers.set(name, {
691
+ element: null,
692
+ html: path.replace(/^html:/, "")
693
+ });
694
+ else if (element !== null && element.type === "JSXElement") handlers.set(name, {
695
+ element,
696
+ html: null
697
+ });
698
+ else missing.push(path.replace(/^html:/, ""));
699
+ }
700
+ return {
701
+ handlers,
702
+ missing
703
+ };
704
+ }
705
+ /** `ReactNode`, imported as a type in TSX so handlers and `rich<ReactNode>()` type-check. */
706
+ function reactTypes(builder) {
707
+ return { node: builder.typeImport("react", "ReactNode") };
708
+ }
709
+ /** A handler wrapping the translated children in the element's opening tag. */
710
+ function elementHandler(handler, selfClosing, r, types) {
711
+ const param = types === null ? "children" : `children: ${types.node}`;
712
+ if (handler.element === null) {
713
+ const tag = handler.html;
714
+ return selfClosing ? `() => <${tag} />` : `(${param}) => <${tag}>{children}</${tag}>`;
715
+ }
716
+ const element = handler.element;
717
+ const opening = element.openingElement;
718
+ if (selfClosing) return `() => ${r.src(opening.start, opening.end).replace(/\s*>$/, "").replace(/\s*\/$/, "")} />`;
719
+ return `(${param}) => ${r.src(opening.start, opening.end).replace(/\s*\/>$/, ">")}{children}</${jsxName(element)}>`;
720
+ }
721
+ /** Whether a message's tag is written self-closing (`<br/>`, `<0/>`). */
722
+ function selfClosingTags(nodes, out = /* @__PURE__ */ new Set()) {
723
+ for (const node of nodes) if (node.type === "tag") {
724
+ if (node.children === null) out.add(node.name);
725
+ else selfClosingTags(node.children, out);
726
+ } else if (node.type === "plural" || node.type === "select") for (const option of node.options) selfClosingTags(option.value, out);
727
+ return out;
728
+ }
729
+ /**
730
+ * Annotates the first parameter of handlers in a values object
731
+ * (`(chunks) => …` → `(chunks: ReactNode) => …`): react-intl's types gave it
732
+ * a type from context, vi18n's values are `unknown`, so under
733
+ * `noImplicitAny` the handler would no longer type-check.
734
+ */
735
+ function annotateHandlers(builder, values, typeName) {
736
+ const props = objectProperties(values);
737
+ if (props === null) return;
738
+ const text = builder.text;
739
+ for (const property of props.order) {
740
+ if (property.type === "SpreadElement") continue;
741
+ const fn = unwrap(property.value);
742
+ if (fn.type !== "ArrowFunctionExpression" && fn.type !== "FunctionExpression") continue;
743
+ const param = fn.params[0];
744
+ if (param === void 0 || param.type !== "Identifier" || isNode(param.typeAnnotation)) continue;
745
+ const name = param.name;
746
+ const parenthesized = text.slice(fn.start, param.start).includes("(");
747
+ builder.replace({
748
+ start: param.start,
749
+ end: param.start + name.length
750
+ }, parenthesized ? `${name}: ${typeName}` : `(${name}: ${typeName})`);
751
+ }
752
+ }
753
+ /** `rich<ReactNode>(message, { … })`. */
754
+ function richCall(r, key, entries, types) {
755
+ const typeArgument = types === null ? "" : `<${types.node}>`;
756
+ return `${r.fn.rich}${typeArgument}(${r.message(key)}, { ${entries.join(", ")} })`;
757
+ }
758
+ /** `name: value`, or the shorthand when the value is the name. */
759
+ function entry(name, code) {
760
+ if (code === name) return name;
761
+ return `${/^[A-Za-z_$][\w$]*$/.test(name) || /^(?:0|[1-9]\d*)$/.test(name) ? name : jsString(name)}: ${code}`;
762
+ }
763
+ // src/cli/commands/migrate/i18next.ts
764
+ /**
765
+ * `vi18n migrate --from i18next` (INTERNALS §2.14): i18next and
766
+ * react-i18next.
767
+ *
768
+ * Catalogs are i18next JSON (v4): nested keys joined by `.`, one file per
769
+ * locale or one per namespace (`<locale>/<ns>.json`), plural suffixes
770
+ * (`_zero`, `_one`, …, `_other`, `_ordinal_*`, v3's `_plural`) folded into
771
+ * one ICU plural, `_<context>` variants into a select on `context`, `{{x}}`
772
+ * into `{x}` (`{{x, number}}`, `datetime`, `currency(EUR)` formatted), and
773
+ * `$t(key)` nesting inlined. Call sites: `t("key", options)` from
774
+ * `useTranslation`, `i18next.t`, a `t` prop; `<Trans>` (components from the
775
+ * `components` prop or the children, as react-i18next maps `<0>…</0>`)
776
+ * becomes `rich()`. `useTranslation` bindings, imports and `<I18nextProvider>`
777
+ * go once nothing else uses them; the rest is reported.
778
+ */
779
+ const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
780
+ ".js",
781
+ ".jsx",
782
+ ".mjs",
783
+ ".cjs",
784
+ ".ts",
785
+ ".tsx",
786
+ ".mts",
787
+ ".cts"
788
+ ]);
789
+ const PLURAL_SUFFIX = /_(zero|one|two|few|many|other)$/;
790
+ const ORDINAL_SUFFIX = /_ordinal_(zero|one|two|few|many|other)$/;
791
+ const CATEGORIES = [
792
+ "zero",
793
+ "one",
794
+ "two",
795
+ "few",
796
+ "many",
797
+ "other"
798
+ ];
799
+ const DEFAULT_NS = "translation";
800
+ /** react-i18next's `transKeepBasicHtmlNodesFor`: rendered as elements when no component maps them. */
801
+ const BASIC_HTML = /* @__PURE__ */ new Set([
802
+ "br",
803
+ "strong",
804
+ "i",
805
+ "p"
806
+ ]);
807
+ /** `t()` options that change what is looked up or returned, with no vi18n counterpart. */
808
+ const UNSUPPORTED_OPTIONS = /* @__PURE__ */ new Set([
809
+ "lng",
810
+ "lngs",
811
+ "fallbackLng",
812
+ "returnObjects",
813
+ "returnDetails",
814
+ "joinArrays",
815
+ "postProcess",
816
+ "interpolation",
817
+ "replace",
818
+ "skipInterpolation"
819
+ ]);
820
+ /** `t()` options that only steer the lookup; the rest are values. */
821
+ const LOOKUP_OPTIONS = /* @__PURE__ */ new Set([
822
+ "defaultValue",
823
+ "ns",
824
+ "keyPrefix",
825
+ "ordinal"
826
+ ]);
827
+ function isOldSource(source) {
828
+ return /^(?:react-|next-)?i18next(?:\/|$)/.test(source) || source.startsWith("i18next-");
829
+ }
830
+ /** Whether a key has plural or ordinal forms (`key_one`, `key_ordinal_two`, v3 `key_plural`). */
831
+ function hasForms(texts, key) {
832
+ return CATEGORIES.some((c) => texts.has(`${key}_${c}`) || texts.has(`${key}_ordinal_${c}`)) || texts.has(`${key}_plural`);
833
+ }
834
+ /** The base key of a plural or ordinal form (`item_one` → `item`). */
835
+ function baseKey(key) {
836
+ return key.replace(ORDINAL_SUFFIX, "").replace(PLURAL_SUFFIX, "").replace(/_plural$/, "");
837
+ }
838
+ /** One `{{…}}` as an ICU node: `count` in a plural branch is `#`. */
839
+ function interpolationNode(inner, inPlural) {
840
+ const body = inner.trim().replace(/^-\s*/, "");
841
+ const comma = body.indexOf(",");
842
+ const name = (comma === -1 ? body : body.slice(0, comma)).trim();
843
+ const format = comma === -1 ? null : body.slice(comma + 1).trim();
844
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { error: `{{${inner}}} reads a nested value, which an ICU argument cannot name` };
845
+ if (format === null) return { node: inPlural && name === "count" ? { type: "pound" } : {
846
+ type: "argument",
847
+ name
848
+ } };
849
+ const m = /^(\w+)(?:\((.*)\))?$/.exec(format);
850
+ const kind = m?.[1]?.toLowerCase();
851
+ const args = m?.[2]?.trim() ?? "";
852
+ if (kind === "number" && args === "") return { node: {
853
+ type: "number",
854
+ name,
855
+ style: null,
856
+ options: null
857
+ } };
858
+ if (kind === "datetime" && args === "") return { node: {
859
+ type: "date",
860
+ name,
861
+ style: null,
862
+ options: null
863
+ } };
864
+ if (kind === "currency") {
865
+ const code = /^(?:currency\s*:\s*)?["']?([A-Za-z]{3})["']?$/.exec(args)?.[1];
866
+ if (code !== void 0) return { node: {
867
+ type: "number",
868
+ name,
869
+ style: {
870
+ kind: "skeleton",
871
+ value: `currency/${code.toUpperCase()}`
872
+ },
873
+ options: null
874
+ } };
875
+ }
876
+ return { error: `{{${inner.trim()}}} uses the ${format} format, which has no ICU counterpart: format the value with fmt.* and pass the string` };
877
+ }
878
+ /**
879
+ * What a `useTranslation()` binding holds: `t` (a `{ t }` property, the
880
+ * first element of `[t, i18n]`, or the whole result), `i18n`, or another
881
+ * property's name; null for a pattern it cannot read.
882
+ */
883
+ function hookRole(slot, pattern) {
884
+ if (slot === null) return "t";
885
+ if (slot.type === "Property") return keyName(slot);
886
+ if (pattern.type !== "ArrayPattern") return null;
887
+ return pattern.elements.indexOf(slot) === 0 ? "t" : "i18n";
888
+ }
889
+ /** The namespace a key without one is looked up in: i18next's default, else the only one. */
890
+ function defaultNamespace(source) {
891
+ if (source.has(DEFAULT_NS)) return DEFAULT_NS;
892
+ return source.size === 1 ? [...source.keys()][0] : null;
893
+ }
894
+ function createI18nextAdapter() {
895
+ return new I18nextAdapter();
896
+ }
897
+ /** A shape with no context, ordinal or tags: a plain `t()` lookup, with plural forms when `count`. */
898
+ const plainShape = (count) => ({
899
+ count,
900
+ ordinal: false,
901
+ context: false,
902
+ tags: false
903
+ });
904
+ /** `ns:key` split off a key whose prefix names one of `namespaces`; else the key in `ns`. */
905
+ function splitNamespace(rawKey, ns, namespaces) {
906
+ const colon = rawKey.indexOf(":");
907
+ if (colon !== -1 && namespaces.has(rawKey.slice(0, colon))) return {
908
+ ns: rawKey.slice(0, colon),
909
+ key: rawKey.slice(colon + 1)
910
+ };
911
+ return {
912
+ ns,
913
+ key: rawKey
914
+ };
915
+ }
916
+ /** The contexts of `key`'s `key_<context>` variants among `keys`. */
917
+ function contextsOf(keys, key) {
918
+ const contexts = /* @__PURE__ */ new Set();
919
+ for (const k of keys) {
920
+ if (!k.startsWith(key + "_")) continue;
921
+ const rest = baseKey(k.slice(key.length + 1));
922
+ if (rest === "" || CATEGORIES.includes(rest) || rest === "plural" || rest.includes(".")) continue;
923
+ contexts.add(rest);
924
+ }
925
+ return [...contexts].sort();
926
+ }
927
+ /** Plural options in ICU's order: `=0` first, then the CLDR categories. */
928
+ function pluralOf(forms, ordinal) {
929
+ const order = ["=0", ...CATEGORIES];
930
+ forms.sort((a, b) => order.indexOf(a.key) - order.indexOf(b.key));
931
+ return { nodes: [{
932
+ type: "plural",
933
+ pluralType: ordinal ? "ordinal" : "cardinal",
934
+ name: "count",
935
+ offset: 0,
936
+ options: forms
937
+ }] };
938
+ }
939
+ /** One text's tokens as ICU nodes, with the `<tag>`s it opens still open on a stack. */
940
+ var TextConverter = class {
941
+ root = [];
942
+ stack = [];
943
+ current() {
944
+ return this.stack.at(-1)?.nodes ?? this.root;
945
+ }
946
+ /** A `<tag>`, `</tag>` or `<tag/>`; an error when it closes no open tag. */
947
+ tag(name, closing, selfClosing) {
948
+ if (closing) {
949
+ const open = this.stack.pop();
950
+ if (open === void 0 || open.name !== name) return `</${name}> closes no <${name}>`;
951
+ this.current().push({
952
+ type: "tag",
953
+ name: open.name,
954
+ children: open.nodes
955
+ });
956
+ } else if (selfClosing) this.current().push({
957
+ type: "tag",
958
+ name,
959
+ children: null
960
+ });
961
+ else this.stack.push({
962
+ name,
963
+ nodes: []
964
+ });
965
+ return null;
966
+ }
967
+ append(nodes) {
968
+ for (const node of nodes) if (node.type === "literal") pushLiteral(this.current(), node.value);
969
+ else this.current().push(node);
970
+ }
971
+ };
972
+ /** The i18next catalogs of a run, and the messages its call sites define from them. */
973
+ var I18nextAdapter = class {
974
+ catalogExtensions = [".json"];
975
+ catalogsRequired = true;
976
+ extensions = MODULE_EXTENSIONS;
977
+ /** locale → namespace → key → text. */
978
+ catalogs = /* @__PURE__ */ new Map();
979
+ namings = /* @__PURE__ */ new Map();
980
+ /** `ns:key` of every source text a call site names, its plural and context forms and nested `$t()` included. */
981
+ referenced = /* @__PURE__ */ new Set();
982
+ sourceLocale = "";
983
+ defaultNs = null;
984
+ mentions(text) {
985
+ return /i18next|\bt\s*\(|<Trans\b/.test(text);
986
+ }
987
+ load(files, env) {
988
+ this.sourceLocale = env.config.sourceLocale;
989
+ for (const file of files) this.readCatalog(file, env);
990
+ this.defaultNs = defaultNamespace(this.namespaces(this.sourceLocale));
991
+ }
992
+ planFile(file, text, env) {
993
+ let program;
994
+ try {
995
+ program = parseModule(text, langFromId(file), file).program;
996
+ } catch (error) {
997
+ if (!isDiagnosticError(error)) throw error;
998
+ env.diagnostics.push({
999
+ ...error.diagnostic,
1000
+ file: env.rel(file)
1001
+ });
1002
+ return null;
1003
+ }
1004
+ return new I18nextModule(this, env, {
1005
+ file,
1006
+ text,
1007
+ program
1008
+ }).plan();
1009
+ }
1010
+ unusedKeys() {
1011
+ const out = /* @__PURE__ */ new Set();
1012
+ for (const [ns, texts] of this.namespaces(this.sourceLocale)) for (const key of texts.keys()) if (!this.referenced.has(`${ns}:${key}`)) out.add(this.messageKey(ns, key));
1013
+ return [...out];
1014
+ }
1015
+ /** Marks a key family (`key`, `key_one`, `key_male_other`…) and what its texts nest as named by code. */
1016
+ reference(ns, key, depth = 0) {
1017
+ if (depth > 8) return;
1018
+ const source = this.namespaces(this.sourceLocale);
1019
+ for (const [k, text] of source.get(ns) ?? []) {
1020
+ if (k !== key && !k.startsWith(key + "_") || this.referenced.has(`${ns}:${k}`)) continue;
1021
+ this.referenced.add(`${ns}:${k}`);
1022
+ for (const m of text.value.matchAll(/\$t\(([^(),]*)/g)) {
1023
+ const target = splitNamespace(m[1].trim(), ns, source);
1024
+ this.reference(target.ns, target.key, depth + 1);
1025
+ }
1026
+ }
1027
+ }
1028
+ namespaces(locale) {
1029
+ return this.catalogs.get(locale) ?? /* @__PURE__ */ new Map();
1030
+ }
1031
+ textOf(locale, ns, key) {
1032
+ return this.namespaces(locale).get(ns)?.get(key);
1033
+ }
1034
+ /** Whether the source locale has `key` itself or one of its plural forms. */
1035
+ hasKey(ns, key) {
1036
+ const texts = this.namespaces(this.sourceLocale).get(ns);
1037
+ if (texts === void 0) return false;
1038
+ return texts.has(key) || hasForms(texts, key);
1039
+ }
1040
+ /** The namespace holding `key`: the call's own, the default, or the only one that has it. */
1041
+ findNamespace(key, preferred) {
1042
+ if (preferred !== null) return this.hasKey(preferred, key) ? preferred : null;
1043
+ if (this.defaultNs !== null && this.hasKey(this.defaultNs, key)) return this.defaultNs;
1044
+ const found = [...this.namespaces(this.sourceLocale).keys()].filter((ns) => this.hasKey(ns, key));
1045
+ return found.length === 1 ? found[0] : null;
1046
+ }
1047
+ messageKey(ns, key) {
1048
+ return ns === this.defaultNs ? key : `${ns}:${key}`;
1049
+ }
1050
+ /** Whether a source key only has plural forms, so a call must pass `count`. */
1051
+ isPlural(ns, key) {
1052
+ const texts = this.namespaces(this.sourceLocale).get(ns);
1053
+ return texts !== void 0 && !texts.has(key) && hasForms(texts, key);
1054
+ }
1055
+ /** `{{x}}`, `$t(…)` and, for `<Trans>`, `<0>…</0>` of one text as ICU nodes. */
1056
+ convert(raw, { locale, ns }, { tags, inPlural }, depth = 0) {
1057
+ const out = new TextConverter();
1058
+ const token = /\{\{(.*?)\}\}|\$t\(([^()]*)\)|<(\/?)([A-Za-z0-9_-]+)\s*(\/?)>/g;
1059
+ let at = 0;
1060
+ for (let m = token.exec(raw); m !== null; m = token.exec(raw)) {
1061
+ const [whole, interpolation, nested, closing, tag, selfClosing] = m;
1062
+ if (tag !== void 0 && !tags) continue;
1063
+ pushLiteral(out.current(), raw.slice(at, m.index));
1064
+ at = m.index + whole.length;
1065
+ let error = null;
1066
+ if (interpolation !== void 0) {
1067
+ const node = interpolationNode(interpolation, inPlural);
1068
+ if ("error" in node) return node;
1069
+ out.current().push(node.node);
1070
+ } else if (nested !== void 0) {
1071
+ const inner = this.nested(nested, {
1072
+ locale,
1073
+ ns
1074
+ }, {
1075
+ tags,
1076
+ inPlural
1077
+ }, depth);
1078
+ if ("error" in inner) return inner;
1079
+ out.append(inner.nodes);
1080
+ } else error = out.tag(tag, closing === "/", selfClosing === "/");
1081
+ if (error !== null) return { error };
1082
+ }
1083
+ const open = out.stack.at(-1);
1084
+ if (open !== void 0) return { error: `<${open.name}> is never closed` };
1085
+ pushLiteral(out.current(), raw.slice(at));
1086
+ return { nodes: out.root };
1087
+ }
1088
+ /** A `$t(key)` nesting, inlined. */
1089
+ nested(nested, { locale, ns }, options, depth) {
1090
+ if (depth > 8) return { error: "$t() nests deeper than 8 levels" };
1091
+ if (nested.includes(",")) return { error: `$t(${nested}) passes options, which cannot be inlined` };
1092
+ const target = splitNamespace(nested.trim(), ns, this.namespaces(locale));
1093
+ const targetNs = target.ns;
1094
+ const text = this.textOf(locale, targetNs, target.key);
1095
+ if (text === void 0) return { error: `$t(${nested}) names no message in ${locale}` };
1096
+ return this.convert(text.value, {
1097
+ locale,
1098
+ ns: targetNs
1099
+ }, options, depth + 1);
1100
+ }
1101
+ /** One key's text, or its plural forms as an ICU plural. */
1102
+ branch(locale, ns, key, shape) {
1103
+ const texts = this.namespaces(locale).get(ns);
1104
+ if (texts === void 0) return null;
1105
+ if (shape.count) {
1106
+ const plural = this.pluralForms(texts, {
1107
+ locale,
1108
+ ns
1109
+ }, key, shape);
1110
+ if (plural !== null) return plural;
1111
+ }
1112
+ const text = texts.get(key);
1113
+ if (text === void 0) return null;
1114
+ return this.convert(text.value, {
1115
+ locale,
1116
+ ns
1117
+ }, {
1118
+ tags: shape.tags,
1119
+ inPlural: false
1120
+ });
1121
+ }
1122
+ /** A key's plural forms as an ICU plural; null when it has none. */
1123
+ pluralForms(texts, where, key, shape) {
1124
+ const options = {
1125
+ tags: shape.tags,
1126
+ inPlural: true
1127
+ };
1128
+ const categories = pluralCategories(where.locale)[shape.ordinal ? "ordinal" : "cardinal"];
1129
+ const forms = [];
1130
+ for (const category of CATEGORIES) {
1131
+ const formKey = shape.ordinal ? `${key}_ordinal_${category}` : `${key}_${category}`;
1132
+ const text = texts.get(formKey);
1133
+ if (text === void 0) continue;
1134
+ const converted = this.convert(text.value, where, options);
1135
+ if ("error" in converted) return { error: `${formKey}: ${converted.error}` };
1136
+ const zero = category === "zero" && !categories.includes("zero");
1137
+ forms.push({
1138
+ key: zero ? "=0" : category,
1139
+ value: converted.nodes
1140
+ });
1141
+ }
1142
+ const legacy = texts.get(`${key}_plural`);
1143
+ if (forms.length === 0 && legacy !== void 0 && !shape.ordinal) {
1144
+ const pairs = [["one", texts.get(key)], ["other", legacy]];
1145
+ for (const [category, text] of pairs) {
1146
+ if (text === void 0) continue;
1147
+ const converted = this.convert(text.value, where, options);
1148
+ if ("error" in converted) return converted;
1149
+ forms.push({
1150
+ key: category,
1151
+ value: converted.nodes
1152
+ });
1153
+ }
1154
+ }
1155
+ if (forms.length === 0) return null;
1156
+ if (!forms.some((f) => f.key === "other")) {
1157
+ const plain = texts.get(key);
1158
+ if (plain === void 0) return { error: `${key} has plural forms but no ${key}_other` };
1159
+ const converted = this.convert(plain.value, where, options);
1160
+ if ("error" in converted) return converted;
1161
+ forms.push({
1162
+ key: "other",
1163
+ value: converted.nodes
1164
+ });
1165
+ }
1166
+ return pluralOf(forms, shape.ordinal);
1167
+ }
1168
+ /** The message of a key and shape in one locale; null when the locale has none of its keys. */
1169
+ build(locale, ns, key, shape) {
1170
+ if (!shape.context) return this.branch(locale, ns, key, shape);
1171
+ const keys = [...this.namespaces(this.sourceLocale).get(ns)?.keys() ?? [], ...this.namespaces(locale).get(ns)?.keys() ?? []];
1172
+ const options = [];
1173
+ for (const context of contextsOf(keys, key)) {
1174
+ const converted = this.branch(locale, ns, `${key}_${context}`, shape);
1175
+ if (converted === null) continue;
1176
+ if ("error" in converted) return converted;
1177
+ options.push({
1178
+ key: context,
1179
+ value: converted.nodes
1180
+ });
1181
+ }
1182
+ const other = this.branch(locale, ns, key, shape);
1183
+ if (other !== null && "error" in other) return other;
1184
+ if (options.length === 0 && other === null) return null;
1185
+ options.push({
1186
+ key: "other",
1187
+ value: other === null ? [] : other.nodes
1188
+ });
1189
+ return { nodes: [{
1190
+ type: "select",
1191
+ name: "context",
1192
+ options
1193
+ }] };
1194
+ }
1195
+ /** Every text of a key family in a locale, for a translator comment. */
1196
+ originalTexts(locale, ns, key) {
1197
+ const parts = [];
1198
+ for (const [k, text] of this.namespaces(locale).get(ns) ?? []) if (k === key) parts.push(text.value);
1199
+ else if (k.startsWith(key + "_")) parts.push(`${k.slice(key.length + 1)}: ${text.value}`);
1200
+ return parts.join(" | ");
1201
+ }
1202
+ /** The first text of a key family in a locale: the key's own, else its first form's. */
1203
+ firstText(locale, ns, key) {
1204
+ return [...this.namespaces(locale).get(ns) ?? []].find(([k]) => k === key || k.startsWith(key + "_"))?.[1];
1205
+ }
1206
+ /**
1207
+ * Registers the message of a key and shape; its registry key, or why it
1208
+ * cannot be. Tags are named through `tags` (path rules and the defining
1209
+ * site's elements); a later site of the same message reuses the naming.
1210
+ */
1211
+ define(env, { ns, key }, shape, { fallback, tags }) {
1212
+ const name = this.messageKey(ns, key);
1213
+ const id = name + shapeSuffix(shape);
1214
+ if (env.message(id) !== void 0) return { key: id };
1215
+ let source = this.build(this.sourceLocale, ns, key, shape);
1216
+ if (source === null && fallback !== null) {
1217
+ const where = {
1218
+ locale: this.sourceLocale,
1219
+ ns
1220
+ };
1221
+ source = this.convert(fallback, where, {
1222
+ tags: shape.tags,
1223
+ inPlural: false
1224
+ });
1225
+ }
1226
+ if (source === null) return { problem: `${name} is in no ${this.sourceLocale} catalog` };
1227
+ if ("error" in source) return { problem: `${name}: ${source.error}` };
1228
+ const naming = newNaming();
1229
+ const finish = (nodes, isSource) => printICU(tags === null ? nodes : renameTags(nodes, naming, tags.pathOf, tags.elementAt, isSource));
1230
+ const origin = this.textOf(this.sourceLocale, ns, key) ?? this.firstText(this.sourceLocale, ns, key);
1231
+ if (!env.define({
1232
+ key: id,
1233
+ named: true,
1234
+ source: finish(source.nodes, true),
1235
+ context: null,
1236
+ hint: null,
1237
+ translations: this.translations({
1238
+ ns,
1239
+ key
1240
+ }, shape, (nodes) => finish(nodes, false)),
1241
+ file: origin?.file ?? "",
1242
+ line: origin?.line ?? 0
1243
+ })) return { problem: `${name} could not be converted` };
1244
+ if (tags !== null) this.namings.set(id, naming);
1245
+ return { key: id };
1246
+ }
1247
+ /** A message's translations in every other locale, printed by `print`. */
1248
+ translations({ ns, key }, shape, print) {
1249
+ const translations = /* @__PURE__ */ new Map();
1250
+ for (const locale of this.catalogs.keys()) {
1251
+ if (locale === this.sourceLocale) continue;
1252
+ const converted = this.build(locale, ns, key, shape);
1253
+ if (converted === null) continue;
1254
+ if (!("error" in converted)) {
1255
+ translations.set(locale, { icu: print(converted.nodes) });
1256
+ continue;
1257
+ }
1258
+ const first = this.firstText(locale, ns, key);
1259
+ translations.set(locale, {
1260
+ unconverted: this.originalTexts(locale, ns, key),
1261
+ reason: converted.error,
1262
+ ...first === void 0 ? {} : {
1263
+ file: first.file,
1264
+ line: first.line
1265
+ }
1266
+ });
1267
+ }
1268
+ return translations;
1269
+ }
1270
+ readCatalog(file, env) {
1271
+ let text;
1272
+ try {
1273
+ text = readFileSync(file.file, "utf8");
1274
+ } catch (error) {
1275
+ const message = `cannot read: ${error.message}`;
1276
+ env.report("catalog-parse", message, { file: file.file }, "error");
1277
+ return;
1278
+ }
1279
+ const parsed = parseJson(text);
1280
+ if (parsed.problem !== null) {
1281
+ const at = {
1282
+ file: file.file,
1283
+ line: parsed.problem.line
1284
+ };
1285
+ env.report("catalog-parse", parsed.problem.message, at, "error");
1286
+ return;
1287
+ }
1288
+ const flat = flattenTree(parsed.value, text);
1289
+ for (const problem of flat.problems) env.report("migrate-unconverted", problem.message, {
1290
+ file: file.file,
1291
+ line: problem.line
1292
+ });
1293
+ const ns = file.namespace ?? DEFAULT_NS;
1294
+ let byNs = this.catalogs.get(file.locale);
1295
+ if (byNs === void 0) this.catalogs.set(file.locale, byNs = /* @__PURE__ */ new Map());
1296
+ let texts = byNs.get(ns);
1297
+ if (texts === void 0) byNs.set(ns, texts = /* @__PURE__ */ new Map());
1298
+ for (const [key, value] of flat.texts) texts.set(key, {
1299
+ ...value,
1300
+ file: file.file
1301
+ });
1302
+ }
1303
+ };
1304
+ /** The registry key's suffix for a shape: one message per key and shape. */
1305
+ function shapeSuffix(shape) {
1306
+ let suffix = "";
1307
+ if (shape.context) suffix += " {context}";
1308
+ if (shape.ordinal) suffix += " {ordinal}";
1309
+ if (shape.tags) suffix += " <Trans>";
1310
+ return suffix;
1311
+ }
1312
+ /** The namespace a `useTranslation()` or `getFixedT()` argument names (a string, or an array's first). */
1313
+ function namespaceArgument(node) {
1314
+ if (node === void 0) return null;
1315
+ const n = unwrap(node);
1316
+ if (n.type === "ArrayExpression") return stringValue(n.elements[0]);
1317
+ return stringValue(n);
1318
+ }
1319
+ /** Whether a `getFixedT(lng)` argument names a locale (not `null` or `undefined`). */
1320
+ function pinsLocale(lng) {
1321
+ if (lng === void 0) return false;
1322
+ const node = unwrap(lng);
1323
+ if (node.type === "Literal" && node.value === null) return false;
1324
+ return identifierName(node) !== "undefined";
1325
+ }
1326
+ /** The path a `<Trans>` tag maps to: an index into the children or the array, a `components` key, or a basic HTML tag. */
1327
+ function transPathOf(indexed, named) {
1328
+ return (name, parent) => {
1329
+ if (/^\d+$/.test(name) && indexed !== null) return parent === null ? name : `${parent}.${name}`;
1330
+ if (named?.has(name) === true) return name;
1331
+ if (BASIC_HTML.has(name)) return `html:${name}`;
1332
+ return null;
1333
+ };
1334
+ }
1335
+ /** The element a `<Trans>` tag path names at this site. */
1336
+ function transElementAt(indexed, named) {
1337
+ return (path) => {
1338
+ if (path.startsWith("html:")) return "html";
1339
+ if (named !== null && !/^\d/.test(path)) return named.get(path) ?? null;
1340
+ let scope = indexed;
1341
+ let found = null;
1342
+ for (const part of path.split(".")) {
1343
+ found = scope?.[Number(part)] ?? null;
1344
+ if (found === null || found.type !== "JSXElement") return null;
1345
+ scope = jsxChildren(found);
1346
+ }
1347
+ return found;
1348
+ };
1349
+ }
1350
+ /** `{{ name }}` objects anywhere among `<Trans>` children (`<strong>{{ name }}</strong>`), as value properties. */
1351
+ function childValues(list, into) {
1352
+ for (const child of list) {
1353
+ if (child.type === "JSXElement") childValues(jsxChildren(child), into);
1354
+ if (child.type !== "JSXExpressionContainer") continue;
1355
+ const props = objectProperties(child.expression);
1356
+ if (props === null) continue;
1357
+ into.push(...props.order.filter((p) => p.type === "SpreadElement" || keyName(p) !== "format"));
1358
+ }
1359
+ }
1360
+ /** The root of a call chain (`i18next.use(a).use(b).init()` → `i18next`). */
1361
+ function chainRoot(node) {
1362
+ let root = unwrap(node);
1363
+ for (;;) if (root.type === "CallExpression") root = unwrap(root.callee);
1364
+ else if (root.type === "MemberExpression") root = unwrap(root.object);
1365
+ else return root;
1366
+ }
1367
+ /** Instance methods with no mechanical counterpart, and what to do instead. */
1368
+ const INSTANCE_NOTES = /* @__PURE__ */ new Map([
1369
+ ["init", "i18next.init(): delete this setup once nothing uses i18next; vi18n needs only its Vite plugin and vi18n.config.ts"],
1370
+ ["changeLanguage", "changeLanguage(lng): use setLocale(lng) from @menapo/vi18n"],
1371
+ ["exists", "exists(key) has no vi18n counterpart: every message the code names exists"]
1372
+ ]);
1373
+ /** `<Trans>` attributes with no vi18n counterpart. */
1374
+ const TRANS_UNSUPPORTED = [
1375
+ "tOptions",
1376
+ "parent",
1377
+ "i18nIsDynamicList",
1378
+ "shouldUnescape"
1379
+ ];
1380
+ /** One module's i18next call sites, planned as rewrites. */
1381
+ var I18nextModule = class {
1382
+ adapter;
1383
+ env;
1384
+ text;
1385
+ program;
1386
+ info;
1387
+ builder;
1388
+ tsx;
1389
+ useTranslation;
1390
+ transNames;
1391
+ providers;
1392
+ translationNames;
1393
+ instances;
1394
+ importedT;
1395
+ withTranslation;
1396
+ scopes = /* @__PURE__ */ new Map();
1397
+ hookInstances = /* @__PURE__ */ new Set();
1398
+ fixedLocale = /* @__PURE__ */ new Set();
1399
+ constructor(adapter, env, { file, text, program }) {
1400
+ this.adapter = adapter;
1401
+ this.env = env;
1402
+ this.text = text;
1403
+ this.program = program;
1404
+ this.info = analyzeModule(program);
1405
+ this.builder = new ModuleBuilder({
1406
+ file,
1407
+ text,
1408
+ info: this.info,
1409
+ isOldSource
1410
+ });
1411
+ this.tsx = extname(file) === ".tsx";
1412
+ this.useTranslation = this.imported("useTranslation");
1413
+ this.transNames = this.imported("Trans");
1414
+ this.providers = this.imported("I18nextProvider");
1415
+ this.translationNames = this.imported("Translation");
1416
+ this.instances = /* @__PURE__ */ new Set([
1417
+ ...this.imported("default"),
1418
+ ...this.imported("i18n"),
1419
+ ...this.imported("i18next")
1420
+ ]);
1421
+ this.importedT = this.imported("t");
1422
+ this.withTranslation = this.imported("withTranslation");
1423
+ }
1424
+ plan() {
1425
+ for (const binding of this.info.bindings) this.readBinding(binding);
1426
+ this.visit(this.program);
1427
+ return this.builder.finish();
1428
+ }
1429
+ imported(name) {
1430
+ const locals = /* @__PURE__ */ new Set();
1431
+ for (const declaration of this.info.imports) {
1432
+ if (!isOldSource(declaration.source)) continue;
1433
+ for (const s of declaration.specifiers) if (s.imported === name) locals.add(s.local);
1434
+ }
1435
+ return locals;
1436
+ }
1437
+ /** A `useTranslation()` or `getFixedT()` binding: its scope, its instance, or its pinned locale. */
1438
+ readBinding(binding) {
1439
+ const init = binding.declarator?.init;
1440
+ if (init === null || init === void 0) return;
1441
+ const call = unwrap(init);
1442
+ if (call.type !== "CallExpression") return;
1443
+ const callee = identifierName(call.callee);
1444
+ const isHook = callee !== null && this.useTranslation.has(callee);
1445
+ const fixed = memberParts(call.callee)?.property === "getFixedT";
1446
+ if (!isHook && !fixed) return;
1447
+ const args = call.arguments;
1448
+ if (isHook) this.builder.hooks.push(binding);
1449
+ const ns = namespaceArgument(isHook ? args[0] : args[1]);
1450
+ const options = isHook ? args[1] : args[2];
1451
+ const keyPrefix = options === void 0 ? void 0 : objectProperties(options)?.properties.get("keyPrefix");
1452
+ const prefix = keyPrefix === void 0 ? null : stringValue(keyPrefix.value);
1453
+ const role = hookRole(binding.slot, binding.declarator.id);
1454
+ if (role === "i18n") this.hookInstances.add(binding);
1455
+ else if (role === "t") this.scopes.set(binding, {
1456
+ ns,
1457
+ prefix
1458
+ });
1459
+ if (!fixed || !pinsLocale(args[0])) return;
1460
+ this.fixedLocale.add(binding);
1461
+ this.builder.note(call.start, "getFixedT(lng) pins a locale; its calls were not rewritten: use withLocale(lng, () => t(…)) or createTranslator(lng) from @menapo/vi18n/server");
1462
+ }
1463
+ /** The innermost binding of `name` visible at `offset`. */
1464
+ resolve(name, offset) {
1465
+ let best = null;
1466
+ for (const b of this.info.bindings) {
1467
+ if (b.name !== name || offset < b.scope.start || offset >= b.scope.end) continue;
1468
+ if (best === null || b.scope.end - b.scope.start < best.scope.end - best.scope.start) best = b;
1469
+ }
1470
+ return best;
1471
+ }
1472
+ /** Keys a computed key can produce, defined so they reach the `msg()` table. */
1473
+ computedKeys(node, { ns, prefix }) {
1474
+ const { adapter } = this;
1475
+ const all = [];
1476
+ for (const [space, texts] of adapter.namespaces(adapter.sourceLocale)) {
1477
+ if (ns !== null && space !== ns) continue;
1478
+ for (const key of new Set([...texts.keys()].map(baseKey))) all.push({
1479
+ ns: space,
1480
+ key
1481
+ });
1482
+ }
1483
+ const found = /* @__PURE__ */ new Set();
1484
+ const add = (e) => {
1485
+ const shape = plainShape(adapter.isPlural(e.ns, e.key));
1486
+ const defined = adapter.define(this.env, e, shape, {
1487
+ fallback: null,
1488
+ tags: null
1489
+ });
1490
+ adapter.reference(e.ns, e.key);
1491
+ if ("key" in defined) found.add(defined.key);
1492
+ };
1493
+ const visitKey = (n) => {
1494
+ const matches = keyMatcher(n, prefix);
1495
+ if (matches !== null) {
1496
+ for (const e of all) if (matches(e.key)) add(e);
1497
+ }
1498
+ if (n.type === "TemplateLiteral") return;
1499
+ for (const [, child] of childEntries(n)) visitKey(child);
1500
+ };
1501
+ visitKey(node);
1502
+ return [...found];
1503
+ }
1504
+ /** What a `t` or `<x>.t` callee is; null when it is not i18next's. */
1505
+ callee(node) {
1506
+ const callee = unwrap(node.callee);
1507
+ const result = {
1508
+ known: false,
1509
+ consume: [],
1510
+ scope: {
1511
+ ns: null,
1512
+ prefix: null
1513
+ },
1514
+ pinned: false
1515
+ };
1516
+ if (callee.type === "Identifier") {
1517
+ const name = callee.name;
1518
+ const binding = this.resolve(name, callee.start);
1519
+ if (binding !== null && this.scopes.has(binding)) this.scoped(result, binding);
1520
+ else if (this.importedT.has(name)) result.known = true;
1521
+ else if (name !== "t" || binding?.kind === "import") return null;
1522
+ result.consume = [callee];
1523
+ return result;
1524
+ }
1525
+ const member = memberParts(callee);
1526
+ if (member === null || member.property !== "t") return null;
1527
+ const object = unwrap(member.object);
1528
+ if (object.type !== "Identifier") return result;
1529
+ result.consume = [object];
1530
+ const binding = this.resolve(object.name, object.start);
1531
+ if (binding !== null && this.scopes.has(binding)) this.scoped(result, binding);
1532
+ else if (this.instances.has(object.name) || binding !== null && this.hookInstances.has(binding)) result.known = true;
1533
+ return result;
1534
+ }
1535
+ scoped(result, binding) {
1536
+ result.known = true;
1537
+ result.pinned = this.fixedLocale.has(binding);
1538
+ result.scope = this.scopes.get(binding);
1539
+ }
1540
+ /** `t(key, options)` or `<x>.t(key, options)`. */
1541
+ tCall(node) {
1542
+ const callee = this.callee(node);
1543
+ const first = node.arguments[0];
1544
+ if (callee === null || first === void 0 || first.type === "SpreadElement") return;
1545
+ const rawKey = stringValue(first);
1546
+ if (rawKey === null) return this.computedCall(first, callee);
1547
+ const call = this.readCall(node, callee, rawKey);
1548
+ const { adapter } = this;
1549
+ const resolvedNs = adapter.findNamespace(call.key, call.ns);
1550
+ if (resolvedNs !== null) adapter.reference(resolvedNs, call.key);
1551
+ if (resolvedNs === null && call.fallback === null) {
1552
+ if (callee.known) {
1553
+ const message = `t(${call.label}): the key is in no ${adapter.sourceLocale} catalog; not rewritten`;
1554
+ this.builder.note(node.start, message);
1555
+ }
1556
+ return;
1557
+ }
1558
+ if (this.unsupported(node, call.label, call.optionProps)) return;
1559
+ const ns = resolvedNs ?? call.ns ?? adapter.defaultNs ?? DEFAULT_NS;
1560
+ if (callee.pinned) return this.pinnedCall(node, {
1561
+ ns,
1562
+ key: call.key
1563
+ }, call.fallback, call.label);
1564
+ this.rewriteCall(node, callee, {
1565
+ ...call,
1566
+ ns
1567
+ });
1568
+ }
1569
+ /** A call with a computed key: reported, with the keys it can produce for the `msg()` table. */
1570
+ computedCall(first, callee) {
1571
+ const keys = this.computedKeys(first, callee.scope);
1572
+ if (keys.length === 0 && !callee.known) return;
1573
+ const call = `t(${this.text.slice(first.start, first.end)})`;
1574
+ this.builder.note(first.start, `${call} uses a computed key and was not rewritten`, keys);
1575
+ }
1576
+ /** What a `t()` call with a string key looks up: namespace, key, default text and options. */
1577
+ readCall(node, callee, rawKey) {
1578
+ const { adapter } = this;
1579
+ const options = node.arguments[1];
1580
+ const optionProps = options === void 0 ? null : objectProperties(options);
1581
+ const nsOption = stringValue(optionProps?.properties.get("ns")?.value);
1582
+ const source = adapter.namespaces(adapter.sourceLocale);
1583
+ const split = splitNamespace(rawKey, nsOption ?? callee.scope.ns, source);
1584
+ const { prefix } = callee.scope;
1585
+ const defaultValue = optionProps?.properties.get("defaultValue")?.value;
1586
+ const fallback = options !== void 0 && optionProps === null ? stringValue(options) : stringValue(defaultValue);
1587
+ return {
1588
+ label: JSON.stringify(rawKey),
1589
+ ns: split.ns,
1590
+ key: prefix === null ? split.key : `${prefix}.${split.key}`,
1591
+ options,
1592
+ optionProps,
1593
+ fallback
1594
+ };
1595
+ }
1596
+ /** A `t()` call rewritten to vi18n's, its lookup options dropped and its values kept. */
1597
+ rewriteCall(node, callee, call) {
1598
+ const { adapter } = this;
1599
+ const { ns, key, label, options, optionProps, fallback } = call;
1600
+ const passesValues = options !== void 0 && optionProps === null && fallback === null;
1601
+ const has = (name) => optionProps?.properties.has(name) === true;
1602
+ const plural = adapter.isPlural(ns, key);
1603
+ const shape = {
1604
+ count: has("count") || passesValues && plural,
1605
+ ordinal: has("ordinal"),
1606
+ context: has("context"),
1607
+ tags: false
1608
+ };
1609
+ if (!shape.count && plural) {
1610
+ this.builder.note(node.start, `t(${label}) has plural forms but passes no count; not rewritten`);
1611
+ return;
1612
+ }
1613
+ const defined = adapter.define(this.env, {
1614
+ ns,
1615
+ key
1616
+ }, shape, {
1617
+ fallback,
1618
+ tags: null
1619
+ });
1620
+ if ("problem" in defined) {
1621
+ this.builder.note(node.start, `${defined.problem}; t(${label}) was not rewritten`);
1622
+ return;
1623
+ }
1624
+ const kept = (optionProps?.order ?? []).filter((p) => p.type === "SpreadElement" || !LOOKUP_OPTIONS.has(keyName(p) ?? ""));
1625
+ const passed = passesValues ? options : null;
1626
+ this.builder.site(node, (r) => {
1627
+ let values = "";
1628
+ if (kept.length > 0) values = `, { ${kept.map((p) => r.src(p.start, p.end)).join(", ")} }`;
1629
+ else if (passed !== null) values = `, ${r.src(passed.start, passed.end)}`;
1630
+ return `${r.fn.t}(${r.message(defined.key)}${values})`;
1631
+ }, {
1632
+ keys: [defined.key],
1633
+ uses: ["t"],
1634
+ consume: callee.consume
1635
+ });
1636
+ }
1637
+ /** Reports a call passing options vi18n has no counterpart for, or a third argument. */
1638
+ unsupported(node, label, optionProps) {
1639
+ const unsupported = [...optionProps?.properties.keys() ?? []].filter((k) => UNSUPPORTED_OPTIONS.has(k));
1640
+ if (unsupported.length === 0 && node.arguments.length <= 2) return false;
1641
+ this.builder.note(node.start, unsupported.includes("lng") || unsupported.includes("lngs") ? `t(${label}) fixes a locale (${unsupported.join(", ")}): use withLocale(lng, () => t(…)) from @menapo/vi18n/server; not rewritten` : `t(${label}, …) passes ${unsupported.join(", ") || "a third argument"}, which vi18n has no counterpart for; not rewritten`);
1642
+ return true;
1643
+ }
1644
+ /** A call through a `getFixedT()` binding: its message defined for the `msg()` table, the call left. */
1645
+ pinnedCall(node, at, fallback, label) {
1646
+ const shape = plainShape(this.adapter.isPlural(at.ns, at.key));
1647
+ const defined = this.adapter.define(this.env, at, shape, {
1648
+ fallback,
1649
+ tags: null
1650
+ });
1651
+ if (!("key" in defined)) return;
1652
+ const message = `t(${label}) uses a locale getFixedT() pinned; not rewritten`;
1653
+ this.builder.note(node.start, message, [defined.key]);
1654
+ }
1655
+ /** `<Trans>`'s key, namespace and default text; null (reported) when they cannot be read. */
1656
+ transKey(element, attributes) {
1657
+ const attr = (name) => attributes.named.get(name)?.value ?? null;
1658
+ const has = (name) => attributes.named.has(name);
1659
+ if (attributes.spreads.length > 0) {
1660
+ this.builder.note(element.start, "<Trans {...props}> spreads props and was not rewritten");
1661
+ return null;
1662
+ }
1663
+ const unsupported = TRANS_UNSUPPORTED.find(has);
1664
+ if (unsupported !== void 0) {
1665
+ this.builder.note(element.start, `<Trans ${unsupported}> has no vi18n counterpart; not rewritten`);
1666
+ return null;
1667
+ }
1668
+ const childString = nodesToString(jsxChildren(element));
1669
+ const key = has("i18nKey") ? attributeString(attr("i18nKey")) : null;
1670
+ if (has("i18nKey") && key === null) {
1671
+ this.builder.note(element.start, "<Trans i18nKey={…}> with a computed key was not rewritten");
1672
+ return null;
1673
+ }
1674
+ const childText = childString.ok ? childString.text : null;
1675
+ const fallback = has("defaults") ? attributeString(attr("defaults")) : childText;
1676
+ const rawKey = key ?? fallback;
1677
+ if (rawKey === null || rawKey === "") {
1678
+ const reason = childString.reason || "no text";
1679
+ this.builder.note(element.start, `<Trans> without i18nKey: ${reason}; not rewritten`);
1680
+ return null;
1681
+ }
1682
+ const { adapter } = this;
1683
+ return {
1684
+ ...splitNamespace(rawKey, has("ns") ? attributeString(attr("ns")) : null, adapter.namespaces(adapter.sourceLocale)),
1685
+ fallback
1686
+ };
1687
+ }
1688
+ /** `<Trans>`'s components: the `components` prop (array or object), else the children by index. */
1689
+ transComponents(element, components) {
1690
+ if (components === null) return {
1691
+ indexed: jsxChildren(element),
1692
+ named: null
1693
+ };
1694
+ const c = unwrap(components);
1695
+ if (c.type === "ArrayExpression") return {
1696
+ indexed: c.elements.map((e) => e === null ? c : unwrap(e)),
1697
+ named: null
1698
+ };
1699
+ const props = objectProperties(c);
1700
+ if (props === null || props.spreads.length > 0) {
1701
+ this.builder.note(element.start, "<Trans components={…}> is not a literal object or array; not rewritten");
1702
+ return null;
1703
+ }
1704
+ return {
1705
+ indexed: null,
1706
+ named: new Map([...props.properties].map(([k, p]) => [k, unwrap(p.value)]))
1707
+ };
1708
+ }
1709
+ /** `<Trans>` as `rich()`, or `t()` when its message has no tags. */
1710
+ trans(element) {
1711
+ const attributes = jsxAttributes(element);
1712
+ const has = (name) => attributes.named.has(name);
1713
+ const expressionOf = (name) => has(name) ? attributeExpression(attributes.named.get(name)?.value ?? null) : null;
1714
+ const read = this.transKey(element, attributes);
1715
+ if (read === null) return;
1716
+ const { adapter } = this;
1717
+ const resolvedNs = adapter.findNamespace(read.key, read.ns);
1718
+ if (resolvedNs !== null) adapter.reference(resolvedNs, read.key);
1719
+ const ns = resolvedNs ?? read.ns ?? adapter.defaultNs ?? DEFAULT_NS;
1720
+ const components = this.transComponents(element, expressionOf("components"));
1721
+ if (components === null) return;
1722
+ const pathOf = transPathOf(components.indexed, components.named);
1723
+ const elementAt = transElementAt(components.indexed, components.named);
1724
+ const shape = {
1725
+ count: has("count"),
1726
+ ordinal: false,
1727
+ context: has("context"),
1728
+ tags: true
1729
+ };
1730
+ const defined = adapter.define(this.env, {
1731
+ ns,
1732
+ key: read.key
1733
+ }, shape, {
1734
+ fallback: resolvedNs === null ? read.fallback : null,
1735
+ tags: {
1736
+ pathOf,
1737
+ elementAt
1738
+ }
1739
+ });
1740
+ if ("problem" in defined) {
1741
+ this.builder.note(element.start, `${defined.problem}; <Trans> was not rewritten`);
1742
+ return;
1743
+ }
1744
+ const message = this.env.message(defined.key);
1745
+ const naming = adapter.namings.get(defined.key);
1746
+ if (message === void 0 || naming === void 0) return;
1747
+ const { handlers, missing } = siteHandlers(naming, elementAt);
1748
+ if (missing.length > 0) {
1749
+ const tags = missing.map((m) => `<${m}>`).join(", ");
1750
+ const maps = missing.length === 1 ? "maps" : "map";
1751
+ this.builder.note(element.start, `<Trans>: ${tags} ${maps} to no element here; not rewritten`, [defined.key]);
1752
+ return;
1753
+ }
1754
+ const values = this.transValues(element, expressionOf("values"));
1755
+ if (values === null) return;
1756
+ const extra = [];
1757
+ for (const name of ["count", "context"]) {
1758
+ const expression = expressionOf(name);
1759
+ if (expression !== null) extra.push([name, expression]);
1760
+ }
1761
+ const selfClosing = selfClosingTags(this.env.codec.parse(message.canonical));
1762
+ const rich = handlers.size > 0;
1763
+ const types = rich && this.tsx ? reactTypes(this.builder) : null;
1764
+ const info = this.info;
1765
+ this.builder.site(element, (r) => {
1766
+ const entries = [];
1767
+ for (const [name, handler] of handlers) entries.push(entry(name, elementHandler(handler, selfClosing.has(name), r, types)));
1768
+ for (const p of values) entries.push(r.src(p.start, p.end));
1769
+ for (const [name, expression] of extra) entries.push(entry(name, r.src(expression.start, expression.end)));
1770
+ const options = entries.length > 0 ? `, { ${entries.join(", ")} }` : "";
1771
+ const call = rich ? richCall(r, defined.key, entries, types) : `${r.fn.t}(${r.message(defined.key)}${options})`;
1772
+ return inJsxChildren(info, element) ? `{${call}}` : call;
1773
+ }, {
1774
+ keys: [defined.key],
1775
+ uses: [rich ? "rich" : "t"],
1776
+ consume: jsxNameNodes(element)
1777
+ });
1778
+ }
1779
+ /** `<Trans>`'s value properties: `values`, then `{{ name }}` objects among its children. */
1780
+ transValues(element, valuesExpr) {
1781
+ const values = [];
1782
+ if (valuesExpr !== null) {
1783
+ const props = objectProperties(valuesExpr);
1784
+ if (props === null) {
1785
+ this.builder.note(element.start, "<Trans values={…}> is not an object literal; not rewritten");
1786
+ return null;
1787
+ }
1788
+ values.push(...props.order);
1789
+ }
1790
+ childValues(jsxChildren(element), values);
1791
+ return values;
1792
+ }
1793
+ unwrapProvider(element) {
1794
+ const children = jsxChildren(element);
1795
+ const opening = element.openingElement;
1796
+ const closing = element.closingElement;
1797
+ this.builder.consumeRange(opening);
1798
+ this.builder.consume(jsxNameNodes(element));
1799
+ const nested = inJsxChildren(this.info, element);
1800
+ this.builder.replace(element, (r) => {
1801
+ if (closing === null) return nested ? "" : "null";
1802
+ if (nested) return r.src(opening.end, closing.start).trim();
1803
+ if (children.length === 1 && children[0].type === "JSXElement") return r.src(children[0].start, children[0].end);
1804
+ return `<>${r.src(opening.end, closing.start)}</>`;
1805
+ });
1806
+ }
1807
+ /** Setup and APIs without a mechanical counterpart, reported. */
1808
+ otherCall(node) {
1809
+ const name = identifierName(node.callee);
1810
+ if (name !== null && this.withTranslation.has(name)) {
1811
+ this.builder.note(node.start, "withTranslation() injects t as a prop: drop it and import t from @menapo/vi18n where the component calls it");
1812
+ return;
1813
+ }
1814
+ const member = memberParts(node.callee);
1815
+ if (member === null) return;
1816
+ const object = identifierName(chainRoot(member.object));
1817
+ const isInstance = object !== null && (this.instances.has(object) || /^i18n(?:ext)?$/.test(object));
1818
+ const note = INSTANCE_NOTES.get(member.property);
1819
+ if (isInstance && note !== void 0) this.builder.note(node.start, note);
1820
+ }
1821
+ visit(node) {
1822
+ if (node.type === "CallExpression") {
1823
+ this.tCall(node);
1824
+ this.otherCall(node);
1825
+ } else if (node.type === "JSXElement") this.element(node);
1826
+ for (const [, child] of childEntries(node)) this.visit(child);
1827
+ }
1828
+ element(node) {
1829
+ const name = jsxName(node);
1830
+ if (this.transNames.has(name)) this.trans(node);
1831
+ else if (this.providers.has(name)) this.unwrapProvider(node);
1832
+ else if (this.translationNames.has(name)) this.builder.note(node.start, "<Translation> render props are not rewritten: call t() from @menapo/vi18n inside");
1833
+ }
1834
+ };
1835
+ /** For a computed key: which catalog keys a string or template part can produce; null for other nodes. */
1836
+ function keyMatcher(n, prefix) {
1837
+ if (n.type === "Literal" && typeof n.value === "string") {
1838
+ const key = prefix === null ? n.value : `${prefix}.${n.value}`;
1839
+ return (k) => k === key;
1840
+ }
1841
+ if (n.type !== "TemplateLiteral") return null;
1842
+ const quasis = n.quasis.map((q) => q.value.cooked ?? "");
1843
+ if (prefix !== null) quasis[0] = `${prefix}.${quasis[0]}`;
1844
+ const pattern = templateKeyPattern(quasis);
1845
+ return pattern === null ? null : (k) => pattern.test(k);
1846
+ }
1847
+ /** react-i18next's `nodesToString`: the key and default text `<Trans>` derives from its children. */
1848
+ function nodesToString(children) {
1849
+ let text = "";
1850
+ for (const [index, child] of children.entries()) {
1851
+ if (child.type === "JSXText") {
1852
+ text += cleanJsxText(child.value);
1853
+ continue;
1854
+ }
1855
+ if (child.type === "JSXExpressionContainer") {
1856
+ const expression = unwrap(child.expression);
1857
+ const literal = stringValue(expression);
1858
+ if (literal !== null) {
1859
+ text += literal;
1860
+ continue;
1861
+ }
1862
+ const props = objectProperties(expression);
1863
+ if (props !== null && props.spreads.length === 0) {
1864
+ const format = stringValue(props.properties.get("format")?.value);
1865
+ const names = [...props.properties.keys()].filter((k) => k !== "format");
1866
+ if (names.length === 1) {
1867
+ text += `{{${format === null ? names[0] : `${names[0]}, ${format}`}}}`;
1868
+ continue;
1869
+ }
1870
+ }
1871
+ return {
1872
+ ok: false,
1873
+ text,
1874
+ reason: `{${text.length > 0 ? "…" : ""}} holds an expression, not text or {{ value }}`
1875
+ };
1876
+ }
1877
+ if (child.type === "JSXElement") {
1878
+ const name = jsxName(child);
1879
+ const attributes = child.openingElement.attributes;
1880
+ const inner = jsxChildren(child);
1881
+ const basic = BASIC_HTML.has(name);
1882
+ if (inner.length === 0) {
1883
+ text += basic && attributes.length === 0 ? `<${name}/>` : `<${index}></${index}>`;
1884
+ continue;
1885
+ }
1886
+ if (basic && attributes.length === 0 && inner.length === 1 && inner[0].type === "JSXText") {
1887
+ text += `<${name}>${cleanJsxText(inner[0].value)}</${name}>`;
1888
+ continue;
1889
+ }
1890
+ const nested = nodesToString(inner);
1891
+ if (!nested.ok) return nested;
1892
+ text += `<${index}>${nested.text}</${index}>`;
1893
+ continue;
1894
+ }
1895
+ return {
1896
+ ok: false,
1897
+ text,
1898
+ reason: `a ${child.type} child`
1899
+ };
1900
+ }
1901
+ return {
1902
+ ok: true,
1903
+ text,
1904
+ reason: ""
1905
+ };
1906
+ }
1907
+ export { linguiId as _, annotateHandlers as a, pushLiteral as b, newNaming as c, richCall as d, selfClosingTags as f, formatjsId as g, formatjsAstToIcu as h, isOldSource as i, reactTypes as l, flattenTree as m, createI18nextAdapter as n, elementHandler as o, siteHandlers as p, interpolationNode as r, entry as s, MODULE_EXTENSIONS as t, renameTags as u, parseJson as v, yamlKeyLines as x, parseYaml as y };