@verbaly/compiler 0.11.0 → 0.13.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.
package/dist/index.js CHANGED
@@ -1,378 +1,409 @@
1
- // src/analyze.ts
2
1
  import { parse } from "@babel/parser";
3
-
4
- // src/key.ts
5
- import { createHash } from "crypto";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
4
+ import { dirname, join, relative, resolve } from "node:path";
5
+ import { RICH_TAGS, createVerbaly, parse as parse$1, parseTags, safeHref } from "verbaly";
6
+ import { pathToFileURL } from "node:url";
7
+ import { glob } from "tinyglobby";
8
+ import MagicString from "magic-string";
9
+ //#region src/key.ts
6
10
  function stableKey(message) {
7
- return createHash("sha256").update(message).digest("base64url").slice(0, 8);
8
- }
9
-
10
- // src/analyze.ts
11
- var SKIP_KEYS = /* @__PURE__ */ new Set(["loc", "leadingComments", "trailingComments", "innerComments", "extra"]);
11
+ return createHash("sha256").update(message).digest("base64url").slice(0, 8);
12
+ }
13
+ //#endregion
14
+ //#region src/analyze.ts
15
+ const SKIP_KEYS = /* @__PURE__ */ new Set([
16
+ "loc",
17
+ "leadingComments",
18
+ "trailingComments",
19
+ "innerComments",
20
+ "extra"
21
+ ]);
12
22
  function analyze(code, file) {
13
- const jsx = /\.[jt]sx$/.test(file);
14
- const ast = parse(code, {
15
- sourceType: "module",
16
- errorRecovery: true,
17
- plugins: jsx ? ["typescript", "jsx"] : ["typescript"]
18
- });
19
- const tagged = [];
20
- const usedKeys = [];
21
- walk(ast.program, (node) => {
22
- if (node.type === "TaggedTemplateExpression") {
23
- const tag = node.tag;
24
- const explicit = explicitId(tag);
25
- if (!explicit && !isTReference(tag)) return;
26
- const quasi = node.quasi;
27
- const message = buildMessage(code, quasi);
28
- if (!message) return;
29
- tagged.push({
30
- key: explicit ? explicit.key : stableKey(message.text),
31
- message: message.text,
32
- params: message.params,
33
- start: node.start,
34
- end: node.end,
35
- tagStart: explicit ? explicit.refStart : tag.start,
36
- tagEnd: explicit ? explicit.refEnd : tag.end,
37
- file
38
- });
39
- } else if (node.type === "CallExpression") {
40
- const callee = node.callee;
41
- if (!isTReference(callee)) return;
42
- const args = node.arguments;
43
- const first = args[0];
44
- if (first?.type === "StringLiteral") {
45
- usedKeys.push({ key: first.value, file });
46
- }
47
- } else if (node.type === "JSXElement") {
48
- handleTrans(code, node, file, tagged, usedKeys);
49
- }
50
- });
51
- return { tagged, usedKeys };
23
+ const ast = parse(code, {
24
+ sourceType: "module",
25
+ errorRecovery: true,
26
+ plugins: /\.[jt]sx$/.test(file) ? ["typescript", "jsx"] : ["typescript"]
27
+ });
28
+ const tagged = [];
29
+ const usedKeys = [];
30
+ walk(ast.program, (node) => {
31
+ if (node.type === "TaggedTemplateExpression") {
32
+ const tag = node.tag;
33
+ const explicit = explicitId(tag);
34
+ if (!explicit && !isTReference(tag)) return;
35
+ const quasi = node.quasi;
36
+ const message = buildMessage(code, quasi);
37
+ if (!message) return;
38
+ tagged.push({
39
+ key: explicit ? explicit.key : stableKey(message.text),
40
+ message: message.text,
41
+ params: message.params,
42
+ start: node.start,
43
+ end: node.end,
44
+ tagStart: explicit ? explicit.refStart : tag.start,
45
+ tagEnd: explicit ? explicit.refEnd : tag.end,
46
+ file
47
+ });
48
+ } else if (node.type === "CallExpression") {
49
+ const callee = node.callee;
50
+ if (!isTReference(callee)) return;
51
+ const first = node.arguments[0];
52
+ if (first?.type === "StringLiteral") usedKeys.push({
53
+ key: first.value,
54
+ file
55
+ });
56
+ } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys);
57
+ });
58
+ return {
59
+ tagged,
60
+ usedKeys
61
+ };
52
62
  }
53
63
  function handleTrans(code, node, file, tagged, usedKeys) {
54
- const opening = node.openingElement;
55
- const nameNode = opening.name;
56
- if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
57
- const attrs = opening.attributes;
58
- const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
59
- const children = node.children;
60
- if (idAttr) {
61
- const value = idAttr.value;
62
- if (value?.type !== "StringLiteral") return;
63
- const id = value.value;
64
- if (attrs.length === 1 && children?.length) {
65
- const built2 = buildTransMessage(code, children);
66
- if (built2?.text.trim()) {
67
- tagged.push({
68
- key: id,
69
- message: built2.text,
70
- params: built2.params,
71
- start: node.start,
72
- end: node.end,
73
- tagStart: nameNode.start,
74
- tagEnd: nameNode.end,
75
- file,
76
- jsx: { name: nameNode.name, components: built2.components }
77
- });
78
- return;
79
- }
80
- }
81
- usedKeys.push({ key: id, file });
82
- return;
83
- }
84
- if (attrs.length > 0) return;
85
- if (!children?.length) return;
86
- const built = buildTransMessage(code, children);
87
- if (!built || !built.text.trim()) return;
88
- tagged.push({
89
- key: stableKey(built.text),
90
- message: built.text,
91
- params: built.params,
92
- start: node.start,
93
- end: node.end,
94
- tagStart: nameNode.start,
95
- tagEnd: nameNode.end,
96
- file,
97
- jsx: { name: nameNode.name, components: built.components }
98
- });
64
+ const opening = node.openingElement;
65
+ const nameNode = opening.name;
66
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
67
+ const attrs = opening.attributes;
68
+ const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
69
+ const children = node.children;
70
+ if (idAttr) {
71
+ const value = idAttr.value;
72
+ if (value?.type !== "StringLiteral") return;
73
+ const id = value.value;
74
+ if (attrs.length === 1 && children?.length) {
75
+ const built = buildTransMessage(code, children);
76
+ if (built?.text.trim()) {
77
+ tagged.push({
78
+ key: id,
79
+ message: built.text,
80
+ params: built.params,
81
+ start: node.start,
82
+ end: node.end,
83
+ tagStart: nameNode.start,
84
+ tagEnd: nameNode.end,
85
+ file,
86
+ jsx: {
87
+ name: nameNode.name,
88
+ components: built.components
89
+ }
90
+ });
91
+ return;
92
+ }
93
+ }
94
+ usedKeys.push({
95
+ key: id,
96
+ file
97
+ });
98
+ return;
99
+ }
100
+ if (attrs.length > 0) return;
101
+ if (!children?.length) return;
102
+ const built = buildTransMessage(code, children);
103
+ if (!built || !built.text.trim()) return;
104
+ tagged.push({
105
+ key: stableKey(built.text),
106
+ message: built.text,
107
+ params: built.params,
108
+ start: node.start,
109
+ end: node.end,
110
+ tagStart: nameNode.start,
111
+ tagEnd: nameNode.end,
112
+ file,
113
+ jsx: {
114
+ name: nameNode.name,
115
+ components: built.components
116
+ }
117
+ });
99
118
  }
100
119
  function explicitId(tag) {
101
- if (tag.type !== "CallExpression") return void 0;
102
- const callee = tag.callee;
103
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
104
- const prop = callee.property;
105
- if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
106
- const obj = callee.object;
107
- if (!isTReference(obj)) return void 0;
108
- const args = tag.arguments;
109
- const first = args[0];
110
- if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
111
- return { key: first.value, refStart: obj.start, refEnd: obj.end };
120
+ if (tag.type !== "CallExpression") return void 0;
121
+ const callee = tag.callee;
122
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
123
+ const prop = callee.property;
124
+ if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
125
+ const obj = callee.object;
126
+ if (!isTReference(obj)) return void 0;
127
+ const args = tag.arguments;
128
+ const first = args[0];
129
+ if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
130
+ return {
131
+ key: first.value,
132
+ refStart: obj.start,
133
+ refEnd: obj.end
134
+ };
112
135
  }
113
136
  function buildTransMessage(code, children) {
114
- const params = [];
115
- const components = [];
116
- const takenParams = /* @__PURE__ */ new Map();
117
- const takenTags = /* @__PURE__ */ new Map();
118
- function walkChildren(nodes) {
119
- let text2 = "";
120
- for (const child of nodes) {
121
- if (child.type === "JSXText") {
122
- text2 += escapeText(cleanJsxText(child.value));
123
- } else if (child.type === "JSXExpressionContainer") {
124
- const expr = child.expression;
125
- if (expr.type === "JSXEmptyExpression") continue;
126
- if (expr.type === "StringLiteral") {
127
- text2 += escapeText(expr.value);
128
- continue;
129
- }
130
- if (expr.type === "TaggedTemplateExpression") return void 0;
131
- const source = code.slice(expr.start, expr.end);
132
- const name = uniqueName(deriveName(expr, params.length), source, takenParams);
133
- params.push({ name, start: expr.start, end: expr.end });
134
- text2 += `{${name}}`;
135
- } else if (child.type === "JSXElement") {
136
- const opening = child.openingElement;
137
- const nameNode = opening.name;
138
- if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
139
- const source = selfClosedSource(code, opening);
140
- const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
141
- if (!components.some((c) => c.name === tag)) components.push({ name: tag, source });
142
- if (!child.closingElement) {
143
- text2 += `<${tag}/>`;
144
- } else {
145
- const inner = walkChildren(child.children);
146
- if (inner === void 0) return void 0;
147
- text2 += `<${tag}>${inner}</${tag}>`;
148
- }
149
- } else {
150
- return void 0;
151
- }
152
- }
153
- return text2;
154
- }
155
- const text = walkChildren(children);
156
- if (text === void 0) return void 0;
157
- return { text, params, components };
137
+ const params = [];
138
+ const components = [];
139
+ const takenParams = /* @__PURE__ */ new Map();
140
+ const takenTags = /* @__PURE__ */ new Map();
141
+ function walkChildren(nodes) {
142
+ let text = "";
143
+ for (const child of nodes) if (child.type === "JSXText") text += escapeText(cleanJsxText(child.value));
144
+ else if (child.type === "JSXExpressionContainer") {
145
+ const expr = child.expression;
146
+ if (expr.type === "JSXEmptyExpression") continue;
147
+ if (expr.type === "StringLiteral") {
148
+ text += escapeText(expr.value);
149
+ continue;
150
+ }
151
+ if (expr.type === "TaggedTemplateExpression") return void 0;
152
+ const source = code.slice(expr.start, expr.end);
153
+ const name = uniqueName(deriveName(expr, params.length), source, takenParams);
154
+ params.push({
155
+ name,
156
+ start: expr.start,
157
+ end: expr.end
158
+ });
159
+ text += `{${name}}`;
160
+ } else if (child.type === "JSXElement") {
161
+ const opening = child.openingElement;
162
+ const nameNode = opening.name;
163
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
164
+ const source = selfClosedSource(code, opening);
165
+ const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
166
+ if (!components.some((c) => c.name === tag)) components.push({
167
+ name: tag,
168
+ source
169
+ });
170
+ if (!child.closingElement) text += `<${tag}/>`;
171
+ else {
172
+ const inner = walkChildren(child.children);
173
+ if (inner === void 0) return void 0;
174
+ text += `<${tag}>${inner}</${tag}>`;
175
+ }
176
+ } else return;
177
+ return text;
178
+ }
179
+ const text = walkChildren(children);
180
+ if (text === void 0) return void 0;
181
+ return {
182
+ text,
183
+ params,
184
+ components
185
+ };
158
186
  }
