@verbaly/compiler 0.66.0 → 0.68.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/cli.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { basename, dirname, join, relative, resolve } from "node:path";
3
2
  import { parseArgs } from "node:util";
4
3
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
6
- import { pathToFileURL } from "node:url";
7
6
  import { glob } from "tinyglobby";
8
7
  import { parse as parse$1 } from "@babel/parser";
9
8
  import { createHash } from "node:crypto";
9
+ import { pathToFileURL } from "node:url";
10
10
  import MagicString from "magic-string";
11
11
  import picomatch from "picomatch";
12
12
  //#region src/catalog.ts
@@ -139,387 +139,835 @@ function wantsNesting(cfg, locale, existing, previous) {
139
139
  return isNested(readTree(cfg, cfg.sourceLocale));
140
140
  }
141
141
  //#endregion
142
- //#region src/pseudo.ts
143
- const PSEUDO_LOCALE = "en-XA";
144
- const ACCENTS = {
145
- a: "á",
146
- b: "ƀ",
147
- c: "ç",
148
- d: "đ",
149
- e: "é",
150
- f: "ƒ",
151
- g: "ğ",
152
- h: "ĥ",
153
- i: "í",
154
- j: "ĵ",
155
- k: "ķ",
156
- l: "ĺ",
157
- m: "ɱ",
158
- n: "ñ",
159
- o: "ó",
160
- p: "þ",
161
- q: "ǫ",
162
- r: "ŕ",
163
- s: "š",
164
- t: "ţ",
165
- u: "ú",
166
- v: "ṽ",
167
- w: "ŵ",
168
- x: "ẋ",
169
- y: "ý",
170
- z: "ž",
171
- A: "Á",
172
- B: "Ɓ",
173
- C: "Ç",
174
- D: "Đ",
175
- E: "É",
176
- F: "Ƒ",
177
- G: "Ğ",
178
- H: "Ĥ",
179
- I: "Í",
180
- J: "Ĵ",
181
- K: "Ķ",
182
- L: "Ĺ",
183
- M: "Ḿ",
184
- N: "Ñ",
185
- O: "Ó",
186
- P: "Þ",
187
- Q: "Ǫ",
188
- R: "Ŕ",
189
- S: "Š",
190
- T: "Ţ",
191
- U: "Ú",
192
- V: "Ṽ",
193
- W: "Ŵ",
194
- X: "Ẍ",
195
- Y: "Ý",
196
- Z: "Ž"
197
- };
198
- const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
199
- function pseudoLocalize(message) {
200
- let out = "";
201
- let letters = 0;
202
- let i = 0;
203
- while (i < message.length) {
204
- const two = message.slice(i, i + 2);
205
- if (two === "{{" || two === "}}" || two === "||" || two === "##") {
206
- out += two;
207
- i += 2;
208
- continue;
209
- }
210
- const ch = message[i];
211
- if (ch === "{") {
212
- const end = matchBrace$1(message, i);
213
- out += message.slice(i, end);
214
- i = end;
215
- continue;
216
- }
217
- if (ch === "<") {
218
- TAG_AT.lastIndex = i;
219
- const m = TAG_AT.exec(message);
220
- if (m) {
221
- out += m[0];
222
- i += m[0].length;
223
- continue;
224
- }
142
+ //#region src/registry.ts
143
+ var MessageRegistry = class {
144
+ files = /* @__PURE__ */ new Map();
145
+ update(file, analysis) {
146
+ this.files.set(file, analysis);
147
+ }
148
+ remove(file) {
149
+ this.files.delete(file);
150
+ }
151
+ messages() {
152
+ const out = /* @__PURE__ */ new Map();
153
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
154
+ const held = out.get(msg.key);
155
+ if (!held || earlier(msg, held)) out.set(msg.key, msg);
225
156
  }
226
- const mapped = ACCENTS[ch];
227
- if (mapped) {
228
- out += mapped;
229
- letters += 1;
230
- } else out += ch;
231
- i += 1;
157
+ return out;
232
158
  }
233
- const pad = "~".repeat(Math.ceil(letters / 3));
234
- return `⟦${out}${pad ? " " + pad : ""}⟧`;
235
- }
236
- function matchBrace$1(message, start) {
237
- let depth = 0;
238
- for (let i = start; i < message.length; i++) {
239
- const two = message.slice(i, i + 2);
240
- if (two === "{{" || two === "}}") {
241
- i += 1;
242
- continue;
159
+ collisions() {
160
+ const winners = this.messages();
161
+ const dropped = /* @__PURE__ */ new Map();
162
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
163
+ if (msg.message === winners.get(msg.key).message) continue;
164
+ dropped.set(msg.key, [...dropped.get(msg.key) ?? [], msg]);
243
165
  }
244
- const ch = message[i];
245
- if (ch === "{") depth += 1;
246
- else if (ch === "}") {
247
- depth -= 1;
248
- if (depth === 0) return i + 1;
166
+ return [...dropped].map(([key, others]) => ({
167
+ key,
168
+ kept: winners.get(key),
169
+ dropped: others.sort((a, b) => earlier(a, b) ? -1 : 1)
170
+ }));
171
+ }
172
+ usedKeys(strict = false) {
173
+ const out = /* @__PURE__ */ new Map();
174
+ for (const analysis of this.inOrder()) for (const used of analysis.usedKeys) {
175
+ if (strict && used.loose) continue;
176
+ const files = out.get(used.key) ?? [];
177
+ if (!files.includes(used.file)) files.push(used.file);
178
+ out.set(used.key, files);
249
179
  }
180
+ return out;
250
181
  }
251
- return message.length;
252
- }
253
- function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
254
- const source = catalogs[cfg.sourceLocale] ?? {};
255
- const target = emptyCatalog();
256
- for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
257
- catalogs[locale] = target;
258
- return Object.keys(target).filter((key) => target[key]);
259
- }
260
- //#endregion
261
- //#region src/config.ts
262
- function resolveConfig(config = {}) {
263
- const root = resolve(config.root ?? process.cwd());
264
- const dir = resolve(root, config.dir ?? "locales");
265
- const sourceLocale = config.sourceLocale ?? "en";
266
- const localesDeclared = config.locales !== void 0;
267
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
268
- if (!localesDeclared && existsSync(dir)) {
269
- for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
182
+ strayImports() {
183
+ return this.inOrder().flatMap((analysis) => analysis.strayImports);
270
184
  }
271
- return {
272
- root,
273
- dir,
274
- sourceLocale,
275
- localesDeclared,
276
- routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
277
- icu: config.icu,
278
- relative: config.relative,
279
- locales: [...locales],
280
- include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
281
- exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
282
- dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts,
283
- translate: config.translate ?? {},
284
- render: config.render ?? {},
285
- bundle: config.bundle ?? {}
286
- };
287
- }
288
- const CONFIG_FILES = [
289
- "verbaly.config.js",
290
- "verbaly.config.mjs",
291
- "verbaly.config.ts",
292
- "verbaly.config.mts",
293
- "verbaly.config.json"
294
- ];
295
- function findConfigFile(root) {
296
- return CONFIG_FILES.find((name) => existsSync(join(root, name)));
297
- }
298
- async function loadConfigFile(root) {
299
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
300
- const path = join(root, name);
301
- if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
185
+ missed() {
186
+ return this.inOrder().flatMap((analysis) => analysis.missed);
302
187
  }
303
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
304
- const path = join(root, name);
305
- if (existsSync(path)) return loadTsConfig(path);
188
+ parseErrors() {
189
+ const out = [];
190
+ for (const file of [...this.files.keys()].sort()) {
191
+ const { parseError } = this.files.get(file);
192
+ if (parseError) out.push({
193
+ file,
194
+ message: parseError
195
+ });
196
+ }
197
+ return out;
306
198
  }
307
- const jsonPath = join(root, "verbaly.config.json");
308
- if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
309
- return {};
310
- }
311
- function readJsonConfig(path) {
312
- const content = readFileSync(path, "utf8");
313
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
314
- try {
315
- return JSON.parse(body);
316
- } catch (error) {
317
- throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
199
+ origins() {
200
+ const out = this.usedKeys();
201
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
202
+ const files = out.get(msg.key) ?? [];
203
+ if (!files.includes(msg.file)) files.push(msg.file);
204
+ out.set(msg.key, files);
205
+ }
206
+ return out;
318
207
  }
319
- }
320
- async function loadTsConfig(path) {
321
- try {
322
- const { bundleRequire } = await import("bundle-require");
323
- const { mod } = await bundleRequire({ filepath: path });
324
- return mod.default ?? {};
325
- } catch (error) {
326
- if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
327
- throw error;
208
+ inOrder() {
209
+ return [...this.files.keys()].sort().map((file) => this.files.get(file));
328
210
  }
329
- }
330
- function isModuleNotFound(error, name) {
331
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
332
- }
333
- function targetLocales(cfg, override) {
334
- return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
335
- }
336
- async function loadConfig(root, overrides = {}) {
337
- return resolveConfig({
338
- ...await loadConfigFile(root),
339
- ...definedOnly(overrides),
340
- root
341
- });
342
- }
343
- function definedOnly(config) {
344
- return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
211
+ };
212
+ function earlier(a, b) {
213
+ return a.file === b.file ? a.start < b.start : a.file < b.file;
345
214
  }
346
215
  //#endregion
347
- //#region src/tag.ts
348
- function isLocaleTag(tag) {
349
- try {
350
- Intl.getCanonicalLocales(tag);
351
- return true;
352
- } catch {
353
- return false;
354
- }
355
- }
356
- function suggestTag(tag) {
357
- const near = tag.replace(/_/g, "-");
358
- return near !== tag && isLocaleTag(near) ? near : void 0;
359
- }
360
- function projectLocale(tag, locales) {
361
- if (locales.includes(tag)) return tag;
362
- const plain = (value) => value.replace(/_/g, "-").toLowerCase();
363
- return locales.find((locale) => plain(locale) === plain(tag));
216
+ //#region src/key.ts
217
+ function stableKey(message) {
218
+ return createHash("sha256").update(message).digest("base64url").slice(0, 8);
364
219
  }
365
220
  //#endregion
366
- //#region src/init.ts
367
- const HOSTS = [
368
- {
369
- name: "nuxt",
370
- dep: "nuxt",
371
- pkg: "@verbaly/nuxt",
372
- wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
373
- },
374
- {
375
- name: "next",
376
- dep: "next",
377
- pkg: "@verbaly/next",
378
- wire: "wrap the export of next.config with withVerbaly"
379
- },
380
- {
381
- name: "sveltekit",
382
- dep: "@sveltejs/kit",
383
- pkg: "@verbaly/vite",
384
- wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
385
- },
386
- {
387
- name: "astro",
388
- dep: "astro",
389
- pkg: "@verbaly/astro",
390
- wire: "add verbaly() to the integrations in astro.config"
391
- },
392
- {
393
- name: "vite",
394
- dep: "vite",
395
- pkg: "@verbaly/vite",
396
- wire: "add verbaly() to the plugins in vite.config"
397
- },
398
- {
399
- name: "webpack",
400
- dep: "webpack",
401
- pkg: "@verbaly/unplugin",
402
- wire: "add the verbaly webpack plugin to your build config"
403
- },
404
- {
405
- name: "rspack",
406
- dep: "@rspack/core",
407
- pkg: "@verbaly/unplugin",
408
- wire: "add the verbaly rspack plugin to your build config"
409
- },
410
- {
411
- name: "rollup",
412
- dep: "rollup",
413
- pkg: "@verbaly/unplugin",
414
- wire: "add the verbaly rollup plugin to your build config"
415
- },
416
- {
417
- name: "esbuild",
418
- dep: "esbuild",
419
- pkg: "@verbaly/unplugin",
420
- wire: "add the verbaly esbuild plugin to your build config"
221
+ //#region src/analyze.ts
222
+ function parseErrorMessage(error) {
223
+ return error instanceof Error ? error.message : String(error);
224
+ }
225
+ const SKIP_KEYS = /* @__PURE__ */ new Set([
226
+ "loc",
227
+ "leadingComments",
228
+ "trailingComments",
229
+ "innerComments",
230
+ "extra"
231
+ ]);
232
+ const DEFAULT_T_NAMES = ["t"];
233
+ const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
234
+ const DEFINE_KEYS = "defineKeys";
235
+ function analyze(code, file, options = {}) {
236
+ return analyzeScript(code, file, options).analysis;
237
+ }
238
+ function analyzeScript(code, file, options = {}) {
239
+ const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
240
+ const ast = parse$1(code, {
241
+ sourceType: "module",
242
+ errorRecovery: true,
243
+ plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
244
+ });
245
+ const tagged = [];
246
+ const usedKeys = [];
247
+ const strayImports = [];
248
+ const bindings = new Bindings(names);
249
+ const candidates = [];
250
+ walk$1(ast.program, (node) => {
251
+ if (node.type === "ImportDeclaration") {
252
+ collectStrayImports(node, file, strayImports);
253
+ bindings.addImport(node);
254
+ } else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
255
+ else if (node.type === "TaggedTemplateExpression") {
256
+ const tag = node.tag;
257
+ const explicit = explicitId(tag, names);
258
+ if (!explicit && !isTReference(tag, names)) {
259
+ candidates.push({
260
+ kind: "tag",
261
+ node
262
+ });
263
+ return;
264
+ }
265
+ const quasi = node.quasi;
266
+ const message = buildMessage(code, quasi, names);
267
+ if (!message) return;
268
+ tagged.push({
269
+ key: explicit ? explicit.key : stableKey(message.text),
270
+ message: message.text,
271
+ params: message.params,
272
+ start: node.start,
273
+ end: node.end,
274
+ line: lineOf(node),
275
+ tagStart: explicit ? explicit.refStart : tag.start,
276
+ tagEnd: explicit ? explicit.refEnd : tag.end,
277
+ file
278
+ });
279
+ } else if (node.type === "CallExpression") {
280
+ const callee = node.callee;
281
+ const args = node.arguments;
282
+ if (callee.type === "Identifier" && callee.name === DEFINE_KEYS) {
283
+ collectDeclaredKeys(args[0], file, usedKeys);
284
+ return;
285
+ }
286
+ if (!isTReference(callee, names)) {
287
+ const key = callee.type === "Identifier" ? staticString(args[0]) : void 0;
288
+ if (key !== void 0) candidates.push({
289
+ kind: "call",
290
+ name: callee.name,
291
+ key
292
+ });
293
+ return;
294
+ }
295
+ const key = staticString(args[0]);
296
+ if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
297
+ } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
298
+ });
299
+ const renamed = bindings.renamed(options.renamed);
300
+ const missed = [];
301
+ for (const candidate of candidates) {
302
+ if (candidate.kind === "call") {
303
+ if (renamed.has(candidate.name)) usedKeys.push({
304
+ key: candidate.key,
305
+ file,
306
+ loose: true
307
+ });
308
+ continue;
309
+ }
310
+ const { node } = candidate;
311
+ const name = renamedTag(node.tag, renamed);
312
+ if (!name) continue;
313
+ missed.push({
314
+ name,
315
+ file,
316
+ start: node.start,
317
+ line: lineOf(node)
318
+ });
319
+ const key = missedKey(code, node, names);
320
+ if (key !== void 0) usedKeys.push({
321
+ key,
322
+ file,
323
+ loose: true
324
+ });
325
+ }
326
+ return {
327
+ analysis: {
328
+ tagged,
329
+ usedKeys,
330
+ strayImports,
331
+ missed
332
+ },
333
+ renamed: [...renamed]
334
+ };
335
+ }
336
+ function lineOf(node) {
337
+ return node.loc?.start.line ?? 1;
338
+ }
339
+ const VERBALY_SOURCE = /^(?:verbaly|virtual:verbaly|@verbaly\/[\w-]+(?:\/[\w-]+)*)$/;
340
+ const T_FACTORIES = /* @__PURE__ */ new Map([["useT", "call"], ["getT", "await"]]);
341
+ const INSTANCE_FACTORIES = /* @__PURE__ */ new Set(["useVerbaly", "getVerbaly"]);
342
+ var Bindings = class {
343
+ names;
344
+ imports = /* @__PURE__ */ new Map();
345
+ direct = /* @__PURE__ */ new Set();
346
+ declared = [];
347
+ destructured = [];
348
+ constructor(names) {
349
+ this.names = names;
350
+ }
351
+ addImport(node) {
352
+ const source = node.source.value;
353
+ if (typeof source !== "string") return;
354
+ for (const spec of node.specifiers) {
355
+ const local = identifierName(spec.local);
356
+ if (!local) continue;
357
+ const imported = spec.type === "ImportSpecifier" ? importedName(spec.imported) : spec.type;
358
+ this.imports.set(local, {
359
+ source,
360
+ imported
361
+ });
362
+ if (source === "virtual:verbaly" && imported === "t") this.direct.add(local);
363
+ }
364
+ }
365
+ addDeclarator(node) {
366
+ const id = node.id;
367
+ const init = node.init;
368
+ if (!init) return;
369
+ if (id.type === "Identifier") {
370
+ this.declared.push({
371
+ name: id.name,
372
+ init
373
+ });
374
+ return;
375
+ }
376
+ if (id.type !== "ObjectPattern") return;
377
+ for (const property of id.properties) {
378
+ if (property.type !== "ObjectProperty" || property.computed) continue;
379
+ if (identifierName(property.key) !== "t") continue;
380
+ const value = property.value;
381
+ const name = identifierName(value.type === "AssignmentPattern" ? value.left : value);
382
+ if (name) this.destructured.push({
383
+ name,
384
+ init
385
+ });
386
+ }
387
+ }
388
+ renamed(seed = []) {
389
+ const out = new Set(seed);
390
+ const add = (name) => {
391
+ if (this.names.has(name)) return;
392
+ out.add(name);
393
+ if (this.names.has("$t")) out.add(`$${name}`);
394
+ };
395
+ for (const name of this.direct) add(name);
396
+ for (const { name, init } of this.declared) if (this.handsOutT(init)) add(name);
397
+ for (const { name, init } of this.destructured) if (this.carriesT(init)) add(name);
398
+ return out;
399
+ }
400
+ handsOutT(init) {
401
+ const awaited = init.type === "AwaitExpression";
402
+ const call = awaited ? init.argument : init;
403
+ if (call.type !== "CallExpression") return false;
404
+ const origin = this.origin(identifierName(call.callee));
405
+ if (origin.verbaly === false) return false;
406
+ const how = T_FACTORIES.get(origin.imported);
407
+ return how !== void 0 && how === "await" === awaited;
408
+ }
409
+ carriesT(init) {
410
+ const inner = init.type === "AwaitExpression" ? init.argument : init;
411
+ const name = identifierName(inner.type === "CallExpression" ? inner.callee : inner);
412
+ if (!name) return false;
413
+ return this.origin(name).verbaly ?? INSTANCE_FACTORIES.has(name);
414
+ }
415
+ origin(local) {
416
+ const found = this.imports.get(local);
417
+ if (!found) return {
418
+ verbaly: void 0,
419
+ imported: local
420
+ };
421
+ return {
422
+ verbaly: VERBALY_SOURCE.test(found.source),
423
+ imported: found.imported
424
+ };
425
+ }
426
+ };
427
+ function importedName(node) {
428
+ return node.type === "StringLiteral" ? node.value : identifierName(node);
429
+ }
430
+ function identifierName(node) {
431
+ return node?.type === "Identifier" ? node.name : "";
432
+ }
433
+ function renamedTag(tag, renamed) {
434
+ if (renamed.size === 0) return void 0;
435
+ const name = identifierName(tag);
436
+ if (renamed.has(name)) return name;
437
+ if (tag.type !== "CallExpression") return void 0;
438
+ const callee = tag.callee;
439
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
440
+ if (identifierName(callee.property) !== "id") return void 0;
441
+ const object = identifierName(callee.object);
442
+ return renamed.has(object) ? object : void 0;
443
+ }
444
+ function missedKey(code, node, names) {
445
+ const tag = node.tag;
446
+ if (tag.type === "CallExpression") {
447
+ const args = tag.arguments;
448
+ const first = args[0];
449
+ return args.length === 1 && first?.type === "StringLiteral" ? first.value : void 0;
450
+ }
451
+ const message = buildMessage(code, node.quasi, names);
452
+ return message ? stableKey(message.text) : void 0;
453
+ }
454
+ function collectDeclaredKeys(node, file, out) {
455
+ if (node?.type !== "ObjectExpression") return;
456
+ for (const property of node.properties) {
457
+ if (property.type !== "ObjectProperty") continue;
458
+ const value = property.value;
459
+ const key = staticString(value);
460
+ if (key !== void 0) {
461
+ if (key !== "") out.push(usedKey(key, file, value));
462
+ } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
463
+ }
464
+ }
465
+ function usedKey(key, file, node) {
466
+ return node?.type === "StringLiteral" ? {
467
+ key,
468
+ file
469
+ } : {
470
+ key,
471
+ file,
472
+ loose: true
473
+ };
474
+ }
475
+ function staticString(node) {
476
+ if (!node) return void 0;
477
+ if (node.type === "StringLiteral") return node.value;
478
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
479
+ if (node.type === "JSXExpressionContainer") return staticString(node.expression);
480
+ }
481
+ const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
482
+ function collectStrayImports(node, file, out) {
483
+ const source = node.source;
484
+ if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
485
+ for (const spec of node.specifiers) {
486
+ if (spec.type !== "ImportSpecifier") continue;
487
+ const imported = spec.imported;
488
+ if (imported.type !== "Identifier") continue;
489
+ const name = imported.name;
490
+ if (name === "t" || name === DEFINE_KEYS) out.push({
491
+ name,
492
+ source: source.value,
493
+ file
494
+ });
495
+ }
496
+ }
497
+ function handleTrans(code, node, file, tagged, usedKeys, names) {
498
+ const opening = node.openingElement;
499
+ const nameNode = opening.name;
500
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
501
+ const attrs = opening.attributes;
502
+ const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
503
+ const children = node.children;
504
+ const push = (key, built) => tagged.push({
505
+ key,
506
+ message: built.text,
507
+ params: built.params,
508
+ start: node.start,
509
+ end: node.end,
510
+ line: lineOf(node),
511
+ tagStart: nameNode.start,
512
+ tagEnd: nameNode.end,
513
+ file,
514
+ jsx: {
515
+ name: nameNode.name,
516
+ components: built.components
517
+ }
518
+ });
519
+ if (idAttr) {
520
+ const value = idAttr.value;
521
+ const id = staticString(value);
522
+ if (id === void 0) return;
523
+ if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
524
+ const built = buildTransMessage(code, children, names);
525
+ if (built?.text.trim()) {
526
+ push(id, built);
527
+ return;
528
+ }
529
+ }
530
+ usedKeys.push(usedKey(id, file, value));
531
+ return;
532
+ }
533
+ if (attrs.length > 0) return;
534
+ if (!children?.length) return;
535
+ const built = buildTransMessage(code, children, names);
536
+ if (!built || !built.text.trim()) return;
537
+ push(stableKey(built.text), built);
538
+ }
539
+ function explicitId(tag, names) {
540
+ if (tag.type !== "CallExpression") return void 0;
541
+ const callee = tag.callee;
542
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
543
+ const prop = callee.property;
544
+ if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
545
+ const obj = callee.object;
546
+ if (!isTReference(obj, names)) return void 0;
547
+ const args = tag.arguments;
548
+ const first = args[0];
549
+ if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
550
+ return {
551
+ key: first.value,
552
+ refStart: obj.start,
553
+ refEnd: obj.end
554
+ };
555
+ }
556
+ function buildTransMessage(code, children, names) {
557
+ const params = [];
558
+ const components = [];
559
+ const takenParams = /* @__PURE__ */ new Map();
560
+ const takenTags = /* @__PURE__ */ new Map();
561
+ function walkChildren(nodes) {
562
+ let text = "";
563
+ for (const child of nodes) if (child.type === "JSXText") text += escapeText(cleanJsxText(child.value));
564
+ else if (child.type === "JSXExpressionContainer") {
565
+ const expr = child.expression;
566
+ if (expr.type === "JSXEmptyExpression") continue;
567
+ if (expr.type === "StringLiteral") {
568
+ text += escapeText(expr.value);
569
+ continue;
570
+ }
571
+ if (containsTaggedT(expr, names)) return void 0;
572
+ const source = code.slice(expr.start, expr.end);
573
+ const name = uniqueName(deriveName(expr, params.length), source, takenParams);
574
+ params.push({
575
+ name,
576
+ start: expr.start,
577
+ end: expr.end
578
+ });
579
+ text += `{${name}}`;
580
+ } else if (child.type === "JSXElement") {
581
+ const opening = child.openingElement;
582
+ const nameNode = opening.name;
583
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
584
+ const source = selfClosedSource(code, opening);
585
+ const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
586
+ if (!components.some((c) => c.name === tag)) components.push({
587
+ name: tag,
588
+ source
589
+ });
590
+ if (!child.closingElement) text += `<${tag}/>`;
591
+ else {
592
+ const inner = walkChildren(child.children);
593
+ if (inner === void 0) return void 0;
594
+ text += `<${tag}>${inner}</${tag}>`;
595
+ }
596
+ } else return;
597
+ return text;
421
598
  }
422
- ];
423
- const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
424
- function readDependencies(root) {
425
- const path = join(root, "package.json");
426
- if (!existsSync(path)) return {};
599
+ const text = walkChildren(children);
600
+ if (text === void 0) return void 0;
601
+ return {
602
+ text,
603
+ params,
604
+ components
605
+ };
606
+ }
607
+ function cleanJsxText(raw) {
608
+ const lines = raw.split(/\r\n|[\r\n]/);
609
+ let out = "";
610
+ for (let i = 0; i < lines.length; i++) {
611
+ let line = lines[i].replace(/\t/g, " ");
612
+ if (i !== 0) line = line.replace(/^ +/, "");
613
+ if (i !== lines.length - 1) line = line.replace(/ +$/, "");
614
+ if (!line) continue;
615
+ if (out && i !== 0) out += " ";
616
+ out += line;
617
+ }
618
+ return out;
619
+ }
620
+ function selfClosedSource(code, opening) {
621
+ const src = code.slice(opening.start, opening.end);
622
+ return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
623
+ }
624
+ function containsTaggedT(node, names) {
625
+ let found = false;
626
+ walk$1(node, (n) => {
627
+ if (n.type !== "TaggedTemplateExpression") return;
628
+ const tag = n.tag;
629
+ if (isTReference(tag, names) || explicitId(tag, names)) found = true;
630
+ });
631
+ return found;
632
+ }
633
+ function isTReference(node, names) {
634
+ if (node.type === "Identifier") return names.has(node.name);
635
+ if (node.type === "MemberExpression" && !node.computed) {
636
+ const prop = node.property;
637
+ return prop.type === "Identifier" && names.has(prop.name);
638
+ }
639
+ return false;
640
+ }
641
+ function buildMessage(code, quasi, names) {
642
+ const quasis = quasi.quasis;
643
+ const expressions = quasi.expressions;
644
+ const params = [];
645
+ const taken = /* @__PURE__ */ new Map();
646
+ let text = escapeText(cookedValue(quasis[0]));
647
+ for (let i = 0; i < expressions.length; i++) {
648
+ const expr = expressions[i];
649
+ if (!expr) return void 0;
650
+ if (containsTaggedT(expr, names)) return void 0;
651
+ const source = code.slice(expr.start, expr.end);
652
+ const name = uniqueName(deriveName(expr, i), source, taken);
653
+ params.push({
654
+ name,
655
+ start: expr.start,
656
+ end: expr.end
657
+ });
658
+ text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
659
+ }
660
+ return {
661
+ text,
662
+ params
663
+ };
664
+ }
665
+ function cookedValue(element) {
666
+ if (!element) return "";
667
+ const value = element.value;
668
+ return value.cooked ?? value.raw;
669
+ }
670
+ function escapeText(text) {
671
+ return text.replace(/[{}]/g, (m) => m + m);
672
+ }
673
+ function deriveName(expr, index) {
674
+ if (expr.type === "Identifier") return expr.name;
675
+ if (expr.type === "MemberExpression" && !expr.computed) {
676
+ const prop = expr.property;
677
+ if (prop.type === "Identifier") return prop.name;
678
+ }
679
+ return `_${index}`;
680
+ }
681
+ function uniqueName(base, source, taken) {
682
+ let name = base;
683
+ let n = 2;
684
+ while (taken.has(name) && taken.get(name) !== source) {
685
+ name = `${base}${n}`;
686
+ n += 1;
687
+ }
688
+ taken.set(name, source);
689
+ return name;
690
+ }
691
+ function walk$1(node, visit) {
692
+ visit(node);
693
+ for (const key in node) {
694
+ if (SKIP_KEYS.has(key)) continue;
695
+ const value = node[key];
696
+ if (Array.isArray(value)) {
697
+ for (const item of value) if (isNode(item)) walk$1(item, visit);
698
+ } else if (isNode(value)) walk$1(value, visit);
699
+ }
700
+ }
701
+ function isNode(value) {
702
+ return typeof value === "object" && value !== null && typeof value.type === "string";
703
+ }
704
+ //#endregion
705
+ //#region src/sfc.ts
706
+ const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
707
+ function analyzeFile(code, file) {
708
+ if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
427
709
  try {
428
- const pkg = JSON.parse(readFileSync(path, "utf8"));
710
+ return analyze(code, file);
711
+ } catch (error) {
429
712
  return {
430
- ...pkg.dependencies,
431
- ...pkg.devDependencies
713
+ tagged: [],
714
+ usedKeys: [],
715
+ strayImports: [],
716
+ missed: [],
717
+ parseError: parseErrorMessage(error)
432
718
  };
433
- } catch {
434
- return {};
435
719
  }
436
720
  }
437
- function cliReachable(root) {
438
- const bin = join(root, "node_modules", ".bin");
439
- return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
721
+ const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
722
+ const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
723
+ const COMMENT_RE = /<!--[\s\S]*?-->/g;
724
+ const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
725
+ const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
726
+ const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
727
+ function analyzeSfc(code, file) {
728
+ const svelte = file.endsWith(".svelte");
729
+ const tNames = svelte ? ["t", "$t"] : ["t"];
730
+ const tagged = [];
731
+ const usedKeys = [];
732
+ const strayImports = [];
733
+ const missed = [];
734
+ const renamed = /* @__PURE__ */ new Set();
735
+ const lineAt = lineCounter(code);
736
+ let parseError;
737
+ const block = (content, offset) => {
738
+ const segment = analyzeSegment(content, file, { tNames });
739
+ parseError ??= segment.error;
740
+ for (const name of segment.renamed) renamed.add(name);
741
+ merge(segment.analysis, offset, false);
742
+ };
743
+ const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
744
+ if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1].length);
745
+ for (const match of code.matchAll(SCRIPT_RE)) {
746
+ const content = match[2];
747
+ if (content) block(content, match.index + match[1].length);
748
+ }
749
+ const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
750
+ const markupOptions = {
751
+ tNames,
752
+ renamed: [...renamed]
753
+ };
754
+ const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
755
+ let range = 0;
756
+ let consumedTo = 0;
757
+ for (const match of markup.matchAll(candidatePattern(svelte, renamed))) {
758
+ const start = match.index;
759
+ if (start < consumedTo) continue;
760
+ while (range < ranges.length && ranges[range][1] <= start) range += 1;
761
+ if (range >= ranges.length || start < ranges[range][0]) continue;
762
+ const end = expressionExtent(markup, start, match[0].length);
763
+ if (end === void 0) continue;
764
+ merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);
765
+ consumedTo = end;
766
+ }
767
+ return {
768
+ tagged,
769
+ usedKeys,
770
+ strayImports,
771
+ missed,
772
+ ...parseError && { parseError }
773
+ };
774
+ function merge(analysis, offset, markupSegment) {
775
+ if (!analysis) return;
776
+ const lines = lineAt(offset) - 1;
777
+ for (const msg of analysis.tagged) tagged.push({
778
+ ...msg,
779
+ start: msg.start + offset,
780
+ end: msg.end + offset,
781
+ line: msg.line + lines,
782
+ tagStart: msg.tagStart + offset,
783
+ tagEnd: msg.tagEnd + offset,
784
+ params: msg.params.map((p) => ({
785
+ ...p,
786
+ start: p.start + offset,
787
+ end: p.end + offset
788
+ })),
789
+ ...markupSegment && { singleQuote: true }
790
+ });
791
+ for (const call of analysis.missed) missed.push({
792
+ ...call,
793
+ start: call.start + offset,
794
+ line: call.line + lines
795
+ });
796
+ usedKeys.push(...analysis.usedKeys);
797
+ strayImports.push(...analysis.strayImports);
798
+ }
799
+ }
800
+ function candidatePattern(svelte, renamed) {
801
+ const names = [.../* @__PURE__ */ new Set(["t", ...[...renamed].map((name) => name.replace(/^\$/, ""))])].map((name) => name.replace(/[$]/g, "\\$")).join("|");
802
+ return new RegExp(`(?<![\\w$])${svelte ? "\\$?" : ""}(?:${names})(?=[\`(]|\\.id\\()`, "g");
803
+ }
804
+ function lineCounter(code) {
805
+ const breaks = [];
806
+ for (let i = code.indexOf("\n"); i !== -1; i = code.indexOf("\n", i + 1)) breaks.push(i);
807
+ return (offset) => {
808
+ let low = 0;
809
+ let high = breaks.length;
810
+ while (low < high) {
811
+ const mid = low + high >> 1;
812
+ if (breaks[mid] < offset) low = mid + 1;
813
+ else high = mid;
814
+ }
815
+ return low + 1;
816
+ };
817
+ }
818
+ function analyzeSegment(code, file, options) {
819
+ try {
820
+ return analyzeScript(code, file, options);
821
+ } catch (error) {
822
+ return {
823
+ renamed: [],
824
+ error: parseErrorMessage(error)
825
+ };
826
+ }
827
+ }
828
+ function blank(source, re) {
829
+ return source.replace(re, (m) => " ".repeat(m.length));
830
+ }
831
+ function braceRanges(markup) {
832
+ const ranges = [];
833
+ let i = 0;
834
+ while (i < markup.length) {
835
+ if (markup[i] === "{") {
836
+ const end = balancedEnd(markup, i);
837
+ if (end !== void 0) {
838
+ ranges.push([i + 1, end - 1]);
839
+ i = end;
840
+ continue;
841
+ }
842
+ }
843
+ i += 1;
844
+ }
845
+ return ranges;
846
+ }
847
+ function vueExpressionRanges(markup) {
848
+ const ranges = [];
849
+ for (const match of markup.matchAll(MUSTACHE_RE)) ranges.push([match.index + 2, match.index + match[0].length - 2]);
850
+ for (const match of markup.matchAll(DIRECTIVE_RE)) {
851
+ const valueStart = match.index + match[0].length - match[1].length + 1;
852
+ ranges.push([valueStart, valueStart + match[1].length - 2]);
853
+ }
854
+ return ranges.sort((a, b) => a[0] - b[0]);
855
+ }
856
+ function expressionExtent(code, start, nameLength) {
857
+ const i = start + nameLength;
858
+ if (code.startsWith(".id(", i)) {
859
+ const close = balancedEnd(code, i + 3);
860
+ if (close === void 0 || code[close] !== "`") return void 0;
861
+ return balancedEnd(code, close);
862
+ }
863
+ if (code[i] === "`" || code[i] === "(") return balancedEnd(code, i);
864
+ }
865
+ function balancedEnd(code, open) {
866
+ const stack = [];
867
+ let i = open;
868
+ while (i < code.length) {
869
+ const ch = code[i];
870
+ if (stack[stack.length - 1] === "`") {
871
+ if (ch === "\\") i += 1;
872
+ else if (ch === "`") stack.pop();
873
+ else if (ch === "$" && code[i + 1] === "{") {
874
+ stack.push("{");
875
+ i += 1;
876
+ }
877
+ } else if (ch === "'" || ch === "\"") i = stringEnd(code, i);
878
+ else if (ch === "`" || ch === "(" || ch === "{") stack.push(ch);
879
+ else if (ch === ")" || ch === "}") {
880
+ if (stack[stack.length - 1] !== (ch === ")" ? "(" : "{")) return void 0;
881
+ stack.pop();
882
+ }
883
+ i += 1;
884
+ if (stack.length === 0) return i;
885
+ }
886
+ }
887
+ function stringEnd(code, start) {
888
+ const quote = code[start];
889
+ let i = start + 1;
890
+ while (i < code.length) if (code[i] === "\\") i += 2;
891
+ else if (code[i] === quote) return i;
892
+ else i += 1;
893
+ return code.length;
440
894
  }
441
- const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
442
- function detectHost(root) {
443
- const deps = readDependencies(root);
444
- return HOSTS.find((host) => deps[host.dep]);
895
+ //#endregion
896
+ //#region src/extract.ts
897
+ async function extractProject(cfg) {
898
+ const files = await glob(cfg.include, {
899
+ cwd: cfg.root,
900
+ ignore: cfg.exclude,
901
+ absolute: true
902
+ });
903
+ const registry = new MessageRegistry();
904
+ for (const file of files.sort()) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
905
+ return registry;
445
906
  }
446
- function configSource(options, typescript) {
447
- const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
448
- if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
449
- if (options.dir) fields.push(` dir: '${options.dir}',`);
450
- const body = `export default {\n${fields.join("\n")}\n}`;
451
- if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
452
- return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
907
+ async function collectOrigins(cfg, reuse) {
908
+ const registry = reuse ?? await extractProject(cfg);
909
+ const origins = Object.create(null);
910
+ for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
911
+ return origins;
453
912
  }
454
- async function init(input = {}) {
455
- const root = input.root ?? process.cwd();
456
- const created = [];
457
- const skipped = [];
458
- const renamed = [];
459
- const refused = [];
460
- const typed = input.locales?.flatMap((locale) => {
461
- if (isLocaleTag(locale)) return [locale];
462
- const near = suggestTag(locale);
463
- if (near) renamed.push({
464
- from: locale,
465
- to: near
466
- });
467
- else refused.push(locale);
468
- return near ? [near] : [];
469
- });
470
- const locales = typed && [...new Set(typed)];
471
- let sourceLocale = input.sourceLocale;
472
- if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
473
- const near = suggestTag(sourceLocale);
474
- if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
475
- renamed.push({
476
- from: sourceLocale,
477
- to: near
913
+ function syncCatalogs(cfg, catalogs, registry) {
914
+ const added = {};
915
+ const replaced = [];
916
+ const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
917
+ for (const [key, msg] of registry.messages()) {
918
+ const before = own(source, key);
919
+ if (before === msg.message) continue;
920
+ source[key] = msg.message;
921
+ if (before) replaced.push({
922
+ key,
923
+ before
478
924
  });
479
- sourceLocale = near;
480
- }
481
- const options = {
482
- ...input,
483
- locales,
484
- sourceLocale
485
- };
486
- const existing = findConfigFile(root);
487
- const typescript = existsSync(join(root, "tsconfig.json"));
488
- const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
489
- if (existing) skipped.push(existing);
490
- else {
491
- writeFileSync(join(root, configFile), configSource(options, typescript));
492
- created.push(configFile);
925
+ else (added[cfg.sourceLocale] ??= []).push(key);
493
926
  }
494
- const fromFile = existing ? await loadConfigFile(root) : {};
495
- const scaffold = {
496
- dir: options.dir ?? fromFile.dir,
497
- sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
498
- locales: options.locales ?? fromFile.locales
499
- };
500
- const dir = join(root, scaffold.dir ?? "locales");
501
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
502
- for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
503
- const file = join(dir, `${locale}.json`);
504
- const label = relative(root, file).replaceAll("\\", "/");
505
- if (existsSync(file)) skipped.push(label);
506
- else {
507
- writeFileSync(file, "{}\n");
508
- created.push(label);
927
+ const needed = Object.keys(source);
928
+ for (const locale of cfg.locales) {
929
+ if (locale === cfg.sourceLocale) continue;
930
+ const catalog = catalogs[locale] ??= emptyCatalog();
931
+ for (const key of needed) if (own(catalog, key) === void 0) {
932
+ catalog[key] = "";
933
+ (added[locale] ??= []).push(key);
509
934
  }
510
935
  }
511
- const host = detectHost(root);
512
- const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
513
936
  return {
514
- created,
515
- skipped,
516
- host: host?.name,
517
- configFile,
518
- next,
519
- renamed,
520
- refused
937
+ added,
938
+ replaced
939
+ };
940
+ }
941
+ function shippedCatalogs(cfg, catalogs, registry, options = {}) {
942
+ const source = Object.assign(emptyCatalog(), flatten(catalogs[cfg.sourceLocale] ?? {}));
943
+ for (const [key, msg] of registry.messages()) if (options.newKeys !== false || own(source, key) !== void 0) source[key] = msg.message;
944
+ return {
945
+ ...catalogs,
946
+ [cfg.sourceLocale]: source
521
947
  };
522
948
  }
949
+ function pruneCatalogs(cfg, catalogs, registry) {
950
+ const removed = {};
951
+ if (registry.parseErrors().length > 0) return removed;
952
+ const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
953
+ for (const locale of cfg.locales) {
954
+ const catalog = catalogs[locale];
955
+ if (!catalog) continue;
956
+ for (const key of Object.keys(catalog)) if (!keep.has(key)) {
957
+ delete catalog[key];
958
+ (removed[locale] ??= []).push(key);
959
+ }
960
+ }
961
+ return removed;
962
+ }
963
+ //#endregion
964
+ //#region src/text.ts
965
+ function counted(count, noun, many = `${noun}s`) {
966
+ return `${count} ${count === 1 ? noun : many}`;
967
+ }
968
+ function truncate(text, max) {
969
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
970
+ }
523
971
  //#endregion
524
972
  //#region src/validate.ts
525
973
  const read = (message) => parse(message, parseIcu);
@@ -533,10 +981,10 @@ const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
533
981
  const EXACT = /^=\d+$/;
534
982
  function shapes(message) {
535
983
  const out = /* @__PURE__ */ new Map();
536
- walk$1(read(message), out);
984
+ walk(read(message), out);
537
985
  return out;
538
986
  }
539
- function walk$1(nodes, out) {
987
+ function walk(nodes, out) {
540
988
  for (const node of nodes) {
541
989
  if (node.kind !== "param" || !node.variants) continue;
542
990
  const selectors = node.variants.map(([key]) => key);
@@ -545,7 +993,7 @@ function walk$1(nodes, out) {
545
993
  plural: selectors.some((key) => PLURAL_CATEGORIES.has(key)),
546
994
  ordinal: node.ordinal === true
547
995
  });
548
- for (const [, body] of node.variants) walk$1(body, out);
996
+ for (const [, body] of node.variants) walk(body, out);
549
997
  }
550
998
  }
551
999
  function paramNames(message) {
@@ -669,948 +1117,1107 @@ const reachable = /* @__PURE__ */ new Map();
669
1117
  function reachableCategories(locale, ordinal) {
670
1118
  const type = ordinal ? "ordinal" : "cardinal";
671
1119
  const cacheKey = `${locale}\u0000${type}`;
672
- const hit = reachable.get(cacheKey);
673
- if (hit) return hit;
674
- let out;
675
- try {
676
- const rules = new Intl.PluralRules(locale.replace(/_/g, "-"), { type });
677
- const seen = /* @__PURE__ */ new Set();
678
- for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));
679
- out = [...seen];
680
- } catch {
681
- out = [];
682
- }
683
- reachable.set(cacheKey, out);
684
- return out;
685
- }
686
- //#endregion
687
- //#region src/check.ts
688
- function gatePasses(result) {
689
- return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
690
- }
691
- function check(cfg, catalogs, registry) {
692
- const extracted = registry.messages();
693
- const flat = {};
694
- for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
695
- const source = flat[cfg.sourceLocale] ?? {};
696
- const used = registry.usedKeys();
697
- const unknown = [];
698
- for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
699
- key,
700
- files
701
- });
702
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
703
- const missing = [];
704
- for (const key of extracted.keys()) if (!source[key]) missing.push({
705
- locale: cfg.sourceLocale,
706
- key,
707
- source: extracted.get(key)?.message
708
- });
709
- for (const locale of cfg.locales) {
710
- if (locale === cfg.sourceLocale) continue;
711
- for (const key of needed) if (!flat[locale]?.[key]) missing.push({
712
- locale,
713
- key,
714
- source: source[key] ?? extracted.get(key)?.message
715
- });
716
- }
717
- const broken = [];
718
- const add = (locale, key, issues) => {
719
- for (const issue of issues) broken.push({
720
- locale,
721
- key,
722
- severity: issue.severity,
723
- issue: issue.message
724
- });
725
- };
726
- const sourceText = Object.assign(emptyCatalog(), source);
727
- for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
728
- for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
729
- for (const locale of cfg.locales) {
730
- if (locale === cfg.sourceLocale) continue;
731
- for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
732
- if (!translated) continue;
733
- add(locale, key, validateMessage(translated, locale));
734
- const text = sourceText[key];
735
- if (text) add(locale, key, validatePair(text, translated));
736
- }
737
- }
738
- const extra = [];
739
- for (const locale of cfg.locales) {
740
- if (locale === cfg.sourceLocale) continue;
741
- for (const key of Object.keys(flat[locale] ?? {})) {
742
- if (source[key] !== void 0 || extracted.has(key)) continue;
743
- extra.push({
744
- locale,
745
- key,
746
- files: used.get(key) ?? []
747
- });
748
- }
749
- }
750
- return {
751
- ok: gatePasses({
752
- missing,
753
- unknown,
754
- broken
755
- }),
756
- missing,
757
- unknown,
758
- broken,
759
- extra
760
- };
761
- }
762
- function formatCheckResult(result, root) {
763
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
764
- const lines = [];
765
- if (result.missing.length > 0) {
766
- lines.push("missing translations:");
767
- for (const entry of result.missing) {
768
- const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
769
- lines.push(` [${entry.locale}] ${entry.key}${hint}`);
770
- }
771
- }
772
- if (result.unknown.length > 0) {
773
- lines.push("unknown keys (not in any catalog):");
774
- for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.map(show).join(", ")})`);
775
- }
776
- const errors = result.broken.filter((entry) => entry.severity === "error");
777
- if (errors.length > 0) {
778
- lines.push("broken translations:");
779
- for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1120
+ const hit = reachable.get(cacheKey);
1121
+ if (hit) return hit;
1122
+ let out;
1123
+ try {
1124
+ const rules = new Intl.PluralRules(locale.replace(/_/g, "-"), { type });
1125
+ const seen = /* @__PURE__ */ new Set();
1126
+ for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));
1127
+ out = [...seen];
1128
+ } catch {
1129
+ out = [];
780
1130
  }
781
- return lines.join("\n");
782
- }
783
- function checkNextSteps(result, cliReachable = true) {
784
- const steps = [];
785
- if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
786
- if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
787
- if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
788
- if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
789
- return steps.join("\n");
1131
+ reachable.set(cacheKey, out);
1132
+ return out;
790
1133
  }
791
- function formatCheckWarnings(result) {
792
- const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
793
- for (const entry of result.extra) lines.push(entry.files.length > 0 ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself` : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`);
794
- return lines.join("\n");
1134
+ //#endregion
1135
+ //#region src/findings.ts
1136
+ function siteOf(msg) {
1137
+ return {
1138
+ file: msg.file,
1139
+ line: msg.line,
1140
+ message: msg.message
1141
+ };
795
1142
  }
796
- function truncate(text, max) {
797
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
1143
+ function collisionEntries(registry) {
1144
+ return registry.collisions().map(({ key, kept, dropped }) => ({
1145
+ key,
1146
+ sites: [kept, ...dropped].map(siteOf)
1147
+ }));
798
1148
  }
799
- function githubCheckAnnotations(result, registry, root) {
1149
+ function scanFindings(cfg, registry, replaced = []) {
800
1150
  const messages = registry.messages();
801
- const contents = /* @__PURE__ */ new Map();
802
- const readSource = (file) => {
803
- if (!contents.has(file)) try {
804
- contents.set(file, readFileSync(file, "utf8"));
805
- } catch {
806
- contents.set(file, void 0);
807
- }
808
- return contents.get(file);
809
- };
810
- const lines = [];
811
- const byKey = /* @__PURE__ */ new Map();
812
- for (const entry of result.missing) {
813
- const grouped = byKey.get(entry.key);
814
- if (grouped) grouped.locales.push(entry.locale);
815
- else byKey.set(entry.key, {
816
- ...entry,
817
- locales: [entry.locale]
1151
+ const out = [];
1152
+ for (const { key, before } of replaced) {
1153
+ const msg = messages.get(key);
1154
+ if (msg) out.push({
1155
+ kind: "replaced",
1156
+ locale: cfg.sourceLocale,
1157
+ key,
1158
+ before,
1159
+ site: siteOf(msg)
818
1160
  });
819
1161
  }
820
- for (const entry of byKey.values()) {
821
- const origin = messages.get(entry.key);
822
- const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
823
- const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
824
- if (origin) {
825
- const file = relative(root, origin.file).replaceAll("\\", "/");
826
- const content = readSource(origin.file);
827
- const line = content === void 0 ? void 0 : lineAt(content, origin.start);
828
- lines.push(`::error file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
829
- } else lines.push(`::error::${text}`);
830
- }
831
- for (const entry of result.unknown) {
832
- const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
833
- const file = entry.files[0];
834
- lines.push(file ? `::error file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::error::${text}`);
1162
+ for (const entry of collisionEntries(registry)) out.push({
1163
+ kind: "collision",
1164
+ ...entry
1165
+ });
1166
+ for (const { name, file, line } of registry.missed()) out.push({
1167
+ kind: "renamed",
1168
+ name,
1169
+ file,
1170
+ line
1171
+ });
1172
+ for (const msg of messages.values()) {
1173
+ const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
1174
+ if (params.length > 0) out.push({
1175
+ kind: "positional",
1176
+ params,
1177
+ site: siteOf(msg)
1178
+ });
1179
+ const slice = escapedSyntax(msg.message);
1180
+ if (slice) out.push({
1181
+ kind: "escaped",
1182
+ slice,
1183
+ site: siteOf(msg)
1184
+ });
835
1185
  }
836
- for (const entry of result.broken) {
837
- const origin = messages.get(entry.key);
838
- const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
839
- const command = entry.severity === "error" ? "error" : "warning";
840
- if (!origin) {
841
- lines.push(`::${command}::${text}`);
1186
+ for (const { file, message } of registry.parseErrors()) out.push({
1187
+ kind: "unparsed",
1188
+ file,
1189
+ message
1190
+ });
1191
+ return out;
1192
+ }
1193
+ function sourcePlace(at, root) {
1194
+ const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1195
+ return at.line ? `${file}:${at.line}` : file;
1196
+ }
1197
+ function quoted(at, root) {
1198
+ return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1199
+ }
1200
+ function formatCollision({ key, sites }, root) {
1201
+ const [kept, ...others] = sites;
1202
+ const texts = new Set(sites.map((at) => at.message)).size;
1203
+ return `${key}: one key with ${counted(texts, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
1204
+ }
1205
+ function formatFinding(finding, root) {
1206
+ switch (finding.kind) {
1207
+ case "collision": return formatCollision(finding, root);
1208
+ case "replaced": {
1209
+ const place = sourcePlace(finding.site, root);
1210
+ return finding.edited ? `${finding.locale}.json: your edit of "${finding.key}" was replaced, its text lives in ${place}: change it there` : `${finding.locale}: ${finding.key} follows the code (${place}): "${truncate(finding.site.message, 40)}", was "${truncate(finding.before, 40)}"`;
1211
+ }
1212
+ case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
1213
+ case "positional": {
1214
+ const names = finding.params.map((name) => `{${name}}`).join(", ");
1215
+ return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
1216
+ }
1217
+ case "escaped": return `${sourcePlace(finding.site, root)}: ${finding.slice} renders as literal text, a tagged template has no params (use t(key, params) for a plural or format block, or pass a \${…} value)`;
1218
+ case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
1219
+ case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
1220
+ }
1221
+ }
1222
+ function findingId(finding) {
1223
+ switch (finding.kind) {
1224
+ case "collision":
1225
+ case "replaced": return `${finding.kind}:${finding.key}`;
1226
+ case "outdated": return `outdated:${finding.locale}:${finding.key}`;
1227
+ case "renamed": return `renamed:${finding.file}:${finding.name}`;
1228
+ case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1229
+ case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1230
+ case "unparsed": return `unparsed:${finding.file}`;
1231
+ }
1232
+ }
1233
+ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
1234
+ const shown = /* @__PURE__ */ new Map();
1235
+ return { report(channel, findings) {
1236
+ const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
1237
+ const now = /* @__PURE__ */ new Set();
1238
+ const fresh = [];
1239
+ for (const finding of findings) {
1240
+ const id = findingId(finding);
1241
+ if (now.has(id)) continue;
1242
+ now.add(id);
1243
+ if (!before.has(id)) fresh.push(finding);
1244
+ }
1245
+ shown.set(channel, now);
1246
+ for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
1247
+ if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
1248
+ } };
1249
+ }
1250
+ //#endregion
1251
+ //#region src/pseudo.ts
1252
+ const PSEUDO_LOCALE = "en-XA";
1253
+ const ACCENTS = {
1254
+ a: "á",
1255
+ b: "ƀ",
1256
+ c: "ç",
1257
+ d: "đ",
1258
+ e: "é",
1259
+ f: "ƒ",
1260
+ g: "ğ",
1261
+ h: "ĥ",
1262
+ i: "í",
1263
+ j: "ĵ",
1264
+ k: "ķ",
1265
+ l: "ĺ",
1266
+ m: "ɱ",
1267
+ n: "ñ",
1268
+ o: "ó",
1269
+ p: "þ",
1270
+ q: "ǫ",
1271
+ r: "ŕ",
1272
+ s: "š",
1273
+ t: "ţ",
1274
+ u: "ú",
1275
+ v: "ṽ",
1276
+ w: "ŵ",
1277
+ x: "ẋ",
1278
+ y: "ý",
1279
+ z: "ž",
1280
+ A: "Á",
1281
+ B: "Ɓ",
1282
+ C: "Ç",
1283
+ D: "Đ",
1284
+ E: "É",
1285
+ F: "Ƒ",
1286
+ G: "Ğ",
1287
+ H: "Ĥ",
1288
+ I: "Í",
1289
+ J: "Ĵ",
1290
+ K: "Ķ",
1291
+ L: "Ĺ",
1292
+ M: "Ḿ",
1293
+ N: "Ñ",
1294
+ O: "Ó",
1295
+ P: "Þ",
1296
+ Q: "Ǫ",
1297
+ R: "Ŕ",
1298
+ S: "Š",
1299
+ T: "Ţ",
1300
+ U: "Ú",
1301
+ V: "Ṽ",
1302
+ W: "Ŵ",
1303
+ X: "Ẍ",
1304
+ Y: "Ý",
1305
+ Z: "Ž"
1306
+ };
1307
+ const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
1308
+ function pseudoLocalize(message) {
1309
+ let out = "";
1310
+ let letters = 0;
1311
+ let i = 0;
1312
+ while (i < message.length) {
1313
+ const two = message.slice(i, i + 2);
1314
+ if (two === "{{" || two === "}}" || two === "||" || two === "##") {
1315
+ out += two;
1316
+ i += 2;
842
1317
  continue;
843
1318
  }
844
- const file = relative(root, origin.file).replaceAll("\\", "/");
845
- const content = readSource(origin.file);
846
- const line = content === void 0 ? void 0 : lineAt(content, origin.start);
847
- lines.push(`::${command} file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
848
- }
849
- for (const entry of result.extra) {
850
- const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);
851
- const file = entry.files[0];
852
- lines.push(file ? `::warning file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::warning::${text}`);
1319
+ const ch = message[i];
1320
+ if (ch === "{") {
1321
+ const end = matchBrace$1(message, i);
1322
+ out += message.slice(i, end);
1323
+ i = end;
1324
+ continue;
1325
+ }
1326
+ if (ch === "<") {
1327
+ TAG_AT.lastIndex = i;
1328
+ const m = TAG_AT.exec(message);
1329
+ if (m) {
1330
+ out += m[0];
1331
+ i += m[0].length;
1332
+ continue;
1333
+ }
1334
+ }
1335
+ const mapped = ACCENTS[ch];
1336
+ if (mapped) {
1337
+ out += mapped;
1338
+ letters += 1;
1339
+ } else out += ch;
1340
+ i += 1;
853
1341
  }
854
- return lines;
855
- }
856
- function lineAt(content, offset) {
857
- let line = 1;
858
- const end = Math.min(offset, content.length);
859
- for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
860
- return line;
1342
+ const pad = "~".repeat(Math.ceil(letters / 3));
1343
+ return `⟦${out}${pad ? " " + pad : ""}⟧`;
861
1344
  }
862
- function escapeData(text) {
863
- return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
1345
+ function matchBrace$1(message, start) {
1346
+ let depth = 0;
1347
+ for (let i = start; i < message.length; i++) {
1348
+ const two = message.slice(i, i + 2);
1349
+ if (two === "{{" || two === "}}") {
1350
+ i += 1;
1351
+ continue;
1352
+ }
1353
+ const ch = message[i];
1354
+ if (ch === "{") depth += 1;
1355
+ else if (ch === "}") {
1356
+ depth -= 1;
1357
+ if (depth === 0) return i + 1;
1358
+ }
1359
+ }
1360
+ return message.length;
864
1361
  }
865
- function escapeProperty(text) {
866
- return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
1362
+ function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
1363
+ const source = catalogs[cfg.sourceLocale] ?? {};
1364
+ const target = emptyCatalog();
1365
+ for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
1366
+ catalogs[locale] = target;
1367
+ return Object.keys(target).filter((key) => target[key]);
867
1368
  }
868
1369
  //#endregion
869
- //#region src/params.ts
870
- const NUMBER_FORMATS = /* @__PURE__ */ new Set([
871
- "number",
872
- "integer",
873
- "percent",
874
- "currency"
875
- ]);
876
- const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
877
- function collectParams(message) {
878
- const out = /* @__PURE__ */ new Map();
879
- visit(parse(message, parseIcu), out);
880
- return out;
1370
+ //#region src/config.ts
1371
+ function resolveConfig(config = {}) {
1372
+ const root = resolve(config.root ?? process.cwd());
1373
+ const dir = resolve(root, config.dir ?? "locales");
1374
+ const sourceLocale = config.sourceLocale ?? "en";
1375
+ const localesDeclared = config.locales !== void 0;
1376
+ const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
1377
+ if (!localesDeclared && existsSync(dir)) {
1378
+ for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
1379
+ }
1380
+ return {
1381
+ root,
1382
+ dir,
1383
+ sourceLocale,
1384
+ localesDeclared,
1385
+ routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
1386
+ icu: config.icu,
1387
+ relative: config.relative,
1388
+ locales: [...locales],
1389
+ include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
1390
+ exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
1391
+ dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts,
1392
+ translate: config.translate ?? {},
1393
+ render: config.render ?? {},
1394
+ bundle: config.bundle ?? {}
1395
+ };
881
1396
  }
882
- function visit(nodes, out) {
883
- for (const node of nodes) {
884
- if (node.kind !== "param") continue;
885
- const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
886
- out.set(node.name, types);
887
- if (node.variants) {
888
- for (const [key, body] of node.variants) {
889
- if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
890
- else if (key !== "other") types.add("string");
891
- visit(body, out);
892
- }
893
- if (types.size === 0) types.add("string");
894
- } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
895
- else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
896
- else types.add("unknown");
1397
+ const CONFIG_FILES = [
1398
+ "verbaly.config.js",
1399
+ "verbaly.config.mjs",
1400
+ "verbaly.config.ts",
1401
+ "verbaly.config.mts",
1402
+ "verbaly.config.json"
1403
+ ];
1404
+ function findConfigFile(root) {
1405
+ return CONFIG_FILES.find((name) => existsSync(join(root, name)));
1406
+ }
1407
+ async function loadConfigFile(root) {
1408
+ for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
1409
+ const path = join(root, name);
1410
+ if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
1411
+ }
1412
+ for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
1413
+ const path = join(root, name);
1414
+ if (existsSync(path)) return loadTsConfig(path);
897
1415
  }
1416
+ const jsonPath = join(root, "verbaly.config.json");
1417
+ if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
1418
+ return {};
898
1419
  }
899
- function renderParamType(types) {
900
- if (types.has("unknown") || types.size === 0) return "unknown";
901
- const members = /* @__PURE__ */ new Set();
902
- if (types.has("number")) members.add("number");
903
- if (types.has("string")) members.add("string");
904
- if (types.has("date")) for (const m of [
905
- "Date",
906
- "number",
907
- "string"
908
- ]) members.add(m);
909
- return [...members].join(" | ");
1420
+ function readJsonConfig(path) {
1421
+ const content = readFileSync(path, "utf8");
1422
+ const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
1423
+ try {
1424
+ return JSON.parse(body);
1425
+ } catch (error) {
1426
+ throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
1427
+ }
910
1428
  }
911
- function generateDts(catalog, options = {}) {
912
- const lines = [];
913
- for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
914
- const params = collectParams(message);
915
- if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
916
- else {
917
- const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
918
- lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
919
- }
1429
+ async function loadTsConfig(path) {
1430
+ try {
1431
+ const { bundleRequire } = await import("bundle-require");
1432
+ const { mod } = await bundleRequire({ filepath: path });
1433
+ return mod.default ?? {};
1434
+ } catch (error) {
1435
+ if (isModuleNotFound(error, "esbuild")) throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, { cause: error });
1436
+ throw error;
920
1437
  }
921
- return `// generated by verbaly: do not edit
922
- declare module 'virtual:verbaly' {
923
- export interface VerbalyMessages {
924
- ${lines.join("\n")}
925
- }
926
- export type VerbalyKey = keyof VerbalyMessages & string;
927
-
928
- export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
929
- export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
930
-
931
- export const verbaly: import('verbaly').Verbaly<VerbalyKey>;
932
-
933
- export const sourceLocale: string;
934
- export const locales: string[];
935
- export const routing: import('verbaly').Routing;
936
- export function localePath(
937
- locale: string,
938
- options?: { path?: string; base?: string },
939
- ): string;
940
- export function localeFromPath(options?: {
941
- path?: string;
942
- base?: string;
943
- }): string | undefined;
944
- export function loadMessages(locale: string): Promise<Record<string, string>>;${options.inlineCatalog ? "\n export function adoptPage(options?: {\n root?: ParentNode;\n path?: string;\n }): string | undefined;" : ""}
945
- export function createInstance(
946
- options?: import('verbaly').VerbalyOptions<VerbalyKey>,
947
- ): import('verbaly').Verbaly<VerbalyKey>;
948
- export function createRequestInstance(
949
- locale: string,
950
- ): Promise<import('verbaly').Verbaly<VerbalyKey>>;
951
-
952
- export function t<K extends VerbalyKey>(
953
- key: K,
954
- ...args: [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
955
- ): string;
956
- export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
957
- export namespace t {
958
- export function id(
959
- key: string,
960
- ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
961
- }
962
-
963
- export function setLocale(locale: string): Promise<void>;
964
- export function switchLocale(
965
- locale: string,
966
- options?: Omit<
967
- import('verbaly').SwitchLocaleOptions,
968
- 'routing' | 'supported' | 'sourceLocale'
969
- >,
970
- ): Promise<void>;
971
- export function getLocale(): string;
972
- export function subscribe(listener: () => void): () => void;
973
1438
  }
974
-
975
- declare module 'virtual:verbaly/locale/*' {
976
- const messages: Record<string, string>;
977
- export default messages;
1439
+ function isModuleNotFound(error, name) {
1440
+ return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
978
1441
  }
979
- `;
1442
+ function targetLocales(cfg, override) {
1443
+ return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
980
1444
  }
981
- function writeDts(cfg, catalog, file) {
982
- const target = file === void 0 ? cfg.dts : file;
983
- if (target === false) return;
984
- file = target ?? join(cfg.root, "verbaly.d.ts");
985
- const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
986
- try {
987
- if (readFileSync(file, "utf8") === content) return;
988
- } catch {}
989
- mkdirSync(dirname(file), { recursive: true });
990
- writeFileSync(file, content);
1445
+ async function loadConfig(root, overrides = {}) {
1446
+ return resolveConfig({
1447
+ ...await loadConfigFile(root),
1448
+ ...definedOnly(overrides),
1449
+ root
1450
+ });
991
1451
  }
992
- //#endregion
993
- //#region src/text.ts
994
- function counted(count, noun, many = `${noun}s`) {
995
- return `${count} ${count === 1 ? noun : many}`;
1452
+ function definedOnly(config) {
1453
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
996
1454
  }
997
1455
  //#endregion
998
- //#region src/bundle.ts
999
- function isExcluded(key, prefixes) {
1000
- return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
1001
- }
1002
- function auditBundle(cfg, catalogs, registry) {
1003
- const prefixes = cfg.bundle.exclude ?? [];
1004
- if (prefixes.length === 0) return [];
1005
- const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
1006
- const used = registry.usedKeys();
1007
- const issues = [];
1008
- for (const prefix of prefixes) {
1009
- if (!source.some((key) => isExcluded(key, [prefix]))) {
1010
- issues.push({
1011
- prefix,
1012
- problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
1013
- fix: "check the spelling against your catalog, or drop it from bundle.exclude"
1014
- });
1015
- continue;
1016
- }
1017
- const files = /* @__PURE__ */ new Set();
1018
- for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
1019
- if (files.size > 0) issues.push({
1020
- prefix,
1021
- problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
1022
- fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
1023
- });
1456
+ //#region src/tag.ts
1457
+ function isLocaleTag(tag) {
1458
+ try {
1459
+ Intl.getCanonicalLocales(tag);
1460
+ return true;
1461
+ } catch {
1462
+ return false;
1024
1463
  }
1025
- return issues;
1026
1464
  }
1027
- function formatBundleIssue(issue) {
1028
- return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
1465
+ function suggestTag(tag) {
1466
+ const near = tag.replace(/_/g, "-");
1467
+ return near !== tag && isLocaleTag(near) ? near : void 0;
1029
1468
  }
1030
- //#endregion
1031
- //#region src/warn.ts
1032
- const warned = /* @__PURE__ */ new Set();
1033
- function warnOnce(message, dedupeKey = message) {
1034
- if (warned.has(dedupeKey)) return;
1035
- warned.add(dedupeKey);
1036
- console.warn(`[verbaly] ${message}`);
1469
+ function projectLocale(tag, locales) {
1470
+ if (locales.includes(tag)) return tag;
1471
+ const plain = (value) => value.replace(/_/g, "-").toLowerCase();
1472
+ return locales.find((locale) => plain(locale) === plain(tag));
1037
1473
  }
1038
1474
  //#endregion
1039
- //#region src/registry.ts
1040
- var MessageRegistry = class {
1041
- files = /* @__PURE__ */ new Map();
1042
- update(file, analysis) {
1043
- this.files.set(file, analysis);
1044
- }
1045
- remove(file) {
1046
- this.files.delete(file);
1047
- }
1048
- messages() {
1049
- const out = /* @__PURE__ */ new Map();
1050
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
1051
- const existing = out.get(msg.key);
1052
- if (existing) {
1053
- if (existing.message !== msg.message) warnOnce(`key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped`, `collision:${msg.key}`);
1054
- continue;
1055
- }
1056
- out.set(msg.key, msg);
1057
- }
1058
- return out;
1059
- }
1060
- usedKeys(strict = false) {
1061
- const out = /* @__PURE__ */ new Map();
1062
- for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
1063
- if (strict && used.loose) continue;
1064
- const files = out.get(used.key) ?? [];
1065
- if (!files.includes(used.file)) files.push(used.file);
1066
- out.set(used.key, files);
1067
- }
1068
- return out;
1475
+ //#region src/init.ts
1476
+ const HOSTS = [
1477
+ {
1478
+ name: "nuxt",
1479
+ dep: "nuxt",
1480
+ pkg: "@verbaly/nuxt",
1481
+ wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
1482
+ },
1483
+ {
1484
+ name: "next",
1485
+ dep: "next",
1486
+ pkg: "@verbaly/next",
1487
+ wire: "wrap the export of next.config with withVerbaly"
1488
+ },
1489
+ {
1490
+ name: "sveltekit",
1491
+ dep: "@sveltejs/kit",
1492
+ pkg: "@verbaly/vite",
1493
+ wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
1494
+ },
1495
+ {
1496
+ name: "astro",
1497
+ dep: "astro",
1498
+ pkg: "@verbaly/astro",
1499
+ wire: "add verbaly() to the integrations in astro.config"
1500
+ },
1501
+ {
1502
+ name: "vite",
1503
+ dep: "vite",
1504
+ pkg: "@verbaly/vite",
1505
+ wire: "add verbaly() to the plugins in vite.config"
1506
+ },
1507
+ {
1508
+ name: "webpack",
1509
+ dep: "webpack",
1510
+ pkg: "@verbaly/unplugin",
1511
+ wire: "add the verbaly webpack plugin to your build config"
1512
+ },
1513
+ {
1514
+ name: "rspack",
1515
+ dep: "@rspack/core",
1516
+ pkg: "@verbaly/unplugin",
1517
+ wire: "add the verbaly rspack plugin to your build config"
1518
+ },
1519
+ {
1520
+ name: "rollup",
1521
+ dep: "rollup",
1522
+ pkg: "@verbaly/unplugin",
1523
+ wire: "add the verbaly rollup plugin to your build config"
1524
+ },
1525
+ {
1526
+ name: "esbuild",
1527
+ dep: "esbuild",
1528
+ pkg: "@verbaly/unplugin",
1529
+ wire: "add the verbaly esbuild plugin to your build config"
1069
1530
  }
1070
- strayImports() {
1071
- return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
1531
+ ];
1532
+ const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
1533
+ function readDependencies(root) {
1534
+ const path = join(root, "package.json");
1535
+ if (!existsSync(path)) return {};
1536
+ try {
1537
+ const pkg = JSON.parse(readFileSync(path, "utf8"));
1538
+ return {
1539
+ ...pkg.dependencies,
1540
+ ...pkg.devDependencies
1541
+ };
1542
+ } catch {
1543
+ return {};
1072
1544
  }
1073
- parseErrors() {
1074
- const out = [];
1075
- for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
1076
- file,
1077
- message: analysis.parseError
1545
+ }
1546
+ function cliReachable(root) {
1547
+ const bin = join(root, "node_modules", ".bin");
1548
+ return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
1549
+ }
1550
+ const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
1551
+ function detectHost(root) {
1552
+ const deps = readDependencies(root);
1553
+ return HOSTS.find((host) => deps[host.dep]);
1554
+ }
1555
+ function configSource(options, typescript) {
1556
+ const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
1557
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
1558
+ if (options.dir) fields.push(` dir: '${options.dir}',`);
1559
+ const body = `export default {\n${fields.join("\n")}\n}`;
1560
+ if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
1561
+ return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
1562
+ }
1563
+ async function init(input = {}) {
1564
+ const root = input.root ?? process.cwd();
1565
+ const created = [];
1566
+ const skipped = [];
1567
+ const renamed = [];
1568
+ const refused = [];
1569
+ const typed = input.locales?.flatMap((locale) => {
1570
+ if (isLocaleTag(locale)) return [locale];
1571
+ const near = suggestTag(locale);
1572
+ if (near) renamed.push({
1573
+ from: locale,
1574
+ to: near
1078
1575
  });
1079
- return out;
1576
+ else refused.push(locale);
1577
+ return near ? [near] : [];
1578
+ });
1579
+ const locales = typed && [...new Set(typed)];
1580
+ let sourceLocale = input.sourceLocale;
1581
+ if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
1582
+ const near = suggestTag(sourceLocale);
1583
+ if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
1584
+ renamed.push({
1585
+ from: sourceLocale,
1586
+ to: near
1587
+ });
1588
+ sourceLocale = near;
1080
1589
  }
1081
- origins() {
1082
- const out = this.usedKeys();
1083
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
1084
- const files = out.get(msg.key) ?? [];
1085
- if (!files.includes(msg.file)) files.push(msg.file);
1086
- out.set(msg.key, files);
1590
+ const options = {
1591
+ ...input,
1592
+ locales,
1593
+ sourceLocale
1594
+ };
1595
+ const existing = findConfigFile(root);
1596
+ const typescript = existsSync(join(root, "tsconfig.json"));
1597
+ const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
1598
+ if (existing) skipped.push(existing);
1599
+ else {
1600
+ writeFileSync(join(root, configFile), configSource(options, typescript));
1601
+ created.push(configFile);
1602
+ }
1603
+ const fromFile = existing ? await loadConfigFile(root) : {};
1604
+ const scaffold = {
1605
+ dir: options.dir ?? fromFile.dir,
1606
+ sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
1607
+ locales: options.locales ?? fromFile.locales
1608
+ };
1609
+ const dir = join(root, scaffold.dir ?? "locales");
1610
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1611
+ for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
1612
+ const file = join(dir, `${locale}.json`);
1613
+ const label = relative(root, file).replaceAll("\\", "/");
1614
+ if (existsSync(file)) skipped.push(label);
1615
+ else {
1616
+ writeFileSync(file, "{}\n");
1617
+ created.push(label);
1087
1618
  }
1088
- return out;
1089
1619
  }
1090
- };
1091
- //#endregion
1092
- //#region src/key.ts
1093
- function stableKey(message) {
1094
- return createHash("sha256").update(message).digest("base64url").slice(0, 8);
1095
- }
1096
- //#endregion
1097
- //#region src/analyze.ts
1098
- function parseErrorMessage(error) {
1099
- return error instanceof Error ? error.message : String(error);
1100
- }
1101
- const SKIP_KEYS = /* @__PURE__ */ new Set([
1102
- "loc",
1103
- "leadingComments",
1104
- "trailingComments",
1105
- "innerComments",
1106
- "extra"
1107
- ]);
1108
- const DEFAULT_T_NAMES = ["t"];
1109
- const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
1110
- const DEFINE_KEYS = "defineKeys";
1111
- function analyze(code, file, options = {}) {
1112
- const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
1113
- const ast = parse$1(code, {
1114
- sourceType: "module",
1115
- errorRecovery: true,
1116
- plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
1117
- });
1118
- const tagged = [];
1119
- const usedKeys = [];
1120
- const strayImports = [];
1121
- walk(ast.program, (node) => {
1122
- if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
1123
- else if (node.type === "TaggedTemplateExpression") {
1124
- const tag = node.tag;
1125
- const explicit = explicitId(tag, names);
1126
- if (!explicit && !isTReference(tag, names)) return;
1127
- const quasi = node.quasi;
1128
- const message = buildMessage(code, quasi, names);
1129
- if (!message) return;
1130
- tagged.push({
1131
- key: explicit ? explicit.key : stableKey(message.text),
1132
- message: message.text,
1133
- params: message.params,
1134
- start: node.start,
1135
- end: node.end,
1136
- tagStart: explicit ? explicit.refStart : tag.start,
1137
- tagEnd: explicit ? explicit.refEnd : tag.end,
1138
- file
1139
- });
1140
- } else if (node.type === "CallExpression") {
1141
- const callee = node.callee;
1142
- const args = node.arguments;
1143
- if (callee.type === "Identifier" && callee.name === DEFINE_KEYS) {
1144
- collectDeclaredKeys(args[0], file, usedKeys);
1145
- return;
1146
- }
1147
- if (!isTReference(callee, names)) return;
1148
- const key = staticString(args[0]);
1149
- if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
1150
- } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
1151
- });
1620
+ const host = detectHost(root);
1621
+ const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1152
1622
  return {
1153
- tagged,
1154
- usedKeys,
1155
- strayImports
1623
+ created,
1624
+ skipped,
1625
+ host: host?.name,
1626
+ configFile,
1627
+ next,
1628
+ renamed,
1629
+ refused
1156
1630
  };
1157
1631
  }
1158
- function collectDeclaredKeys(node, file, out) {
1159
- if (node?.type !== "ObjectExpression") return;
1160
- for (const property of node.properties) {
1161
- if (property.type !== "ObjectProperty") continue;
1162
- const value = property.value;
1163
- const key = staticString(value);
1164
- if (key !== void 0) {
1165
- if (key !== "") out.push(usedKey(key, file, value));
1166
- } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
1167
- }
1168
- }
1169
- function usedKey(key, file, node) {
1170
- return node?.type === "StringLiteral" ? {
1171
- key,
1172
- file
1632
+ //#endregion
1633
+ //#region src/state.ts
1634
+ const STATE_FILE = ".verbaly-state.json";
1635
+ const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1636
+ function statePath(cfg, file = STATE_FILE) {
1637
+ return join(cfg.dir, file);
1638
+ }
1639
+ function loadState(cfg) {
1640
+ const current = readJson(statePath(cfg));
1641
+ if (current !== void 0 && !isObject(current)) throw corrupt(statePath(cfg));
1642
+ const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1643
+ if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1644
+ const state = isObject(current) ? {
1645
+ drafts: readDrafts(current.drafts),
1646
+ fingerprints: readFingerprints(current.fingerprints)
1173
1647
  } : {
1174
- key,
1175
- file,
1176
- loose: true
1648
+ drafts: {},
1649
+ fingerprints: {}
1177
1650
  };
1651
+ if (legacy !== void 0) for (const [locale, keys] of Object.entries(readDrafts(legacy))) markDrafts(state.drafts, locale, keys);
1652
+ return state;
1178
1653
  }
1179
- function staticString(node) {
1180
- if (!node) return void 0;
1181
- if (node.type === "StringLiteral") return node.value;
1182
- if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
1183
- if (node.type === "JSXExpressionContainer") return staticString(node.expression);
1654
+ function readState(cfg) {
1655
+ try {
1656
+ return { state: loadState(cfg) };
1657
+ } catch (error) {
1658
+ return {
1659
+ state: {
1660
+ drafts: {},
1661
+ fingerprints: {}
1662
+ },
1663
+ problem: error.message.replace(/^\[verbaly\] /, "")
1664
+ };
1665
+ }
1184
1666
  }
1185
- const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
1186
- function collectStrayImports(node, file, out) {
1187
- const source = node.source;
1188
- if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
1189
- for (const spec of node.specifiers) {
1190
- if (spec.type !== "ImportSpecifier") continue;
1191
- const imported = spec.imported;
1192
- if (imported.type !== "Identifier") continue;
1193
- const name = imported.name;
1194
- if (name === "t" || name === DEFINE_KEYS) out.push({
1195
- name,
1196
- source: source.value,
1197
- file
1198
- });
1667
+ function saveState(cfg, state) {
1668
+ const serialized = serializeState(state);
1669
+ const path = statePath(cfg);
1670
+ const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1671
+ if (serialized === void 0) {
1672
+ rmSync(path, { force: true });
1673
+ rmSync(legacy, { force: true });
1674
+ return;
1199
1675
  }
1676
+ let existing;
1677
+ try {
1678
+ existing = readFileSync(path, "utf8");
1679
+ } catch {
1680
+ mkdirSync(cfg.dir, { recursive: true });
1681
+ }
1682
+ if (existing !== serialized) writeFileSync(path, serialized);
1683
+ if (existsSync(legacy)) rmSync(legacy);
1200
1684
  }
1201
- function handleTrans(code, node, file, tagged, usedKeys, names) {
1202
- const opening = node.openingElement;
1203
- const nameNode = opening.name;
1204
- if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
1205
- const attrs = opening.attributes;
1206
- const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
1207
- const children = node.children;
1208
- const push = (key, built) => tagged.push({
1209
- key,
1210
- message: built.text,
1211
- params: built.params,
1212
- start: node.start,
1213
- end: node.end,
1214
- tagStart: nameNode.start,
1215
- tagEnd: nameNode.end,
1216
- file,
1217
- jsx: {
1218
- name: nameNode.name,
1219
- components: built.components
1220
- }
1221
- });
1222
- if (idAttr) {
1223
- const value = idAttr.value;
1224
- const id = staticString(value);
1225
- if (id === void 0) return;
1226
- if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
1227
- const built = buildTransMessage(code, children, names);
1228
- if (built?.text.trim()) {
1229
- push(id, built);
1230
- return;
1231
- }
1685
+ function updateState(cfg, catalogs) {
1686
+ const next = refreshState(cfg, catalogs, loadState(cfg));
1687
+ saveState(cfg, next);
1688
+ return next;
1689
+ }
1690
+ function refreshState(cfg, catalogs, previous) {
1691
+ const flat = flatCatalogs(catalogs);
1692
+ const source = flat[cfg.sourceLocale] ?? {};
1693
+ const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
1694
+ const drafts = {};
1695
+ for (const [locale, keys] of Object.entries(previous.drafts)) {
1696
+ if (!shown.has(locale)) {
1697
+ drafts[locale] = keys;
1698
+ continue;
1232
1699
  }
1233
- usedKeys.push(usedKey(id, file, value));
1234
- return;
1700
+ const live = keys.filter((key) => own(flat[locale], key));
1701
+ if (live.length) drafts[locale] = live;
1702
+ }
1703
+ const fingerprints = {};
1704
+ for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
1705
+ for (const locale of shown) {
1706
+ const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
1707
+ if (Object.keys(stamps).length) fingerprints[locale] = stamps;
1235
1708
  }
1236
- if (attrs.length > 0) return;
1237
- if (!children?.length) return;
1238
- const built = buildTransMessage(code, children, names);
1239
- if (!built || !built.text.trim()) return;
1240
- push(stableKey(built.text), built);
1241
- }
1242
- function explicitId(tag, names) {
1243
- if (tag.type !== "CallExpression") return void 0;
1244
- const callee = tag.callee;
1245
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
1246
- const prop = callee.property;
1247
- if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
1248
- const obj = callee.object;
1249
- if (!isTReference(obj, names)) return void 0;
1250
- const args = tag.arguments;
1251
- const first = args[0];
1252
- if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
1253
1709
  return {
1254
- key: first.value,
1255
- refStart: obj.start,
1256
- refEnd: obj.end
1710
+ drafts,
1711
+ fingerprints
1257
1712
  };
1258
1713
  }
1259
- function buildTransMessage(code, children, names) {
1260
- const params = [];
1261
- const components = [];
1262
- const takenParams = /* @__PURE__ */ new Map();
1263
- const takenTags = /* @__PURE__ */ new Map();
1264
- function walkChildren(nodes) {
1265
- let text = "";
1266
- for (const child of nodes) if (child.type === "JSXText") text += escapeText(cleanJsxText(child.value));
1267
- else if (child.type === "JSXExpressionContainer") {
1268
- const expr = child.expression;
1269
- if (expr.type === "JSXEmptyExpression") continue;
1270
- if (expr.type === "StringLiteral") {
1271
- text += escapeText(expr.value);
1272
- continue;
1273
- }
1274
- if (containsTaggedT(expr, names)) return void 0;
1275
- const source = code.slice(expr.start, expr.end);
1276
- const name = uniqueName(deriveName(expr, params.length), source, takenParams);
1277
- params.push({
1278
- name,
1279
- start: expr.start,
1280
- end: expr.end
1281
- });
1282
- text += `{${name}}`;
1283
- } else if (child.type === "JSXElement") {
1284
- const opening = child.openingElement;
1285
- const nameNode = opening.name;
1286
- if (nameNode.type !== "JSXIdentifier" || nameNode.name === "Trans") return void 0;
1287
- const source = selfClosedSource(code, opening);
1288
- const tag = uniqueName(nameNode.name.toLowerCase(), source, takenTags);
1289
- if (!components.some((c) => c.name === tag)) components.push({
1290
- name: tag,
1291
- source
1714
+ function refreshStamps(source, catalog, before) {
1715
+ const after = emptyCatalog();
1716
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
1717
+ const translated = own(catalog, key);
1718
+ if (!translated) continue;
1719
+ const was = own(before, key);
1720
+ if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
1721
+ after[key] = was;
1722
+ continue;
1723
+ }
1724
+ const text = own(source, key);
1725
+ if (text && tracked(key, text)) after[key] = stamp(text, translated);
1726
+ else if (was !== void 0) after[key] = was;
1727
+ }
1728
+ return after;
1729
+ }
1730
+ function recordTranslations(cfg, source, writes) {
1731
+ const state = loadState(cfg);
1732
+ for (const { locale, entries, draft } of writes) {
1733
+ if (entries.length === 0) continue;
1734
+ const stamps = state.fingerprints[locale] ??= emptyCatalog();
1735
+ for (const entry of entries) {
1736
+ const from = entry.source || own(source, entry.key);
1737
+ if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
1738
+ }
1739
+ const keys = entries.map((entry) => entry.key);
1740
+ if (draft === true) markDrafts(state.drafts, locale, keys);
1741
+ else if (draft === false) clearDrafts(state.drafts, locale, keys);
1742
+ }
1743
+ saveState(cfg, state);
1744
+ return state;
1745
+ }
1746
+ function effectiveDrafts(drafts, catalogs) {
1747
+ const out = {};
1748
+ for (const [locale, keys] of Object.entries(drafts)) {
1749
+ const catalog = catalogs[locale] ?? {};
1750
+ const live = keys.filter((key) => own(catalog, key));
1751
+ if (live.length) out[locale] = live;
1752
+ }
1753
+ return out;
1754
+ }
1755
+ function markDrafts(drafts, locale, keys) {
1756
+ if (!keys.length) return;
1757
+ drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1758
+ }
1759
+ function clearDrafts(drafts, locale, keys) {
1760
+ if (!drafts[locale]) return;
1761
+ if (!keys) {
1762
+ delete drafts[locale];
1763
+ return;
1764
+ }
1765
+ const drop = new Set(keys);
1766
+ drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1767
+ if (!drafts[locale].length) delete drafts[locale];
1768
+ }
1769
+ function fingerprint(text) {
1770
+ return stableKey(text);
1771
+ }
1772
+ function tracked(key, text) {
1773
+ return stableKey(text) !== key;
1774
+ }
1775
+ function stamp(source, translated) {
1776
+ return `${fingerprint(source)}.${fingerprint(translated)}`;
1777
+ }
1778
+ function outdatedTranslations(cfg, catalogs, fingerprints) {
1779
+ const source = catalogs[cfg.sourceLocale] ?? {};
1780
+ const out = [];
1781
+ for (const locale of targetLocales(cfg)) {
1782
+ const catalog = catalogs[locale] ?? {};
1783
+ for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
1784
+ const text = own(source, key);
1785
+ const translated = own(catalog, key);
1786
+ if (!text || !translated) continue;
1787
+ if (translationOf(was) !== fingerprint(translated)) continue;
1788
+ if (sourceOf(was) !== fingerprint(text)) out.push({
1789
+ locale,
1790
+ key
1292
1791
  });
1293
- if (!child.closingElement) text += `<${tag}/>`;
1294
- else {
1295
- const inner = walkChildren(child.children);
1296
- if (inner === void 0) return void 0;
1297
- text += `<${tag}>${inner}</${tag}>`;
1298
- }
1299
- } else return;
1300
- return text;
1792
+ }
1301
1793
  }
1302
- const text = walkChildren(children);
1303
- if (text === void 0) return void 0;
1304
- return {
1305
- text,
1306
- params,
1307
- components
1308
- };
1794
+ return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
1309
1795
  }
1310
- function cleanJsxText(raw) {
1311
- const lines = raw.split(/\r\n|[\r\n]/);
1312
- let out = "";
1313
- for (let i = 0; i < lines.length; i++) {
1314
- let line = lines[i].replace(/\t/g, " ");
1315
- if (i !== 0) line = line.replace(/^ +/, "");
1316
- if (i !== lines.length - 1) line = line.replace(/ +$/, "");
1317
- if (!line) continue;
1318
- if (out && i !== 0) out += " ";
1319
- out += line;
1796
+ function acceptOutdated(cfg, catalogs, fingerprints, entries) {
1797
+ const source = catalogs[cfg.sourceLocale] ?? {};
1798
+ for (const { locale, key } of entries) {
1799
+ const text = own(source, key);
1800
+ const translated = own(catalogs[locale] ?? {}, key);
1801
+ if (!text || !translated) continue;
1802
+ (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
1320
1803
  }
1804
+ }
1805
+ function sourceOf(stamped) {
1806
+ return stamped.slice(0, stamped.indexOf("."));
1807
+ }
1808
+ function translationOf(stamped) {
1809
+ return stamped.slice(stamped.indexOf(".") + 1);
1810
+ }
1811
+ function flatCatalogs(catalogs) {
1812
+ const out = {};
1813
+ for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
1321
1814
  return out;
1322
1815
  }
1323
- function selfClosedSource(code, opening) {
1324
- const src = code.slice(opening.start, opening.end);
1325
- return src.endsWith("/>") ? src : `${src.slice(0, -1).trimEnd()} />`;
1816
+ function serializeState(state) {
1817
+ const drafts = {};
1818
+ for (const locale of Object.keys(state.drafts).sort()) {
1819
+ const keys = [...new Set(state.drafts[locale])].sort();
1820
+ if (keys.length) drafts[locale] = keys;
1821
+ }
1822
+ const fingerprints = {};
1823
+ for (const locale of Object.keys(state.fingerprints).sort()) {
1824
+ const entries = state.fingerprints[locale] ?? {};
1825
+ const keys = Object.keys(entries).sort();
1826
+ if (!keys.length) continue;
1827
+ fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1828
+ }
1829
+ const out = {};
1830
+ if (Object.keys(drafts).length) out.drafts = drafts;
1831
+ if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1832
+ if (!out.drafts && !out.fingerprints) return void 0;
1833
+ return JSON.stringify(out, null, 2) + "\n";
1326
1834
  }
1327
- function containsTaggedT(node, names) {
1328
- let found = false;
1329
- walk(node, (n) => {
1330
- if (n.type !== "TaggedTemplateExpression") return;
1331
- const tag = n.tag;
1332
- if (isTReference(tag, names) || explicitId(tag, names)) found = true;
1333
- });
1334
- return found;
1835
+ function readJson(path) {
1836
+ let content;
1837
+ try {
1838
+ content = readFileSync(path, "utf8");
1839
+ } catch {
1840
+ return;
1841
+ }
1842
+ try {
1843
+ return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1844
+ } catch (error) {
1845
+ throw corrupt(path, error);
1846
+ }
1335
1847
  }
1336
- function isTReference(node, names) {
1337
- if (node.type === "Identifier") return names.has(node.name);
1338
- if (node.type === "MemberExpression" && !node.computed) {
1339
- const prop = node.property;
1340
- return prop.type === "Identifier" && names.has(prop.name);
1848
+ function corrupt(path, cause) {
1849
+ return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
1850
+ }
1851
+ function isObject(value) {
1852
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1853
+ }
1854
+ function readDrafts(value) {
1855
+ const out = {};
1856
+ if (!isObject(value)) return out;
1857
+ for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1858
+ return out;
1859
+ }
1860
+ function readFingerprints(value) {
1861
+ const out = {};
1862
+ if (!isObject(value)) return out;
1863
+ for (const [locale, entries] of Object.entries(value)) {
1864
+ if (!isObject(entries)) continue;
1865
+ const kept = emptyCatalog();
1866
+ for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
1867
+ out[locale] = kept;
1341
1868
  }
1342
- return false;
1869
+ return out;
1343
1870
  }
1344
- function buildMessage(code, quasi, names) {
1345
- const quasis = quasi.quasis;
1346
- const expressions = quasi.expressions;
1347
- const params = [];
1348
- const taken = /* @__PURE__ */ new Map();
1349
- let text = escapeText(cookedValue(quasis[0]));
1350
- for (let i = 0; i < expressions.length; i++) {
1351
- const expr = expressions[i];
1352
- if (!expr) return void 0;
1353
- if (containsTaggedT(expr, names)) return void 0;
1354
- const source = code.slice(expr.start, expr.end);
1355
- const name = uniqueName(deriveName(expr, i), source, taken);
1356
- params.push({
1357
- name,
1358
- start: expr.start,
1359
- end: expr.end
1871
+ //#endregion
1872
+ //#region src/check.ts
1873
+ function gatePasses(result) {
1874
+ return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
1875
+ }
1876
+ function check(cfg, catalogs, registry, fingerprints = {}) {
1877
+ const extracted = registry.messages();
1878
+ const flat = {};
1879
+ for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1880
+ const source = flat[cfg.sourceLocale] ?? {};
1881
+ const shipped = shippedCatalogs(cfg, flat, registry);
1882
+ const sourceText = shipped[cfg.sourceLocale];
1883
+ const used = registry.usedKeys();
1884
+ const unknown = [];
1885
+ for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
1886
+ key,
1887
+ files
1888
+ });
1889
+ const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
1890
+ const missing = [];
1891
+ for (const key of extracted.keys()) if (!source[key]) missing.push({
1892
+ locale: cfg.sourceLocale,
1893
+ key,
1894
+ source: extracted.get(key)?.message
1895
+ });
1896
+ for (const locale of cfg.locales) {
1897
+ if (locale === cfg.sourceLocale) continue;
1898
+ for (const key of needed) if (!flat[locale]?.[key]) missing.push({
1899
+ locale,
1900
+ key,
1901
+ source: source[key] ?? extracted.get(key)?.message
1360
1902
  });
1361
- text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));
1362
1903
  }
1363
- return {
1364
- text,
1365
- params
1366
- };
1904
+ const broken = [];
1905
+ const add = (locale, key, issues) => {
1906
+ for (const issue of issues) broken.push({
1907
+ locale,
1908
+ key,
1909
+ severity: issue.severity,
1910
+ issue: issue.message
1911
+ });
1912
+ };
1913
+ const divergent = [];
1914
+ for (const [key, entry] of extracted) {
1915
+ const written = source[key];
1916
+ if (written && written !== entry.message) divergent.push({
1917
+ key,
1918
+ catalog: written,
1919
+ code: siteOf(entry)
1920
+ });
1921
+ }
1922
+ for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
1923
+ for (const locale of cfg.locales) {
1924
+ if (locale === cfg.sourceLocale) continue;
1925
+ for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
1926
+ if (!translated) continue;
1927
+ add(locale, key, validateMessage(translated, locale));
1928
+ const text = sourceText[key];
1929
+ if (text) add(locale, key, validatePair(text, translated));
1930
+ }
1931
+ }
1932
+ const extra = [];
1933
+ for (const locale of cfg.locales) {
1934
+ if (locale === cfg.sourceLocale) continue;
1935
+ for (const key of Object.keys(flat[locale] ?? {})) {
1936
+ if (source[key] !== void 0 || extracted.has(key)) continue;
1937
+ extra.push({
1938
+ locale,
1939
+ key,
1940
+ files: used.get(key) ?? []
1941
+ });
1942
+ }
1943
+ }
1944
+ return {
1945
+ ok: gatePasses({
1946
+ missing,
1947
+ unknown,
1948
+ broken
1949
+ }),
1950
+ missing,
1951
+ unknown,
1952
+ broken,
1953
+ extra,
1954
+ collisions: collisionEntries(registry),
1955
+ divergent,
1956
+ outdated: outdatedTranslations(cfg, shipped, fingerprints)
1957
+ };
1958
+ }
1959
+ function formatCheckResult(result, root) {
1960
+ const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
1961
+ const lines = [];
1962
+ if (result.missing.length > 0) {
1963
+ lines.push("missing translations:");
1964
+ for (const entry of result.missing) {
1965
+ const hint = entry.source ? `: "${truncate(entry.source, 40)}"` : "";
1966
+ lines.push(` [${entry.locale}] ${entry.key}${hint}`);
1967
+ }
1968
+ }
1969
+ if (result.unknown.length > 0) {
1970
+ lines.push("unknown keys (not in any catalog):");
1971
+ for (const entry of result.unknown) lines.push(` ${entry.key} (used in ${entry.files.map(show).join(", ")})`);
1972
+ }
1973
+ const errors = result.broken.filter((entry) => entry.severity === "error");
1974
+ if (errors.length > 0) {
1975
+ lines.push("broken translations:");
1976
+ for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1977
+ }
1978
+ return lines.join("\n");
1367
1979
  }
1368
- function cookedValue(element) {
1369
- if (!element) return "";
1370
- const value = element.value;
1371
- return value.cooked ?? value.raw;
1980
+ function checkNextSteps(result, cliReachable = true) {
1981
+ const steps = [];
1982
+ if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
1983
+ if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
1984
+ if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
1985
+ if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
1986
+ return steps.join("\n");
1372
1987
  }
1373
- function escapeText(text) {
1374
- return text.replace(/[{}]/g, (m) => m + m);
1988
+ function formatCheckWarnings(result, root, options = {}) {
1989
+ const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1990
+ for (const entry of result.extra) lines.push(entry.files.length > 0 ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself` : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`);
1991
+ for (const entry of result.collisions) lines.push(` ${formatFinding({
1992
+ kind: "collision",
1993
+ ...entry
1994
+ }, root)}`);
1995
+ for (const { key, catalog, code } of result.divergent) lines.push(` ${key}: the source catalog says "${truncate(catalog, 40)}" and the code says "${truncate(code.message, 40)}" (${sourcePlace(code, root)}): the code wins, so edit the text there (extract writes it into the catalog)`);
1996
+ if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
1997
+ kind: "outdated",
1998
+ ...entry
1999
+ }, root)}`);
2000
+ return lines.join("\n");
1375
2001
  }
1376
- function deriveName(expr, index) {
1377
- if (expr.type === "Identifier") return expr.name;
1378
- if (expr.type === "MemberExpression" && !expr.computed) {
1379
- const prop = expr.property;
1380
- if (prop.type === "Identifier") return prop.name;
2002
+ function githubCheckAnnotations(result, registry, cfg, options = {}) {
2003
+ const messages = registry.messages();
2004
+ const rel = (file) => escapeProperty(relative(cfg.root, file).replaceAll("\\", "/"));
2005
+ const at = (file, line) => `file=${rel(file)}${line ? `,line=${line}` : ""}`;
2006
+ const lines = [];
2007
+ const byKey = /* @__PURE__ */ new Map();
2008
+ for (const entry of result.missing) {
2009
+ const grouped = byKey.get(entry.key);
2010
+ if (grouped) grouped.locales.push(entry.locale);
2011
+ else byKey.set(entry.key, {
2012
+ ...entry,
2013
+ locales: [entry.locale]
2014
+ });
1381
2015
  }
1382
- return `_${index}`;
1383
- }
1384
- function uniqueName(base, source, taken) {
1385
- let name = base;
1386
- let n = 2;
1387
- while (taken.has(name) && taken.get(name) !== source) {
1388
- name = `${base}${n}`;
1389
- n += 1;
2016
+ for (const entry of byKey.values()) {
2017
+ const origin = messages.get(entry.key);
2018
+ const hint = entry.source ? `: "${truncate(entry.source, 60)}"` : "";
2019
+ const text = escapeData(`missing [${entry.locales.join(", ")}] ${entry.key}${hint}`);
2020
+ if (origin) lines.push(`::error ${at(origin.file, origin.line)}::${text}`);
2021
+ else lines.push(`::error::${text}`);
1390
2022
  }
1391
- taken.set(name, source);
1392
- return name;
1393
- }
1394
- function walk(node, visit) {
1395
- visit(node);
1396
- for (const key in node) {
1397
- if (SKIP_KEYS.has(key)) continue;
1398
- const value = node[key];
1399
- if (Array.isArray(value)) {
1400
- for (const item of value) if (isNode(item)) walk(item, visit);
1401
- } else if (isNode(value)) walk(value, visit);
2023
+ for (const entry of result.unknown) {
2024
+ const text = escapeData(`unknown key "${entry.key}" (not in any catalog)`);
2025
+ const file = entry.files[0];
2026
+ lines.push(file ? `::error file=${rel(file)}::${text}` : `::error::${text}`);
1402
2027
  }
1403
- }
1404
- function isNode(value) {
1405
- return typeof value === "object" && value !== null && typeof value.type === "string";
1406
- }
1407
- //#endregion
1408
- //#region src/sfc.ts
1409
- const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
1410
- function analyzeFile(code, file) {
1411
- if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
1412
- try {
1413
- return analyze(code, file);
1414
- } catch (error) {
1415
- return {
1416
- tagged: [],
1417
- usedKeys: [],
1418
- strayImports: [],
1419
- parseError: parseErrorMessage(error)
1420
- };
2028
+ for (const entry of result.broken) {
2029
+ const origin = messages.get(entry.key);
2030
+ const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);
2031
+ const command = entry.severity === "error" ? "error" : "warning";
2032
+ if (!origin) {
2033
+ lines.push(`::${command}::${text}`);
2034
+ continue;
2035
+ }
2036
+ lines.push(`::${command} ${at(origin.file, origin.line)}::${text}`);
1421
2037
  }
1422
- }
1423
- const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
1424
- const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
1425
- const COMMENT_RE = /<!--[\s\S]*?-->/g;
1426
- const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
1427
- const CANDIDATE_SVELTE = /(?<![\w$])\$?t(?=[`(]|\.id\()/g;
1428
- const CANDIDATE_VUE = /(?<![\w$])t(?=[`(]|\.id\()/g;
1429
- const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
1430
- const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
1431
- function analyzeSfc(code, file) {
1432
- const svelte = file.endsWith(".svelte");
1433
- const options = svelte ? { tNames: ["t", "$t"] } : void 0;
1434
- const tagged = [];
1435
- const usedKeys = [];
1436
- const strayImports = [];
1437
- let parseError;
1438
- const block = (segment, offset) => {
1439
- parseError ??= segment.error;
1440
- merge(segment.analysis, offset, false);
1441
- };
1442
- const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
1443
- if (frontmatter?.[2]) block(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length);
1444
- for (const match of code.matchAll(SCRIPT_RE)) {
1445
- const content = match[2];
1446
- if (!content) continue;
1447
- block(analyzeSegment(content, file, options), match.index + match[1].length);
2038
+ for (const entry of result.extra) {
2039
+ const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);
2040
+ const file = entry.files[0];
2041
+ lines.push(file ? `::warning file=${rel(file)}::${text}` : `::warning::${text}`);
1448
2042
  }
1449
- const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
1450
- const candidates = svelte ? CANDIDATE_SVELTE : CANDIDATE_VUE;
1451
- const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
1452
- let range = 0;
1453
- let consumedTo = 0;
1454
- for (const match of markup.matchAll(candidates)) {
1455
- const start = match.index;
1456
- if (start < consumedTo) continue;
1457
- while (range < ranges.length && ranges[range][1] <= start) range += 1;
1458
- if (range >= ranges.length || start < ranges[range][0]) continue;
1459
- const end = expressionExtent(markup, start);
1460
- if (end === void 0) continue;
1461
- merge(analyzeSegment(code.slice(start, end), file, options).analysis, start, true);
1462
- consumedTo = end;
2043
+ for (const { key, sites } of result.collisions) {
2044
+ const texts = new Set(sites.map((place) => place.message)).size;
2045
+ const text = escapeData(`"${key}" has ${counted(texts, "text")}, and every place shows the first one`);
2046
+ for (const place of sites) lines.push(`::warning ${at(place.file, place.line)}::${text}`);
1463
2047
  }
1464
- return {
1465
- tagged,
1466
- usedKeys,
1467
- strayImports,
1468
- ...parseError && { parseError }
1469
- };
1470
- function merge(analysis, offset, markupSegment) {
1471
- if (!analysis) return;
1472
- for (const msg of analysis.tagged) tagged.push({
1473
- ...msg,
1474
- start: msg.start + offset,
1475
- end: msg.end + offset,
1476
- tagStart: msg.tagStart + offset,
1477
- tagEnd: msg.tagEnd + offset,
1478
- params: msg.params.map((p) => ({
1479
- ...p,
1480
- start: p.start + offset,
1481
- end: p.end + offset
1482
- })),
1483
- ...markupSegment && { singleQuote: true }
1484
- });
1485
- usedKeys.push(...analysis.usedKeys);
1486
- strayImports.push(...analysis.strayImports);
2048
+ for (const { key, code } of result.divergent) {
2049
+ const text = escapeData(`"${key}": the source catalog has another text, the code's one ships`);
2050
+ lines.push(`::warning ${at(code.file, code.line)}::${text}`);
1487
2051
  }
1488
- }
1489
- function analyzeSegment(code, file, options) {
1490
- try {
1491
- return { analysis: analyze(code, file, options) };
1492
- } catch (error) {
1493
- return { error: parseErrorMessage(error) };
2052
+ const outdated = options.outdatedFails ? "error" : "warning";
2053
+ for (const { locale, key } of result.outdated) {
2054
+ const text = escapeData(`[${locale}] ${key}: translated from an older source text`);
2055
+ lines.push(`::${outdated} file=${rel(catalogPath(cfg, locale))}::${text}`);
1494
2056
  }
2057
+ return lines;
1495
2058
  }
1496
- function blank(source, re) {
1497
- return source.replace(re, (m) => " ".repeat(m.length));
1498
- }
1499
- function braceRanges(markup) {
1500
- const ranges = [];
1501
- let i = 0;
1502
- while (i < markup.length) {
1503
- if (markup[i] === "{") {
1504
- const end = balancedEnd(markup, i);
1505
- if (end !== void 0) {
1506
- ranges.push([i + 1, end - 1]);
1507
- i = end;
1508
- continue;
1509
- }
1510
- }
1511
- i += 1;
1512
- }
1513
- return ranges;
2059
+ function escapeData(text) {
2060
+ return text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
1514
2061
  }
1515
- function vueExpressionRanges(markup) {
1516
- const ranges = [];
1517
- for (const match of markup.matchAll(MUSTACHE_RE)) ranges.push([match.index + 2, match.index + match[0].length - 2]);
1518
- for (const match of markup.matchAll(DIRECTIVE_RE)) {
1519
- const valueStart = match.index + match[0].length - match[1].length + 1;
1520
- ranges.push([valueStart, valueStart + match[1].length - 2]);
1521
- }
1522
- return ranges.sort((a, b) => a[0] - b[0]);
2062
+ function escapeProperty(text) {
2063
+ return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
1523
2064
  }
1524
- function expressionExtent(code, start) {
1525
- let i = start;
1526
- if (code[i] === "$") i += 1;
1527
- i += 1;
1528
- if (code.startsWith(".id(", i)) {
1529
- const close = balancedEnd(code, i + 3);
1530
- if (close === void 0 || code[close] !== "`") return void 0;
1531
- return balancedEnd(code, close);
1532
- }
1533
- if (code[i] === "`" || code[i] === "(") return balancedEnd(code, i);
2065
+ //#endregion
2066
+ //#region src/bundle.ts
2067
+ function isExcluded(key, prefixes) {
2068
+ return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
1534
2069
  }
1535
- function balancedEnd(code, open) {
1536
- const stack = [];
1537
- let i = open;
1538
- while (i < code.length) {
1539
- const ch = code[i];
1540
- if (stack[stack.length - 1] === "`") {
1541
- if (ch === "\\") i += 1;
1542
- else if (ch === "`") stack.pop();
1543
- else if (ch === "$" && code[i + 1] === "{") {
1544
- stack.push("{");
1545
- i += 1;
1546
- }
1547
- } else if (ch === "'" || ch === "\"") i = stringEnd(code, i);
1548
- else if (ch === "`" || ch === "(" || ch === "{") stack.push(ch);
1549
- else if (ch === ")" || ch === "}") {
1550
- if (stack[stack.length - 1] !== (ch === ")" ? "(" : "{")) return void 0;
1551
- stack.pop();
2070
+ function auditBundle(cfg, catalogs, registry) {
2071
+ const prefixes = cfg.bundle.exclude ?? [];
2072
+ if (prefixes.length === 0) return [];
2073
+ const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
2074
+ const used = registry.usedKeys();
2075
+ const issues = [];
2076
+ for (const prefix of prefixes) {
2077
+ if (!source.some((key) => isExcluded(key, [prefix]))) {
2078
+ issues.push({
2079
+ prefix,
2080
+ problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
2081
+ fix: "check the spelling against your catalog, or drop it from bundle.exclude"
2082
+ });
2083
+ continue;
1552
2084
  }
1553
- i += 1;
1554
- if (stack.length === 0) return i;
2085
+ const files = /* @__PURE__ */ new Set();
2086
+ for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
2087
+ if (files.size > 0) issues.push({
2088
+ prefix,
2089
+ problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
2090
+ fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
2091
+ });
1555
2092
  }
2093
+ return issues;
1556
2094
  }
1557
- function stringEnd(code, start) {
1558
- const quote = code[start];
1559
- let i = start + 1;
1560
- while (i < code.length) if (code[i] === "\\") i += 2;
1561
- else if (code[i] === quote) return i;
1562
- else i += 1;
1563
- return code.length;
1564
- }
1565
- //#endregion
1566
- //#region src/extract.ts
1567
- async function extractProject(cfg) {
1568
- const files = await glob(cfg.include, {
1569
- cwd: cfg.root,
1570
- ignore: cfg.exclude,
1571
- absolute: true
1572
- });
1573
- const registry = new MessageRegistry();
1574
- for (const file of files) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
1575
- return registry;
2095
+ function formatBundleIssue(issue) {
2096
+ return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
1576
2097
  }
1577
- async function collectOrigins(cfg, reuse) {
1578
- const registry = reuse ?? await extractProject(cfg);
1579
- const origins = Object.create(null);
1580
- for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
1581
- return origins;
2098
+ //#endregion
2099
+ //#region src/params.ts
2100
+ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
2101
+ "number",
2102
+ "integer",
2103
+ "percent",
2104
+ "currency"
2105
+ ]);
2106
+ const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
2107
+ function collectParams(message) {
2108
+ const out = /* @__PURE__ */ new Map();
2109
+ visit(parse(message, parseIcu), out);
2110
+ return out;
1582
2111
  }
1583
- function syncCatalogs(cfg, catalogs, registry) {
1584
- const added = {};
1585
- const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
1586
- for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) {
1587
- source[key] = msg.message;
1588
- (added[cfg.sourceLocale] ??= []).push(key);
1589
- }
1590
- const needed = Object.keys(source);
1591
- for (const locale of cfg.locales) {
1592
- if (locale === cfg.sourceLocale) continue;
1593
- const catalog = catalogs[locale] ??= emptyCatalog();
1594
- for (const key of needed) if (own(catalog, key) === void 0) {
1595
- catalog[key] = "";
1596
- (added[locale] ??= []).push(key);
1597
- }
2112
+ function visit(nodes, out) {
2113
+ for (const node of nodes) {
2114
+ if (node.kind !== "param") continue;
2115
+ const types = out.get(node.name) ?? /* @__PURE__ */ new Set();
2116
+ out.set(node.name, types);
2117
+ if (node.variants) {
2118
+ for (const [key, body] of node.variants) {
2119
+ if (PLURAL_CATEGORIES.has(key) || /^=\d+$/.test(key)) types.add("number");
2120
+ else if (key !== "other") types.add("string");
2121
+ visit(body, out);
2122
+ }
2123
+ if (types.size === 0) types.add("string");
2124
+ } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
2125
+ else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
2126
+ else types.add("unknown");
1598
2127
  }
1599
- return { added };
1600
2128
  }
1601
- function pruneCatalogs(cfg, catalogs, registry) {
1602
- const removed = {};
1603
- if (registry.parseErrors().length > 0) return removed;
1604
- const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
1605
- for (const locale of cfg.locales) {
1606
- const catalog = catalogs[locale];
1607
- if (!catalog) continue;
1608
- for (const key of Object.keys(catalog)) if (!keep.has(key)) {
1609
- delete catalog[key];
1610
- (removed[locale] ??= []).push(key);
2129
+ function renderParamType(types) {
2130
+ if (types.has("unknown") || types.size === 0) return "unknown";
2131
+ const members = /* @__PURE__ */ new Set();
2132
+ if (types.has("number")) members.add("number");
2133
+ if (types.has("string")) members.add("string");
2134
+ if (types.has("date")) for (const m of [
2135
+ "Date",
2136
+ "number",
2137
+ "string"
2138
+ ]) members.add(m);
2139
+ return [...members].join(" | ");
2140
+ }
2141
+ function generateDts(catalog, options = {}) {
2142
+ const lines = [];
2143
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
2144
+ const params = collectParams(message);
2145
+ if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
2146
+ else {
2147
+ const fields = [...params.entries()].map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`).join("; ");
2148
+ lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
1611
2149
  }
1612
2150
  }
1613
- return removed;
2151
+ return `// generated by verbaly: do not edit
2152
+ declare module 'virtual:verbaly' {
2153
+ export interface VerbalyMessages {
2154
+ ${lines.join("\n")}
2155
+ }
2156
+ export type VerbalyKey = keyof VerbalyMessages & string;
2157
+
2158
+ export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
2159
+ export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
2160
+
2161
+ export const verbaly: import('verbaly').Verbaly<VerbalyKey>;
2162
+
2163
+ export const sourceLocale: string;
2164
+ export const locales: string[];
2165
+ export const routing: import('verbaly').Routing;
2166
+ export function localePath(
2167
+ locale: string,
2168
+ options?: { path?: string; base?: string },
2169
+ ): string;
2170
+ export function localeFromPath(options?: {
2171
+ path?: string;
2172
+ base?: string;
2173
+ }): string | undefined;
2174
+ export function loadMessages(locale: string): Promise<Record<string, string>>;${options.inlineCatalog ? "\n export function adoptPage(options?: {\n root?: ParentNode;\n path?: string;\n }): string | undefined;" : ""}
2175
+ export function createInstance(
2176
+ options?: import('verbaly').VerbalyOptions<VerbalyKey>,
2177
+ ): import('verbaly').Verbaly<VerbalyKey>;
2178
+ export function createRequestInstance(
2179
+ locale: string,
2180
+ ): Promise<import('verbaly').Verbaly<VerbalyKey>>;
2181
+
2182
+ export function t<K extends VerbalyKey>(
2183
+ key: K,
2184
+ ...args: [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
2185
+ ): string;
2186
+ export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
2187
+ export namespace t {
2188
+ export function id(
2189
+ key: string,
2190
+ ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
2191
+ }
2192
+
2193
+ export function setLocale(locale: string): Promise<void>;
2194
+ export function switchLocale(
2195
+ locale: string,
2196
+ options?: Omit<
2197
+ import('verbaly').SwitchLocaleOptions,
2198
+ 'routing' | 'supported' | 'sourceLocale'
2199
+ >,
2200
+ ): Promise<void>;
2201
+ export function getLocale(): string;
2202
+ export function subscribe(listener: () => void): () => void;
2203
+ }
2204
+
2205
+ declare module 'virtual:verbaly/locale/*' {
2206
+ const messages: Record<string, string>;
2207
+ export default messages;
2208
+ }
2209
+ `;
2210
+ }
2211
+ function writeDts(cfg, catalog, file) {
2212
+ const target = file === void 0 ? cfg.dts : file;
2213
+ if (target === false) return;
2214
+ file = target ?? join(cfg.root, "verbaly.d.ts");
2215
+ const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
2216
+ try {
2217
+ if (readFileSync(file, "utf8") === content) return;
2218
+ } catch {}
2219
+ mkdirSync(dirname(file), { recursive: true });
2220
+ writeFileSync(file, content);
1614
2221
  }
1615
2222
  //#endregion
1616
2223
  //#region src/doctor.ts
@@ -1738,6 +2345,16 @@ async function doctor(cfg) {
1738
2345
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1739
2346
  error("imports", `t is imported from a verbaly package, which never exports it, in ${counted(files.length, "file")} (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
1740
2347
  }
2348
+ const missed = registry.missed();
2349
+ if (missed.length > 0) {
2350
+ const first = missed[0];
2351
+ warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
2352
+ }
2353
+ const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
2354
+ if (positional.length > 0) {
2355
+ const first = positional[0];
2356
+ warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
2357
+ }
1741
2358
  const escaped = [...registry.messages().values()].map((msg) => ({
1742
2359
  file: rel(msg.file),
1743
2360
  slice: escapedSyntax(msg.message)
@@ -1758,8 +2375,17 @@ async function doctor(cfg) {
1758
2375
  for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
1759
2376
  if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
1760
2377
  }
2378
+ const { state, problem } = readState(cfg);
2379
+ if (problem) warn("state", problem, `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
2380
+ if (catalogsHealthy) {
2381
+ const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2382
+ const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
2383
+ return keys.filter((key) => !live.has(key)).map((key) => `${locale}: ${key}`);
2384
+ });
2385
+ if (stale.length > 0) warn("drafts", `${STATE_FILE} lists ${counted(stale.length, "draft")} whose translation is gone (${preview(stale)})`, "run `npx verbaly extract`, which drops them");
2386
+ }
1761
2387
  if (catalogsHealthy) {
1762
- const result = check(cfg, catalogs, registry);
2388
+ const result = check(cfg, catalogs, registry, state.fingerprints);
1763
2389
  if (result.unknown.length > 0) error("keys", `${counted(result.unknown.length, "unknown key")} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
1764
2390
  if (result.missing.length > 0) {
1765
2391
  const locales = [...new Set(result.missing.map((m) => m.locale))];
@@ -1776,6 +2402,18 @@ async function doctor(cfg) {
1776
2402
  }
1777
2403
  const warnings = result.broken.filter((entry) => entry.severity === "warning");
1778
2404
  if (warnings.length > 0) warn("translations", `${counted(warnings.length, "structural warning")} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
2405
+ if (result.collisions.length > 0) {
2406
+ const first = result.collisions[0];
2407
+ warn("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
2408
+ }
2409
+ if (result.divergent.length > 0) {
2410
+ const first = result.divergent[0];
2411
+ warn("source texts", `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, "text")}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`, "edit those texts in the code; `npx verbaly extract` writes them into the catalog");
2412
+ }
2413
+ if (result.outdated.length > 0) {
2414
+ const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
2415
+ warn("outdated", `${counted(result.outdated.length, "translation")} written for an older source text (${preview(shown)})`, "update them, or keep them with `npx verbaly review --approve`");
2416
+ }
1779
2417
  if (result.ok) ok("translations", "all translations complete");
1780
2418
  }
1781
2419
  return {
@@ -1788,66 +2426,6 @@ function preview(keys) {
1788
2426
  return keys.length > PREVIEW ? `${head}, …` : head;
1789
2427
  }
1790
2428
  //#endregion
1791
- //#region src/drafts.ts
1792
- const DRAFTS_FILE = ".verbaly-drafts.json";
1793
- function draftsPath(cfg) {
1794
- return join(cfg.dir, DRAFTS_FILE);
1795
- }
1796
- function loadDrafts(cfg) {
1797
- let content;
1798
- try {
1799
- content = readFileSync(draftsPath(cfg), "utf8");
1800
- } catch {
1801
- return {};
1802
- }
1803
- try {
1804
- return JSON.parse(content.replace(/^\uFEFF/, ""));
1805
- } catch (error) {
1806
- throw new Error(`[verbaly] ${draftsPath(cfg)} is not valid JSON, fix or delete the file`, { cause: error });
1807
- }
1808
- }
1809
- function serializeDrafts(drafts) {
1810
- const sorted = {};
1811
- for (const locale of Object.keys(drafts).sort()) {
1812
- const keys = [...new Set(drafts[locale])].sort();
1813
- if (keys.length) sorted[locale] = keys;
1814
- }
1815
- return JSON.stringify(sorted, null, 2) + "\n";
1816
- }
1817
- function saveDrafts(cfg, drafts) {
1818
- const serialized = serializeDrafts(drafts);
1819
- const path = draftsPath(cfg);
1820
- try {
1821
- if (readFileSync(path, "utf8") === serialized) return;
1822
- } catch {
1823
- mkdirSync(cfg.dir, { recursive: true });
1824
- }
1825
- writeFileSync(path, serialized);
1826
- }
1827
- function markDrafts(drafts, locale, keys) {
1828
- if (!keys.length) return;
1829
- drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1830
- }
1831
- function clearDrafts(drafts, locale, keys) {
1832
- if (!drafts[locale]) return;
1833
- if (!keys) {
1834
- delete drafts[locale];
1835
- return;
1836
- }
1837
- const drop = new Set(keys);
1838
- drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1839
- if (!drafts[locale].length) delete drafts[locale];
1840
- }
1841
- function effectiveDrafts(drafts, catalogs) {
1842
- const out = {};
1843
- for (const [locale, keys] of Object.entries(drafts)) {
1844
- const catalog = catalogs[locale] ?? {};
1845
- const live = keys.filter((key) => own(catalog, key));
1846
- if (live.length) out[locale] = live;
1847
- }
1848
- return out;
1849
- }
1850
- //#endregion
1851
2429
  //#region src/inline.ts
1852
2430
  const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
1853
2431
  function messageToInline(text) {
@@ -2127,6 +2705,7 @@ function toPo(sourceLocale, locale, entries) {
2127
2705
  }
2128
2706
  function parsePo(content) {
2129
2707
  const entries = Object.create(null);
2708
+ const sources = Object.create(null);
2130
2709
  let locale;
2131
2710
  let msgctxt;
2132
2711
  let msgid;
@@ -2137,7 +2716,10 @@ function parsePo(content) {
2137
2716
  if (msgid === "" && msgctxt === void 0) {
2138
2717
  const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
2139
2718
  if (lang) locale = lang;
2140
- } else if (msgctxt !== void 0 && msgid !== void 0) entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
2719
+ } else if (msgctxt !== void 0 && msgid !== void 0) {
2720
+ entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
2721
+ sources[msgctxt] = msgid;
2722
+ }
2141
2723
  msgctxt = msgid = msgstr = field = void 0;
2142
2724
  fuzzy = false;
2143
2725
  };
@@ -2177,7 +2759,8 @@ function parsePo(content) {
2177
2759
  finish();
2178
2760
  return {
2179
2761
  locale,
2180
- entries
2762
+ entries,
2763
+ sources
2181
2764
  };
2182
2765
  }
2183
2766
  function poString(text) {
@@ -2337,7 +2920,7 @@ function formatTranslateFailures(failed) {
2337
2920
  async function resolveProvider(cfg, model) {
2338
2921
  const configured = cfg.translate.provider;
2339
2922
  if (typeof configured === "function") return configured;
2340
- const { claudeProvider } = await import("./claude-BmD8W9uW.js");
2923
+ const { claudeProvider } = await import("./claude-DmnZ1cvR.js");
2341
2924
  return claudeProvider({ model: model ?? cfg.translate.model });
2342
2925
  }
2343
2926
  function structureMatches(source, translated) {
@@ -2441,7 +3024,8 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
2441
3024
  skipped: {},
2442
3025
  unknown: {},
2443
3026
  unmatched: [],
2444
- mapped: []
3027
+ mapped: [],
3028
+ sources: {}
2445
3029
  };
2446
3030
  for (const file of files) {
2447
3031
  const parsed = parseExchangeFile(file, options.locale);
@@ -2485,6 +3069,8 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
2485
3069
  }
2486
3070
  if (!options.dryRun) catalog[key] = text;
2487
3071
  (result.imported[locale] ??= []).push(key);
3072
+ const seen = parsed.sources[key];
3073
+ if (seen) (result.sources[locale] ??= {})[key] = seen;
2488
3074
  }
2489
3075
  }
2490
3076
  return result;
@@ -2497,18 +3083,20 @@ function parseExchangeFile(file, localeOverride) {
2497
3083
  if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>.`);
2498
3084
  return {
2499
3085
  locale,
2500
- entries: parsed.entries
3086
+ entries: parsed.entries,
3087
+ sources: parsed.sources
2501
3088
  };
2502
3089
  }
2503
3090
  if (/\.csv$/i.test(file)) return {
2504
3091
  locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
2505
- entries: parseCsv(content)
3092
+ ...parseCsv(content)
2506
3093
  };
2507
3094
  if (/\.po$/i.test(file)) {
2508
3095
  const parsed = parsePo(content);
2509
3096
  return {
2510
3097
  locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
2511
- entries: parsed.entries
3098
+ entries: parsed.entries,
3099
+ sources: parsed.sources
2512
3100
  };
2513
3101
  }
2514
3102
  throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po.`);
@@ -2544,15 +3132,19 @@ function newLocale(cfg, detected) {
2544
3132
  function parseXliff(content) {
2545
3133
  const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
2546
3134
  const entries = Object.create(null);
3135
+ const sources = Object.create(null);
2547
3136
  for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
2548
3137
  const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
2549
3138
  if (!id) continue;
2550
3139
  const target = /<target\b[^>]*>([\s\S]*?)<\/target>/.exec(match[2])?.[1];
2551
3140
  entries[unescapeXml(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
3141
+ const source = /<source\b[^>]*>([\s\S]*?)<\/source>/.exec(match[2])?.[1];
3142
+ if (source !== void 0) sources[unescapeXml(id)] = inlineToMessage(stripCdata(source));
2552
3143
  }
2553
3144
  return {
2554
3145
  locale,
2555
- entries
3146
+ entries,
3147
+ sources
2556
3148
  };
2557
3149
  }
2558
3150
  function stripCdata(text) {
@@ -2573,13 +3165,21 @@ function parseCsv(content) {
2573
3165
  const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
2574
3166
  const keyCol = header.indexOf("key");
2575
3167
  const targetCol = header.indexOf("target");
3168
+ const sourceCol = header.indexOf("source");
2576
3169
  if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
2577
3170
  const entries = Object.create(null);
3171
+ const sources = Object.create(null);
2578
3172
  for (const row of rows.slice(1)) {
2579
3173
  const key = row[keyCol];
2580
- if (key) entries[key] = row[targetCol] ?? "";
3174
+ if (!key) continue;
3175
+ entries[key] = row[targetCol] ?? "";
3176
+ const source = sourceCol === -1 ? void 0 : row[sourceCol];
3177
+ if (source) sources[key] = source;
2581
3178
  }
2582
- return entries;
3179
+ return {
3180
+ entries,
3181
+ sources
3182
+ };
2583
3183
  }
2584
3184
  function csvRows(content) {
2585
3185
  const rows = [];
@@ -2775,6 +3375,63 @@ function migrateCatalogs(cfg, options = {}) {
2775
3375
  };
2776
3376
  }
2777
3377
  //#endregion
3378
+ //#region src/project.ts
3379
+ async function syncProject(cfg, options = {}) {
3380
+ const registry = options.registry ?? await extractProject(cfg);
3381
+ const catalogs = options.catalogs ?? loadCatalogs(cfg);
3382
+ if (options.confirm) confirmFromDisk(cfg, catalogs, registry);
3383
+ const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;
3384
+ const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};
3385
+ const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
3386
+ const result = {
3387
+ registry,
3388
+ catalogs,
3389
+ added,
3390
+ replaced,
3391
+ pruned,
3392
+ pruneBlocked,
3393
+ findings: scanFindings(cfg, registry, replaced),
3394
+ written: {}
3395
+ };
3396
+ if (options.dryRun) return result;
3397
+ const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
3398
+ if (replaced.length > 0) changed.add(cfg.sourceLocale);
3399
+ for (const locale of cfg.locales) {
3400
+ if (options.write === "changed" && !changed.has(locale)) continue;
3401
+ result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
3402
+ }
3403
+ writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
3404
+ try {
3405
+ result.state = updateState(cfg, catalogs);
3406
+ } catch (error) {
3407
+ result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
3408
+ }
3409
+ return result;
3410
+ }
3411
+ function confirmFromDisk(cfg, catalogs, registry) {
3412
+ const source = catalogs[cfg.sourceLocale] ?? {};
3413
+ const stale = /* @__PURE__ */ new Set();
3414
+ for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
3415
+ for (const file of stale) {
3416
+ let code;
3417
+ try {
3418
+ code = readFileSync(file, "utf8");
3419
+ } catch {
3420
+ registry.remove(file);
3421
+ continue;
3422
+ }
3423
+ registry.update(file, analyzeFile(code, file));
3424
+ }
3425
+ }
3426
+ //#endregion
3427
+ //#region src/warn.ts
3428
+ const warned = /* @__PURE__ */ new Set();
3429
+ function warnOnce(message, dedupeKey = message) {
3430
+ if (warned.has(dedupeKey)) return;
3431
+ warned.add(dedupeKey);
3432
+ console.warn(`[verbaly] ${message}`);
3433
+ }
3434
+ //#endregion
2778
3435
  //#region src/render.ts
2779
3436
  function localeInstance(catalogs, locale, sourceLocale) {
2780
3437
  return createVerbaly({
@@ -3218,13 +3875,16 @@ function decodeEntities(text) {
3218
3875
  }
3219
3876
  //#endregion
3220
3877
  //#region src/status.ts
3221
- function status(cfg, catalogs, registry, drafts = {}) {
3878
+ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
3222
3879
  const extracted = registry.messages();
3223
3880
  const flat = {};
3224
3881
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
3225
3882
  const source = flat[cfg.sourceLocale] ?? {};
3226
3883
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
3227
3884
  const live = effectiveDrafts(drafts, flat);
3885
+ const shipped = shippedCatalogs(cfg, flat, registry);
3886
+ const sourceText = shipped[cfg.sourceLocale];
3887
+ const outdated = outdatedTranslations(cfg, shipped, fingerprints);
3228
3888
  const locales = [];
3229
3889
  for (const locale of cfg.locales) {
3230
3890
  if (locale === cfg.sourceLocale) continue;
@@ -3234,7 +3894,7 @@ function status(cfg, catalogs, registry, drafts = {}) {
3234
3894
  let broken = 0;
3235
3895
  for (const [key, text] of Object.entries(catalog)) {
3236
3896
  if (!text) continue;
3237
- const from = source[key] ?? extracted.get(key)?.message;
3897
+ const from = sourceText[key];
3238
3898
  if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
3239
3899
  }
3240
3900
  locales.push({
@@ -3242,7 +3902,8 @@ function status(cfg, catalogs, registry, drafts = {}) {
3242
3902
  translated,
3243
3903
  total: needed.size,
3244
3904
  drafts: live[locale]?.length ?? 0,
3245
- broken
3905
+ broken,
3906
+ outdated: outdated.filter((entry) => entry.locale === locale).length
3246
3907
  });
3247
3908
  }
3248
3909
  return {
@@ -3257,10 +3918,14 @@ function formatStatusResult(result) {
3257
3918
  lines.push(" no target locales (add locales to your config)");
3258
3919
  return lines.join("\n");
3259
3920
  }
3260
- for (const { locale, translated, total, drafts, broken } of result.locales) {
3921
+ for (const { locale, translated, total, drafts, broken, outdated } of result.locales) {
3261
3922
  const pct = total === 0 ? 100 : Math.floor(translated / total * 100);
3262
- const mark = translated === total && broken === 0 ? " ✓" : "";
3263
- const notes = [drafts > 0 ? `${drafts} unreviewed` : "", broken > 0 ? `${broken} broken` : ""].filter(Boolean);
3923
+ const mark = translated === total && broken === 0 && outdated === 0 ? " ✓" : "";
3924
+ const notes = [
3925
+ drafts > 0 ? `${drafts} unreviewed` : "",
3926
+ broken > 0 ? `${broken} broken` : "",
3927
+ outdated > 0 ? `${outdated} outdated` : ""
3928
+ ].filter(Boolean);
3264
3929
  const note = notes.length > 0 ? `, ${notes.join(", ")}` : "";
3265
3930
  lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);
3266
3931
  }
@@ -3427,7 +4092,7 @@ function wrapCode(code, file) {
3427
4092
  const s = new MagicString(code);
3428
4093
  const visited = /* @__PURE__ */ new Set();
3429
4094
  let changed = false;
3430
- walk(ast, (node) => {
4095
+ walk$1(ast, (node) => {
3431
4096
  if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
3432
4097
  if (visited.has(node)) return;
3433
4098
  processElement(node);
@@ -3556,7 +4221,7 @@ function wrapCode(code, file) {
3556
4221
  return text.length > 60 ? text.slice(0, 59) + "…" : text;
3557
4222
  }
3558
4223
  function markSubtree(node) {
3559
- walk(node, (n) => {
4224
+ walk$1(node, (n) => {
3560
4225
  if (n.type === "JSXElement" || n.type === "JSXFragment") visited.add(n);
3561
4226
  });
3562
4227
  }
@@ -3572,7 +4237,7 @@ function hasDirective(program, value) {
3572
4237
  }
3573
4238
  function declaresT(program) {
3574
4239
  let found = false;
3575
- walk(program, (node) => {
4240
+ walk$1(program, (node) => {
3576
4241
  if (found) return;
3577
4242
  if (node.type === "ImportDeclaration") {
3578
4243
  for (const spec of node.specifiers) if (isTName(spec.local?.name)) found = true;
@@ -3604,7 +4269,7 @@ function hasVerbalyAttr(opening) {
3604
4269
  }
3605
4270
  function usesT(node) {
3606
4271
  let found = false;
3607
- walk(node, (n) => {
4272
+ walk$1(node, (n) => {
3608
4273
  if (n.type === "TaggedTemplateExpression" && isTReference(n.tag, T_NAMES)) found = true;
3609
4274
  if (n.type === "CallExpression" && isTReference(n.callee, T_NAMES)) found = true;
3610
4275
  });
@@ -3612,7 +4277,7 @@ function usesT(node) {
3612
4277
  }
3613
4278
  function containsJsx(node) {
3614
4279
  let found = false;
3615
- walk(node, (n) => {
4280
+ walk$1(node, (n) => {
3616
4281
  if (n.type === "JSXElement" || n.type === "JSXFragment") found = true;
3617
4282
  });
3618
4283
  return found;
@@ -3642,7 +4307,7 @@ Usage:
3642
4307
  verbaly status translation coverage per locale, at a glance
3643
4308
  verbaly check verify translations are complete (CI)
3644
4309
  verbaly translate fill missing translations via a provider (default: claude)
3645
- verbaly review list machine translations awaiting review (--approve marks them reviewed)
4310
+ verbaly review [keys…] list translations awaiting review: machine drafts and outdated ones (--approve accepts them)
3646
4311
  verbaly export write translator files (XLIFF 2.0, CSV, gettext PO) or mobile resources (Android, iOS)
3647
4312
  verbaly import <files…> fill catalogs back from translated XLIFF/CSV/PO files
3648
4313
  verbaly pseudo generate a pseudo-locale catalog for i18n QA (default: en-XA)
@@ -3659,7 +4324,8 @@ Options:
3659
4324
  --plurals also merge _one/_other into one message with variants (migrate)
3660
4325
  --json machine-readable output (status)
3661
4326
  --drafts also fail on unreviewed machine translations (check)
3662
- --approve mark listed drafts as reviewed (review)
4327
+ --outdated also fail on translations written for an older source text (check)
4328
+ --approve accept what review lists, drafts and outdated, or only the keys given (review)
3663
4329
  --reporter <name> failure format: text (default) or github annotations (check)
3664
4330
  --model <id> model override for the claude provider (translate)
3665
4331
  --dry-run list what would happen, write nothing (translate, import, extract)
@@ -3667,6 +4333,7 @@ Options:
3667
4333
  --out <path> export directory (export, default: verbaly-export)
3668
4334
  --missing export only untranslated entries (export)
3669
4335
  --overwrite replace existing translations on import (import)
4336
+ --draft mark what the files bring as drafts a person still has to review (import)
3670
4337
  --locale <id> pseudo-locale id (pseudo) / one locale only (review, import)
3671
4338
  --site <path> built site directory (render, default: dist)
3672
4339
  --attribute <name> base data attribute (render, default: data-verbaly)
@@ -3693,6 +4360,8 @@ async function runCli(args = process.argv.slice(2)) {
3693
4360
  write: { type: "boolean" },
3694
4361
  json: { type: "boolean" },
3695
4362
  drafts: { type: "boolean" },
4363
+ outdated: { type: "boolean" },
4364
+ draft: { type: "boolean" },
3696
4365
  approve: { type: "boolean" },
3697
4366
  reporter: { type: "string" },
3698
4367
  model: { type: "string" },
@@ -3766,25 +4435,28 @@ async function runCli(args = process.argv.slice(2)) {
3766
4435
  process.exitCode = 1;
3767
4436
  return;
3768
4437
  }
4438
+ const reporter = values.watch ? createDevReporter(cfg.root, (line) => console.warn(` ${line}`)) : void 0;
3769
4439
  async function runExtract() {
3770
- const registry = await extractProject(cfg);
3771
- const catalogs = loadCatalogs(cfg);
3772
- if (values.prune) {
3773
- const removed = pruneCatalogs(cfg, catalogs, registry);
3774
- const unread = registry.parseErrors().length;
3775
- if (unread > 0) console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
3776
- for (const [locale, keys] of Object.entries(removed)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
3777
- }
3778
- const { added } = syncCatalogs(cfg, catalogs, registry);
3779
- if (!dryRun) {
3780
- for (const locale of cfg.locales) writeCatalog(cfg, locale, catalogs[locale] ?? {});
3781
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
4440
+ const result = await syncProject(cfg, {
4441
+ prune: values.prune,
4442
+ dryRun
4443
+ });
4444
+ if (result.pruneBlocked) {
4445
+ const unread = result.registry.parseErrors().length;
4446
+ console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
3782
4447
  }
3783
- const total = registry.messages().size;
4448
+ for (const [locale, keys] of Object.entries(result.pruned)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
4449
+ const total = result.registry.messages().size;
3784
4450
  console.log(`[verbaly] ${counted(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
3785
- for (const [locale, keys] of Object.entries(added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
3786
- reportParseErrors(cfg, registry);
3787
- reportEscapedSyntax(cfg, registry);
4451
+ for (const [locale, keys] of Object.entries(result.added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
4452
+ const warnings = result.findings.filter((finding) => {
4453
+ if (finding.kind !== "replaced") return true;
4454
+ console.log(` ${formatFinding(finding, cfg.root)}`);
4455
+ return false;
4456
+ });
4457
+ if (reporter) reporter.report("extract", warnings);
4458
+ else for (const finding of warnings) console.warn(` ${formatFinding(finding, cfg.root)}`);
4459
+ if (result.stateProblem) console.warn(` ${result.stateProblem}, so drafts and outdated translations were not updated`);
3788
4460
  }
3789
4461
  await runExtract();
3790
4462
  if (values.watch) {
@@ -3850,7 +4522,9 @@ async function runCli(args = process.argv.slice(2)) {
3850
4522
  }
3851
4523
  if (command === "status") {
3852
4524
  const registry = await extractProject(cfg);
3853
- const result = status(cfg, loadCatalogs(cfg), registry, loadDrafts(cfg));
4525
+ const { state, problem } = readState(cfg);
4526
+ if (problem) console.warn(`[verbaly] ${problem}, so drafts and outdated translations are not counted`);
4527
+ const result = status(cfg, loadCatalogs(cfg), registry, state.drafts, state.fingerprints);
3854
4528
  console.log(values.json ? JSON.stringify(result) : formatStatusResult(result));
3855
4529
  return;
3856
4530
  }
@@ -3863,39 +4537,44 @@ async function runCli(args = process.argv.slice(2)) {
3863
4537
  }
3864
4538
  const registry = await extractProject(cfg);
3865
4539
  const catalogs = loadCatalogs(cfg);
3866
- const result = check(cfg, catalogs, registry);
3867
- const unreviewed = values.drafts ? effectiveDrafts(loadDrafts(cfg), catalogs) : {};
3868
- const draftKeys = Object.entries(unreviewed);
3869
- if (reporter === "github") for (const line of githubCheckAnnotations(result, registry, cfg.root)) console.error(line);
4540
+ const state = checkState(cfg, values.drafts === true || values.outdated === true);
4541
+ const result = check(cfg, catalogs, registry, state.fingerprints);
4542
+ const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};
4543
+ const outdated = values.outdated ? result.outdated : [];
4544
+ const gated = { outdatedFails: values.outdated === true };
4545
+ if (reporter === "github") for (const line of githubCheckAnnotations(result, registry, cfg, gated)) console.error(line);
3870
4546
  else {
3871
- const warnings = formatCheckWarnings(result);
4547
+ const warnings = formatCheckWarnings(result, cfg.root, gated);
3872
4548
  if (warnings) console.warn(`[verbaly] warnings (the gate still passes)\n${warnings}`);
3873
4549
  }
3874
- if (result.ok && draftKeys.length === 0) {
4550
+ const awaiting = [...Object.entries(unreviewed).map(([locale, keys]) => ` [${locale}] ${keys.length} unreviewed: ${keys.join(", ")}`), ...byLocale(outdated).map(([locale, keys]) => ` [${locale}] ${keys.length} outdated: ${keys.join(", ")}`)];
4551
+ if (result.ok && awaiting.length === 0) {
3875
4552
  console.log("[verbaly] all translations complete ✓");
3876
4553
  return;
3877
4554
  }
3878
- if (result.ok && draftKeys.length > 0) {
3879
- for (const [locale, keys] of draftKeys) console.error(` [${locale}] ${keys.length} unreviewed: ${keys.join(", ")}`);
3880
- console.error("[verbaly] check failed: machine translations awaiting review (run verbaly review --approve)");
3881
- process.exitCode = 1;
3882
- return;
4555
+ if (!result.ok) {
4556
+ const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
4557
+ const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
4558
+ console.error(`${report}\n${checkNextSteps(result)}`);
4559
+ }
4560
+ if (awaiting.length > 0) {
4561
+ for (const line of awaiting) console.error(line);
4562
+ console.error("[verbaly] check failed: translations awaiting review (run verbaly review, then --approve what holds)");
3883
4563
  }
3884
- const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
3885
- const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
3886
- console.error(`${report}\n${checkNextSteps(result)}`);
3887
4564
  process.exitCode = 1;
3888
4565
  return;
3889
4566
  }
3890
4567
  if (command === "translate") {
3891
- const catalogs = loadCatalogs(cfg);
4568
+ if (!values["dry-run"]) loadState(cfg);
4569
+ const registry = await extractProject(cfg);
4570
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
3892
4571
  const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
3893
4572
  locales: csv(values.locales),
3894
4573
  batchSize: cfg.translate.batchSize,
3895
4574
  concurrency: cfg.translate.concurrency,
3896
4575
  retries: cfg.translate.retries,
3897
4576
  dryRun: values["dry-run"],
3898
- origins: values["dry-run"] ? void 0 : await collectOrigins(cfg),
4577
+ origins: values["dry-run"] ? void 0 : await collectOrigins(cfg, registry),
3899
4578
  onProgress: values["dry-run"] ? void 0 : reportProgress
3900
4579
  });
3901
4580
  if (values["dry-run"]) {
@@ -3907,15 +4586,24 @@ async function runCli(args = process.argv.slice(2)) {
3907
4586
  for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.length} missing: ${keys.join(", ")}`);
3908
4587
  return;
3909
4588
  }
3910
- const drafts = loadDrafts(cfg);
4589
+ const source = catalogs[cfg.sourceLocale] ?? {};
4590
+ const writes = [];
3911
4591
  for (const [locale, keys] of Object.entries(result.translated)) {
3912
- const written = mergeTranslations(cfg, locale, catalogs[locale] ?? {}, keys);
3913
- markDrafts(drafts, locale, written);
4592
+ const catalog = catalogs[locale] ?? {};
4593
+ const written = mergeTranslations(cfg, locale, catalog, keys);
4594
+ writes.push({
4595
+ locale,
4596
+ draft: true,
4597
+ entries: written.map((key) => ({
4598
+ key,
4599
+ text: catalog[key]
4600
+ }))
4601
+ });
3914
4602
  console.log(` ${locale}: +${written.length} translated (draft)`);
3915
4603
  const kept = keys.length - written.length;
3916
4604
  if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
3917
4605
  }
3918
- if (Object.keys(result.translated).length > 0) saveDrafts(cfg, drafts);
4606
+ if (writes.length > 0) recordTranslations(cfg, source, writes);
3919
4607
  for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
3920
4608
  for (const line of formatTranslateFailures(result.failed)) console.error(line);
3921
4609
  if (result.failed.length > 0) process.exitCode = 1;
@@ -3923,29 +4611,49 @@ async function runCli(args = process.argv.slice(2)) {
3923
4611
  return;
3924
4612
  }
3925
4613
  if (command === "review") {
4614
+ const registry = await extractProject(cfg);
3926
4615
  const catalogs = loadCatalogs(cfg);
3927
- const drafts = loadDrafts(cfg);
3928
- const live = effectiveDrafts(drafts, catalogs);
3929
- const targets = values.locale ? { [values.locale]: live[values.locale] ?? [] } : live;
3930
- const entries = Object.entries(targets).filter(([, keys]) => keys.length);
3931
- if (entries.length === 0) {
3932
- console.log("[verbaly] no machine translations awaiting review ✓");
4616
+ const shipped = shippedCatalogs(cfg, catalogs, registry);
4617
+ const state = loadState(cfg);
4618
+ const only = new Set(positionals.slice(1));
4619
+ const wanted = ({ locale, key }) => (!values.locale || locale === values.locale) && (only.size === 0 || only.has(key));
4620
+ const drafts = Object.entries(effectiveDrafts(state.drafts, catalogs)).flatMap(([locale, keys]) => keys.map((key) => ({
4621
+ locale,
4622
+ key
4623
+ }))).filter(wanted);
4624
+ const outdated = outdatedTranslations(cfg, shipped, state.fingerprints).filter(wanted);
4625
+ if (drafts.length === 0 && outdated.length === 0) {
4626
+ console.log("[verbaly] nothing awaiting review ✓");
3933
4627
  return;
3934
4628
  }
3935
4629
  if (values.approve) {
3936
- let count = 0;
3937
- for (const [locale, keys] of entries) {
3938
- clearDrafts(drafts, locale, keys);
3939
- count += keys.length;
4630
+ for (const [locale, keys] of byLocale(drafts)) {
4631
+ clearDrafts(state.drafts, locale, keys);
3940
4632
  console.log(` ${locale}: ${keys.length} approved`);
3941
4633
  }
3942
- saveDrafts(cfg, drafts);
3943
- console.log(`[verbaly] ${counted(count, "translation")} marked reviewed ✓`);
4634
+ acceptOutdated(cfg, shipped, state.fingerprints, outdated);
4635
+ for (const [locale, keys] of byLocale(outdated)) console.log(` ${locale}: ${keys.length} kept for the new source text`);
4636
+ saveState(cfg, state);
4637
+ const reviewed = new Set([...drafts, ...outdated].map(({ locale, key }) => `${locale}:${key}`));
4638
+ console.log(`[verbaly] ${counted(reviewed.size, "translation")} marked reviewed ✓`);
3944
4639
  return;
3945
4640
  }
3946
- const total = entries.reduce((sum, [, keys]) => sum + keys.length, 0);
3947
- console.log(`[verbaly] ${counted(total, "machine translation")} awaiting review (--approve to accept)`);
3948
- for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.join(", ")}`);
4641
+ const source = shipped[cfg.sourceLocale] ?? {};
4642
+ const show = (locale, keys) => {
4643
+ console.log(` ${locale}:`);
4644
+ for (const key of keys) {
4645
+ const translated = catalogs[locale]?.[key] ?? "";
4646
+ console.log(` ${key}: "${truncate(source[key] ?? "", 60)}" → "${truncate(translated, 60)}"`);
4647
+ }
4648
+ };
4649
+ if (drafts.length > 0) {
4650
+ console.log(`[verbaly] ${counted(drafts.length, "machine translation")} awaiting review (--approve to accept)`);
4651
+ for (const [locale, keys] of byLocale(drafts)) show(locale, keys);
4652
+ }
4653
+ if (outdated.length > 0) {
4654
+ console.log(`[verbaly] ${counted(outdated.length, "translation")} written for an older source text (update them, or --approve keeps them)`);
4655
+ for (const [locale, keys] of byLocale(outdated)) show(locale, keys);
4656
+ }
3949
4657
  return;
3950
4658
  }
3951
4659
  if (command === "export") {
@@ -3966,12 +4674,13 @@ async function runCli(args = process.argv.slice(2)) {
3966
4674
  process.exitCode = 1;
3967
4675
  return;
3968
4676
  }
3969
- const result = exportCatalogs(cfg, loadCatalogs(cfg), {
4677
+ const registry = await extractProject(cfg);
4678
+ const result = exportCatalogs(cfg, shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false }), {
3970
4679
  locales: csv(values.locales),
3971
4680
  format,
3972
4681
  out: values.out,
3973
4682
  missing: values.missing,
3974
- origins: isMobileFormat(format) ? void 0 : await collectOrigins(cfg)
4683
+ origins: isMobileFormat(format) ? void 0 : await collectOrigins(cfg, registry)
3975
4684
  });
3976
4685
  if (result.files.length === 0) {
3977
4686
  console.log("[verbaly] no target locales to export (add locales to your config)");
@@ -3989,7 +4698,9 @@ async function runCli(args = process.argv.slice(2)) {
3989
4698
  process.exitCode = 1;
3990
4699
  return;
3991
4700
  }
3992
- const catalogs = loadCatalogs(cfg);
4701
+ if (!values["dry-run"]) loadState(cfg);
4702
+ const registry = await extractProject(cfg);
4703
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
3993
4704
  const result = importCatalogs(cfg, catalogs, files, {
3994
4705
  locale: values.locale,
3995
4706
  overwrite: values.overwrite,
@@ -4006,18 +4717,27 @@ async function runCli(args = process.argv.slice(2)) {
4006
4717
  }
4007
4718
  process.exitCode = 1;
4008
4719
  }
4009
- const drafts = loadDrafts(cfg);
4010
- let draftsChanged = false;
4720
+ const writes = [];
4011
4721
  for (const [locale, keys] of Object.entries(result.imported)) {
4012
4722
  if (!values["dry-run"]) {
4013
- writeCatalog(cfg, locale, catalogs[locale] ?? {});
4014
- clearDrafts(drafts, locale, keys);
4015
- draftsChanged = true;
4723
+ const catalog = catalogs[locale] ?? {};
4724
+ writeCatalog(cfg, locale, catalog);
4725
+ const seen = result.sources[locale] ?? {};
4726
+ const entries = keys.map((key) => ({
4727
+ key,
4728
+ text: catalog[key],
4729
+ source: seen[key]
4730
+ }));
4731
+ writes.push({
4732
+ locale,
4733
+ entries,
4734
+ draft: values.draft === true
4735
+ });
4016
4736
  }
4017
4737
  const verb = values["dry-run"] ? "would import" : "imported";
4018
- console.log(` ${locale}: +${keys.length} ${verb}`);
4738
+ console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? " (draft)" : ""}`);
4019
4739
  }
4020
- if (draftsChanged) saveDrafts(cfg, drafts);
4740
+ if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
4021
4741
  for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
4022
4742
  for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
4023
4743
  for (const [locale, keys] of Object.entries(result.unknown)) console.warn(` ${locale}: ${counted(keys.length, "unknown key")} ignored (not in the source catalog): ${keys.join(", ")}`);
@@ -4062,20 +4782,20 @@ function formatCliError(error) {
4062
4782
  const message = error instanceof Error ? error.message : String(error);
4063
4783
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
4064
4784
  }
4065
- function reportParseErrors(cfg, registry) {
4066
- for (const { file, message } of registry.parseErrors()) {
4067
- const rel = relative(cfg.root, file).replaceAll("\\", "/");
4068
- console.warn(` ${rel}: could not be parsed (${message}), its messages were not extracted`);
4069
- }
4785
+ function checkState(cfg, gating) {
4786
+ if (gating) return loadState(cfg);
4787
+ const { state, problem } = readState(cfg);
4788
+ if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);
4789
+ return state;
4070
4790
  }
4071
- function reportEscapedSyntax(cfg, registry) {
4072
- for (const msg of registry.messages().values()) {
4073
- const slice = escapedSyntax(msg.message);
4074
- if (!slice) continue;
4075
- const file = relative(cfg.root, msg.file).replaceAll("\\", "/");
4076
- console.warn(` ${file}: ${slice} renders as literal text, a tagged template has no params`);
4077
- console.warn(" use t(key, params) for a plural or format block, or pass a ${…} value");
4791
+ function byLocale(entries) {
4792
+ const out = /* @__PURE__ */ new Map();
4793
+ for (const { locale, key } of entries) {
4794
+ const keys = out.get(locale);
4795
+ if (keys) keys.push(key);
4796
+ else out.set(locale, [key]);
4078
4797
  }
4798
+ return [...out];
4079
4799
  }
4080
4800
  const COMMON_FLAGS = /* @__PURE__ */ new Set([
4081
4801
  "root",
@@ -4095,7 +4815,11 @@ const COMMAND_FLAGS = {
4095
4815
  wrap: ["write"],
4096
4816
  migrate: ["write", "plurals"],
4097
4817
  status: ["json"],
4098
- check: ["reporter", "drafts"],
4818
+ check: [
4819
+ "reporter",
4820
+ "drafts",
4821
+ "outdated"
4822
+ ],
4099
4823
  translate: ["model", "dry-run"],
4100
4824
  review: ["approve", "locale"],
4101
4825
  export: [
@@ -4106,7 +4830,8 @@ const COMMAND_FLAGS = {
4106
4830
  import: [
4107
4831
  "locale",
4108
4832
  "overwrite",
4109
- "dry-run"
4833
+ "dry-run",
4834
+ "draft"
4110
4835
  ],
4111
4836
  pseudo: ["locale"],
4112
4837
  render: [
@@ -4136,6 +4861,6 @@ runCli().catch((error) => {
4136
4861
  process.exitCode = 1;
4137
4862
  });
4138
4863
  //#endregion
4139
- export { isModuleNotFound as n, counted as t };
4864
+ export { counted as n, isModuleNotFound as t };
4140
4865
 
4141
4866
  //# sourceMappingURL=cli.js.map