159
187
  function cleanJsxText(raw) {
160
- const lines = raw.split(/\r\n|[\r\n]/);
161
- let out = "";
162
- for (let i = 0; i < lines.length; i++) {
163
- let line = lines[i].replace(/\t/g, " ");
164
- if (i !== 0) line = line.replace(/^ +/, "");
165
- if (i !== lines.length - 1) line = line.replace(/ +$/, "");
166
- if (!line) continue;
167
- if (out && i !== 0) out += " ";
168
- out += line;
169
- }
170
- return out;
188
+ const lines = raw.split(/\r\n|[\r\n]/);
189
+ let out = "";
190
+ for (let i = 0; i < lines.length; i++) {
191
+ let line = lines[i].replace(/\t/g, " ");
192
+ if (i !== 0) line = line.replace(/^ +/, "");
193
+ if (i !== lines.length - 1) line = line.replace(/ +$/, "");
194
+ if (!line) continue;
195
+ if (out && i !== 0) out += " ";
196
+ out += line;
197
+ }
198
+ return out;
171
199
  }
172
200
  function selfClosedSource(code, opening) {
173
- const src = code.slice(opening.start, opening.end);
174
- return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
201
+ const src = code.slice(opening.start, opening.end);
202
+ return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
175
203
  }
176
204
  function isTReference(node) {
177
- if (node.type === "Identifier") return node.name === "t";
178
- if (node.type === "MemberExpression" && !node.computed) {
179
- const prop = node.property;
180
- return prop.type === "Identifier" && prop.name === "t";
181
- }
182
- return false;
205
+ if (node.type === "Identifier") return node.name === "t";
206
+ if (node.type === "MemberExpression" && !node.computed) {
207
+ const prop = node.property;
208
+ return prop.type === "Identifier" && prop.name === "t";
209
+ }
210
+ return false;
183
211
  }
184
212
  function buildMessage(code, quasi) {
185
- const quasis = quasi.quasis;
186
- const expressions = quasi.expressions;
187
- const params = [];
188
- const taken = /* @__PURE__ */ new Map();
189
- let text = escapeText(cookedValue(quasis[0]));
190
- for (let i = 0; i < expressions.length; i++) {
191
- const expr = expressions[i];
192
- if (!expr) return void 0;
193
- const source = code.slice(expr.start, expr.end);
194
- const name = uniqueName(deriveName(expr, i), source, taken);
195
- params.push({ name, start: expr.start, end: expr.end });
196
- text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
197
- }
198
- return { text, params };
213
+ const quasis = quasi.quasis;
214
+ const expressions = quasi.expressions;
215
+ const params = [];
216
+ const taken = /* @__PURE__ */ new Map();
217
+ let text = escapeText(cookedValue(quasis[0]));
218
+ for (let i = 0; i < expressions.length; i++) {
219
+ const expr = expressions[i];
220
+ if (!expr) return void 0;
221
+ const source = code.slice(expr.start, expr.end);
222
+ const name = uniqueName(deriveName(expr, i), source, taken);
223
+ params.push({
224
+ name,
225
+ start: expr.start,
226
+ end: expr.end
227
+ });
228
+ text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
229
+ }
230
+ return {
231
+ text,
232
+ params
233
+ };
199
234
  }
200
235
  function cookedValue(element) {
201
- if (!element) return "";
202
- const value = element.value;
203
- return value.cooked ?? value.raw;
236
+ if (!element) return "";
237
+ const value = element.value;
238
+ return value.cooked ?? value.raw;
204
239
  }
205
240
  function escapeText(text) {
206
- return text.replace(/[{}]/g, (m) => m + m);
241
+ return text.replace(/[{}]/g, (m) => m + m);
207
242
  }
208
243
  function deriveName(expr, index) {
209
- if (expr.type === "Identifier") return expr.name;
210
- if (expr.type === "MemberExpression" && !expr.computed) {
211
- const prop = expr.property;
212
- if (prop.type === "Identifier") return prop.name;
213
- }
214
- return `_${index}`;
244
+ if (expr.type === "Identifier") return expr.name;
245
+ if (expr.type === "MemberExpression" && !expr.computed) {
246
+ const prop = expr.property;
247
+ if (prop.type === "Identifier") return prop.name;
248
+ }
249
+ return `_${index}`;
215
250
  }
216
251
  function uniqueName(base, source, taken) {
217
- let name = base;
218
- let n = 2;
219
- while (taken.has(name) && taken.get(name) !== source) {
220
- name = `${base}${n}`;
221
- n += 1;
222
- }
223
- taken.set(name, source);
224
- return name;
225
- }
226
- function walk(node, visit2) {
227
- visit2(node);
228
- for (const [key, value] of Object.entries(node)) {
229
- if (SKIP_KEYS.has(key)) continue;
230
- if (Array.isArray(value)) {
231
- for (const item of value) {
232
- if (isNode(item)) walk(item, visit2);
233
- }
234
- } else if (isNode(value)) {
235
- walk(value, visit2);
236
- }
237
- }
252
+ let name = base;
253
+ let n = 2;
254
+ while (taken.has(name) && taken.get(name) !== source) {
255
+ name = `${base}${n}`;
256
+ n += 1;
257
+ }
258
+ taken.set(name, source);
259
+ return name;
260
+ }
261
+ function walk(node, visit) {
262
+ visit(node);
263
+ for (const [key, value] of Object.entries(node)) {
264
+ if (SKIP_KEYS.has(key)) continue;
265
+ if (Array.isArray(value)) {
266
+ for (const item of value) if (isNode(item)) walk(item, visit);
267
+ } else if (isNode(value)) walk(value, visit);
268
+ }
238
269
  }
239
270
  function isNode(value) {
240
- return typeof value === "object" && value !== null && typeof value.type === "string";
271
+ return typeof value === "object" && value !== null && typeof value.type === "string";
241
272
  }
242
-
243
- // src/catalog.ts
244
- import { mkdirSync, readFileSync, writeFileSync } from "fs";
245
- import { join } from "path";
273
+ //#endregion
274
+ //#region src/catalog.ts
246
275
  function catalogPath(cfg, locale) {
247
- return join(cfg.dir, `${locale}.json`);
276
+ return join(cfg.dir, `${locale}.json`);
248
277
  }
249
278
  function readCatalog(cfg, locale) {
250
- try {
251
- return JSON.parse(readFileSync(catalogPath(cfg, locale), "utf8"));
252
- } catch {
253
- return {};
254
- }
279
+ try {
280
+ return JSON.parse(readFileSync(catalogPath(cfg, locale), "utf8"));
281
+ } catch {
282
+ return {};
283
+ }
255
284
  }
256
285
  function loadCatalogs(cfg) {
257
- const catalogs = {};
258
- for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
259
- return catalogs;
286
+ const catalogs = {};
287
+ for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
288
+ return catalogs;
260
289
  }
261
290
  function serializeCatalog(catalog) {
262
- const sorted = {};
263
- for (const key of Object.keys(catalog).sort()) {
264
- const value = catalog[key];
265
- if (value !== void 0) sorted[key] = value;
266
- }
267
- return JSON.stringify(sorted, null, 2) + "\n";
291
+ const sorted = {};
292
+ for (const key of Object.keys(catalog).sort()) {
293
+ const value = catalog[key];
294
+ if (value !== void 0) sorted[key] = value;
295
+ }
296
+ return JSON.stringify(sorted, null, 2) + "\n";
268
297
  }
269
298
  function writeCatalog(cfg, locale, catalog) {
270
- const serialized = serializeCatalog(catalog);
271
- mkdirSync(cfg.dir, { recursive: true });
272
- writeFileSync(catalogPath(cfg, locale), serialized);
273
- return serialized;
299
+ const serialized = serializeCatalog(catalog);
300
+ mkdirSync(cfg.dir, { recursive: true });
301
+ writeFileSync(catalogPath(cfg, locale), serialized);
302
+ return serialized;
274
303
  }
275
-
276
- // src/check.ts
304
+ //#endregion
305
+ //#region src/check.ts
277
306
  function check(cfg, catalogs, registry) {
278
- const source = catalogs[cfg.sourceLocale] ?? {};
279
- const extracted = registry.messages();
280
- const unknown = [];
281
- for (const [key, files] of registry.usedKeys()) {
282
- const known = extracted.has(key) || cfg.locales.some((locale) => catalogs[locale]?.[key] !== void 0);
283
- if (!known) unknown.push({ key, files });
284
- }
285
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
286
- const missing = [];
287
- for (const key of extracted.keys()) {
288
- if (!source[key]) {
289
- missing.push({ locale: cfg.sourceLocale, key, source: extracted.get(key)?.message });
290
- }
291
- }
292
- for (const locale of cfg.locales) {
293
- if (locale === cfg.sourceLocale) continue;
294
- for (const key of needed) {
295
- if (!catalogs[locale]?.[key]) {
296
- missing.push({ locale, key, source: source[key] ?? extracted.get(key)?.message });
297
- }
298
- }
299
- }
300
- return { ok: missing.length === 0 && unknown.length === 0, missing, unknown };
307
+ const source = catalogs[cfg.sourceLocale] ?? {};
308
+ const extracted = registry.messages();
309
+ const unknown = [];
310
+ for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => catalogs[locale]?.[key] !== void 0))) unknown.push({
311
+ key,
312
+ files
313
+ });
314
+ const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
315
+ const missing = [];
316
+ for (const key of extracted.keys()) if (!source[key]) missing.push({
317
+ locale: cfg.sourceLocale,
318
+ key,
319
+ source: extracted.get(key)?.message
320
+ });
321
+ for (const locale of cfg.locales) {
322
+ if (locale === cfg.sourceLocale) continue;
323
+ for (const key of needed) if (!catalogs[locale]?.[key]) missing.push({
324
+ locale,
325
+ key,
326
+ source: source[key] ?? extracted.get(key)?.message
327
+ });
328
+ }
329
+ return {
330
+ ok: missing.length === 0 && unknown.length === 0,
331
+ missing,
332
+ unknown
333
+ };
301
334
  }
302
335
  function formatCheckResult(result) {
303
- const lines = [];
304
- if (result.missing.length > 0) {
305
- lines.push("missing translations:");
306
- for (const entry of result.missing) {
307
- const hint = entry.source ? ` \u2014 "${truncate(entry.source, 40)}"` : "";
308
- lines.push(` [${entry.locale}] ${entry.key}${hint}`);
309
- }
310
- }
311
- if (result.unknown.length > 0) {
312
- lines.push("unknown keys (not in any catalog):");
313
- for (const entry of result.unknown) {
314
- lines.push(` ${entry.key} \u2014 used in ${entry.files.join(", ")}`);
315
- }
316
- }
317
- return lines.join("\n");
336
+ const lines = [];
337
+ if (result.missing.length > 0) {
338
+ lines.push("missing translations:");
339
+ for (const entry of result.missing) {
340
+ const hint = entry.source ? ` "${truncate(entry.source, 40)}"` : "";
341
+ lines.push(` [${entry.locale}] ${entry.key}${hint}`);
342
+ }
343
+ }
344
+ if (result.unknown.length > 0) {
345
+ lines.push("unknown keys (not in any catalog):");
346
+ for (const entry of result.unknown) lines.push(` ${entry.key} — used in ${entry.files.join(", ")}`);
347
+ }
348
+ return lines.join("\n");
318
349
  }
319
350
  function truncate(text, max) {
320
- return text.length > max ? text.slice(0, max - 1) + "\u2026" : text;
321
- }
322
-
323
- // src/codegen.ts
324
- import { writeFileSync as writeFileSync2 } from "fs";
325
- import { join as join2 } from "path";
326
-
327
- // src/params.ts
328
- import { parse as parse2 } from "verbaly";
329
- var PLURAL_KEYS = /* @__PURE__ */ new Set(["zero", "one", "two", "few", "many"]);
330
- var NUMBER_FORMATS = /* @__PURE__ */ new Set(["number", "integer", "percent", "currency"]);
331
- var DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
351
+ return text.length > max ? text.slice(0, max - 1) + "" : text;
352
+ }
353
+ //#endregion
354
+ //#region src/params.ts
355
+ const PLURAL_KEYS = /* @__PURE__ */ new Set([
356
+ "zero",
357
+ "one",
358
+ "two",
359
+ "few",
360
+ "many"
361
+ ]);
362
+ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
363
+ "number",
364
+ "integer",
365
+ "percent",
366
+ "currency"
367
+ ]);
368
+ const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
332
369
  function collectParams(message) {
333
- const out = /* @__PURE__ */ new Map();
334
- visit(parse2(message), out);
335
- return out;
370
+ const out = /* @__PURE__ */ new Map();
371
+ visit(parse$1(message), out);
372
+ return out;
336
373
  }
337
374
  function visit(nodes, out) {
338
- for (const node of nodes) {
339
- if (node.kind !== "param") continue;
340
- const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
341
- out.set(node.name, types);
342
- if (node.variants) {
343
- for (const [key, body] of node.variants) {
344
- if (PLURAL_KEYS.has(key) || /^=\d+$/.test(key)) types.add("number");
345
- else if (key !== "other") types.add("string");
346
- visit(body, out);
347
- }
348
- if (types.size === 0) types.add("string");
349
- } else if (node.format && NUMBER_FORMATS.has(node.format)) {
350
- types.add("number");
351
- } else if (node.format && DATE_FORMATS.has(node.format)) {
352
- types.add("date");
353
- } else {
354
- types.add("unknown");
355
- }
356
- }
375
+ for (const node of nodes) {
376
+ if (node.kind !== "param") continue;
377
+ const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
378
+ out.set(node.name, types);
379
+ if (node.variants) {
380
+ for (const [key, body] of node.variants) {
381
+ if (PLURAL_KEYS.has(key) || /^=\d+$/.test(key)) types.add("number");
382
+ else if (key !== "other") types.add("string");
383
+ visit(body, out);
384
+ }
385
+ if (types.size === 0) types.add("string");
386
+ } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
387
+ else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
388
+ else types.add("unknown");
389
+ }
357
390
  }
358
391
  function renderParamType(types) {
359
- if (types.has("unknown") || types.size === 0) return "unknown";
360
- const parts = [];
361
- if (types.has("number")) parts.push("number");
362
- if (types.has("string")) parts.push("string");
363
- if (types.has("date")) parts.push("Date | number | string");
364
- return parts.join(" | ");
365
- }
366
-
367
- // src/codegen.ts
368
- var VIRTUAL_ID = "virtual:verbaly";
392
+ if (types.has("unknown") || types.size === 0) return "unknown";
393
+ const parts = [];
394
+ if (types.has("number")) parts.push("number");
395
+ if (types.has("string")) parts.push("string");
396
+ if (types.has("date")) parts.push("Date | number | string");
397
+ return parts.join(" | ");
398
+ }
399
+ //#endregion
400
+ //#region src/codegen.ts
401
+ const VIRTUAL_ID = "virtual:verbaly";
369
402
  function generateRuntimeModule(cfg) {
370
- const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
371
- const src = JSON.stringify(cfg.sourceLocale);
372
- const loaders = others.map(
373
- (locale) => ` ${JSON.stringify(locale)}: () => import('${VIRTUAL_ID}/locale/${locale}'),`
374
- ).join("\n");
375
- return `import { createVerbaly } from 'verbaly';
403
+ const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
404
+ const src = JSON.stringify(cfg.sourceLocale);
405
+ const loaders = others.map((locale) => ` ${JSON.stringify(locale)}: () => import('${VIRTUAL_ID}/locale/${locale}'),`).join("\n");
406
+ return `import { createVerbaly } from 'verbaly';
376
407
  import source from '${VIRTUAL_ID}/locale/${cfg.sourceLocale}';
377
408
 
378
409
  const v = createVerbaly({
@@ -402,21 +433,19 @@ export async function setLocale(locale) {
402
433
  `;
403
434
  }
404
435
  function generateLocaleModule(catalog) {
405
- return `export default ${JSON.stringify(catalog)};
406
- `;
436
+ return `export default ${JSON.stringify(catalog)};\n`;
407
437
  }
408
438
  function generateDts(entries) {
409
- const lines = [];
410
- for (const [key, message] of [...entries.entries()].sort(([a], [b]) => a.localeCompare(b))) {
411
- const params = collectParams(message);
412
- if (params.size === 0) {
413
- lines.push(` ${JSON.stringify(key)}: never;`);
414
- } else {
415
- const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
416
- lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
417
- }
418
- }
419
- return `// generated by verbaly \u2014 do not edit
439
+ const lines = [];
440
+ for (const [key, message] of [...entries.entries()].sort(([a], [b]) => a.localeCompare(b))) {
441
+ const params = collectParams(message);
442
+ if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
443
+ else {
444
+ const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
445
+ lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
446
+ }
447
+ }
448
+ return `// generated by verbaly — do not edit
420
449
  declare module 'virtual:verbaly' {
421
450
  export interface VerbalyMessages {
422
451
  ${lines.join("\n")}
@@ -448,700 +477,783 @@ declare module 'virtual:verbaly/locale/*' {
448
477
  `;
449
478
  }
450
479
  function writeDts(cfg, entries) {
451
- writeFileSync2(join2(cfg.root, "verbaly.d.ts"), generateDts(entries));
480
+ writeFileSync(join(cfg.root, "verbaly.d.ts"), generateDts(entries));
452
481
  }
453
-
454
- // src/config.ts
455
- import { existsSync, readFileSync as readFileSync2, readdirSync } from "fs";
456
- import { join as join3, resolve } from "path";
457
- import { pathToFileURL } from "url";
482
+ //#endregion
483
+ //#region src/config.ts
458
484
  function resolveConfig(config = {}) {
459
- const root = resolve(config.root ?? process.cwd());
460
- const dir = resolve(root, config.dir ?? "locales");
461
- const sourceLocale = config.sourceLocale ?? "en";
462
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
463
- if (existsSync(dir)) {
464
- for (const file of readdirSync(dir)) {
465
- if (file.endsWith(".json")) locales.add(file.slice(0, -5));
466
- }
467
- }
468
- return {
469
- root,
470
- dir,
471
- sourceLocale,
472
- locales: [...locales],
473
- include: config.include ?? ["src/**/*.{js,jsx,ts,tsx,mjs,mts}"],
474
- exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
475
- translate: config.translate ?? {},
476
- render: config.render ?? {}
477
- };
485
+ const root = resolve(config.root ?? process.cwd());
486
+ const dir = resolve(root, config.dir ?? "locales");
487
+ const sourceLocale = config.sourceLocale ?? "en";
488
+ const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
489
+ if (existsSync(dir)) {
490
+ for (const file of readdirSync(dir)) if (file.endsWith(".json")) locales.add(file.slice(0, -5));
491
+ }
492
+ return {
493
+ root,
494
+ dir,
495
+ sourceLocale,
496
+ locales: [...locales],
497
+ include: config.include ?? ["src/**/*.{js,jsx,ts,tsx,mjs,mts}"],
498
+ exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
499
+ translate: config.translate ?? {},
500
+ render: config.render ?? {}
501
+ };
502
+ }
503
+ const CONFIG_FILES = [
504
+ "verbaly.config.js",
505
+ "verbaly.config.mjs",
506
+ "verbaly.config.ts",
507
+ "verbaly.config.mts",
508
+ "verbaly.config.json"
509
+ ];
510
+ function findConfigFile(root) {
511
+ return CONFIG_FILES.find((name) => existsSync(join(root, name)));
478
512
  }
479
513
  async function loadConfigFile(root) {
480
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
481
- const path = join3(root, name);
482
- if (existsSync(path)) {
483
- const mod = await import(pathToFileURL(path).href);
484
- return mod.default ?? {};
485
- }
486
- }
487
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
488
- const path = join3(root, name);
489
- if (existsSync(path)) return loadTsConfig(path);
490
- }
491
- const jsonPath = join3(root, "verbaly.config.json");
492
- if (existsSync(jsonPath)) {
493
- return JSON.parse(readFileSync2(jsonPath, "utf8"));
494
- }
495
- return {};
514
+ for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
515
+ const path = join(root, name);
516
+ if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
517
+ }
518
+ for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
519
+ const path = join(root, name);
520
+ if (existsSync(path)) return loadTsConfig(path);
521
+ }
522
+ const jsonPath = join(root, "verbaly.config.json");
523
+ if (existsSync(jsonPath)) return JSON.parse(readFileSync(jsonPath, "utf8"));
524
+ return {};
496
525
  }
497
526
  async function loadTsConfig(path) {
498
- try {
499
- const { bundleRequire } = await import("bundle-require");
500
- const { mod } = await bundleRequire({ filepath: path });
501
- return mod.default ?? {};
502
- } catch (error) {
503
- if (isModuleNotFound(error, "esbuild")) {
504
- throw new Error(`[verbaly] ${path} needs esbuild \u2014 install it: pnpm add -D esbuild`, {
505
- cause: error
506
- });
507
- }
508
- throw error;
509
- }
510
- }
511
- function isModuleNotFound(error, name) {
512
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
527
+ try {
528
+ const { bundleRequire } = await import("bundle-require");
529
+ const { mod } = await bundleRequire({ filepath: path });
530
+ return mod.default ?? {};
531
+ } catch (error) {
532
+ if (isModuleNotFound$1(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild — install it: pnpm add -D esbuild`, { cause: error });
533
+ throw error;
534
+ }
535
+ }
536
+ function isModuleNotFound$1(error, name) {
537
+ return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
513
538
  }
514
539
  async function loadConfig(root, overrides = {}) {
515
- const fileConfig = await loadConfigFile(root);
516
- return resolveConfig({ ...fileConfig, ...definedOnly(overrides), root });
540
+ return resolveConfig({
541
+ ...await loadConfigFile(root),
542
+ ...definedOnly(overrides),
543
+ root
544
+ });
517
545
  }
518
546
  function definedOnly(config) {
519
- return Object.fromEntries(
520
- Object.entries(config).filter(([, value]) => value !== void 0)
521
- );
547
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
522
548
  }
523
-
524
- // src/extract.ts
525
- import { readFileSync as readFileSync3 } from "fs";
526
- import { glob } from "tinyglobby";
527
-
528
- // src/registry.ts
549
+ //#endregion
550
+ //#region src/registry.ts
529
551
  var MessageRegistry = class {
530
- files = /* @__PURE__ */ new Map();
531
- update(file, analysis) {
532
- this.files.set(file, analysis);
533
- }
534
- remove(file) {
535
- this.files.delete(file);
536
- }
537
- messages() {
538
- const out = /* @__PURE__ */ new Map();
539
- for (const analysis of this.files.values()) {
540
- for (const msg of analysis.tagged) {
541
- const existing = out.get(msg.key);
542
- if (existing) {
543
- if (existing.message !== msg.message) {
544
- console.warn(
545
- `[verbaly] key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)} \u2014 second dropped.`
546
- );
547
- }
548
- continue;
549
- }
550
- out.set(msg.key, msg);
551
- }
552
- }
553
- return out;
554
- }
555
- usedKeys() {
556
- const out = /* @__PURE__ */ new Map();
557
- for (const analysis of this.files.values()) {
558
- for (const used of analysis.usedKeys) {
559
- const files = out.get(used.key) ?? [];
560
- if (!files.includes(used.file)) files.push(used.file);
561
- out.set(used.key, files);
562
- }
563
- }
564
- return out;
565
- }
552
+ files = /* @__PURE__ */ new Map();
553
+ update(file, analysis) {
554
+ this.files.set(file, analysis);
555
+ }
556
+ remove(file) {
557
+ this.files.delete(file);
558
+ }
559
+ messages() {
560
+ const out = /* @__PURE__ */ new Map();
561
+ for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
562
+ const existing = out.get(msg.key);
563
+ if (existing) {
564
+ if (existing.message !== msg.message) console.warn(`[verbaly] key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)} — second dropped.`);
565
+ continue;
566
+ }
567
+ out.set(msg.key, msg);
568
+ }
569
+ return out;
570
+ }
571
+ usedKeys() {
572
+ const out = /* @__PURE__ */ new Map();
573
+ for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
574
+ const files = out.get(used.key) ?? [];
575
+ if (!files.includes(used.file)) files.push(used.file);
576
+ out.set(used.key, files);
577
+ }
578
+ return out;
579
+ }
566
580
  };
567
-
568
- // src/extract.ts
581
+ //#endregion
582
+ //#region src/extract.ts
569
583
  async function extractProject(cfg) {
570
- const files = await glob(cfg.include, {
571
- cwd: cfg.root,
572
- ignore: cfg.exclude,
573
- absolute: true
574
- });
575
- const registry = new MessageRegistry();
576
- for (const file of files) {
577
- registry.update(file, analyze(readFileSync3(file, "utf8"), file));
578
- }
579
- return registry;
584
+ const files = await glob(cfg.include, {
585
+ cwd: cfg.root,
586
+ ignore: cfg.exclude,
587
+ absolute: true
588
+ });
589
+ const registry = new MessageRegistry();
590
+ for (const file of files) registry.update(file, analyze(readFileSync(file, "utf8"), file));
591
+ return registry;
580
592
  }
581
593
  function syncCatalogs(cfg, catalogs, registry) {
582
- const added = {};
583
- const source = catalogs[cfg.sourceLocale] ??= {};
584
- for (const [key, msg] of registry.messages()) {
585
- if (source[key] !== msg.message) {
586
- source[key] = msg.message;
587
- (added[cfg.sourceLocale] ??= []).push(key);
588
- }
589
- }
590
- const needed = Object.keys(source);
591
- for (const locale of cfg.locales) {
592
- if (locale === cfg.sourceLocale) continue;
593
- const catalog = catalogs[locale] ??= {};
594
- for (const key of needed) {
595
- if (catalog[key] === void 0) {
596
- catalog[key] = "";
597
- (added[locale] ??= []).push(key);
598
- }
599
- }
600
- }
601
- return { added };
594
+ const added = {};
595
+ const source = catalogs[cfg.sourceLocale] ??= {};
596
+ for (const [key, msg] of registry.messages()) if (source[key] !== msg.message) {
597
+ source[key] = msg.message;
598
+ (added[cfg.sourceLocale] ??= []).push(key);
599
+ }
600
+ const needed = Object.keys(source);
601
+ for (const locale of cfg.locales) {
602
+ if (locale === cfg.sourceLocale) continue;
603
+ const catalog = catalogs[locale] ??= {};
604
+ for (const key of needed) if (catalog[key] === void 0) {
605
+ catalog[key] = "";
606
+ (added[locale] ??= []).push(key);
607
+ }
608
+ }
609
+ return { added };
602
610
  }
603
611
  function pruneCatalogs(cfg, catalogs, registry) {
604
- const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
605
- const removed = {};
606
- for (const locale of cfg.locales) {
607
- const catalog = catalogs[locale];
608
- if (!catalog) continue;
609
- for (const key of Object.keys(catalog)) {
610
- if (!keep.has(key)) {
611
- delete catalog[key];
612
- (removed[locale] ??= []).push(key);
613
- }
614
- }
615
- }
616
- return removed;
617
- }
618
-
619
- // src/providers/claude.ts
620
- var DEFAULT_MODEL = "claude-sonnet-5";
621
- var SYSTEM = `You translate UI strings for the Verbaly i18n library.
612
+ const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
613
+ const removed = {};
614
+ for (const locale of cfg.locales) {
615
+ const catalog = catalogs[locale];
616
+ if (!catalog) continue;
617
+ for (const key of Object.keys(catalog)) if (!keep.has(key)) {
618
+ delete catalog[key];
619
+ (removed[locale] ??= []).push(key);
620
+ }
621
+ }
622
+ return removed;
623
+ }
624
+ //#endregion
625
+ //#region src/init.ts
626
+ const BUNDLERS = [
627
+ "vite",
628
+ "webpack",
629
+ "rollup",
630
+ "rspack",
631
+ "esbuild"
632
+ ];
633
+ function detectBundler(root) {
634
+ const path = join(root, "package.json");
635
+ if (!existsSync(path)) return void 0;
636
+ try {
637
+ const pkg = JSON.parse(readFileSync(path, "utf8"));
638
+ const deps = {
639
+ ...pkg.dependencies,
640
+ ...pkg.devDependencies
641
+ };
642
+ return BUNDLERS.find((name) => deps[name]);
643
+ } catch {
644
+ return;
645
+ }
646
+ }
647
+ function configSource(options, typescript) {
648
+ const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
649
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
650
+ if (options.dir) fields.push(` dir: '${options.dir}',`);
651
+ const body = `export default {\n${fields.join("\n")}\n}`;
652
+ if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
653
+ return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
654
+ }
655
+ function init(options = {}) {
656
+ const root = options.root ?? process.cwd();
657
+ const created = [];
658
+ const skipped = [];
659
+ const existing = findConfigFile(root);
660
+ const typescript = existsSync(join(root, "tsconfig.json"));
661
+ const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
662
+ if (existing) skipped.push(existing);
663
+ else {
664
+ writeFileSync(join(root, configFile), configSource(options, typescript));
665
+ created.push(configFile);
666
+ }
667
+ const dir = join(root, options.dir ?? "locales");
668
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
669
+ for (const locale of /* @__PURE__ */ new Set([options.sourceLocale ?? "en", ...options.locales ?? []])) {
670
+ const file = join(dir, `${locale}.json`);
671
+ const label = relative(root, file).replaceAll("\\", "/");
672
+ if (existsSync(file)) skipped.push(label);
673
+ else {
674
+ writeFileSync(file, "{}\n");
675
+ created.push(label);
676
+ }
677
+ }
678
+ const bundler = detectBundler(root);
679
+ const next = [];
680
+ if (bundler === "vite") next.push("install the plugin: pnpm add -D @verbaly/vite", "add verbaly() to the plugins in vite.config");
681
+ else if (bundler) next.push("install the plugin: pnpm add -D @verbaly/unplugin", `add the verbaly ${bundler} plugin to your build config`);
682
+ else next.push("run \"verbaly extract\" after writing your first t`…` message");
683
+ return {
684
+ created,
685
+ skipped,
686
+ bundler,
687
+ configFile,
688
+ next
689
+ };
690
+ }
691
+ //#endregion
692
+ //#region src/doctor.ts
693
+ const PREVIEW = 5;
694
+ async function doctor(cfg) {
695
+ const entries = [];
696
+ const ok = (check, message) => entries.push({
697
+ level: "ok",
698
+ check,
699
+ message
700
+ });
701
+ const warn = (check, message, fix) => entries.push({
702
+ level: "warn",
703
+ check,
704
+ message,
705
+ fix
706
+ });
707
+ const error = (check, message, fix) => entries.push({
708
+ level: "error",
709
+ check,
710
+ message,
711
+ fix
712
+ });
713
+ const rel = (path) => relative(cfg.root, path).replaceAll("\\", "/");
714
+ const configFile = findConfigFile(cfg.root);
715
+ if (configFile) ok("config", `${configFile} found`);
716
+ else warn("config", "no config file — running on defaults", "run `npx verbaly init`");
717
+ const catalogs = {};
718
+ let catalogsHealthy = true;
719
+ if (!existsSync(cfg.dir)) {
720
+ catalogsHealthy = false;
721
+ error("catalogs", `catalogs directory ${rel(cfg.dir)}/ does not exist`, "run `npx verbaly init` to scaffold it");
722
+ } else {
723
+ for (const locale of cfg.locales) {
724
+ const file = join(cfg.dir, `${locale}.json`);
725
+ if (!existsSync(file)) {
726
+ catalogsHealthy = false;
727
+ error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
728
+ continue;
729
+ }
730
+ try {
731
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
732
+ const bad = Object.entries(parsed).find(([, value]) => typeof value !== "string");
733
+ if (bad) {
734
+ catalogsHealthy = false;
735
+ error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad[0]}"`, "catalogs are flat key → string JSON; fix the value");
736
+ } else catalogs[locale] = parsed;
737
+ } catch {
738
+ catalogsHealthy = false;
739
+ error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
740
+ }
741
+ }
742
+ if (catalogsHealthy) ok("catalogs", `${cfg.locales.length} locales (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/`);
743
+ }
744
+ const source = catalogs[cfg.sourceLocale];
745
+ if (source && Object.keys(source).length === 0) warn("source", `source catalog ${cfg.sourceLocale}.json is empty`, "write your first t`…` message and run `npx verbaly extract`");
746
+ const deps = readDeps(cfg.root);
747
+ const bundler = detectBundler(cfg.root);
748
+ const wired = deps["@verbaly/vite"] || deps["@verbaly/unplugin"];
749
+ if (!bundler) ok("plugin", "no bundler detected — CLI flow (extract/check) applies");
750
+ else if (wired) ok("plugin", `${deps["@verbaly/vite"] ? "@verbaly/vite" : "@verbaly/unplugin"} installed for ${bundler}`);
751
+ else if (bundler === "vite") warn("plugin", "vite detected but @verbaly/vite is not installed", "pnpm add -D @verbaly/vite and add verbaly() to the plugins in vite.config");
752
+ else warn("plugin", `${bundler} detected but @verbaly/unplugin is not installed`, `pnpm add -D @verbaly/unplugin and add the verbaly ${bundler} plugin to your build config`);
753
+ if (source) {
754
+ const dtsPath = join(cfg.root, "verbaly.d.ts");
755
+ if (!existsSync(dtsPath)) warn("types", "verbaly.d.ts has not been generated", "run `npx verbaly extract`");
756
+ else if (readFileSync(dtsPath, "utf8") !== generateDts(new Map(Object.entries(source)))) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
757
+ else ok("types", "verbaly.d.ts is up to date");
758
+ }
759
+ const registry = await extractProject(cfg);
760
+ if (source) {
761
+ const extracted = registry.messages();
762
+ const used = registry.usedKeys();
763
+ const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
764
+ if (orphans.length > 0) warn("orphans", `${orphans.length} catalog ${orphans.length === 1 ? "key is" : "keys are"} no longer referenced (${preview(orphans)})`, "run `npx verbaly extract --prune` to drop them");
765
+ else ok("orphans", "no orphan keys");
766
+ }
767
+ if (catalogsHealthy) {
768
+ const result = check(cfg, catalogs, registry);
769
+ if (result.unknown.length > 0) error("keys", `${result.unknown.length} unknown ${result.unknown.length === 1 ? "key" : "keys"} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs — `npx verbaly check` for details");
770
+ if (result.missing.length > 0) {
771
+ const locales = [...new Set(result.missing.map((m) => m.locale))];
772
+ warn("translations", `${result.missing.length} missing ${result.missing.length === 1 ? "translation" : "translations"} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs — `npx verbaly check` for details");
773
+ }
774
+ if (result.ok) ok("translations", "all translations complete");
775
+ }
776
+ return {
777
+ ok: entries.every((entry) => entry.level !== "error"),
778
+ entries
779
+ };
780
+ }
781
+ function preview(keys) {
782
+ const head = keys.slice(0, PREVIEW).join(", ");
783
+ return keys.length > PREVIEW ? `${head}, …` : head;
784
+ }
785
+ function readDeps(root) {
786
+ try {
787
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
788
+ return {
789
+ ...pkg.dependencies,
790
+ ...pkg.devDependencies
791
+ };
792
+ } catch {
793
+ return {};
794
+ }
795
+ }
796
+ //#endregion
797
+ //#region src/providers/claude.ts
798
+ const DEFAULT_MODEL = "claude-sonnet-5";
799
+ const SYSTEM = `You translate UI strings for the Verbaly i18n library.
622
800
  Rules:
623
801
  - Translate only the human-readable text, naturally for the target locale.
624
802
  - Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.
625
803
  - Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;
626
804
  function claudeProvider(options = {}) {
627
- return async (request) => {
628
- const Anthropic = await loadSdk();
629
- const client = new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {});
630
- const response = await client.messages.create({
631
- model: options.model ?? DEFAULT_MODEL,
632
- max_tokens: options.maxTokens ?? 16e3,
633
- thinking: { type: "disabled" },
634
- system: SYSTEM,
635
- messages: [{ role: "user", content: buildPrompt(request) }],
636
- output_config: { format: batchFormat(request) }
637
- });
638
- const text = response.content.find((block) => block.type === "text")?.text ?? "{}";
639
- return JSON.parse(text);
640
- };
805
+ return async (request) => {
806
+ const text = (await new (await (loadSdk()))(options.apiKey ? { apiKey: options.apiKey } : {}).messages.create({
807
+ model: options.model ?? DEFAULT_MODEL,
808
+ max_tokens: options.maxTokens ?? 16e3,
809
+ thinking: { type: "disabled" },
810
+ system: SYSTEM,
811
+ messages: [{
812
+ role: "user",
813
+ content: buildPrompt(request)
814
+ }],
815
+ output_config: { format: batchFormat(request) }
816
+ })).content.find((block) => block.type === "text")?.text ?? "{}";
817
+ return JSON.parse(text);
818
+ };
641
819
  }
642
820
  function buildPrompt(request) {
643
- return `Translate each value from "${request.sourceLocale}" to "${request.targetLocale}". Return a JSON object with the same keys and translated values.
644
-
645
- ` + JSON.stringify(request.messages, null, 2);
821
+ return `Translate each value from "${request.sourceLocale}" to "${request.targetLocale}". Return a JSON object with the same keys and translated values.\n\n` + JSON.stringify(request.messages, null, 2);
646
822
  }
647
823
  function batchFormat(request) {
648
- const keys = Object.keys(request.messages);
649
- return {
650
- type: "json_schema",
651
- schema: {
652
- type: "object",
653
- properties: Object.fromEntries(keys.map((key) => [key, { type: "string" }])),
654
- required: keys,
655
- additionalProperties: false
656
- }
657
- };
658
- }
659
- async function loadSdk() {
660
- try {
661
- const mod = await import("@anthropic-ai/sdk");
662
- return mod.default;
663
- } catch (error) {
664
- if (isModuleNotFound2(error, "@anthropic-ai/sdk")) {
665
- throw new Error(
666
- "[verbaly] the claude translate provider needs @anthropic-ai/sdk \u2014 install it as a dev dependency (e.g. `pnpm add -D @anthropic-ai/sdk` / `npm i -D @anthropic-ai/sdk`) and set ANTHROPIC_API_KEY",
667
- { cause: error }
668
- );
669
- }
670
- throw error;
671
- }
824
+ const keys = Object.keys(request.messages);
825
+ return {
826
+ type: "json_schema",
827
+ schema: {
828
+ type: "object",
829
+ properties: Object.fromEntries(keys.map((key) => [key, { type: "string" }])),
830
+ required: keys,
831
+ additionalProperties: false
832
+ }
833
+ };
834
+ }
835
+ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
836
+ try {
837
+ return (await load()).default;
838
+ } catch (error) {
839
+ if (isModuleNotFound(error, "@anthropic-ai/sdk")) throw new Error("[verbaly] the claude translate provider needs @anthropic-ai/sdk — install it as a dev dependency (e.g. `pnpm add -D @anthropic-ai/sdk` / `npm i -D @anthropic-ai/sdk`) and set ANTHROPIC_API_KEY", { cause: error });
840
+ throw error;
841
+ }
672
842
  }
673
- function isModuleNotFound2(error, name) {
674
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
675
- }
676
-
677
- // src/pseudo.ts
678
- var PSEUDO_LOCALE = "en-XA";
679
- var ACCENTS = {
680
- a: "\xE1",
681
- b: "\u0180",
682
- c: "\xE7",
683
- d: "\u0111",
684
- e: "\xE9",
685
- f: "\u0192",
686
- g: "\u011F",
687
- h: "\u0125",
688
- i: "\xED",
689
- j: "\u0135",
690
- k: "\u0137",
691
- l: "\u013A",
692
- m: "\u0271",
693
- n: "\xF1",
694
- o: "\xF3",
695
- p: "\xFE",
696
- q: "\u01EB",
697
- r: "\u0155",
698
- s: "\u0161",
699
- t: "\u0163",
700
- u: "\xFA",
701
- v: "\u1E7D",
702
- w: "\u0175",
703
- x: "\u1E8B",
704
- y: "\xFD",
705
- z: "\u017E",
706
- A: "\xC1",
707
- B: "\u0181",
708
- C: "\xC7",
709
- D: "\u0110",
710
- E: "\xC9",
711
- F: "\u0191",
712
- G: "\u011E",
713
- H: "\u0124",
714
- I: "\xCD",
715
- J: "\u0134",
716
- K: "\u0136",
717
- L: "\u0139",
718
- M: "\u1E3E",
719
- N: "\xD1",
720
- O: "\xD3",
721
- P: "\xDE",
722
- Q: "\u01EA",
723
- R: "\u0154",
724
- S: "\u0160",
725
- T: "\u0162",
726
- U: "\xDA",
727
- V: "\u1E7C",
728
- W: "\u0174",
729
- X: "\u1E8C",
730
- Y: "\xDD",
731
- Z: "\u017D"
843
+ function isModuleNotFound(error, name) {
844
+ return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
845
+ }
846
+ //#endregion
847
+ //#region src/pseudo.ts
848
+ const PSEUDO_LOCALE = "en-XA";
849
+ const ACCENTS = {
850
+ a: "á",
851
+ b: "ƀ",
852
+ c: "ç",
853
+ d: "đ",
854
+ e: "é",
855
+ f: "ƒ",
856
+ g: "ğ",
857
+ h: "ĥ",
858
+ i: "í",
859
+ j: "ĵ",
860
+ k: "ķ",
861
+ l: "ĺ",
862
+ m: "ɱ",
863
+ n: "ñ",
864
+ o: "ó",
865
+ p: "þ",
866
+ q: "ǫ",
867
+ r: "ŕ",
868
+ s: "š",
869
+ t: "ţ",
870
+ u: "ú",
871
+ v: "",
872
+ w: "ŵ",
873
+ x: "",
874
+ y: "ý",
875
+ z: "ž",
876
+ A: "Á",
877
+ B: "Ɓ",
878
+ C: "Ç",
879
+ D: "Đ",
880
+ E: "É",
881
+ F: "Ƒ",
882
+ G: "Ğ",
883
+ H: "Ĥ",
884
+ I: "Í",
885
+ J: "Ĵ",
886
+ K: "Ķ",
887
+ L: "Ĺ",
888
+ M: "",
889
+ N: "Ñ",
890
+ O: "Ó",
891
+ P: "Þ",
892
+ Q: "Ǫ",
893
+ R: "Ŕ",
894
+ S: "Š",
895
+ T: "Ţ",
896
+ U: "Ú",
897
+ V: "",
898
+ W: "Ŵ",
899
+ X: "",
900
+ Y: "Ý",
901
+ Z: "Ž"
732
902
  };
733
- var TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
903
+ const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
734
904
  function pseudoLocalize(message) {
735
- let out = "";
736
- let letters = 0;
737
- let i = 0;
738
- while (i < message.length) {
739
- const two = message.slice(i, i + 2);
740
- if (two === "{{" || two === "}}" || two === "||" || two === "##") {
741
- out += two;
742
- i += 2;
743
- continue;
744
- }
745
- const ch = message[i];
746
- if (ch === "{") {
747
- const end = matchBrace(message, i);
748
- out += message.slice(i, end);
749
- i = end;
750
- continue;
751
- }
752
- if (ch === "<") {
753
- TAG_AT.lastIndex = i;
754
- const m = TAG_AT.exec(message);
755
- if (m) {
756
- out += m[0];
757
- i += m[0].length;
758
- continue;
759
- }
760
- }
761
- const mapped = ACCENTS[ch];
762
- if (mapped) {
763
- out += mapped;
764
- letters += 1;
765
- } else {
766
- out += ch;
767
- }
768
- i += 1;
769
- }
770
- const pad = "~".repeat(Math.ceil(letters / 3));
771
- return `\u27E6${out}${pad ? " " + pad : ""}\u27E7`;
905
+ let out = "";
906
+ let letters = 0;
907
+ let i = 0;
908
+ while (i < message.length) {
909
+ const two = message.slice(i, i + 2);
910
+ if (two === "{{" || two === "}}" || two === "||" || two === "##") {
911
+ out += two;
912
+ i += 2;
913
+ continue;
914
+ }
915
+ const ch = message[i];
916
+ if (ch === "{") {
917
+ const end = matchBrace(message, i);
918
+ out += message.slice(i, end);
919
+ i = end;
920
+ continue;
921
+ }
922
+ if (ch === "<") {
923
+ TAG_AT.lastIndex = i;
924
+ const m = TAG_AT.exec(message);
925
+ if (m) {
926
+ out += m[0];
927
+ i += m[0].length;
928
+ continue;
929
+ }
930
+ }
931
+ const mapped = ACCENTS[ch];
932
+ if (mapped) {
933
+ out += mapped;
934
+ letters += 1;
935
+ } else out += ch;
936
+ i += 1;
937
+ }
938
+ const pad = "~".repeat(Math.ceil(letters / 3));
939
+ return `⟦${out}${pad ? " " + pad : ""}⟧`;
772
940
  }
773
941
  function matchBrace(message, start) {
774
- let depth = 0;
775
- for (let i = start; i < message.length; i++) {
776
- const two = message.slice(i, i + 2);
777
- if (two === "{{" || two === "}}") {
778
- i += 1;
779
- continue;
780
- }
781
- const ch = message[i];
782
- if (ch === "{") depth += 1;
783
- else if (ch === "}") {
784
- depth -= 1;
785
- if (depth === 0) return i + 1;
786
- }
787
- }
788
- return message.length;
942
+ let depth = 0;
943
+ for (let i = start; i < message.length; i++) {
944
+ const two = message.slice(i, i + 2);
945
+ if (two === "{{" || two === "}}") {
946
+ i += 1;
947
+ continue;
948
+ }
949
+ const ch = message[i];
950
+ if (ch === "{") depth += 1;
951
+ else if (ch === "}") {
952
+ depth -= 1;
953
+ if (depth === 0) return i + 1;
954
+ }
955
+ }
956
+ return message.length;
789
957
  }
790
958
  function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
791
- const source = catalogs[cfg.sourceLocale] ?? {};
792
- const target = {};
793
- for (const [key, msg] of Object.entries(source)) {
794
- target[key] = msg ? pseudoLocalize(msg) : "";
795
- }
796
- catalogs[locale] = target;
797
- return Object.keys(target).filter((key) => target[key]);
798
- }
799
-
800
- // src/render.ts
801
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
802
- import { dirname, join as join4, relative } from "path";
803
- import MagicString from "magic-string";
804
- import { glob as glob2 } from "tinyglobby";
805
- import {
806
- createVerbaly,
807
- parseTags,
808
- RICH_TAGS,
809
- safeHref
810
- } from "verbaly";
811
- var VOID_TAGS = /* @__PURE__ */ new Set([
812
- "area",
813
- "base",
814
- "br",
815
- "col",
816
- "embed",
817
- "hr",
818
- "img",
819
- "input",
820
- "link",
821
- "meta",
822
- "param",
823
- "source",
824
- "track",
825
- "wbr"
959
+ const source = catalogs[cfg.sourceLocale] ?? {};
960
+ const target = {};
961
+ for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
962
+ catalogs[locale] = target;
963
+ return Object.keys(target).filter((key) => target[key]);
964
+ }
965
+ //#endregion
966
+ //#region src/render.ts
967
+ const VOID_TAGS = /* @__PURE__ */ new Set([
968
+ "area",
969
+ "base",
970
+ "br",
971
+ "col",
972
+ "embed",
973
+ "hr",
974
+ "img",
975
+ "input",
976
+ "link",
977
+ "meta",
978
+ "param",
979
+ "source",
980
+ "track",
981
+ "wbr"
826
982
  ]);
827
- var START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
828
- var ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
983
+ const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
984
+ const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
829
985
  function renderHtml(html, options) {
830
- const attr = options.attribute ?? "data-verbaly";
831
- const argsAttr = `${attr}-args`;
832
- const attrsAttr = `${attr}-attr`;
833
- const richAttr = `${attr}-rich`;
834
- const linksAttr = `${attr}-links`;
835
- const richTags = new Set(options.richTags ?? RICH_TAGS);
836
- const globalLinks = options.richLinks;
837
- const sourceLocale = options.sourceLocale ?? "en";
838
- const messages = {};
839
- for (const [locale, catalog] of Object.entries(options.catalogs)) {
840
- const clean = {};
841
- for (const [key, msg] of Object.entries(catalog)) if (msg) clean[key] = msg;
842
- messages[locale] = clean;
843
- }
844
- const v = createVerbaly({ locale: options.locale, fallback: sourceLocale, messages });
845
- const t = v.t;
846
- const ms = new MagicString(html);
847
- const missing = /* @__PURE__ */ new Set();
848
- const skip = protectedRanges(html);
849
- const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
850
- START_TAG.lastIndex = 0;
851
- let m;
852
- while ((m = START_TAG.exec(html)) !== null) {
853
- if (inSkip(m.index)) continue;
854
- const [full, rawName, attrChunk] = m;
855
- const tagName = rawName.toLowerCase();
856
- const openEnd = m.index + full.length;
857
- const chunkStart = m.index + 1 + rawName.length;
858
- if (tagName === "html" && options.setLang !== false) {
859
- setAttribute(ms, html, chunkStart, openEnd, attrChunk, "lang", options.locale);
860
- continue;
861
- }
862
- const attrs = parseAttrs(attrChunk);
863
- const key = attrs.get(attr);
864
- const attrMapRaw = attrs.get(attrsAttr);
865
- if (key === void 0 && attrMapRaw === void 0) continue;
866
- const args = parseArgs(attrs.get(argsAttr));
867
- if (key) {
868
- if (!v.has(key)) {
869
- missing.add(key);
870
- } else if (!VOID_TAGS.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
871
- const close = findClose(html, tagName, openEnd, inSkip);
872
- if (close) {
873
- const text = t(key, args);
874
- const own = parseArgs(attrs.get(linksAttr));
875
- const links = own ? globalLinks ? { ...globalLinks, ...own } : own : globalLinks;
876
- const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
877
- if (html.slice(openEnd, close.contentEnd) !== content) {
878
- if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
879
- else ms.overwrite(openEnd, close.contentEnd, content);
880
- }
881
- }
882
- }
883
- }
884
- if (attrMapRaw !== void 0) {
885
- const map = parseArgs(attrMapRaw);
886
- if (map) {
887
- for (const [name, attrKey] of Object.entries(map)) {
888
- if (typeof attrKey !== "string" || name.toLowerCase().startsWith("on")) continue;
889
- if (!v.has(attrKey)) {
890
- missing.add(attrKey);
891
- continue;
892
- }
893
- setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, t(attrKey, args));
894
- }
895
- }
896
- }
897
- }
898
- return { html: ms.toString(), missing: [...missing] };
986
+ const attr = options.attribute ?? "data-verbaly";
987
+ const argsAttr = `${attr}-args`;
988
+ const attrsAttr = `${attr}-attr`;
989
+ const richAttr = `${attr}-rich`;
990
+ const linksAttr = `${attr}-links`;
991
+ const richTags = new Set(options.richTags ?? RICH_TAGS);
992
+ const globalLinks = options.richLinks;
993
+ const sourceLocale = options.sourceLocale ?? "en";
994
+ const messages = {};
995
+ for (const [locale, catalog] of Object.entries(options.catalogs)) {
996
+ const clean = {};
997
+ for (const [key, msg] of Object.entries(catalog)) if (msg) clean[key] = msg;
998
+ messages[locale] = clean;
999
+ }
1000
+ const v = createVerbaly({
1001
+ locale: options.locale,
1002
+ fallback: sourceLocale,
1003
+ messages
1004
+ });
1005
+ const t = v.t;
1006
+ const ms = new MagicString(html);
1007
+ const missing = /* @__PURE__ */ new Set();
1008
+ const skip = protectedRanges(html);
1009
+ const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
1010
+ START_TAG.lastIndex = 0;
1011
+ let m;
1012
+ while ((m = START_TAG.exec(html)) !== null) {
1013
+ if (inSkip(m.index)) continue;
1014
+ const [full, rawName, attrChunk] = m;
1015
+ const tagName = rawName.toLowerCase();
1016
+ const openEnd = m.index + full.length;
1017
+ const chunkStart = m.index + 1 + rawName.length;
1018
+ if (tagName === "html" && options.setLang !== false) {
1019
+ setAttribute(ms, html, chunkStart, openEnd, attrChunk, "lang", options.locale);
1020
+ continue;
1021
+ }
1022
+ const attrs = parseAttrs(attrChunk);
1023
+ const key = attrs.get(attr);
1024
+ const attrMapRaw = attrs.get(attrsAttr);
1025
+ if (key === void 0 && attrMapRaw === void 0) continue;
1026
+ const args = parseArgs(attrs.get(argsAttr));
1027
+ if (key) {
1028
+ if (!v.has(key)) missing.add(key);
1029
+ else if (!VOID_TAGS.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
1030
+ const close = findClose(html, tagName, openEnd, inSkip);
1031
+ if (close) {
1032
+ const text = t(key, args);
1033
+ const own = parseArgs(attrs.get(linksAttr));
1034
+ const links = own ? globalLinks ? {
1035
+ ...globalLinks,
1036
+ ...own
1037
+ } : own : globalLinks;
1038
+ const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
1039
+ if (html.slice(openEnd, close.contentEnd) !== content) if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
1040
+ else ms.overwrite(openEnd, close.contentEnd, content);
1041
+ }
1042
+ }
1043
+ }
1044
+ if (attrMapRaw !== void 0) {
1045
+ const map = parseArgs(attrMapRaw);
1046
+ if (map) for (const [name, attrKey] of Object.entries(map)) {
1047
+ if (typeof attrKey !== "string" || name.toLowerCase().startsWith("on")) continue;
1048
+ if (!v.has(attrKey)) {
1049
+ missing.add(attrKey);
1050
+ continue;
1051
+ }
1052
+ setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, t(attrKey, args));
1053
+ }
1054
+ }
1055
+ }
1056
+ return {
1057
+ html: ms.toString(),
1058
+ missing: [...missing]
1059
+ };
899
1060
  }
900
1061
  async function renderSite(cfg, options = {}) {
901
- const site = join4(cfg.root, options.site ?? "dist");
902
- const locales = options.locales ?? cfg.locales;
903
- const catalogs = loadCatalogs(cfg);
904
- const files = await glob2("**/*.html", {
905
- cwd: site,
906
- absolute: true,
907
- ignore: locales.map((locale) => `${locale}/**`)
908
- });
909
- const missing = {};
910
- for (const file of files) {
911
- const html = readFileSync4(file, "utf8");
912
- const rel = relative(site, file);
913
- for (const locale of locales) {
914
- const result = renderHtml(html, {
915
- locale,
916
- catalogs,
917
- sourceLocale: cfg.sourceLocale,
918
- attribute: options.attribute,
919
- richTags: options.richTags,
920
- richLinks: options.richLinks ?? cfg.render.links
921
- });
922
- for (const key of result.missing) {
923
- const list = missing[locale] ??= [];
924
- if (!list.includes(key)) list.push(key);
925
- }
926
- const out = locale === cfg.sourceLocale ? file : join4(site, locale, rel);
927
- mkdirSync2(dirname(out), { recursive: true });
928
- writeFileSync3(out, result.html);
929
- }
930
- }
931
- return { files: files.length, locales: [...locales], missing };
1062
+ const site = join(cfg.root, options.site ?? "dist");
1063
+ const locales = options.locales ?? cfg.locales;
1064
+ const catalogs = loadCatalogs(cfg);
1065
+ const files = await glob("**/*.html", {
1066
+ cwd: site,
1067
+ absolute: true,
1068
+ ignore: locales.map((locale) => `${locale}/**`)
1069
+ });
1070
+ const missing = {};
1071
+ for (const file of files) {
1072
+ const html = readFileSync(file, "utf8");
1073
+ const rel = relative(site, file);
1074
+ for (const locale of locales) {
1075
+ const result = renderHtml(html, {
1076
+ locale,
1077
+ catalogs,
1078
+ sourceLocale: cfg.sourceLocale,
1079
+ attribute: options.attribute,
1080
+ richTags: options.richTags,
1081
+ richLinks: options.richLinks ?? cfg.render.links
1082
+ });
1083
+ for (const key of result.missing) {
1084
+ const list = missing[locale] ??= [];
1085
+ if (!list.includes(key)) list.push(key);
1086
+ }
1087
+ const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);
1088
+ mkdirSync(dirname(out), { recursive: true });
1089
+ writeFileSync(out, result.html);
1090
+ }
1091
+ }
1092
+ return {
1093
+ files: files.length,
1094
+ locales: [...locales],
1095
+ missing
1096
+ };
932
1097
  }
933
1098
  function parseAttrs(chunk) {
934
- const attrs = /* @__PURE__ */ new Map();
935
- ATTR.lastIndex = 0;
936
- let m;
937
- while ((m = ATTR.exec(chunk)) !== null) {
938
- attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
939
- }
940
- return attrs;
1099
+ const attrs = /* @__PURE__ */ new Map();
1100
+ ATTR.lastIndex = 0;
1101
+ let m;
1102
+ while ((m = ATTR.exec(chunk)) !== null) attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
1103
+ return attrs;
941
1104
  }
942
1105
  function parseArgs(raw) {
943
- if (!raw) return void 0;
944
- try {
945
- return JSON.parse(decodeEntities(raw));
946
- } catch {
947
- console.warn(`[verbaly] invalid args JSON: ${raw}`);
948
- return void 0;
949
- }
1106
+ if (!raw) return void 0;
1107
+ try {
1108
+ return JSON.parse(decodeEntities(raw));
1109
+ } catch {
1110
+ console.warn(`[verbaly] invalid args JSON: ${raw}`);
1111
+ return;
1112
+ }
950
1113
  }
951
1114
  function protectedRanges(html) {
952
- const ranges = [];
953
- const re = /<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
954
- let m;
955
- while ((m = re.exec(html)) !== null) {
956
- const openEnd = m[0].startsWith("<!--") ? m.index : html.indexOf(">", m.index) + 1;
957
- ranges.push([openEnd, m.index + m[0].length]);
958
- }
959
- return ranges;
1115
+ const ranges = [];
1116
+ const re = /<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
1117
+ let m;
1118
+ while ((m = re.exec(html)) !== null) {
1119
+ const openEnd = m[0].startsWith("<!--") ? m.index : html.indexOf(">", m.index) + 1;
1120
+ ranges.push([openEnd, m.index + m[0].length]);
1121
+ }
1122
+ return ranges;
960
1123
  }
961
1124
  function findClose(html, tagName, from, inSkip) {
962
- const re = new RegExp(
963
- `<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`,
964
- "gi"
965
- );
966
- re.lastIndex = from;
967
- let depth = 1;
968
- let m;
969
- while ((m = re.exec(html)) !== null) {
970
- if (inSkip(m.index)) continue;
971
- if (m[0][1] === "/") {
972
- depth -= 1;
973
- if (depth === 0) return { contentEnd: m.index };
974
- } else if (!m[0].endsWith("/>")) {
975
- depth += 1;
976
- }
977
- }
978
- return null;
1125
+ const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
1126
+ re.lastIndex = from;
1127
+ let depth = 1;
1128
+ let m;
1129
+ while ((m = re.exec(html)) !== null) {
1130
+ if (inSkip(m.index)) continue;
1131
+ if (m[0][1] === "/") {
1132
+ depth -= 1;
1133
+ if (depth === 0) return { contentEnd: m.index };
1134
+ } else if (!m[0].endsWith("/>")) depth += 1;
1135
+ }
1136
+ return null;
979
1137
  }
980
1138
  function setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value) {
981
- const escaped = escapeAttr(value);
982
- const existing = new RegExp(`(\\s${name}\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s>]+)`, "i").exec(
983
- attrChunk
984
- );
985
- if (existing) {
986
- const valueStart = chunkStart + existing.index + existing[1].length;
987
- const valueEnd = valueStart + existing[2].length;
988
- if (html.slice(valueStart, valueEnd) !== `"${escaped}"`) {
989
- ms.overwrite(valueStart, valueEnd, `"${escaped}"`);
990
- }
991
- return;
992
- }
993
- const selfClosing = html.slice(openEnd - 2, openEnd) === "/>";
994
- const insertAt = openEnd - (selfClosing ? 2 : 1);
995
- ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
1139
+ const escaped = escapeAttr(value);
1140
+ const existing = new RegExp(`(\\s${name}\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s>]+)`, "i").exec(attrChunk);
1141
+ if (existing) {
1142
+ const valueStart = chunkStart + existing.index + existing[1].length;
1143
+ const valueEnd = valueStart + existing[2].length;
1144
+ if (html.slice(valueStart, valueEnd) !== `"${escaped}"`) ms.overwrite(valueStart, valueEnd, `"${escaped}"`);
1145
+ return;
1146
+ }
1147
+ const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
1148
+ ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
996
1149
  }
997
1150
  function richToHtml(nodes, allowed, links) {
998
- let out = "";
999
- for (const node of nodes) {
1000
- if (typeof node === "string") {
1001
- out += escapeHtml(node);
1002
- } else if (links?.[node.name] !== void 0) {
1003
- const link = links[node.name];
1004
- const { href, target, rel } = typeof link === "string" ? { href: link } : link;
1005
- const safe = safeHref(href);
1006
- let attrs = safe !== void 0 ? ` href="${escapeAttr(safe)}"` : "";
1007
- if (target) attrs += ` target="${escapeAttr(target)}"`;
1008
- if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
1009
- out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
1010
- } else if (allowed.has(node.name)) {
1011
- out += `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
1012
- } else {
1013
- out += richToHtml(node.children, allowed, links);
1014
- }
1015
- }
1016
- return out;
1151
+ let out = "";
1152
+ for (const node of nodes) if (typeof node === "string") out += escapeHtml(node);
1153
+ else if (links?.[node.name] !== void 0) {
1154
+ const link = links[node.name];
1155
+ const { href, target, rel } = typeof link === "string" ? { href: link } : link;
1156
+ const safe = safeHref(href);
1157
+ let attrs = safe !== void 0 ? ` href="${escapeAttr(safe)}"` : "";
1158
+ if (target) attrs += ` target="${escapeAttr(target)}"`;
1159
+ if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
1160
+ out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
1161
+ } else if (allowed.has(node.name)) out += `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
1162
+ else out += richToHtml(node.children, allowed, links);
1163
+ return out;
1017
1164
  }
1018
1165
  function escapeHtml(text) {
1019
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1166
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1020
1167
  }
1021
1168
  function escapeAttr(text) {
1022
- return escapeHtml(text).replace(/"/g, "&quot;");
1169
+ return escapeHtml(text).replace(/"/g, "&quot;");
1023
1170
  }
1024
1171
  function decodeEntities(text) {
1025
- return text.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
1172
+ return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
1026
1173
  }
1027
-
1028
- // src/transform.ts
1029
- import MagicString2 from "magic-string";
1174
+ //#endregion
1175
+ //#region src/transform.ts
1030
1176
  function transformCode(code, file, analysis) {
1031
- const { tagged } = analysis ?? analyze(code, file);
1032
- if (tagged.length === 0) return null;
1033
- const s = new MagicString2(code);
1034
- for (const msg of tagged) {
1035
- const seen = /* @__PURE__ */ new Set();
1036
- const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));
1037
- const pairs = entries.map((p) => `${JSON.stringify(p.name)}: ${code.slice(p.start, p.end)}`).join(", ");
1038
- if (msg.jsx) {
1039
- const values = entries.length ? ` values={{ ${pairs} }}` : "";
1040
- const components = msg.jsx.components.length ? ` components={{ ${msg.jsx.components.map((c) => `${JSON.stringify(c.name)}: ${c.source}`).join(", ")} }}` : "";
1041
- s.overwrite(
1042
- msg.start,
1043
- msg.end,
1044
- `<${msg.jsx.name} id=${JSON.stringify(msg.key)}${values}${components} />`
1045
- );
1046
- continue;
1047
- }
1048
- const tagSource = code.slice(msg.tagStart, msg.tagEnd);
1049
- const args = entries.length ? `, { ${pairs} }` : "";
1050
- s.overwrite(msg.start, msg.end, `${tagSource}(${JSON.stringify(msg.key)}${args})`);
1051
- }
1052
- return { code: s.toString(), map: s.generateMap({ hires: true }) };
1053
- }
1054
-
1055
- // src/translate.ts
1177
+ const { tagged } = analysis ?? analyze(code, file);
1178
+ if (tagged.length === 0) return null;
1179
+ const s = new MagicString(code);
1180
+ for (const msg of tagged) {
1181
+ const seen = /* @__PURE__ */ new Set();
1182
+ const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));
1183
+ const pairs = entries.map((p) => `${JSON.stringify(p.name)}: ${code.slice(p.start, p.end)}`).join(", ");
1184
+ if (msg.jsx) {
1185
+ const values = entries.length ? ` values={{ ${pairs} }}` : "";
1186
+ const components = msg.jsx.components.length ? ` components={{ ${msg.jsx.components.map((c) => `${JSON.stringify(c.name)}: ${c.source}`).join(", ")} }}` : "";
1187
+ s.overwrite(msg.start, msg.end, `<${msg.jsx.name} id=${JSON.stringify(msg.key)}${values}${components} />`);
1188
+ continue;
1189
+ }
1190
+ const tagSource = code.slice(msg.tagStart, msg.tagEnd);
1191
+ const args = entries.length ? `, { ${pairs} }` : "";
1192
+ s.overwrite(msg.start, msg.end, `${tagSource}(${JSON.stringify(msg.key)}${args})`);
1193
+ }
1194
+ return {
1195
+ code: s.toString(),
1196
+ map: s.generateMap({ hires: true })
1197
+ };
1198
+ }
1199
+ //#endregion
1200
+ //#region src/translate.ts
1056
1201
  async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1057
- const batchSize = options.batchSize ?? 20;
1058
- const targets = (options.locales ?? cfg.locales).filter(
1059
- (locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale)
1060
- );
1061
- const source = catalogs[cfg.sourceLocale] ?? {};
1062
- const result = { translated: {}, invalid: {}, pending: {} };
1063
- for (const locale of targets) {
1064
- const catalog = catalogs[locale] ??= {};
1065
- const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
1066
- if (missing.length === 0) continue;
1067
- if (options.dryRun) {
1068
- result.pending[locale] = missing;
1069
- continue;
1070
- }
1071
- for (let i = 0; i < missing.length; i += batchSize) {
1072
- const keys = missing.slice(i, i + batchSize);
1073
- const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
1074
- const out = await provider({
1075
- sourceLocale: cfg.sourceLocale,
1076
- targetLocale: locale,
1077
- messages
1078
- });
1079
- for (const key of keys) {
1080
- const text = out[key];
1081
- if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
1082
- catalog[key] = text;
1083
- (result.translated[locale] ??= []).push(key);
1084
- } else {
1085
- (result.invalid[locale] ??= []).push(key);
1086
- }
1087
- }
1088
- }
1089
- }
1090
- return result;
1202
+ const batchSize = options.batchSize ?? 20;
1203
+ const targets = (options.locales ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
1204
+ const source = catalogs[cfg.sourceLocale] ?? {};
1205
+ const result = {
1206
+ translated: {},
1207
+ invalid: {},
1208
+ pending: {}
1209
+ };
1210
+ for (const locale of targets) {
1211
+ const catalog = catalogs[locale] ??= {};
1212
+ const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
1213
+ if (missing.length === 0) continue;
1214
+ if (options.dryRun) {
1215
+ result.pending[locale] = missing;
1216
+ continue;
1217
+ }
1218
+ for (let i = 0; i < missing.length; i += batchSize) {
1219
+ const keys = missing.slice(i, i + batchSize);
1220
+ const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
1221
+ const out = await provider({
1222
+ sourceLocale: cfg.sourceLocale,
1223
+ targetLocale: locale,
1224
+ messages
1225
+ });
1226
+ for (const key of keys) {
1227
+ const text = out[key];
1228
+ if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
1229
+ catalog[key] = text;
1230
+ (result.translated[locale] ??= []).push(key);
1231
+ } else (result.invalid[locale] ??= []).push(key);
1232
+ }
1233
+ }
1234
+ }
1235
+ return result;
1091
1236
  }
1092
1237
  function structureMatches(source, translated) {
1093
- return sameMembers(paramNames(source), paramNames(translated)) && sameMembers(tagTokens(source), tagTokens(translated));
1238
+ return sameMembers(paramNames(source), paramNames(translated)) && sameMembers(tagTokens(source), tagTokens(translated));
1094
1239
  }
1095
1240
  function paramNames(message) {
1096
- try {
1097
- return [...collectParams(message).keys()].sort();
1098
- } catch {
1099
- return ["\0invalid"];
1100
- }
1241
+ try {
1242
+ return [...collectParams(message).keys()].sort();
1243
+ } catch {
1244
+ return ["\0invalid"];
1245
+ }
1101
1246
  }
1102
- var TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
1247
+ const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
1103
1248
  function tagTokens(message) {
1104
- const out = [];
1105
- for (const match of message.matchAll(TAG)) {
1106
- out.push(`${match[1]}${match[2]}${match[3]}`);
1107
- }
1108
- return out.sort();
1249
+ const out = [];
1250
+ for (const match of message.matchAll(TAG)) out.push(`${match[1]}${match[2]}${match[3]}`);
1251
+ return out.sort();
1109
1252
  }
1110
1253
  function sameMembers(a, b) {
1111
- return a.length === b.length && a.every((value, i) => value === b[i]);
1112
- }
1113
- export {
1114
- MessageRegistry,
1115
- PSEUDO_LOCALE,
1116
- VIRTUAL_ID,
1117
- analyze,
1118
- catalogPath,
1119
- check,
1120
- claudeProvider,
1121
- collectParams,
1122
- extractProject,
1123
- formatCheckResult,
1124
- generateDts,
1125
- generateLocaleModule,
1126
- generateRuntimeModule,
1127
- loadCatalogs,
1128
- loadConfig,
1129
- loadConfigFile,
1130
- pruneCatalogs,
1131
- pseudoCatalogs,
1132
- pseudoLocalize,
1133
- readCatalog,
1134
- renderHtml,
1135
- renderParamType,
1136
- renderSite,
1137
- resolveConfig,
1138
- serializeCatalog,
1139
- stableKey,
1140
- structureMatches,
1141
- syncCatalogs,
1142
- transformCode,
1143
- translateCatalogs,
1144
- writeCatalog,
1145
- writeDts
1146
- };
1254
+ return a.length === b.length && a.every((value, i) => value === b[i]);
1255
+ }
1256
+ //#endregion
1257
+ export { MessageRegistry, PSEUDO_LOCALE, VIRTUAL_ID, analyze, catalogPath, check, claudeProvider, collectParams, detectBundler, doctor, extractProject, findConfigFile, formatCheckResult, generateDts, generateLocaleModule, generateRuntimeModule, init, loadCatalogs, loadConfig, loadConfigFile, pruneCatalogs, pseudoCatalogs, pseudoLocalize, readCatalog, renderHtml, renderParamType, renderSite, resolveConfig, serializeCatalog, stableKey, structureMatches, syncCatalogs, transformCode, translateCatalogs, writeCatalog, writeDts };
1258
+
1147
1259
  //# sourceMappingURL=index.js.map