@verbaly/compiler 0.78.0 → 0.80.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.
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
@@ -10,7 +10,7 @@ import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
10
10
  import picomatch from "picomatch";
11
11
  import MagicString from "magic-string";
12
12
  import { parseArgs } from "node:util";
13
- // src/host.ts
13
+ // src/config/host.ts
14
14
  const HOSTS = [
15
15
  {
16
16
  name: "nuxt",
@@ -130,6 +130,11 @@ function installCommand(root, packages, dev = false) {
130
130
  const manager = packageManager(root);
131
131
  return `${manager} ${manager === "npm" ? "install" : "add"}${dev ? manager === "bun" ? " -d" : " -D" : ""} ${packages.join(" ")}`;
132
132
  }
133
+ function cliReachable(root) {
134
+ const bin = join(root, "node_modules", ".bin");
135
+ return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
136
+ }
137
+ const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
133
138
  const TYPE_SLOTS = {
134
139
  next: [".verbaly", "types.d.ts"],
135
140
  astro: [
@@ -145,17 +150,155 @@ function defaultTypesPath(root, host = detectHost(root)?.name) {
145
150
  if (slot) return join(root, ...slot);
146
151
  return existsSync(join(root, "src")) ? join(root, "src", "verbaly.d.ts") : join(root, "verbaly.d.ts");
147
152
  }
148
- // src/eol.ts
153
+ // src/util/warn.ts
154
+ const warned = /* @__PURE__ */ new Set();
155
+ function warnOnce(message, dedupeKey = message) {
156
+ if (warned.has(dedupeKey)) return;
157
+ warned.add(dedupeKey);
158
+ console.warn(`[verbaly] ${message}`);
159
+ }
160
+ function warnParseError(file, message) {
161
+ warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
162
+ }
163
+ // src/config/config.ts
164
+ const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}";
165
+ const PSEUDO_LOCALE = "en-XA";
166
+ function resolveConfig(config = {}) {
167
+ const root = resolve(config.root ?? process.cwd());
168
+ const dir = resolve(root, config.dir ?? "locales");
169
+ const sourceLocale = config.sourceLocale ?? "en";
170
+ const host = detectHost(root)?.name;
171
+ const localesDeclared = config.locales !== void 0;
172
+ const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
173
+ if (!localesDeclared && existsSync(dir)) {
174
+ for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
175
+ }
176
+ return {
177
+ root,
178
+ dir,
179
+ sourceLocale,
180
+ localesDeclared,
181
+ routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
182
+ icu: config.icu,
183
+ relative: config.relative,
184
+ locales: [...locales],
185
+ include: config.include ?? [`{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}`],
186
+ exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
187
+ dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts === false ? false : defaultTypesPath(root, host),
188
+ translate: config.translate ?? {},
189
+ render: config.render ?? {},
190
+ bundle: config.bundle ?? {},
191
+ host,
192
+ trailingSlash: config.trailingSlash
193
+ };
194
+ }
195
+ const CONFIG_FILES = [
196
+ "verbaly.config.js",
197
+ "verbaly.config.mjs",
198
+ "verbaly.config.ts",
199
+ "verbaly.config.mts",
200
+ "verbaly.config.json"
201
+ ];
202
+ function findConfigFile(root) {
203
+ return CONFIG_FILES.find((name) => existsSync(join(root, name)));
204
+ }
205
+ async function loadConfigFile(root) {
206
+ for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
207
+ const path = join(root, name);
208
+ if (existsSync(path)) {
209
+ const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
210
+ const cache = createRequire(import.meta.url).cache;
211
+ delete cache[realpathSync(path)];
212
+ delete cache[resolve(path)];
213
+ return (await import(url)).default ?? {};
214
+ }
215
+ }
216
+ for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
217
+ const path = join(root, name);
218
+ if (existsSync(path)) return loadTsConfig(path);
219
+ }
220
+ const jsonPath = join(root, "verbaly.config.json");
221
+ if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
222
+ return {};
223
+ }
224
+ function readJsonConfig(path) {
225
+ const content = readFileSync(path, "utf8");
226
+ const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
227
+ try {
228
+ return JSON.parse(body);
229
+ } catch (error) {
230
+ throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
231
+ }
232
+ }
233
+ async function loadTsConfig(path) {
234
+ const { createJiti } = await import("jiti");
235
+ const mod = await createJiti(import.meta.url, {
236
+ fsCache: false,
237
+ moduleCache: false,
238
+ interopDefault: false
239
+ }).import(path);
240
+ return mod.__esModule ? mod.default ?? {} : mod;
241
+ }
242
+ function isModuleNotFound(error, name) {
243
+ return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
244
+ }
245
+ function targetLocales(cfg, override) {
246
+ return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
247
+ }
248
+ async function loadConfig(root, overrides = {}, from = {}) {
249
+ const fileConfig = await loadConfigFile(root);
250
+ if (from.plugin) warnPluginOnly(root, fileConfig, overrides);
251
+ return resolveConfig({
252
+ ...fileConfig,
253
+ ...definedOnly(overrides),
254
+ root
255
+ });
256
+ }
257
+ const READ_BY_CLI = [
258
+ "sourceLocale",
259
+ "locales",
260
+ "dir",
261
+ "include",
262
+ "exclude"
263
+ ];
264
+ const pluginOnly = /* @__PURE__ */ new Map();
265
+ function pluginOnlyOptions(root) {
266
+ return pluginOnly.get(root) ?? "";
267
+ }
268
+ function warnPluginOnly(root, file, overrides) {
269
+ const cli = resolveConfig({
270
+ ...file,
271
+ root
272
+ });
273
+ const build = resolveConfig({
274
+ ...file,
275
+ ...definedOnly(overrides),
276
+ root
277
+ });
278
+ const keys = READ_BY_CLI.filter((key) => overrides[key] !== void 0 && JSON.stringify(cli[key]) !== JSON.stringify(build[key]));
279
+ if (keys.length === 0) {
280
+ pluginOnly.delete(cli.root);
281
+ return;
282
+ }
283
+ const names = keys.length > 1 ? `${keys.slice(0, -1).join(", ")} and ${keys.at(-1)}` : keys[0];
284
+ pluginOnly.set(cli.root, names);
285
+ const [verb, pronoun] = keys.length > 1 ? ["are", "them"] : ["is", "it"];
286
+ warnOnce(`${names} ${verb} set in the plugin options, which \`verbaly check\` and \`verbaly extract\` never read: move ${pronoun} to verbaly.config so the command line checks what the build ships`, `plugin-only:${root}`);
287
+ }
288
+ function definedOnly(config) {
289
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
290
+ }
291
+ // src/util/eol.ts
149
292
  function withLineEndings(text, existing) {
150
293
  const first = existing?.indexOf("\n") ?? -1;
151
294
  return first > 0 && existing[first - 1] === "\r" ? text.replace(/\r?\n/g, "\r\n") : text;
152
295
  }
153
- // src/catalog.ts
296
+ // src/catalog/catalog.ts
154
297
  function emptyCatalog() {
155
298
  return Object.create(null);
156
299
  }
157
- function own(catalog, key) {
158
- return Object.hasOwn(catalog, key) ? catalog[key] : void 0;
300
+ function own(map, key) {
301
+ return Object.hasOwn(map, key) ? map[key] : void 0;
159
302
  }
160
303
  function flatView(tree) {
161
304
  if (typeof tree !== "object" || tree === null || Object.getPrototypeOf(tree) !== null) return flatten(tree);
@@ -208,7 +351,7 @@ function isTree(value) {
208
351
  return typeof value === "object" && value !== null && !Array.isArray(value);
209
352
  }
210
353
  function loadCatalogs(cfg) {
211
- const catalogs = {};
354
+ const catalogs = emptyCatalog();
212
355
  for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
213
356
  return catalogs;
214
357
  }
@@ -305,269 +448,29 @@ function someLeaf(tree, pattern) {
305
448
  } else if (isTree(value) && someLeaf(value, pattern)) return true;
306
449
  return false;
307
450
  }
308
- // src/pseudo.ts
309
- const PSEUDO_LOCALE = "en-XA";
310
- const ACCENTS = {
311
- a: "á",
312
- b: "ƀ",
313
- c: "ç",
314
- d: "đ",
315
- e: "é",
316
- f: "ƒ",
317
- g: "ğ",
318
- h: "ĥ",
319
- i: "í",
320
- j: "ĵ",
321
- k: "ķ",
322
- l: "ĺ",
323
- m: "ɱ",
324
- n: "ñ",
325
- o: "ó",
326
- p: "þ",
327
- q: "ǫ",
328
- r: "ŕ",
329
- s: "š",
330
- t: "ţ",
331
- u: "ú",
332
- v: "ṽ",
333
- w: "ŵ",
334
- x: "ẋ",
335
- y: "ý",
336
- z: "ž",
337
- A: "Á",
338
- B: "Ɓ",
339
- C: "Ç",
340
- D: "Đ",
341
- E: "É",
342
- F: "Ƒ",
343
- G: "Ğ",
344
- H: "Ĥ",
345
- I: "Í",
346
- J: "Ĵ",
347
- K: "Ķ",
348
- L: "Ĺ",
349
- M: "Ḿ",
350
- N: "Ñ",
351
- O: "Ó",
352
- P: "Þ",
353
- Q: "Ǫ",
354
- R: "Ŕ",
355
- S: "Š",
356
- T: "Ţ",
357
- U: "Ú",
358
- V: "Ṽ",
359
- W: "Ŵ",
360
- X: "Ẍ",
361
- Y: "Ý",
362
- Z: "Ž"
363
- };
364
- const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
365
- function pseudoLocalize(message) {
366
- let out = "";
367
- let letters = 0;
368
- let i = 0;
369
- while (i < message.length) {
370
- const two = message.slice(i, i + 2);
371
- if (two === "{{" || two === "}}" || two === "||" || two === "##") {
372
- out += two;
373
- i += 2;
374
- continue;
375
- }
376
- const ch = message[i];
377
- if (ch === "{") {
378
- const end = matchBrace$1(message, i);
379
- out += message.slice(i, end);
380
- i = end;
381
- continue;
382
- }
383
- if (ch === "<") {
384
- TAG_AT.lastIndex = i;
385
- const m = TAG_AT.exec(message);
386
- if (m) {
387
- out += m[0];
388
- i += m[0].length;
389
- continue;
390
- }
391
- }
392
- const mapped = ACCENTS[ch];
393
- if (mapped) {
394
- out += mapped;
395
- letters += 1;
396
- } else out += ch;
397
- i += 1;
398
- }
399
- const pad = "~".repeat(Math.ceil(letters / 3));
400
- return `⟦${out}${pad ? " " + pad : ""}⟧`;
451
+ // src/util/text.ts
452
+ function counted(count, noun, many = `${noun}s`) {
453
+ return `${count} ${count === 1 ? noun : many}`;
401
454
  }
402
- function matchBrace$1(message, start) {
403
- let depth = 0;
404
- for (let i = start; i < message.length; i++) {
405
- const two = message.slice(i, i + 2);
406
- if (two === "{{" || two === "}}") {
407
- i += 1;
408
- continue;
409
- }
410
- const ch = message[i];
411
- if (ch === "{") depth += 1;
412
- else if (ch === "}") {
413
- depth -= 1;
414
- if (depth === 0) return i + 1;
415
- }
416
- }
417
- return message.length;
455
+ function truncate(text, max) {
456
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
418
457
  }
419
- function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
420
- const source = catalogs[cfg.sourceLocale] ?? {};
421
- const target = emptyCatalog();
422
- for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
423
- catalogs[locale] = target;
424
- return Object.keys(target).filter((key) => target[key]);
458
+ function trimTrailingSlashes(text) {
459
+ let end = text.length;
460
+ while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
461
+ return text.slice(0, end);
425
462
  }
426
- // src/warn.ts
427
- const warned = /* @__PURE__ */ new Set();
428
- function warnOnce(message, dedupeKey = message) {
429
- if (warned.has(dedupeKey)) return;
430
- warned.add(dedupeKey);
431
- console.warn(`[verbaly] ${message}`);
463
+ function byCodeUnit(a, b) {
464
+ return a < b ? -1 : a > b ? 1 : 0;
432
465
  }
433
- function warnParseError(file, message) {
434
- warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
435
- }
436
- // src/config.ts
437
- const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}";
438
- function resolveConfig(config = {}) {
439
- const root = resolve(config.root ?? process.cwd());
440
- const dir = resolve(root, config.dir ?? "locales");
441
- const sourceLocale = config.sourceLocale ?? "en";
442
- const host = detectHost(root)?.name;
443
- const localesDeclared = config.locales !== void 0;
444
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
445
- if (!localesDeclared && existsSync(dir)) {
446
- for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
447
- }
448
- return {
449
- root,
450
- dir,
451
- sourceLocale,
452
- localesDeclared,
453
- routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
454
- icu: config.icu,
455
- relative: config.relative,
456
- locales: [...locales],
457
- include: config.include ?? [`{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}`],
458
- exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
459
- dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts === false ? false : defaultTypesPath(root, host),
460
- translate: config.translate ?? {},
461
- render: config.render ?? {},
462
- bundle: config.bundle ?? {},
463
- host,
464
- trailingSlash: config.trailingSlash
465
- };
466
- }
467
- const CONFIG_FILES = [
468
- "verbaly.config.js",
469
- "verbaly.config.mjs",
470
- "verbaly.config.ts",
471
- "verbaly.config.mts",
472
- "verbaly.config.json"
473
- ];
474
- function findConfigFile(root) {
475
- return CONFIG_FILES.find((name) => existsSync(join(root, name)));
476
- }
477
- async function loadConfigFile(root) {
478
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
479
- const path = join(root, name);
480
- if (existsSync(path)) {
481
- const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
482
- delete createRequire(import.meta.url).cache[resolve(path)];
483
- return (await import(url)).default ?? {};
484
- }
485
- }
486
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
487
- const path = join(root, name);
488
- if (existsSync(path)) return loadTsConfig(path);
489
- }
490
- const jsonPath = join(root, "verbaly.config.json");
491
- if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
492
- return {};
493
- }
494
- function readJsonConfig(path) {
495
- const content = readFileSync(path, "utf8");
496
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
497
- try {
498
- return JSON.parse(body);
499
- } catch (error) {
500
- throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
501
- }
502
- }
503
- async function loadTsConfig(path) {
504
- const { createJiti } = await import("jiti");
505
- const mod = await createJiti(import.meta.url, {
506
- fsCache: false,
507
- moduleCache: false,
508
- interopDefault: false
509
- }).import(path);
510
- return mod.__esModule ? mod.default ?? {} : mod;
511
- }
512
- function isModuleNotFound(error, name) {
513
- return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
514
- }
515
- function targetLocales(cfg, override) {
516
- return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
517
- }
518
- async function loadConfig(root, overrides = {}, from = {}) {
519
- const fileConfig = await loadConfigFile(root);
520
- if (from.plugin) warnPluginOnly(root, fileConfig, overrides);
521
- return resolveConfig({
522
- ...fileConfig,
523
- ...definedOnly(overrides),
524
- root
525
- });
526
- }
527
- const READ_BY_CLI = [
528
- "sourceLocale",
529
- "locales",
530
- "dir",
531
- "include",
532
- "exclude"
533
- ];
534
- function warnPluginOnly(root, file, overrides) {
535
- const cli = resolveConfig({
536
- ...file,
537
- root
538
- });
539
- const build = resolveConfig({
540
- ...file,
541
- ...definedOnly(overrides),
542
- root
543
- });
544
- const keys = READ_BY_CLI.filter((key) => overrides[key] !== void 0 && JSON.stringify(cli[key]) !== JSON.stringify(build[key]));
545
- if (keys.length === 0) return;
546
- const names = keys.length > 1 ? `${keys.slice(0, -1).join(", ")} and ${keys.at(-1)}` : keys[0];
547
- const [verb, pronoun] = keys.length > 1 ? ["are", "them"] : ["is", "it"];
548
- warnOnce(`${names} ${verb} set in the plugin options, which \`verbaly check\` and \`verbaly extract\` never read: move ${pronoun} to verbaly.config so the command line checks what the build ships`, `plugin-only:${root}`);
549
- }
550
- function definedOnly(config) {
551
- return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
552
- }
553
- // src/text.ts
554
- function counted(count, noun, many = `${noun}s`) {
555
- return `${count} ${count === 1 ? noun : many}`;
556
- }
557
- function truncate(text, max) {
558
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
559
- }
560
- function byCodeUnit(a, b) {
561
- return a < b ? -1 : a > b ? 1 : 0;
562
- }
563
- // src/bundle.ts
466
+ // src/emit/bundle.ts
564
467
  function isExcluded(key, prefixes) {
565
468
  return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
566
469
  }
567
470
  function clientCatalogs(cfg, catalogs) {
568
471
  const prefixes = cfg.bundle.exclude ?? [];
569
472
  if (prefixes.length === 0) return catalogs;
570
- const out = {};
473
+ const out = emptyCatalog();
571
474
  for (const [locale, catalog] of Object.entries(catalogs)) {
572
475
  const kept = emptyCatalog();
573
476
  for (const [key, message] of Object.entries(catalog)) if (!isExcluded(key, prefixes)) kept[key] = message;
@@ -603,7 +506,7 @@ function auditBundle(cfg, catalogs, registry) {
603
506
  function formatBundleIssue(issue) {
604
507
  return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
605
508
  }
606
- // src/registry.ts
509
+ // src/scan/registry.ts
607
510
  var MessageRegistry = class {
608
511
  files = /* @__PURE__ */ new Map();
609
512
  update(file, analysis) {
@@ -676,18 +579,18 @@ var MessageRegistry = class {
676
579
  function earlier(a, b) {
677
580
  return a.file === b.file ? a.start < b.start : a.file < b.file;
678
581
  }
679
- // src/ids.ts
582
+ // src/util/ids.ts
680
583
  const VIRTUAL_ID = "virtual:verbaly";
681
584
  const APP_ID = "verbaly/app";
682
585
  const LOCALE_IMPORT = "@verbaly/app/locale/";
683
586
  function isAppModule(source) {
684
587
  return source === "verbaly/app" || source === "virtual:verbaly";
685
588
  }
686
- // src/key.ts
589
+ // src/util/key.ts
687
590
  function stableKey(message) {
688
591
  return createHash("sha256").update(message).digest("base64url").slice(0, 8);
689
592
  }
690
- // src/analyze.ts
593
+ // src/scan/analyze.ts
691
594
  function parseErrorMessage(error) {
692
595
  return error instanceof Error ? error.message : String(error);
693
596
  }
@@ -716,11 +619,21 @@ function analyzeScript(code, file, options = {}) {
716
619
  const strayImports = [];
717
620
  const bindings = new Bindings(names);
718
621
  const candidates = [];
622
+ let adapterImport;
623
+ let appImported = false;
624
+ const noteLoad = (node) => {
625
+ const source = node.source?.value;
626
+ if (typeof source !== "string" || !loadsAtRuntime(node)) return;
627
+ if (isAppModule(source)) appImported = true;
628
+ else if (ADAPTER_SOURCE.test(source)) adapterImport ??= node.start;
629
+ };
719
630
  walk$1(ast.program, (node) => {
720
631
  if (node.type === "ImportDeclaration") {
721
632
  collectStrayImports(node, file, strayImports);
722
633
  bindings.addImport(node);
723
- } else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
634
+ noteLoad(node);
635
+ } else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") noteLoad(node);
636
+ else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
724
637
  else if (node.type === "TaggedTemplateExpression") {
725
638
  const tag = node.tag;
726
639
  const explicit = explicitId(tag, names);
@@ -794,16 +707,26 @@ function analyzeScript(code, file, options = {}) {
794
707
  loose: true
795
708
  });
796
709
  }
710
+ const analysis = {
711
+ tagged,
712
+ usedKeys,
713
+ strayImports,
714
+ missed
715
+ };
716
+ if (adapterImport !== void 0) analysis.adapterImport = adapterImport;
717
+ if (appImported) analysis.appImported = true;
797
718
  return {
798
- analysis: {
799
- tagged,
800
- usedKeys,
801
- strayImports,
802
- missed
803
- },
719
+ analysis,
804
720
  renamed: [...renamed]
805
721
  };
806
722
  }
723
+ const ADAPTER_SOURCE = /^@verbaly\/(?:react|vue|svelte)(?:\/Trans\.svelte)?$/;
724
+ function loadsAtRuntime(node) {
725
+ if (node.importKind === "type" || node.exportKind === "type") return false;
726
+ const specifiers = node.specifiers ?? [];
727
+ if (specifiers.length === 0) return true;
728
+ return specifiers.some((spec) => spec.importKind !== "type" && spec.exportKind !== "type");
729
+ }
807
730
  function lineOf(node) {
808
731
  return node.loc?.start.line ?? 1;
809
732
  }
@@ -1213,7 +1136,50 @@ function walk$1(node, visit) {
1213
1136
  function isNode(value) {
1214
1137
  return typeof value === "object" && value !== null && typeof value.type === "string";
1215
1138
  }
1216
- // src/sfc.ts
1139
+ // src/util/blocks.ts
1140
+ function blocks(source, shapes) {
1141
+ const found = [];
1142
+ const opens = shapes.map(() => void 0);
1143
+ let from = 0;
1144
+ for (;;) {
1145
+ let pick = -1;
1146
+ for (let i = 0; i < shapes.length; i += 1) {
1147
+ if (opens[i] === null) continue;
1148
+ if (opens[i] === void 0 || opens[i][0] < from) opens[i] = search(source, shapes[i].open, from);
1149
+ if (opens[i] && (pick < 0 || opens[i][0] < opens[pick][0])) pick = i;
1150
+ }
1151
+ if (pick < 0) return found;
1152
+ const block = closed(source, shapes[pick], opens[pick]);
1153
+ if (block) {
1154
+ found.push(block);
1155
+ from = block.end;
1156
+ } else opens[pick] = null;
1157
+ }
1158
+ }
1159
+ function closed(source, shape, [start, openEnd]) {
1160
+ const body = shape.openTag ? source.indexOf(">", openEnd) + 1 : openEnd;
1161
+ if (body === 0) return null;
1162
+ const close = search(source, shape.close, body);
1163
+ if (!close) return null;
1164
+ const end = shape.closeTag ? source.indexOf(">", close[1]) + 1 : close[1];
1165
+ if (end === 0) return null;
1166
+ return {
1167
+ start,
1168
+ body,
1169
+ close: close[0],
1170
+ end
1171
+ };
1172
+ }
1173
+ function search(source, what, from) {
1174
+ if (typeof what === "string") {
1175
+ const at = source.indexOf(what, from);
1176
+ return at < 0 ? null : [at, at + what.length];
1177
+ }
1178
+ what.lastIndex = from;
1179
+ const found = what.exec(source);
1180
+ return found ? [found.index, what.lastIndex] : null;
1181
+ }
1182
+ // src/scan/sfc.ts
1217
1183
  const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
1218
1184
  function analyzeFile(code, file) {
1219
1185
  if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
@@ -1229,11 +1195,25 @@ function analyzeFile(code, file) {
1229
1195
  };
1230
1196
  }
1231
1197
  }
1232
- const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
1233
- const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
1234
- const COMMENT_RE = /<!--[\s\S]*?-->/g;
1198
+ const SCRIPT_BLOCK = {
1199
+ open: /<script\b/gi,
1200
+ openTag: true,
1201
+ close: /<\/script\s*>/gi
1202
+ };
1203
+ const STYLE_BLOCK = {
1204
+ open: /<style\b/gi,
1205
+ openTag: true,
1206
+ close: /<\/style\s*>/gi
1207
+ };
1208
+ const COMMENT_BLOCK = {
1209
+ open: "<!--",
1210
+ close: "-->"
1211
+ };
1235
1212
  const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
1236
- const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
1213
+ const MUSTACHE_BLOCK = {
1214
+ open: "{{",
1215
+ close: "}}"
1216
+ };
1237
1217
  const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
1238
1218
  function analyzeSfc(code, file) {
1239
1219
  const svelte = file.endsWith(".svelte");
@@ -1245,6 +1225,8 @@ function analyzeSfc(code, file) {
1245
1225
  const renamed = /* @__PURE__ */ new Set();
1246
1226
  const lineAt = lineCounter(code);
1247
1227
  let parseError;
1228
+ let adapterImport;
1229
+ let appImported = false;
1248
1230
  const block = (content, offset) => {
1249
1231
  const segment = analyzeSegment(content, file, { tNames });
1250
1232
  parseError ??= segment.error;
@@ -1253,11 +1235,8 @@ function analyzeSfc(code, file) {
1253
1235
  };
1254
1236
  const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
1255
1237
  if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1].length);
1256
- for (const match of code.matchAll(SCRIPT_RE)) {
1257
- const content = match[2];
1258
- if (content) block(content, match.index + match[1].length);
1259
- }
1260
- const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
1238
+ for (const script of blocks(code, [SCRIPT_BLOCK])) if (script.close > script.body) block(code.slice(script.body, script.close), script.body);
1239
+ const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_BLOCK), STYLE_BLOCK), COMMENT_BLOCK);
1261
1240
  const markupOptions = {
1262
1241
  tNames,
1263
1242
  renamed: [...renamed]
@@ -1275,15 +1254,20 @@ function analyzeSfc(code, file) {
1275
1254
  merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);
1276
1255
  consumedTo = end;
1277
1256
  }
1278
- return {
1257
+ const analysis = {
1279
1258
  tagged,
1280
1259
  usedKeys,
1281
1260
  strayImports,
1282
- missed,
1283
- ...parseError && { parseError }
1261
+ missed
1284
1262
  };
1263
+ if (parseError) analysis.parseError = parseError;
1264
+ if (adapterImport !== void 0) analysis.adapterImport = adapterImport;
1265
+ if (appImported) analysis.appImported = true;
1266
+ return analysis;
1285
1267
  function merge(analysis, offset, markupSegment) {
1286
1268
  if (!analysis) return;
1269
+ if (analysis.adapterImport !== void 0) adapterImport ??= analysis.adapterImport + offset;
1270
+ if (analysis.appImported) appImported = true;
1287
1271
  const lines = lineAt(offset) - 1;
1288
1272
  for (const msg of analysis.tagged) tagged.push({
1289
1273
  ...msg,
@@ -1336,8 +1320,14 @@ function analyzeSegment(code, file, options) {
1336
1320
  };
1337
1321
  }
1338
1322
  }
1339
- function blank(source, re) {
1340
- return source.replace(re, (m) => " ".repeat(m.length));
1323
+ function blank(source, shape) {
1324
+ let out = "";
1325
+ let at = 0;
1326
+ for (const { start, end } of blocks(source, [shape])) {
1327
+ out += source.slice(at, start) + " ".repeat(end - start);
1328
+ at = end;
1329
+ }
1330
+ return out + source.slice(at);
1341
1331
  }
1342
1332
  function braceRanges(markup) {
1343
1333
  const ranges = [];
@@ -1357,7 +1347,7 @@ function braceRanges(markup) {
1357
1347
  }
1358
1348
  function vueExpressionRanges(markup) {
1359
1349
  const ranges = [];
1360
- for (const match of markup.matchAll(MUSTACHE_RE)) ranges.push([match.index + 2, match.index + match[0].length - 2]);
1350
+ for (const { body, close } of blocks(markup, [MUSTACHE_BLOCK])) ranges.push([body, close]);
1361
1351
  for (const match of markup.matchAll(DIRECTIVE_RE)) {
1362
1352
  const valueStart = match.index + match[0].length - match[1].length + 1;
1363
1353
  ranges.push([valueStart, valueStart + match[1].length - 2]);
@@ -1403,7 +1393,7 @@ function stringEnd(code, start) {
1403
1393
  else i += 1;
1404
1394
  return code.length;
1405
1395
  }
1406
- // src/extract.ts
1396
+ // src/scan/extract.ts
1407
1397
  const kept = /* @__PURE__ */ new WeakMap();
1408
1398
  async function extractProject(cfg, options = {}) {
1409
1399
  const files = await glob(cfg.include, {
@@ -1439,9 +1429,9 @@ async function collectOrigins(cfg, reuse) {
1439
1429
  return origins;
1440
1430
  }
1441
1431
  function syncCatalogs(cfg, catalogs, registry) {
1442
- const added = {};
1432
+ const added = emptyCatalog();
1443
1433
  const replaced = [];
1444
- const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
1434
+ const source = own(catalogs, cfg.sourceLocale) ?? (catalogs[cfg.sourceLocale] = emptyCatalog());
1445
1435
  for (const [key, msg] of registry.messages()) {
1446
1436
  const before = own(source, key);
1447
1437
  if (before === msg.message) continue;
@@ -1455,7 +1445,7 @@ function syncCatalogs(cfg, catalogs, registry) {
1455
1445
  const needed = Object.keys(source);
1456
1446
  for (const locale of cfg.locales) {
1457
1447
  if (locale === cfg.sourceLocale) continue;
1458
- const catalog = catalogs[locale] ??= emptyCatalog();
1448
+ const catalog = own(catalogs, locale) ?? (catalogs[locale] = emptyCatalog());
1459
1449
  for (const key of needed) if (own(catalog, key) === void 0) {
1460
1450
  catalog[key] = "";
1461
1451
  (added[locale] ??= []).push(key);
@@ -1469,17 +1459,14 @@ function syncCatalogs(cfg, catalogs, registry) {
1469
1459
  function shippedCatalogs(cfg, catalogs, registry, options = {}) {
1470
1460
  const source = flatten(catalogs[cfg.sourceLocale] ?? {});
1471
1461
  for (const [key, msg] of registry.messages()) if (options.newKeys !== false || own(source, key) !== void 0) source[key] = msg.message;
1472
- return {
1473
- ...catalogs,
1474
- [cfg.sourceLocale]: source
1475
- };
1462
+ return Object.assign(emptyCatalog(), catalogs, { [cfg.sourceLocale]: source });
1476
1463
  }
1477
1464
  function pruneCatalogs(cfg, catalogs, registry) {
1478
- const removed = {};
1465
+ const removed = emptyCatalog();
1479
1466
  if (registry.parseErrors().length > 0) return removed;
1480
1467
  const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
1481
1468
  for (const locale of cfg.locales) {
1482
- const catalog = catalogs[locale];
1469
+ const catalog = own(catalogs, locale);
1483
1470
  if (!catalog) continue;
1484
1471
  for (const key of Object.keys(catalog)) if (!keep.has(key)) {
1485
1472
  delete catalog[key];
@@ -1488,7 +1475,7 @@ function pruneCatalogs(cfg, catalogs, registry) {
1488
1475
  }
1489
1476
  return removed;
1490
1477
  }
1491
- // src/validate.ts
1478
+ // src/gate/validate.ts
1492
1479
  let remembered = /* @__PURE__ */ new Map();
1493
1480
  let reading;
1494
1481
  function read(message) {
@@ -1699,7 +1686,7 @@ function reachableCategories(locale, ordinal) {
1699
1686
  reachable.set(cacheKey, out);
1700
1687
  return out;
1701
1688
  }
1702
- // src/params.ts
1689
+ // src/emit/params.ts
1703
1690
  const NUMBER_FORMATS = /* @__PURE__ */ new Set([
1704
1691
  "number",
1705
1692
  "integer",
@@ -1741,7 +1728,7 @@ function renderParamType(types) {
1741
1728
  ]) members.add(m);
1742
1729
  return [...members].join(" | ");
1743
1730
  }
1744
- // src/tsconfig.ts
1731
+ // src/config/tsconfig.ts
1745
1732
  function readTsconfig(root) {
1746
1733
  const path = join(root, "tsconfig.json");
1747
1734
  let text;
@@ -1763,7 +1750,7 @@ function covered(list, entry) {
1763
1750
  if (!Array.isArray(list)) return false;
1764
1751
  return list.some((item) => {
1765
1752
  if (typeof item !== "string") return false;
1766
- const pattern = item.replace(/^\.\//, "").replace(/\/+$/, "");
1753
+ const pattern = trimTrailingSlashes(item.replace(/^\.\//, ""));
1767
1754
  return picomatch(pattern)(entry) || picomatch(`${pattern}/**/*`)(entry);
1768
1755
  });
1769
1756
  }
@@ -1800,7 +1787,7 @@ function includeTypes(root, file) {
1800
1787
  writeFileSync(read.path, applyEdits(read.text, edits));
1801
1788
  return "added";
1802
1789
  }
1803
- // src/codegen.ts
1790
+ // src/emit/codegen.ts
1804
1791
  const DTS_HEADER = "// generated by verbaly: do not edit";
1805
1792
  const SLICE_HELPERS = `function readSlice(root, path) {
1806
1793
  const locale = readPath({ supported: locales, path });
@@ -1816,11 +1803,14 @@ export function adoptPage(options) {
1816
1803
  }
1817
1804
 
1818
1805
  `;
1806
+ function loaderKey(locale) {
1807
+ return locale === "__proto__" ? "[\"__proto__\"]" : JSON.stringify(locale);
1808
+ }
1819
1809
  function generateRuntimeModule(cfg, options = {}) {
1820
1810
  const importPath = options.localeImport ?? ((locale) => "@verbaly/app/locale/" + locale);
1821
1811
  const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
1822
1812
  const src = JSON.stringify(cfg.sourceLocale);
1823
- const loaders = others.map((locale) => ` ${JSON.stringify(locale)}: () => import('${importPath(locale)}'),`).join("\n");
1813
+ const loaders = others.map((locale) => ` ${loaderKey(locale)}: () => import('${importPath(locale)}'),`).join("\n");
1824
1814
  const icu = options.icu ? ",\n parseIcu" : "";
1825
1815
  const rel = options.relative ? ",\n relativeFormatter" : "";
1826
1816
  const slice = options.inlineCatalog ? ",\n inlineMessages" : "";
@@ -1829,6 +1819,7 @@ function generateRuntimeModule(cfg, options = {}) {
1829
1819
  createVerbaly,
1830
1820
  localeFromPath as readPath,
1831
1821
  localePath as writePath,
1822
+ persistLocale,
1832
1823
  switchLocale as runSwitch${icu}${rel}${slice},
1833
1824
  } from 'verbaly';
1834
1825
  import source from '${importPath(cfg.sourceLocale)}';
@@ -1907,9 +1898,11 @@ export function subscribe(listener) {
1907
1898
  return v.subscribe(listener);
1908
1899
  }
1909
1900
 
1901
+ // <html lang> and dir follow; no choice is saved, since a startup read would freeze the browser's
1910
1902
  export async function setLocale(locale) {
1911
1903
  await v.loadLocale(locale);
1912
1904
  v.setLocale(locale);
1905
+ persistLocale(locale, false);
1913
1906
  }
1914
1907
  ${options.extraExports ?? ""}`;
1915
1908
  }
@@ -2079,7 +2072,7 @@ function removeRootDts(cfg, target) {
2079
2072
  rmSync(old);
2080
2073
  warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
2081
2074
  }
2082
- // src/findings.ts
2075
+ // src/gate/findings.ts
2083
2076
  function siteOf(msg) {
2084
2077
  return {
2085
2078
  file: msg.file,
@@ -2200,7 +2193,7 @@ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${lin
2200
2193
  if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
2201
2194
  } };
2202
2195
  }
2203
- // src/state.ts
2196
+ // src/catalog/state.ts
2204
2197
  const STATE_FILE = "verbaly.lock";
2205
2198
  const LOCK_VERSION = 1;
2206
2199
  const README = "Written by Verbaly: the source text each translation was made for, which ones are drafts, and which languages migrate converted. Commit it with your catalogs and never edit it: deleting it marks every draft as reviewed.";
@@ -2218,8 +2211,8 @@ function loadState(cfg) {
2218
2211
  for (const side of lock) checkVersion(statePath(cfg), side.version);
2219
2212
  const [legacyState = [], legacyDrafts = []] = legacyPaths(cfg).map((path) => readSides(path) ?? []);
2220
2213
  const state = {
2221
- drafts: {},
2222
- fingerprints: {}
2214
+ drafts: emptyCatalog(),
2215
+ fingerprints: emptyCatalog()
2223
2216
  };
2224
2217
  const kept = lock.length > 1 ? keptStamp(cfg) : void 0;
2225
2218
  [...lock, ...legacyState].forEach((source, index) => {
@@ -2276,12 +2269,13 @@ function readState(cfg) {
2276
2269
  ...marked
2277
2270
  };
2278
2271
  } catch (error) {
2272
+ const problem = error.message.replace(/^\[verbaly\] /, "");
2279
2273
  return {
2280
2274
  state: {
2281
- drafts: {},
2282
- fingerprints: {}
2275
+ drafts: emptyCatalog(),
2276
+ fingerprints: emptyCatalog()
2283
2277
  },
2284
- problem: error.message.replace(/^\[verbaly\] /, ""),
2278
+ problem,
2285
2279
  ...marked
2286
2280
  };
2287
2281
  }
@@ -2319,7 +2313,7 @@ function refreshState(cfg, catalogs, previous) {
2319
2313
  const flat = flatCatalogs(catalogs);
2320
2314
  const source = flat[cfg.sourceLocale] ?? {};
2321
2315
  const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
2322
- const drafts = {};
2316
+ const drafts = emptyCatalog();
2323
2317
  for (const [locale, keys] of Object.entries(previous.drafts)) {
2324
2318
  if (!shown.has(locale)) {
2325
2319
  drafts[locale] = keys;
@@ -2328,7 +2322,7 @@ function refreshState(cfg, catalogs, previous) {
2328
2322
  const live = keys.filter((key) => own(flat[locale], key));
2329
2323
  if (live.length) drafts[locale] = live;
2330
2324
  }
2331
- const fingerprints = {};
2325
+ const fingerprints = emptyCatalog();
2332
2326
  for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
2333
2327
  for (const locale of shown) {
2334
2328
  const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
@@ -2373,7 +2367,7 @@ function recordTranslations(cfg, source, writes) {
2373
2367
  return state;
2374
2368
  }
2375
2369
  function effectiveDrafts(drafts, catalogs) {
2376
- const out = {};
2370
+ const out = emptyCatalog();
2377
2371
  for (const [locale, keys] of Object.entries(drafts)) {
2378
2372
  const catalog = catalogs[locale] ?? {};
2379
2373
  const live = keys.filter((key) => own(catalog, key));
@@ -2438,17 +2432,17 @@ function translationOf(stamped) {
2438
2432
  return stamped.slice(stamped.indexOf(".") + 1);
2439
2433
  }
2440
2434
  function flatCatalogs(catalogs) {
2441
- const out = {};
2435
+ const out = emptyCatalog();
2442
2436
  for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
2443
2437
  return out;
2444
2438
  }
2445
2439
  function serializeState(state) {
2446
- const drafts = {};
2440
+ const drafts = emptyCatalog();
2447
2441
  for (const locale of Object.keys(state.drafts).sort()) {
2448
2442
  const keys = [...new Set(state.drafts[locale])].sort();
2449
2443
  if (keys.length) drafts[locale] = keys;
2450
2444
  }
2451
- const fingerprints = {};
2445
+ const fingerprints = emptyCatalog();
2452
2446
  for (const locale of Object.keys(state.fingerprints).sort()) {
2453
2447
  const entries = state.fingerprints[locale] ?? {};
2454
2448
  const keys = Object.keys(entries).sort();
@@ -2512,7 +2506,7 @@ function isObject(value) {
2512
2506
  return typeof value === "object" && value !== null && !Array.isArray(value);
2513
2507
  }
2514
2508
  function readDrafts(value) {
2515
- const out = {};
2509
+ const out = emptyCatalog();
2516
2510
  if (!isObject(value)) return out;
2517
2511
  for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
2518
2512
  return out;
@@ -2523,7 +2517,7 @@ function readMigrated(value) {
2523
2517
  return locales.length ? locales : void 0;
2524
2518
  }
2525
2519
  function readFingerprints(value) {
2526
- const out = {};
2520
+ const out = emptyCatalog();
2527
2521
  if (!isObject(value)) return out;
2528
2522
  for (const [locale, entries] of Object.entries(value)) {
2529
2523
  if (!isObject(entries)) continue;
@@ -2533,7 +2527,7 @@ function readFingerprints(value) {
2533
2527
  }
2534
2528
  return out;
2535
2529
  }
2536
- // src/project.ts
2530
+ // src/project/project.ts
2537
2531
  async function syncProject(cfg, options = {}) {
2538
2532
  const registry = options.registry ?? await extractProject(cfg);
2539
2533
  const catalogs = options.catalogs ?? loadCatalogs(cfg);
@@ -2551,7 +2545,7 @@ async function syncProject(cfg, options = {}) {
2551
2545
  pruned,
2552
2546
  pruneBlocked,
2553
2547
  findings: scanFindings(cfg, registry, replaced),
2554
- written: {}
2548
+ written: emptyCatalog()
2555
2549
  };
2556
2550
  if (options.dryRun) return result;
2557
2551
  const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
@@ -2589,369 +2583,19 @@ function confirmFromDisk(cfg, catalogs, registry) {
2589
2583
  registry.update(file, analyzeFile(code, file));
2590
2584
  }
2591
2585
  }
2592
- // src/migrate.ts
2593
- const KNOWN = [
2594
- "i18next",
2595
- "react-i18next",
2596
- "vue-i18n",
2597
- "react-intl",
2598
- "next-intl",
2599
- "svelte-i18n"
2600
- ];
2601
- function detectLibraries(root) {
2602
- const path = join(root, "package.json");
2603
- if (!existsSync(path)) return [];
2604
- let manifest;
2605
- try {
2606
- manifest = JSON.parse(readFileSync(path, "utf8"));
2607
- } catch {
2608
- return [];
2609
- }
2610
- const deps = {
2611
- ...manifest.dependencies,
2612
- ...manifest.devDependencies
2613
- };
2614
- return KNOWN.filter((name) => deps[name] !== void 0);
2615
- }
2616
- const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
2617
- const FORMATTED = /\{\{\s*-?\s*[A-Za-z_$][\w$]*\s*,[^}]*\}\}/;
2618
- const UNESCAPED = /\{\{\s*-\s*[A-Za-z_$][\w$]*\s*\}\}/;
2619
- const NESTED = /\$t\(/;
2620
- const DOUBLE = /\{\{[^{}]*\}\}/;
2621
- const DOUBLES = new RegExp(DOUBLE.source, "g");
2622
- const ONE_PLAIN = new RegExp(`^${PLAIN.source}$`);
2623
- const NAME = /^\s*([A-Za-z_$][\w$]*)\s*$/;
2624
- const CATEGORIES = [
2625
- "zero",
2626
- "one",
2627
- "two",
2628
- "few",
2629
- "many",
2630
- "other"
2631
- ];
2632
- const SUFFIX = new RegExp(`^(.*)_(${[...CATEGORIES, "plural"].join("|")})$`);
2633
- function i18nextProblem(text) {
2634
- if (NESTED.test(text)) return "uses $t() nesting, which has no direct equivalent";
2635
- if (UNESCAPED.test(text)) return "uses {{- name}}, so decide whether the message is rich";
2636
- if (FORMATTED.test(text)) return "uses an i18next format, which needs the matching Verbaly one";
2637
- for (const [double] of text.matchAll(DOUBLES)) if (!ONE_PLAIN.test(double)) return "uses {{…}} with more than a name, which needs a Verbaly param";
2638
- }
2639
- function convertBraces(text) {
2640
- let out = "";
2641
- let last = 0;
2642
- for (const match of text.matchAll(PLAIN)) {
2643
- out += escapeBraces(text.slice(last, match.index)) + `{${match[1]}}`;
2644
- last = match.index + match[0].length;
2645
- }
2646
- return out + escapeBraces(text.slice(last));
2647
- }
2648
- function escapeBraces(text) {
2649
- return text.replace(/[{}]/g, (brace) => brace + brace);
2586
+ // src/gate/check.ts
2587
+ function gatePasses(result) {
2588
+ return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2650
2589
  }
2651
- function toVariant(text) {
2652
- let out = "";
2653
- let i = 0;
2654
- while (i < text.length) {
2655
- const ch = text[i];
2656
- if ((ch === "{" || ch === "}") && text[i + 1] === ch) {
2657
- out += ch + ch;
2658
- i += 2;
2659
- } else if (ch === "{") {
2660
- const close = text.indexOf("}", i);
2661
- const name = close < 0 ? void 0 : NAME.exec(text.slice(i + 1, close))?.[1];
2662
- if (name === void 0) return void 0;
2663
- out += name === "count" ? "#" : `{${name}}`;
2664
- i = close + 1;
2665
- } else {
2666
- out += ch === "#" || ch === "|" || ch === "}" ? ch + ch : ch;
2667
- i += 1;
2668
- }
2669
- }
2670
- return out;
2590
+ function warningCount(result) {
2591
+ return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.divergent.length + result.outdated.length;
2671
2592
  }
2672
- function order(a, b) {
2673
- return CATEGORIES.indexOf(a) - CATEGORIES.indexOf(b);
2674
- }
2675
- function mergePlurals(locale, catalog, out, plurals, skipped, fromI18next) {
2676
- const groups = /* @__PURE__ */ new Map();
2677
- const legacy = /* @__PURE__ */ new Set();
2678
- for (const [key, value] of Object.entries(catalog)) {
2679
- const match = SUFFIX.exec(key);
2680
- if (!match || typeof value !== "string") continue;
2681
- const [, base, suffix] = match;
2682
- if (suffix === "plural") legacy.add(base);
2683
- const category = suffix === "plural" ? "other" : suffix;
2684
- if (!groups.has(base)) groups.set(base, /* @__PURE__ */ new Map());
2685
- groups.get(base).set(category, {
2686
- key,
2687
- value
2688
- });
2689
- }
2690
- for (const [base, forms] of groups) {
2691
- const bare = catalog[base];
2692
- if (legacy.has(base) && typeof bare === "string" && !forms.has("one")) forms.set("one", {
2693
- key: base,
2694
- value: bare
2695
- });
2696
- else if (bare !== void 0) {
2697
- skipped.push({
2698
- locale,
2699
- key: base,
2700
- reason: `"${base}" already exists, so merging would overwrite it`
2701
- });
2702
- continue;
2703
- }
2704
- if (!forms.has("other")) {
2705
- skipped.push({
2706
- locale,
2707
- key: base,
2708
- reason: "no _other form, so the block would have no catch-all"
2709
- });
2710
- continue;
2711
- }
2712
- if (forms.size === 1) {
2713
- skipped.push({
2714
- locale,
2715
- key: base,
2716
- reason: "only a plural form, so add the singular before merging"
2717
- });
2718
- continue;
2719
- }
2720
- const sorted = [...forms.entries()].sort((a, b) => order(a[0], b[0]));
2721
- const cases = [];
2722
- let problem;
2723
- for (const [category, form] of sorted) {
2724
- problem = fromI18next ? i18nextProblem(form.value) : void 0;
2725
- const body = problem ? void 0 : toVariant(fromI18next ? convertBraces(form.value) : form.value);
2726
- if (body === void 0) {
2727
- problem ??= "a form holds more than a name in braces, so merge it by hand";
2728
- break;
2729
- }
2730
- cases.push(`${category}: ${body}`);
2731
- }
2732
- if (problem) {
2733
- skipped.push({
2734
- locale,
2735
- key: base,
2736
- reason: problem
2737
- });
2738
- continue;
2739
- }
2740
- const merged = `{count | ${cases.join(" | ")}}`;
2741
- for (const [, form] of sorted) delete out[form.key];
2742
- out[base] = merged;
2743
- plurals.push({
2744
- locale,
2745
- key: base,
2746
- from: sorted.map(([, form]) => form.key),
2747
- after: merged
2748
- });
2749
- }
2750
- }
2751
- function migrateCatalogs(cfg, options = {}) {
2752
- const braces = [];
2753
- const plurals = [];
2754
- const skipped = [];
2755
- const written = [];
2756
- const state = loadState(cfg);
2757
- const done = new Set(state.migrated ?? []);
2758
- const catalogs = new Map(cfg.locales.map((locale) => [locale, readCatalog(cfg, locale)]));
2759
- const pending = cfg.locales.filter((locale) => !done.has(locale));
2760
- const fromI18next = pending.some((locale) => Object.values(catalogs.get(locale)).some((value) => typeof value === "string" && (DOUBLE.test(value) || NESTED.test(value))));
2761
- for (const locale of cfg.locales) {
2762
- const catalog = catalogs.get(locale);
2763
- const out = Object.assign(emptyCatalog(), catalog);
2764
- const convert = fromI18next && !done.has(locale);
2765
- for (const [key, value] of Object.entries(catalog)) {
2766
- if (!convert || typeof value !== "string") continue;
2767
- const problem = i18nextProblem(value);
2768
- if (problem) {
2769
- skipped.push({
2770
- locale,
2771
- key,
2772
- reason: problem
2773
- });
2774
- continue;
2775
- }
2776
- const after = convertBraces(value);
2777
- if (after !== value) {
2778
- braces.push({
2779
- locale,
2780
- key,
2781
- before: value,
2782
- after
2783
- });
2784
- out[key] = after;
2785
- }
2786
- }
2787
- if (options.plurals) mergePlurals(locale, catalog, out, plurals, skipped, convert);
2788
- if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
2789
- writeCatalog(cfg, locale, out);
2790
- written.push(locale);
2791
- }
2792
- }
2793
- if (options.write && fromI18next) {
2794
- const converted = pending.filter((locale) => existsSync(catalogPath(cfg, locale)));
2795
- if (converted.length) saveState(cfg, {
2796
- ...state,
2797
- migrated: [...done, ...converted]
2798
- });
2799
- }
2800
- const remembered = cfg.locales.filter((locale) => done.has(locale));
2801
- return {
2802
- detected: detectLibraries(cfg.root),
2803
- braces,
2804
- plurals,
2805
- skipped,
2806
- written,
2807
- remembered
2808
- };
2809
- }
2810
- // src/tag.ts
2811
- function isLocaleTag(tag) {
2812
- try {
2813
- Intl.getCanonicalLocales(tag);
2814
- return true;
2815
- } catch {
2816
- return false;
2817
- }
2818
- }
2819
- function suggestTag(tag) {
2820
- const near = tag.replace(/_/g, "-");
2821
- return near !== tag && isLocaleTag(near) ? near : void 0;
2822
- }
2823
- function projectLocale(tag, locales) {
2824
- if (locales.includes(tag)) return tag;
2825
- const plain = (value) => value.replace(/_/g, "-").toLowerCase();
2826
- return locales.find((locale) => plain(locale) === plain(tag));
2827
- }
2828
- // src/init.ts
2829
- const CATALOG_DIRS = [
2830
- "locales",
2831
- "src/locales",
2832
- "src/i18n/locales",
2833
- "src/i18n",
2834
- "i18n",
2835
- "lang",
2836
- "src/lang",
2837
- "translations",
2838
- "src/translations",
2839
- "messages"
2840
- ];
2841
- function existingCatalogs(root) {
2842
- return CATALOG_DIRS.find((dir) => {
2843
- try {
2844
- return readdirSync(join(root, dir)).some((file) => file.endsWith(".json") && isLocaleTag(file.slice(0, -5)));
2845
- } catch {
2846
- return false;
2847
- }
2848
- });
2849
- }
2850
- function cliReachable(root) {
2851
- const bin = join(root, "node_modules", ".bin");
2852
- return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
2853
- }
2854
- const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
2855
- function configSource(options, typescript) {
2856
- const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
2857
- if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
2858
- if (options.dir) fields.push(` dir: '${options.dir}',`);
2859
- const body = `export default {\n${fields.join("\n")}\n}`;
2860
- if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
2861
- return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
2862
- }
2863
- async function init(input = {}) {
2864
- const root = input.root ?? process.cwd();
2865
- const created = [];
2866
- const skipped = [];
2867
- const renamed = [];
2868
- const refused = [];
2869
- const typed = input.locales?.flatMap((locale) => {
2870
- if (isLocaleTag(locale)) return [locale];
2871
- const near = suggestTag(locale);
2872
- if (near) renamed.push({
2873
- from: locale,
2874
- to: near
2875
- });
2876
- else refused.push(locale);
2877
- return near ? [near] : [];
2878
- });
2879
- const locales = typed && [...new Set(typed)];
2880
- let sourceLocale = input.sourceLocale;
2881
- if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
2882
- const near = suggestTag(sourceLocale);
2883
- if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
2884
- renamed.push({
2885
- from: sourceLocale,
2886
- to: near
2887
- });
2888
- sourceLocale = near;
2889
- }
2890
- const options = {
2891
- ...input,
2892
- locales,
2893
- sourceLocale
2894
- };
2895
- const existing = findConfigFile(root);
2896
- const typescript = existsSync(join(root, "tsconfig.json"));
2897
- const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
2898
- const found = existing || options.dir ? void 0 : existingCatalogs(root);
2899
- if (existing) skipped.push(existing);
2900
- else {
2901
- const dir = found === "locales" ? void 0 : found;
2902
- writeFileSync(join(root, configFile), configSource({
2903
- ...options,
2904
- dir: options.dir ?? dir
2905
- }, typescript));
2906
- created.push(configFile);
2907
- }
2908
- const fromFile = existing ? await loadConfigFile(root) : {};
2909
- const scaffold = {
2910
- dir: options.dir ?? fromFile.dir ?? found,
2911
- sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
2912
- locales: options.locales ?? fromFile.locales
2913
- };
2914
- const dir = join(root, scaffold.dir ?? "locales");
2915
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
2916
- for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
2917
- const file = join(dir, `${locale}.json`);
2918
- const label = relative(root, file).replaceAll("\\", "/");
2919
- if (existsSync(file)) skipped.push(label);
2920
- else {
2921
- writeFileSync(file, "{}\n");
2922
- created.push(label);
2923
- }
2924
- }
2925
- const host = detectHost(root);
2926
- const deps = readDependencies(root);
2927
- const missing = host?.install.filter((pkg) => !deps[pkg]) ?? [];
2928
- const next = host ? [...missing.length ? [installCommand(root, missing)] : [], host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
2929
- const others = detectLibraries(root);
2930
- if (found && others.length) next.push(`port the ${others.join(" and ")} catalogs: npx verbaly migrate reports, --write applies`);
2931
- return {
2932
- created,
2933
- skipped,
2934
- host: host?.name,
2935
- configFile,
2936
- next,
2937
- renamed,
2938
- refused,
2939
- found
2940
- };
2941
- }
2942
- // src/check.ts
2943
- function gatePasses(result) {
2944
- return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2945
- }
2946
- function warningCount(result) {
2947
- return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.divergent.length + result.outdated.length;
2948
- }
2949
- function check(cfg, catalogs, registry, fingerprints = {}) {
2950
- return gatePass(() => checkPass(cfg, catalogs, registry, fingerprints));
2593
+ function check(cfg, catalogs, registry, fingerprints = emptyCatalog()) {
2594
+ return gatePass(() => checkPass(cfg, catalogs, registry, fingerprints));
2951
2595
  }
2952
2596
  function checkPass(cfg, catalogs, registry, fingerprints) {
2953
2597
  const extracted = registry.messages();
2954
- const flat = {};
2598
+ const flat = emptyCatalog();
2955
2599
  for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
2956
2600
  const source = flat[cfg.sourceLocale] ?? {};
2957
2601
  const shipped = shippedCatalogs(cfg, flat, registry);
@@ -3091,7 +2735,7 @@ function formatBuildReport(result, sourceLocale, root, cap = 5) {
3091
2735
  }
3092
2736
  function checkNextSteps(result, cliReachable = true) {
3093
2737
  const steps = [];
3094
- if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
2738
+ if (result.missing.length > 0) steps.push("missing: fill the empty translations in your catalogs, or run `npx verbaly translate` (`npx verbaly extract` adds a key a catalog does not have yet)");
3095
2739
  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`");
3096
2740
  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");
3097
2741
  if (result.collisions.length > 0) steps.push("collisions: give each text its own key in t.id(…), or write the same text in every place");
@@ -3171,17 +2815,19 @@ function escapeData(text) {
3171
2815
  function escapeProperty(text) {
3172
2816
  return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
3173
2817
  }
3174
- // src/transform.ts
2818
+ // src/scan/transform.ts
3175
2819
  function quote(text, single) {
3176
2820
  if (!single) return JSON.stringify(text);
3177
2821
  return `'${text.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
3178
2822
  }
3179
- function transformCode(code, file, analysis) {
2823
+ function transformCode(code, file, analysis, options = {}) {
3180
2824
  const own = analysis ?? analyzeFile(code, file);
3181
2825
  if (!analysis && own.parseError) warnParseError(file, own.parseError);
3182
2826
  const { tagged } = own;
3183
- if (tagged.length === 0) return null;
2827
+ const appAt = options.appImport && !own.appImported ? own.adapterImport : void 0;
2828
+ if (tagged.length === 0 && appAt === void 0) return null;
3184
2829
  const s = new MagicString(code);
2830
+ if (appAt !== void 0) s.appendLeft(appAt, `import '${APP_ID}'; `);
3185
2831
  for (const msg of tagged) {
3186
2832
  const seen = /* @__PURE__ */ new Set();
3187
2833
  const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));
@@ -3201,7 +2847,7 @@ function transformCode(code, file, analysis) {
3201
2847
  map: s.generateMap({ hires: true })
3202
2848
  };
3203
2849
  }
3204
- // src/plugin.ts
2850
+ // src/emit/plugin.ts
3205
2851
  const RESOLVED_VIRTUAL_ID = "\0" + VIRTUAL_ID;
3206
2852
  const LOCALE_MODULE_PREFIX = `${RESOLVED_VIRTUAL_ID}/locale/`;
3207
2853
  const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
@@ -3238,9 +2884,18 @@ function transformSource(code, id, registry, scan) {
3238
2884
  for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
3239
2885
  return {
3240
2886
  messages,
3241
- result: transformCode(code, id, analysis) ?? null
2887
+ result: transformCode(code, id, analysis, { appImport: true }) ?? null
3242
2888
  };
3243
2889
  }
2890
+ function writeBuildTypes(cfg, catalogs) {
2891
+ try {
2892
+ writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
2893
+ } catch (error) {
2894
+ const code = error?.code;
2895
+ if (typeof code !== "string") throw error;
2896
+ warnOnce(`could not write the types to ${cfg.dts === false ? "" : relative(cfg.root, cfg.dts).replaceAll("\\", "/")} (${code}): run \`npx verbaly typegen\` where the project can be written`, `types:${cfg.root}`);
2897
+ }
2898
+ }
3244
2899
  function runBuildGate(cfg, registry, failOnMissing) {
3245
2900
  const catalogs = loadCatalogs(cfg);
3246
2901
  for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
@@ -3248,7 +2903,16 @@ function runBuildGate(cfg, registry, failOnMissing) {
3248
2903
  if (failOnMissing === true && !gatePasses(found)) throw new Error(`[verbaly] build blocked\n${formatCheckResult(found, cfg.root)}\n${checkNextSteps(found, cliReachable(cfg.root))}`);
3249
2904
  reportGate(cfg, found);
3250
2905
  const warnings = warningCount(found);
3251
- if (warnings > 0) warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: run \`npx verbaly check\` to read them`, "gate:warnings");
2906
+ if (warnings > 0) {
2907
+ const once = onceMoved(cfg.root);
2908
+ const read = once ? `\`npx verbaly check\` reads them${once}` : "run `npx verbaly check` to read them";
2909
+ warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: ${read}`, "gate:warnings");
2910
+ }
2911
+ }
2912
+ function onceMoved(root) {
2913
+ const moved = pluginOnlyOptions(root);
2914
+ if (!moved) return "";
2915
+ return ` once ${moved} ${moved.includes(" and ") ? "move" : "moves"} to verbaly.config`;
3252
2916
  }
3253
2917
  const reported = /* @__PURE__ */ new Map();
3254
2918
  function reportGate(cfg, found) {
@@ -3276,7 +2940,7 @@ function reportGate(cfg, found) {
3276
2940
  ...lines.map((line) => line.startsWith(" ") ? line : `[verbaly] ${line}`),
3277
2941
  "[verbaly] to fix them:",
3278
2942
  ...steps.split("\n").map((step) => ` ${step}`),
3279
- "[verbaly] `npx verbaly check` lists every one, and in your CI it stops a release on them"
2943
+ `[verbaly] \`npx verbaly check\` lists every one${onceMoved(cfg.root)}, and in your CI it stops a release on them`
3280
2944
  ];
3281
2945
  console.warn(block.join("\n"));
3282
2946
  }
@@ -3285,7 +2949,7 @@ function buildFingerprints(cfg) {
3285
2949
  if (problem) warnOnce(`${problem}, so outdated translations are not reported`, "gate:state");
3286
2950
  return state.fingerprints;
3287
2951
  }
3288
- // src/scope.ts
2952
+ // src/scan/scope.ts
3289
2953
  const TAGGED_HINT = /(?<![\w$.])\$?t(?:\.id\s*\([^)]*\))?\s*`/;
3290
2954
  const NOT_SOURCE = [
3291
2955
  "**/node_modules/**",
@@ -3351,10 +3015,10 @@ async function filesOutsideInclude(cfg) {
3351
3015
  }
3352
3016
  return found;
3353
3017
  }
3354
- // src/status.ts
3355
- function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
3018
+ // src/gate/status.ts
3019
+ function status(cfg, catalogs, registry, drafts = emptyCatalog(), fingerprints = emptyCatalog()) {
3356
3020
  const extracted = registry.messages();
3357
- const flat = {};
3021
+ const flat = emptyCatalog();
3358
3022
  for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
3359
3023
  const source = flat[cfg.sourceLocale] ?? {};
3360
3024
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
@@ -3408,7 +3072,129 @@ function formatStatusResult(result) {
3408
3072
  }
3409
3073
  return lines.join("\n");
3410
3074
  }
3411
- // src/doctor.ts
3075
+ // src/cli/args.ts
3076
+ const OPTIONS = {
3077
+ root: { type: "string" },
3078
+ dir: { type: "string" },
3079
+ source: { type: "string" },
3080
+ locales: { type: "string" },
3081
+ prune: { type: "boolean" },
3082
+ watch: { type: "boolean" },
3083
+ write: { type: "boolean" },
3084
+ json: { type: "boolean" },
3085
+ drafts: { type: "boolean" },
3086
+ outdated: { type: "boolean" },
3087
+ draft: { type: "boolean" },
3088
+ approve: { type: "boolean" },
3089
+ reporter: { type: "string" },
3090
+ model: { type: "string" },
3091
+ locale: { type: "string" },
3092
+ site: { type: "string" },
3093
+ attribute: { type: "string" },
3094
+ base: { type: "string" },
3095
+ "base-url": { type: "string" },
3096
+ redirect: { type: "boolean" },
3097
+ sitemap: { type: "boolean" },
3098
+ clean: { type: "boolean" },
3099
+ "dry-run": { type: "boolean" },
3100
+ plurals: { type: "boolean" },
3101
+ format: { type: "string" },
3102
+ out: { type: "string" },
3103
+ missing: { type: "boolean" },
3104
+ overwrite: { type: "boolean" },
3105
+ help: {
3106
+ type: "boolean",
3107
+ short: "h"
3108
+ }
3109
+ };
3110
+ function parseCli(args) {
3111
+ return parseArgs({
3112
+ args,
3113
+ allowPositionals: true,
3114
+ options: OPTIONS
3115
+ });
3116
+ }
3117
+ function csv(value) {
3118
+ return value?.split(",").map((item) => item.trim()).filter(Boolean);
3119
+ }
3120
+ // src/cli/output.ts
3121
+ function sayLockNews(cfg, before) {
3122
+ const news = lockNews(cfg, before);
3123
+ if (news) console.log(` ${formatFinding({
3124
+ kind: "lock",
3125
+ ...news
3126
+ }, cfg.root)}`);
3127
+ }
3128
+ function byLocale(entries) {
3129
+ const out = /* @__PURE__ */ new Map();
3130
+ for (const { locale, key } of entries) {
3131
+ const keys = out.get(locale);
3132
+ if (keys) keys.push(key);
3133
+ else out.set(locale, [key]);
3134
+ }
3135
+ return [...out];
3136
+ }
3137
+ // src/cli/commands/check.ts
3138
+ async function checkCommand(cfg, values) {
3139
+ const reporter = values.reporter ?? "text";
3140
+ if (reporter !== "text" && reporter !== "github") {
3141
+ console.error(`[verbaly] unknown reporter "${values.reporter}", use text or github`);
3142
+ process.exitCode = 1;
3143
+ return;
3144
+ }
3145
+ const registry = await extractProject(cfg);
3146
+ const catalogs = loadCatalogs(cfg);
3147
+ const state = checkState(cfg, values.drafts === true || values.outdated === true);
3148
+ const result = check(cfg, catalogs, registry, state.fingerprints);
3149
+ const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};
3150
+ const outdated = values.outdated ? result.outdated : [];
3151
+ const gated = { outdatedFails: values.outdated === true };
3152
+ if (reporter === "github") for (const line of githubCheckAnnotations(result, registry, cfg, gated)) console.error(line);
3153
+ else {
3154
+ const warnings = formatCheckWarnings(result, cfg.root, gated);
3155
+ if (warnings) console.warn(`[verbaly] warnings (the gate still passes)\n${warnings}`);
3156
+ }
3157
+ 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(", ")}`)];
3158
+ if (result.ok && awaiting.length === 0) {
3159
+ console.log("[verbaly] all translations complete ✓");
3160
+ return;
3161
+ }
3162
+ if (!result.ok) {
3163
+ const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
3164
+ const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken, ${counted(result.collisions.length, "collision")}` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
3165
+ console.error(`${report}\n${checkNextSteps(result)}`);
3166
+ }
3167
+ if (awaiting.length > 0) {
3168
+ for (const line of awaiting) console.error(line);
3169
+ console.error("[verbaly] check failed: translations awaiting review (run verbaly review, then --approve what holds)");
3170
+ }
3171
+ process.exitCode = 1;
3172
+ }
3173
+ function checkState(cfg, gating) {
3174
+ if (gating) return loadState(cfg);
3175
+ const { state, problem } = readState(cfg);
3176
+ if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);
3177
+ return state;
3178
+ }
3179
+ // src/util/tag.ts
3180
+ function isLocaleTag(tag) {
3181
+ try {
3182
+ Intl.getCanonicalLocales(tag);
3183
+ return true;
3184
+ } catch {
3185
+ return false;
3186
+ }
3187
+ }
3188
+ function suggestTag(tag) {
3189
+ const near = tag.replace(/_/g, "-");
3190
+ return near !== tag && isLocaleTag(near) ? near : void 0;
3191
+ }
3192
+ function projectLocale(tag, locales) {
3193
+ if (locales.includes(tag)) return tag;
3194
+ const plain = (value) => value.replace(/_/g, "-").toLowerCase();
3195
+ return locales.find((locale) => plain(locale) === plain(tag));
3196
+ }
3197
+ // src/project/doctor.ts
3412
3198
  const PREVIEW = 5;
3413
3199
  function readRoutingChoice(root, configFile) {
3414
3200
  try {
@@ -3417,6 +3203,31 @@ function readRoutingChoice(root, configFile) {
3417
3203
  return false;
3418
3204
  }
3419
3205
  }
3206
+ function readAstroRouting(root, source) {
3207
+ for (const file of [
3208
+ "astro.config.mjs",
3209
+ "astro.config.js",
3210
+ "astro.config.ts",
3211
+ "astro.config.mts"
3212
+ ]) {
3213
+ let text;
3214
+ try {
3215
+ text = readFileSync(join(root, file), "utf8");
3216
+ } catch {
3217
+ continue;
3218
+ }
3219
+ if (!/\bi18n\s*:/.test(text) || /\brouting\s*:\s*['"]manual['"]/.test(text)) return void 0;
3220
+ if (/\bprefixDefaultLocale\s*:\s*true\b/.test(text)) return {
3221
+ mode: "prefix-all",
3222
+ file
3223
+ };
3224
+ const atRoot = /\bdefaultLocale\s*:\s*['"]([^'"]+)['"]/.exec(text)?.[1];
3225
+ return atRoot && atRoot !== source ? void 0 : {
3226
+ mode: "prefix-except-source",
3227
+ file
3228
+ };
3229
+ }
3230
+ }
3420
3231
  const ROUTING_SAYS = {
3421
3232
  "prefix-except-source": "the source locale has no prefix, every other locale does",
3422
3233
  "prefix-all": "every locale has a prefix, the source included",
@@ -3462,7 +3273,7 @@ async function doctor(cfg) {
3462
3273
  else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
3463
3274
  if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
3464
3275
  else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
3465
- const catalogs = {};
3276
+ const catalogs = emptyCatalog();
3466
3277
  let catalogsHealthy = true;
3467
3278
  if (!existsSync(cfg.dir)) {
3468
3279
  catalogsHealthy = false;
@@ -3509,8 +3320,16 @@ async function doctor(cfg) {
3509
3320
  if (cfg.routing === "no-prefix" && mirrors) warn("routing", "routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale", "drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls");
3510
3321
  else if (cfg.routing === "prefix-all" && mirrors) warn("routing", `routing is "prefix-all" but render keeps ${cfg.sourceLocale} at the root, so its links point at a /${cfg.sourceLocale}/ tree nobody wrote`, "set routing to \"prefix-except-source\", the url tree render writes");
3511
3322
  else {
3512
- const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
3513
- ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
3323
+ const named = configFile ? readRoutingChoice(cfg.root, configFile) : false;
3324
+ const astro = cfg.host === "astro" && cfg.routing === "no-prefix" ? readAstroRouting(cfg.root, cfg.sourceLocale) : void 0;
3325
+ if (astro && named) warn("routing", `routing is "no-prefix" in ${configFile}, but @verbaly/astro uses ${astro.mode}: Astro's i18n in ${astro.file} puts the language in the url`, `remove routing from ${configFile}, or remove i18n from ${astro.file}`);
3326
+ else if (astro) {
3327
+ const how = ` (from Astro's i18n in ${astro.file}, which @verbaly/astro follows)`;
3328
+ ok("routing", `${astro.mode}${how}: ${ROUTING_SAYS[astro.mode]}`);
3329
+ } else {
3330
+ const how = named ? "" : " (from your setup, no routing set)";
3331
+ ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
3332
+ }
3514
3333
  }
3515
3334
  const deps = readDependencies(cfg.root);
3516
3335
  const host = detectHost(cfg.root);
@@ -3634,7 +3453,23 @@ function preview(keys) {
3634
3453
  const head = keys.slice(0, PREVIEW).join(", ");
3635
3454
  return keys.length > PREVIEW ? `${head}, …` : head;
3636
3455
  }
3637
- // src/inline.ts
3456
+ // src/cli/commands/doctor.ts
3457
+ async function doctorCommand(cfg) {
3458
+ const result = await doctor(cfg);
3459
+ console.log(`[verbaly] doctor: ${counted(result.entries.length, "check")}`);
3460
+ for (const entry of result.entries) {
3461
+ const line = formatDoctorEntry(entry);
3462
+ if (entry.level === "error") console.error(line);
3463
+ else if (entry.level === "warn") console.warn(line);
3464
+ else console.log(line);
3465
+ }
3466
+ if (result.ok) console.log(`[verbaly] ${formatDoctorHealth(result)} ✓`);
3467
+ else {
3468
+ console.error("[verbaly] doctor found problems");
3469
+ process.exitCode = 1;
3470
+ }
3471
+ }
3472
+ // src/exchange/inline.ts
3638
3473
  const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
3639
3474
  const BREAK = /^(?:br|wbr)$/;
3640
3475
  function messageToInline(text) {
@@ -3711,7 +3546,7 @@ function parseParts(text, pos, closeTag) {
3711
3546
  continue;
3712
3547
  }
3713
3548
  if (text[i] === "{") {
3714
- const end = matchBrace(text, i);
3549
+ const end = matchBrace$1(text, i);
3715
3550
  if (end === -1) {
3716
3551
  plain += "{";
3717
3552
  i += 1;
@@ -3780,7 +3615,7 @@ function parseParts(text, pos, closeTag) {
3780
3615
  closed: false
3781
3616
  };
3782
3617
  }
3783
- function matchBrace(text, start) {
3618
+ function matchBrace$1(text, start) {
3784
3619
  let depth = 0;
3785
3620
  for (let i = start; i < text.length; i++) {
3786
3621
  const pair = text[i] + (text[i + 1] ?? "");
@@ -3850,7 +3685,7 @@ function attr(attrs, name) {
3850
3685
  const value = new RegExp(`\\b${name}\\s*=\\s*"([^"]*)"`).exec(attrs)?.[1];
3851
3686
  return value === void 0 ? void 0 : unescapeXml(value);
3852
3687
  }
3853
- // src/mobile.ts
3688
+ // src/exchange/mobile.ts
3854
3689
  function androidValuesDir(locale, sourceLocale) {
3855
3690
  if (locale === sourceLocale) return "values";
3856
3691
  const parts = locale.split("-");
@@ -3888,7 +3723,7 @@ function androidText(text) {
3888
3723
  function iosText(text) {
3889
3724
  return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
3890
3725
  }
3891
- // src/po.ts
3726
+ // src/exchange/po.ts
3892
3727
  function toPo(sourceLocale, locale, entries) {
3893
3728
  return [
3894
3729
  [
@@ -3983,7 +3818,7 @@ function poUnquote(text) {
3983
3818
  return ch;
3984
3819
  });
3985
3820
  }
3986
- // src/translate.ts
3821
+ // src/exchange/translate.ts
3987
3822
  const RETRY_STATUS = /* @__PURE__ */ new Set([
3988
3823
  408,
3989
3824
  409,
@@ -4028,9 +3863,9 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
4028
3863
  const targets = targetLocales(cfg, options.locales);
4029
3864
  const source = catalogs[cfg.sourceLocale] ?? {};
4030
3865
  const result = {
4031
- translated: {},
4032
- invalid: {},
4033
- pending: {},
3866
+ translated: emptyCatalog(),
3867
+ invalid: emptyCatalog(),
3868
+ pending: emptyCatalog(),
4034
3869
  failed: []
4035
3870
  };
4036
3871
  const jobs = [];
@@ -4162,7 +3997,7 @@ function formatTranslateFailures(failed) {
4162
3997
  async function resolveProvider(cfg, model) {
4163
3998
  const configured = cfg.translate.provider;
4164
3999
  if (typeof configured === "function") return configured;
4165
- const { claudeProvider } = await import("./claude-DZkzlC5g.js");
4000
+ const { claudeProvider } = await import("./claude-DelQkcx5.js");
4166
4001
  return claudeProvider({ model: model ?? cfg.translate.model });
4167
4002
  }
4168
4003
  function structureMatches(source, translated) {
@@ -4192,7 +4027,7 @@ function glossaryFor(cfg, locale, messages) {
4192
4027
  }
4193
4028
  return Object.keys(out).length > 0 ? out : void 0;
4194
4029
  }
4195
- // src/exchange.ts
4030
+ // src/exchange/exchange.ts
4196
4031
  function isMobileFormat(format) {
4197
4032
  return format === "android-xml" || format === "ios-strings";
4198
4033
  }
@@ -4260,13 +4095,13 @@ function exportMobile(cfg, catalogs, format, dir, source, targets) {
4260
4095
  function importCatalogs(cfg, catalogs, files, options = {}) {
4261
4096
  const source = catalogs[cfg.sourceLocale] ?? {};
4262
4097
  const result = {
4263
- imported: {},
4264
- rejected: {},
4265
- skipped: {},
4266
- unknown: {},
4098
+ imported: emptyCatalog(),
4099
+ rejected: emptyCatalog(),
4100
+ skipped: emptyCatalog(),
4101
+ unknown: emptyCatalog(),
4267
4102
  unmatched: [],
4268
4103
  mapped: [],
4269
- sources: {}
4104
+ sources: emptyCatalog()
4270
4105
  };
4271
4106
  for (const file of files) {
4272
4107
  const parsed = parseExchangeFile(file, options.locale);
@@ -4287,172 +4122,886 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
4287
4122
  });
4288
4123
  continue;
4289
4124
  }
4290
- if (locale !== detected) result.mapped.push({
4291
- file,
4292
- from: detected,
4293
- to: locale
4294
- });
4295
- const catalog = catalogs[locale] ??= emptyCatalog();
4296
- for (const [key, text] of Object.entries(parsed.entries)) {
4297
- if (!text.trim()) continue;
4298
- const from = own(source, key);
4299
- if (!from) {
4300
- (result.unknown[locale] ??= []).push(key);
4301
- continue;
4302
- }
4303
- if (own(catalog, key) && !options.overwrite) {
4304
- (result.skipped[locale] ??= []).push(key);
4305
- continue;
4306
- }
4307
- if (!structureMatches(from, text)) {
4308
- (result.rejected[locale] ??= []).push(key);
4125
+ if (locale !== detected) result.mapped.push({
4126
+ file,
4127
+ from: detected,
4128
+ to: locale
4129
+ });
4130
+ const catalog = catalogs[locale] ??= emptyCatalog();
4131
+ for (const [key, text] of Object.entries(parsed.entries)) {
4132
+ if (!text.trim()) continue;
4133
+ const from = own(source, key);
4134
+ if (!from) {
4135
+ (result.unknown[locale] ??= []).push(key);
4136
+ continue;
4137
+ }
4138
+ if (own(catalog, key) && !options.overwrite) {
4139
+ (result.skipped[locale] ??= []).push(key);
4140
+ continue;
4141
+ }
4142
+ if (!structureMatches(from, text)) {
4143
+ (result.rejected[locale] ??= []).push(key);
4144
+ continue;
4145
+ }
4146
+ if (!options.dryRun) catalog[key] = text;
4147
+ (result.imported[locale] ??= []).push(key);
4148
+ const seen = parsed.sources[key];
4149
+ if (seen) (result.sources[locale] ??= emptyCatalog())[key] = seen;
4150
+ }
4151
+ }
4152
+ return result;
4153
+ }
4154
+ function parseExchangeFile(file, localeOverride) {
4155
+ const content = readFileSync(file, "utf8");
4156
+ if (/\.(xlf|xliff)$/i.test(file)) {
4157
+ const parsed = parseXliff(content);
4158
+ const locale = localeOverride ?? parsed.locale;
4159
+ if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>.`);
4160
+ return {
4161
+ locale,
4162
+ entries: parsed.entries,
4163
+ sources: parsed.sources
4164
+ };
4165
+ }
4166
+ if (/\.csv$/i.test(file)) return {
4167
+ locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
4168
+ ...parseCsv(content)
4169
+ };
4170
+ if (/\.po$/i.test(file)) {
4171
+ const parsed = parsePo(content);
4172
+ return {
4173
+ locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
4174
+ entries: parsed.entries,
4175
+ sources: parsed.sources
4176
+ };
4177
+ }
4178
+ throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po.`);
4179
+ }
4180
+ function toXliff(sourceLocale, locale, entries) {
4181
+ const units = entries.map(({ key, source, target, location }) => [
4182
+ ` <unit id="${escapeXml(key)}">`,
4183
+ ...location?.length ? [
4184
+ " <notes>",
4185
+ ...location.map((file) => ` <note category="location">${escapeXml(file)}</note>`),
4186
+ " </notes>"
4187
+ ] : [],
4188
+ ` <segment state="${target ? "translated" : "initial"}">`,
4189
+ ` <source>${messageToInline(source)}</source>`,
4190
+ ` <target>${messageToInline(target)}</target>`,
4191
+ " </segment>",
4192
+ " </unit>"
4193
+ ].join("\n")).join("\n");
4194
+ return [
4195
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
4196
+ `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
4197
+ ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
4198
+ units,
4199
+ " </file>",
4200
+ "</xliff>",
4201
+ ""
4202
+ ].join("\n");
4203
+ }
4204
+ function newLocale(cfg, detected) {
4205
+ if (cfg.localesDeclared) return void 0;
4206
+ return isLocaleTag(detected) ? detected : suggestTag(detected);
4207
+ }
4208
+ function parseXliff(content) {
4209
+ const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
4210
+ const entries = Object.create(null);
4211
+ const sources = Object.create(null);
4212
+ for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
4213
+ const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
4214
+ if (!id) continue;
4215
+ const target = /<target\b[^>]*>([\s\S]*?)<\/target>/.exec(match[2])?.[1];
4216
+ entries[unescapeXml(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
4217
+ const source = /<source\b[^>]*>([\s\S]*?)<\/source>/.exec(match[2])?.[1];
4218
+ if (source !== void 0) sources[unescapeXml(id)] = inlineToMessage(stripCdata(source));
4219
+ }
4220
+ return {
4221
+ locale,
4222
+ entries,
4223
+ sources
4224
+ };
4225
+ }
4226
+ function stripCdata(text) {
4227
+ return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
4228
+ }
4229
+ function toCsv(entries) {
4230
+ return [
4231
+ "key,source,target,location",
4232
+ ...entries.map(({ key, source, target, location }) => `${csvField(key)},${csvField(source)},${csvField(target)},${csvField(location?.join("; ") ?? "")}`),
4233
+ ""
4234
+ ].join("\r\n");
4235
+ }
4236
+ function csvField(text) {
4237
+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
4238
+ }
4239
+ function parseCsv(content) {
4240
+ const rows = csvRows(content);
4241
+ const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
4242
+ const keyCol = header.indexOf("key");
4243
+ const targetCol = header.indexOf("target");
4244
+ const sourceCol = header.indexOf("source");
4245
+ if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
4246
+ const entries = Object.create(null);
4247
+ const sources = Object.create(null);
4248
+ for (const row of rows.slice(1)) {
4249
+ const key = row[keyCol];
4250
+ if (!key) continue;
4251
+ entries[key] = row[targetCol] ?? "";
4252
+ const source = sourceCol === -1 ? void 0 : row[sourceCol];
4253
+ if (source) sources[key] = source;
4254
+ }
4255
+ return {
4256
+ entries,
4257
+ sources
4258
+ };
4259
+ }
4260
+ function csvRows(content) {
4261
+ const rows = [];
4262
+ let row = [];
4263
+ let field = "";
4264
+ let quoted = false;
4265
+ for (let i = 0; i < content.length; i++) {
4266
+ const char = content[i];
4267
+ if (quoted) {
4268
+ if (char === "\"") {
4269
+ if (content[i + 1] === "\"") {
4270
+ field += "\"";
4271
+ i++;
4272
+ } else quoted = false;
4273
+ } else field += char;
4274
+ } else if (char === "\"") quoted = true;
4275
+ else if (char === ",") {
4276
+ row.push(field);
4277
+ field = "";
4278
+ } else if (char === "\n" || char === "\r") {
4279
+ if (char === "\r" && content[i + 1] === "\n") i++;
4280
+ row.push(field);
4281
+ field = "";
4282
+ if (row.some((cell) => cell !== "")) rows.push(row);
4283
+ row = [];
4284
+ } else field += char;
4285
+ }
4286
+ row.push(field);
4287
+ if (row.some((cell) => cell !== "")) rows.push(row);
4288
+ return rows;
4289
+ }
4290
+ // src/cli/commands/export.ts
4291
+ async function exportCommand(cfg, values) {
4292
+ const format = values.format ?? "xliff";
4293
+ if (![
4294
+ "xliff",
4295
+ "csv",
4296
+ "po",
4297
+ "android-xml",
4298
+ "ios-strings"
4299
+ ].includes(format)) {
4300
+ console.error(`[verbaly] unknown format "${values.format}", use xliff, csv, po, android-xml or ios-strings`);
4301
+ process.exitCode = 1;
4302
+ return;
4303
+ }
4304
+ if (values.missing && isMobileFormat(format)) {
4305
+ console.error(`[verbaly] --missing is for translator formats (xliff, csv): ${format} already skips untranslated keys so the app falls back to the source locale`);
4306
+ process.exitCode = 1;
4307
+ return;
4308
+ }
4309
+ const registry = await extractProject(cfg);
4310
+ const result = exportCatalogs(cfg, shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false }), {
4311
+ locales: csv(values.locales),
4312
+ format,
4313
+ out: values.out,
4314
+ missing: values.missing,
4315
+ origins: isMobileFormat(format) ? void 0 : await collectOrigins(cfg, registry)
4316
+ });
4317
+ if (result.files.length === 0) {
4318
+ console.log("[verbaly] no target locales to export (add locales to your config)");
4319
+ return;
4320
+ }
4321
+ const note = isMobileFormat(result.format) ? "untranslated skipped" : "untranslated";
4322
+ console.log(`[verbaly] exported ${counted(result.files.length, "locale")} (${result.format}) → ${result.dir}`);
4323
+ for (const file of result.files) console.log(` ${file.locale}: ${counted(file.total, "message")} (${file.untranslated} ${note}) → ${file.path}`);
4324
+ }
4325
+ // src/emit/watch.ts
4326
+ const NATIVE_TREE = process.platform === "darwin" || process.platform === "win32";
4327
+ function watchTree(root, options, onFile) {
4328
+ const watchers = /* @__PURE__ */ new Map();
4329
+ const close = (name) => {
4330
+ watchers.get(name)?.close();
4331
+ watchers.delete(name);
4332
+ };
4333
+ const open = (name, recursive, listener) => {
4334
+ const watcher = watch(join(root, name), {
4335
+ recursive,
4336
+ persistent: options.persistent ?? true
4337
+ }, listener);
4338
+ watcher.on("error", (error) => {
4339
+ close(name);
4340
+ console.warn(`[verbaly] stopped watching ${name || "the project"}:`, error);
4341
+ });
4342
+ watchers.set(name, watcher);
4343
+ };
4344
+ if (options.native ?? NATIVE_TREE) open("", true, (_event, file) => {
4345
+ if (file) onFile(file);
4346
+ });
4347
+ else {
4348
+ const sync = (name) => {
4349
+ close(name);
4350
+ if (name !== options.keep && (name === "node_modules" || name.startsWith("."))) return;
4351
+ try {
4352
+ if (!lstatSync(join(root, name)).isDirectory()) return;
4353
+ open(name, true, (_event, file) => {
4354
+ if (file) onFile(`${name}/${file}`);
4355
+ });
4356
+ } catch (error) {
4357
+ if (error.code !== "ENOENT") console.warn(`[verbaly] could not watch ${name}:`, error);
4358
+ }
4359
+ };
4360
+ open("", false, (event, file) => {
4361
+ if (!file) return;
4362
+ if (event === "rename") sync(file);
4363
+ onFile(file);
4364
+ });
4365
+ for (const entry of readdirSync(root, { withFileTypes: true })) if (entry.isDirectory()) sync(entry.name);
4366
+ }
4367
+ return () => {
4368
+ for (const name of [...watchers.keys()]) close(name);
4369
+ };
4370
+ }
4371
+ function watchProject(cfg, run, options = {}) {
4372
+ const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
4373
+ let timer;
4374
+ let running = false;
4375
+ let queued = false;
4376
+ async function refresh() {
4377
+ if (running) {
4378
+ queued = true;
4379
+ return;
4380
+ }
4381
+ running = true;
4382
+ try {
4383
+ await run();
4384
+ } catch (error) {
4385
+ console.warn("[verbaly] watch run failed:", error);
4386
+ } finally {
4387
+ running = false;
4388
+ if (queued) {
4389
+ queued = false;
4390
+ schedule();
4391
+ }
4392
+ }
4393
+ }
4394
+ function schedule() {
4395
+ clearTimeout(timer);
4396
+ timer = setTimeout(() => void refresh(), options.debounce ?? 150);
4397
+ }
4398
+ const close = watchTree(cfg.root, {}, (filename) => {
4399
+ if (!filename) return;
4400
+ const file = filename.replaceAll("\\", "/");
4401
+ if (file.includes("node_modules/") || file.endsWith(".d.ts")) return;
4402
+ if (catalogDir && file.startsWith(`${catalogDir}/`)) return;
4403
+ if (SOURCE_FILE_RE.test(file)) schedule();
4404
+ });
4405
+ return () => {
4406
+ clearTimeout(timer);
4407
+ close();
4408
+ };
4409
+ }
4410
+ // src/cli/commands/extract.ts
4411
+ async function extractCommand(cfg, values) {
4412
+ const dryRun = values["dry-run"];
4413
+ if (values.watch && (dryRun || values.prune)) {
4414
+ console.error("[verbaly] --watch runs alone: prune is a deliberate one-shot action and dry-run writes nothing");
4415
+ process.exitCode = 1;
4416
+ return;
4417
+ }
4418
+ const reporter = values.watch ? createDevReporter(cfg.root, (line) => console.warn(` ${line}`)) : void 0;
4419
+ async function runExtract() {
4420
+ const result = await syncProject(cfg, {
4421
+ prune: values.prune,
4422
+ dryRun
4423
+ });
4424
+ if (result.pruneBlocked) {
4425
+ const unread = result.registry.parseErrors().length;
4426
+ console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
4427
+ }
4428
+ for (const [locale, keys] of Object.entries(result.pruned)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
4429
+ const origin = result.inCode === result.messages ? "" : ` (${result.inCode} in code)`;
4430
+ console.log(`[verbaly] ${counted(result.messages, "message")}${origin} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
4431
+ for (const [locale, keys] of Object.entries(result.added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
4432
+ const warnings = result.findings.filter((finding) => {
4433
+ if (finding.kind !== "replaced" && finding.kind !== "lock") return true;
4434
+ console.log(` ${formatFinding(finding, cfg.root)}`);
4435
+ return false;
4436
+ });
4437
+ if (reporter) reporter.report("extract", warnings);
4438
+ else for (const finding of warnings) console.warn(` ${formatFinding(finding, cfg.root)}`);
4439
+ if (result.stateProblem) console.warn(` ${result.stateProblem}, so drafts and outdated translations were not updated`);
4440
+ }
4441
+ await runExtract();
4442
+ if (values.watch) {
4443
+ watchProject(cfg, runExtract);
4444
+ console.log("[verbaly] watching for source changes (ctrl+c to stop)");
4445
+ }
4446
+ }
4447
+ // src/cli/commands/import.ts
4448
+ async function importCommand(cfg, values, positionals) {
4449
+ const files = positionals.slice(1);
4450
+ if (files.length === 0) {
4451
+ console.error("[verbaly] import needs at least one file: verbaly import verbaly-export/es.xlf");
4452
+ process.exitCode = 1;
4453
+ return;
4454
+ }
4455
+ if (!values["dry-run"]) loadState(cfg);
4456
+ const registry = await extractProject(cfg);
4457
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
4458
+ const result = importCatalogs(cfg, catalogs, files, {
4459
+ locale: values.locale,
4460
+ overwrite: values.overwrite,
4461
+ dryRun: values["dry-run"]
4462
+ });
4463
+ for (const { file, from, to } of result.mapped) console.log(` ${file}: "${from}" read as ${to}`);
4464
+ for (const { file, locale, reason } of result.unmatched) {
4465
+ if (reason === "undeclared") {
4466
+ console.warn(` ${file}: "${locale}" is not one of this project's locales (${cfg.locales.join(", ")}), so nothing was imported from it`);
4467
+ console.warn(` fix: add ${locale} to locales in your verbaly config, or pass --locale with one of them`);
4468
+ } else {
4469
+ console.warn(` ${file}: "${locale}" is not a locale tag, so nothing was imported from it`);
4470
+ console.warn(" fix: pass --locale with the tag it stands for, like pt-BR");
4471
+ }
4472
+ process.exitCode = 1;
4473
+ }
4474
+ const writes = [];
4475
+ for (const [locale, keys] of Object.entries(result.imported)) {
4476
+ if (!values["dry-run"]) {
4477
+ const catalog = catalogs[locale] ?? {};
4478
+ writeCatalog(cfg, locale, catalog);
4479
+ const seen = result.sources[locale] ?? {};
4480
+ const entries = keys.map((key) => ({
4481
+ key,
4482
+ text: catalog[key],
4483
+ source: seen[key]
4484
+ }));
4485
+ writes.push({
4486
+ locale,
4487
+ entries,
4488
+ draft: values.draft === true
4489
+ });
4490
+ }
4491
+ const verb = values["dry-run"] ? "would import" : "imported";
4492
+ console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? " (draft)" : ""}`);
4493
+ }
4494
+ const lockBefore = stateFile(cfg);
4495
+ if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
4496
+ sayLockNews(cfg, lockBefore);
4497
+ for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
4498
+ for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
4499
+ 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(", ")}`);
4500
+ if (Object.keys(result.imported).length === 0 && result.unmatched.length === 0) console.log("[verbaly] nothing to import ✓");
4501
+ }
4502
+ // src/catalog/migrate.ts
4503
+ const KNOWN = [
4504
+ "i18next",
4505
+ "react-i18next",
4506
+ "vue-i18n",
4507
+ "react-intl",
4508
+ "next-intl",
4509
+ "svelte-i18n"
4510
+ ];
4511
+ function detectLibraries(root) {
4512
+ const path = join(root, "package.json");
4513
+ if (!existsSync(path)) return [];
4514
+ let manifest;
4515
+ try {
4516
+ manifest = JSON.parse(readFileSync(path, "utf8"));
4517
+ } catch {
4518
+ return [];
4519
+ }
4520
+ const deps = {
4521
+ ...manifest.dependencies,
4522
+ ...manifest.devDependencies
4523
+ };
4524
+ return KNOWN.filter((name) => deps[name] !== void 0);
4525
+ }
4526
+ const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
4527
+ const FORMATTED = /\{\{\s*-?\s*[A-Za-z_$][\w$]*\s*,[^}]*\}\}/;
4528
+ const UNESCAPED = /\{\{\s*-\s*[A-Za-z_$][\w$]*\s*\}\}/;
4529
+ const NESTED = /\$t\(/;
4530
+ const DOUBLE = /\{\{[^{}]*\}\}/;
4531
+ const DOUBLES = new RegExp(DOUBLE.source, "g");
4532
+ const ONE_PLAIN = new RegExp(`^${PLAIN.source}$`);
4533
+ const NAME = /^\s*([A-Za-z_$][\w$]*)\s*$/;
4534
+ const CATEGORIES = [
4535
+ "zero",
4536
+ "one",
4537
+ "two",
4538
+ "few",
4539
+ "many",
4540
+ "other"
4541
+ ];
4542
+ const SUFFIX = new RegExp(`^(.*)_(${[...CATEGORIES, "plural"].join("|")})$`);
4543
+ function i18nextProblem(text) {
4544
+ if (NESTED.test(text)) return "uses $t() nesting, which has no direct equivalent";
4545
+ if (UNESCAPED.test(text)) return "uses {{- name}}, so decide whether the message is rich";
4546
+ if (FORMATTED.test(text)) return "uses an i18next format, which needs the matching Verbaly one";
4547
+ for (const [double] of text.matchAll(DOUBLES)) if (!ONE_PLAIN.test(double)) return "uses {{…}} with more than a name, which needs a Verbaly param";
4548
+ }
4549
+ function convertBraces(text) {
4550
+ let out = "";
4551
+ let last = 0;
4552
+ for (const match of text.matchAll(PLAIN)) {
4553
+ out += escapeBraces(text.slice(last, match.index)) + `{${match[1]}}`;
4554
+ last = match.index + match[0].length;
4555
+ }
4556
+ return out + escapeBraces(text.slice(last));
4557
+ }
4558
+ function escapeBraces(text) {
4559
+ return text.replace(/[{}]/g, (brace) => brace + brace);
4560
+ }
4561
+ function toVariant(text) {
4562
+ let out = "";
4563
+ let i = 0;
4564
+ while (i < text.length) {
4565
+ const ch = text[i];
4566
+ if ((ch === "{" || ch === "}") && text[i + 1] === ch) {
4567
+ out += ch + ch;
4568
+ i += 2;
4569
+ } else if (ch === "{") {
4570
+ const close = text.indexOf("}", i);
4571
+ const name = close < 0 ? void 0 : NAME.exec(text.slice(i + 1, close))?.[1];
4572
+ if (name === void 0) return void 0;
4573
+ out += name === "count" ? "#" : `{${name}}`;
4574
+ i = close + 1;
4575
+ } else {
4576
+ out += ch === "#" || ch === "|" || ch === "}" ? ch + ch : ch;
4577
+ i += 1;
4578
+ }
4579
+ }
4580
+ return out;
4581
+ }
4582
+ function order(a, b) {
4583
+ return CATEGORIES.indexOf(a) - CATEGORIES.indexOf(b);
4584
+ }
4585
+ function mergePlurals(locale, catalog, out, plurals, skipped, fromI18next) {
4586
+ const groups = /* @__PURE__ */ new Map();
4587
+ const legacy = /* @__PURE__ */ new Set();
4588
+ for (const [key, value] of Object.entries(catalog)) {
4589
+ const match = SUFFIX.exec(key);
4590
+ if (!match || typeof value !== "string") continue;
4591
+ const [, base, suffix] = match;
4592
+ if (suffix === "plural") legacy.add(base);
4593
+ const category = suffix === "plural" ? "other" : suffix;
4594
+ if (!groups.has(base)) groups.set(base, /* @__PURE__ */ new Map());
4595
+ groups.get(base).set(category, {
4596
+ key,
4597
+ value
4598
+ });
4599
+ }
4600
+ for (const [base, forms] of groups) {
4601
+ const bare = catalog[base];
4602
+ if (legacy.has(base) && typeof bare === "string" && !forms.has("one")) forms.set("one", {
4603
+ key: base,
4604
+ value: bare
4605
+ });
4606
+ else if (bare !== void 0) {
4607
+ skipped.push({
4608
+ locale,
4609
+ key: base,
4610
+ reason: `"${base}" already exists, so merging would overwrite it`
4611
+ });
4612
+ continue;
4613
+ }
4614
+ if (!forms.has("other")) {
4615
+ skipped.push({
4616
+ locale,
4617
+ key: base,
4618
+ reason: "no _other form, so the block would have no catch-all"
4619
+ });
4620
+ continue;
4621
+ }
4622
+ if (forms.size === 1) {
4623
+ skipped.push({
4624
+ locale,
4625
+ key: base,
4626
+ reason: "only a plural form, so add the singular before merging"
4627
+ });
4628
+ continue;
4629
+ }
4630
+ const sorted = [...forms.entries()].sort((a, b) => order(a[0], b[0]));
4631
+ const cases = [];
4632
+ let problem;
4633
+ for (const [category, form] of sorted) {
4634
+ problem = fromI18next ? i18nextProblem(form.value) : void 0;
4635
+ const body = problem ? void 0 : toVariant(fromI18next ? convertBraces(form.value) : form.value);
4636
+ if (body === void 0) {
4637
+ problem ??= "a form holds more than a name in braces, so merge it by hand";
4638
+ break;
4639
+ }
4640
+ cases.push(`${category}: ${body}`);
4641
+ }
4642
+ if (problem) {
4643
+ skipped.push({
4644
+ locale,
4645
+ key: base,
4646
+ reason: problem
4647
+ });
4648
+ continue;
4649
+ }
4650
+ const merged = `{count | ${cases.join(" | ")}}`;
4651
+ for (const [, form] of sorted) delete out[form.key];
4652
+ out[base] = merged;
4653
+ plurals.push({
4654
+ locale,
4655
+ key: base,
4656
+ from: sorted.map(([, form]) => form.key),
4657
+ after: merged
4658
+ });
4659
+ }
4660
+ }
4661
+ function migrateCatalogs(cfg, options = {}) {
4662
+ const braces = [];
4663
+ const plurals = [];
4664
+ const skipped = [];
4665
+ const written = [];
4666
+ const state = loadState(cfg);
4667
+ const done = new Set(state.migrated ?? []);
4668
+ const catalogs = new Map(cfg.locales.map((locale) => [locale, readCatalog(cfg, locale)]));
4669
+ const pending = cfg.locales.filter((locale) => !done.has(locale));
4670
+ const fromI18next = pending.some((locale) => Object.values(catalogs.get(locale)).some((value) => typeof value === "string" && (DOUBLE.test(value) || NESTED.test(value))));
4671
+ for (const locale of cfg.locales) {
4672
+ const catalog = catalogs.get(locale);
4673
+ const out = Object.assign(emptyCatalog(), catalog);
4674
+ const convert = fromI18next && !done.has(locale);
4675
+ for (const [key, value] of Object.entries(catalog)) {
4676
+ if (!convert || typeof value !== "string") continue;
4677
+ const problem = i18nextProblem(value);
4678
+ if (problem) {
4679
+ skipped.push({
4680
+ locale,
4681
+ key,
4682
+ reason: problem
4683
+ });
4684
+ continue;
4685
+ }
4686
+ const after = convertBraces(value);
4687
+ if (after !== value) {
4688
+ braces.push({
4689
+ locale,
4690
+ key,
4691
+ before: value,
4692
+ after
4693
+ });
4694
+ out[key] = after;
4695
+ }
4696
+ }
4697
+ if (options.plurals) mergePlurals(locale, catalog, out, plurals, skipped, convert);
4698
+ if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
4699
+ writeCatalog(cfg, locale, out);
4700
+ written.push(locale);
4701
+ }
4702
+ }
4703
+ if (options.write && fromI18next) {
4704
+ const converted = pending.filter((locale) => existsSync(catalogPath(cfg, locale)));
4705
+ if (converted.length) saveState(cfg, {
4706
+ ...state,
4707
+ migrated: [...done, ...converted]
4708
+ });
4709
+ }
4710
+ const remembered = cfg.locales.filter((locale) => done.has(locale));
4711
+ return {
4712
+ detected: detectLibraries(cfg.root),
4713
+ braces,
4714
+ plurals,
4715
+ skipped,
4716
+ written,
4717
+ remembered
4718
+ };
4719
+ }
4720
+ // src/project/init.ts
4721
+ const CATALOG_DIRS = [
4722
+ "locales",
4723
+ "src/locales",
4724
+ "src/i18n/locales",
4725
+ "src/i18n",
4726
+ "i18n",
4727
+ "lang",
4728
+ "src/lang",
4729
+ "translations",
4730
+ "src/translations",
4731
+ "messages"
4732
+ ];
4733
+ function existingCatalogs(root) {
4734
+ return CATALOG_DIRS.find((dir) => {
4735
+ try {
4736
+ return readdirSync(join(root, dir)).some((file) => file.endsWith(".json") && isLocaleTag(file.slice(0, -5)));
4737
+ } catch {
4738
+ return false;
4739
+ }
4740
+ });
4741
+ }
4742
+ function configSource(options, typescript) {
4743
+ const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
4744
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
4745
+ if (options.dir) fields.push(` dir: '${options.dir}',`);
4746
+ const body = `export default {\n${fields.join("\n")}\n}`;
4747
+ if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
4748
+ return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
4749
+ }
4750
+ async function init(input = {}) {
4751
+ const root = input.root ?? process.cwd();
4752
+ const created = [];
4753
+ const skipped = [];
4754
+ const renamed = [];
4755
+ const refused = [];
4756
+ const typed = input.locales?.flatMap((locale) => {
4757
+ if (isLocaleTag(locale)) return [locale];
4758
+ const near = suggestTag(locale);
4759
+ if (near) renamed.push({
4760
+ from: locale,
4761
+ to: near
4762
+ });
4763
+ else refused.push(locale);
4764
+ return near ? [near] : [];
4765
+ });
4766
+ const locales = typed && [...new Set(typed)];
4767
+ let sourceLocale = input.sourceLocale;
4768
+ if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
4769
+ const near = suggestTag(sourceLocale);
4770
+ if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
4771
+ renamed.push({
4772
+ from: sourceLocale,
4773
+ to: near
4774
+ });
4775
+ sourceLocale = near;
4776
+ }
4777
+ const options = {
4778
+ ...input,
4779
+ locales,
4780
+ sourceLocale
4781
+ };
4782
+ const existing = findConfigFile(root);
4783
+ const typescript = existsSync(join(root, "tsconfig.json"));
4784
+ const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
4785
+ const found = existing || options.dir ? void 0 : existingCatalogs(root);
4786
+ if (existing) skipped.push(existing);
4787
+ else {
4788
+ const dir = found === "locales" ? void 0 : found;
4789
+ writeFileSync(join(root, configFile), configSource({
4790
+ ...options,
4791
+ dir: options.dir ?? dir
4792
+ }, typescript));
4793
+ created.push(configFile);
4794
+ }
4795
+ const fromFile = existing ? await loadConfigFile(root) : {};
4796
+ const scaffold = {
4797
+ dir: options.dir ?? fromFile.dir ?? found,
4798
+ sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
4799
+ locales: options.locales ?? fromFile.locales
4800
+ };
4801
+ const dir = join(root, scaffold.dir ?? "locales");
4802
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
4803
+ for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
4804
+ const file = join(dir, `${locale}.json`);
4805
+ const label = relative(root, file).replaceAll("\\", "/");
4806
+ if (existsSync(file)) skipped.push(label);
4807
+ else {
4808
+ writeFileSync(file, "{}\n");
4809
+ created.push(label);
4810
+ }
4811
+ }
4812
+ const host = detectHost(root);
4813
+ const deps = readDependencies(root);
4814
+ const missing = host?.install.filter((pkg) => !deps[pkg]) ?? [];
4815
+ const next = host ? [...missing.length ? [installCommand(root, missing)] : [], host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
4816
+ const others = detectLibraries(root);
4817
+ if (found && others.length) next.push(`port the ${others.join(" and ")} catalogs: npx verbaly migrate reports, --write applies`);
4818
+ const source = scaffold.sourceLocale ?? "en";
4819
+ const catalogs = readdirSync(dir).filter((name) => name.endsWith(".json") && name[0] !== ".");
4820
+ if (!scaffold.locales?.some((locale) => locale !== source) && catalogs.length <= 1) {
4821
+ const other = source === "es" ? "en" : "es";
4822
+ next.push(`add a language: locales: ['${source}', '${other}'] in ${configFile}, then npx verbaly extract`);
4823
+ }
4824
+ return {
4825
+ created,
4826
+ skipped,
4827
+ host: host?.name,
4828
+ configFile,
4829
+ next,
4830
+ renamed,
4831
+ refused,
4832
+ found
4833
+ };
4834
+ }
4835
+ // src/cli/commands/init.ts
4836
+ async function initCommand(values) {
4837
+ const result = await init({
4838
+ root: values.root,
4839
+ dir: values.dir,
4840
+ sourceLocale: values.source,
4841
+ locales: csv(values.locales)
4842
+ });
4843
+ if (result.created.length) console.log(`[verbaly] created: ${result.created.join(", ")}`);
4844
+ if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(", ")}`);
4845
+ for (const { from, to } of result.renamed) console.log(` wrote ${to} for ${from}, since a locale tag takes a hyphen`);
4846
+ for (const locale of result.refused) console.warn(` left out "${locale}": it is not a locale tag, use one like es or pt-BR`);
4847
+ if (result.found) console.log(` catalogs: ${result.found}, kept where they already are`);
4848
+ if (result.host) console.log(` detected: ${result.host}`);
4849
+ console.log([" next steps:", ...result.next.map((step, i) => ` ${i + 1}. ${step}`)].join("\n"));
4850
+ }
4851
+ // src/cli/commands/migrate.ts
4852
+ async function migrateCommand(cfg, values) {
4853
+ const lockBefore = stateFile(cfg);
4854
+ const result = migrateCatalogs(cfg, {
4855
+ write: values.write,
4856
+ plurals: values.plurals
4857
+ });
4858
+ const from = result.detected.length ? result.detected.join(", ") : "no known i18n library";
4859
+ const changes = result.braces.length + result.plurals.length;
4860
+ const before = result.remembered.length ? `, ${counted(result.remembered.length, "language")} converted before` : "";
4861
+ if (changes === 0 && result.skipped.length === 0) {
4862
+ console.log(`[verbaly] catalogs need nothing (${from}${before}) ✓`);
4863
+ return;
4864
+ }
4865
+ const verb = values.write ? "ported" : "would port";
4866
+ const note = values.write ? "" : " (report only, use --write to apply)";
4867
+ console.log(`[verbaly] ${verb} ${counted(changes, "message")} from ${from}${before}${note}`);
4868
+ for (const entry of result.braces) console.log(` ${entry.locale} ${entry.key} ${entry.before} → ${entry.after}`);
4869
+ for (const entry of result.plurals) console.log(` ${entry.locale} ${entry.key} ${entry.from.join(" + ")} → ${entry.after}`);
4870
+ if (!values.plurals && changes > 0) console.log(" --plurals also merges _one/_other into one message with variants");
4871
+ if (result.skipped.length > 0) {
4872
+ console.log(" needs a human:");
4873
+ for (const entry of result.skipped) console.log(` ${entry.locale} ${entry.key} ${entry.reason}`);
4874
+ }
4875
+ if (values.write && result.braces.length > 0) console.log(` ${STATE_FILE} remembers the converted languages, so a later run never reads them as i18next again`);
4876
+ sayLockNews(cfg, lockBefore);
4877
+ if (values.write) console.log(" next: run verbaly check");
4878
+ }
4879
+ // src/catalog/pseudo.ts
4880
+ const ACCENTS = {
4881
+ a: "á",
4882
+ b: "ƀ",
4883
+ c: "ç",
4884
+ d: "đ",
4885
+ e: "é",
4886
+ f: "ƒ",
4887
+ g: "ğ",
4888
+ h: "ĥ",
4889
+ i: "í",
4890
+ j: "ĵ",
4891
+ k: "ķ",
4892
+ l: "ĺ",
4893
+ m: "ɱ",
4894
+ n: "ñ",
4895
+ o: "ó",
4896
+ p: "þ",
4897
+ q: "ǫ",
4898
+ r: "ŕ",
4899
+ s: "š",
4900
+ t: "ţ",
4901
+ u: "ú",
4902
+ v: "ṽ",
4903
+ w: "ŵ",
4904
+ x: "ẋ",
4905
+ y: "ý",
4906
+ z: "ž",
4907
+ A: "Á",
4908
+ B: "Ɓ",
4909
+ C: "Ç",
4910
+ D: "Đ",
4911
+ E: "É",
4912
+ F: "Ƒ",
4913
+ G: "Ğ",
4914
+ H: "Ĥ",
4915
+ I: "Í",
4916
+ J: "Ĵ",
4917
+ K: "Ķ",
4918
+ L: "Ĺ",
4919
+ M: "Ḿ",
4920
+ N: "Ñ",
4921
+ O: "Ó",
4922
+ P: "Þ",
4923
+ Q: "Ǫ",
4924
+ R: "Ŕ",
4925
+ S: "Š",
4926
+ T: "Ţ",
4927
+ U: "Ú",
4928
+ V: "Ṽ",
4929
+ W: "Ŵ",
4930
+ X: "Ẍ",
4931
+ Y: "Ý",
4932
+ Z: "Ž"
4933
+ };
4934
+ const TAG_AT = /<\/?[a-zA-Z][\w-]*\/?>/y;
4935
+ function pseudoLocalize(message) {
4936
+ let out = "";
4937
+ let letters = 0;
4938
+ let i = 0;
4939
+ while (i < message.length) {
4940
+ const two = message.slice(i, i + 2);
4941
+ if (two === "{{" || two === "}}" || two === "||" || two === "##") {
4942
+ out += two;
4943
+ i += 2;
4944
+ continue;
4945
+ }
4946
+ const ch = message[i];
4947
+ if (ch === "{") {
4948
+ const end = matchBrace(message, i);
4949
+ out += message.slice(i, end);
4950
+ i = end;
4951
+ continue;
4952
+ }
4953
+ if (ch === "<") {
4954
+ TAG_AT.lastIndex = i;
4955
+ const m = TAG_AT.exec(message);
4956
+ if (m) {
4957
+ out += m[0];
4958
+ i += m[0].length;
4309
4959
  continue;
4310
4960
  }
4311
- if (!options.dryRun) catalog[key] = text;
4312
- (result.imported[locale] ??= []).push(key);
4313
- const seen = parsed.sources[key];
4314
- if (seen) (result.sources[locale] ??= {})[key] = seen;
4315
4961
  }
4962
+ const mapped = ACCENTS[ch];
4963
+ if (mapped) {
4964
+ out += mapped;
4965
+ letters += 1;
4966
+ } else out += ch;
4967
+ i += 1;
4316
4968
  }
4317
- return result;
4318
- }
4319
- function parseExchangeFile(file, localeOverride) {
4320
- const content = readFileSync(file, "utf8");
4321
- if (/\.(xlf|xliff)$/i.test(file)) {
4322
- const parsed = parseXliff(content);
4323
- const locale = localeOverride ?? parsed.locale;
4324
- if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>.`);
4325
- return {
4326
- locale,
4327
- entries: parsed.entries,
4328
- sources: parsed.sources
4329
- };
4330
- }
4331
- if (/\.csv$/i.test(file)) return {
4332
- locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
4333
- ...parseCsv(content)
4334
- };
4335
- if (/\.po$/i.test(file)) {
4336
- const parsed = parsePo(content);
4337
- return {
4338
- locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
4339
- entries: parsed.entries,
4340
- sources: parsed.sources
4341
- };
4342
- }
4343
- throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po.`);
4344
- }
4345
- function toXliff(sourceLocale, locale, entries) {
4346
- const units = entries.map(({ key, source, target, location }) => [
4347
- ` <unit id="${escapeXml(key)}">`,
4348
- ...location?.length ? [
4349
- " <notes>",
4350
- ...location.map((file) => ` <note category="location">${escapeXml(file)}</note>`),
4351
- " </notes>"
4352
- ] : [],
4353
- ` <segment state="${target ? "translated" : "initial"}">`,
4354
- ` <source>${messageToInline(source)}</source>`,
4355
- ` <target>${messageToInline(target)}</target>`,
4356
- " </segment>",
4357
- " </unit>"
4358
- ].join("\n")).join("\n");
4359
- return [
4360
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
4361
- `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
4362
- ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
4363
- units,
4364
- " </file>",
4365
- "</xliff>",
4366
- ""
4367
- ].join("\n");
4368
- }
4369
- function newLocale(cfg, detected) {
4370
- if (cfg.localesDeclared) return void 0;
4371
- return isLocaleTag(detected) ? detected : suggestTag(detected);
4969
+ const pad = "~".repeat(Math.ceil(letters / 3));
4970
+ return `⟦${out}${pad ? " " + pad : ""}⟧`;
4372
4971
  }
4373
- function parseXliff(content) {
4374
- const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
4375
- const entries = Object.create(null);
4376
- const sources = Object.create(null);
4377
- for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
4378
- const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
4379
- if (!id) continue;
4380
- const target = /<target\b[^>]*>([\s\S]*?)<\/target>/.exec(match[2])?.[1];
4381
- entries[unescapeXml(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
4382
- const source = /<source\b[^>]*>([\s\S]*?)<\/source>/.exec(match[2])?.[1];
4383
- if (source !== void 0) sources[unescapeXml(id)] = inlineToMessage(stripCdata(source));
4972
+ function matchBrace(message, start) {
4973
+ let depth = 0;
4974
+ for (let i = start; i < message.length; i++) {
4975
+ const two = message.slice(i, i + 2);
4976
+ if (two === "{{" || two === "}}") {
4977
+ i += 1;
4978
+ continue;
4979
+ }
4980
+ const ch = message[i];
4981
+ if (ch === "{") depth += 1;
4982
+ else if (ch === "}") {
4983
+ depth -= 1;
4984
+ if (depth === 0) return i + 1;
4985
+ }
4384
4986
  }
4385
- return {
4386
- locale,
4387
- entries,
4388
- sources
4389
- };
4390
- }
4391
- function stripCdata(text) {
4392
- return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
4393
- }
4394
- function toCsv(entries) {
4395
- return [
4396
- "key,source,target,location",
4397
- ...entries.map(({ key, source, target, location }) => `${csvField(key)},${csvField(source)},${csvField(target)},${csvField(location?.join("; ") ?? "")}`),
4398
- ""
4399
- ].join("\r\n");
4400
- }
4401
- function csvField(text) {
4402
- return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
4987
+ return message.length;
4403
4988
  }
4404
- function parseCsv(content) {
4405
- const rows = csvRows(content);
4406
- const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
4407
- const keyCol = header.indexOf("key");
4408
- const targetCol = header.indexOf("target");
4409
- const sourceCol = header.indexOf("source");
4410
- if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
4411
- const entries = Object.create(null);
4412
- const sources = Object.create(null);
4413
- for (const row of rows.slice(1)) {
4414
- const key = row[keyCol];
4415
- if (!key) continue;
4416
- entries[key] = row[targetCol] ?? "";
4417
- const source = sourceCol === -1 ? void 0 : row[sourceCol];
4418
- if (source) sources[key] = source;
4419
- }
4420
- return {
4421
- entries,
4422
- sources
4423
- };
4989
+ function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
4990
+ const source = catalogs[cfg.sourceLocale] ?? {};
4991
+ const target = emptyCatalog();
4992
+ for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
4993
+ catalogs[locale] = target;
4994
+ return Object.keys(target).filter((key) => target[key]);
4424
4995
  }
4425
- function csvRows(content) {
4426
- const rows = [];
4427
- let row = [];
4428
- let field = "";
4429
- let quoted = false;
4430
- for (let i = 0; i < content.length; i++) {
4431
- const char = content[i];
4432
- if (quoted) {
4433
- if (char === "\"") {
4434
- if (content[i + 1] === "\"") {
4435
- field += "\"";
4436
- i++;
4437
- } else quoted = false;
4438
- } else field += char;
4439
- } else if (char === "\"") quoted = true;
4440
- else if (char === ",") {
4441
- row.push(field);
4442
- field = "";
4443
- } else if (char === "\n" || char === "\r") {
4444
- if (char === "\r" && content[i + 1] === "\n") i++;
4445
- row.push(field);
4446
- field = "";
4447
- if (row.some((cell) => cell !== "")) rows.push(row);
4448
- row = [];
4449
- } else field += char;
4450
- }
4451
- row.push(field);
4452
- if (row.some((cell) => cell !== "")) rows.push(row);
4453
- return rows;
4996
+ // src/cli/commands/pseudo.ts
4997
+ async function pseudoCommand(cfg, values) {
4998
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg), { newKeys: false });
4999
+ const locale = values.locale ?? "en-XA";
5000
+ const keys = pseudoCatalogs(cfg, catalogs, locale);
5001
+ writeCatalog(cfg, locale, catalogs[locale] ?? {});
5002
+ console.log(`[verbaly] ${counted(keys.length, "message")} pseudo-localized → ${locale}`);
4454
5003
  }
4455
- // src/render.ts
5004
+ // src/emit/render.ts
4456
5005
  function localeInstance(catalogs, locale, sourceLocale) {
4457
5006
  return createVerbaly({
4458
5007
  locale,
@@ -4588,11 +5137,11 @@ function pageSlice(v, locale, used) {
4588
5137
  return slice;
4589
5138
  }
4590
5139
  function sameUrl(written, url) {
4591
- return url !== void 0 && written.replace(/\/+$/, "") === url.replace(/\/+$/, "");
5140
+ return url !== void 0 && trimTrailingSlashes(written) === trimTrailingSlashes(url);
4592
5141
  }
4593
5142
  function publicPath(rel) {
4594
5143
  const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
4595
- return path.length > 1 ? path.replace(/\/+$/, "") : path;
5144
+ return path.length > 1 ? trimTrailingSlashes(path) : path;
4596
5145
  }
4597
5146
  function linkFor(links, name) {
4598
5147
  return links && Object.hasOwn(links, name) ? links[name] : void 0;
@@ -4643,7 +5192,7 @@ function stripBase(path, base) {
4643
5192
  return rest.startsWith("/") ? rest : path;
4644
5193
  }
4645
5194
  function normalizeBase(base) {
4646
- const trimmed = base?.replace(/^\/+/, "").replace(/\/+$/, "");
5195
+ const trimmed = trimTrailingSlashes(base?.replace(/^\/+/, "") ?? "");
4647
5196
  return trimmed ? `/${trimmed}` : "";
4648
5197
  }
4649
5198
  const REDIRECT_BODY = "(function(){var T=/^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|[0-9]{3}))?$/i;function M(t,g){t=String(t||\"\");if(S.indexOf(t)>=0)return t;if(g&&!T.test(t))return;while(t){var i=t.lastIndexOf(\"-\");if(i<0)return;t=t.slice(0,i);if(S.indexOf(t)>=0)return t}}var p=location.pathname;if(B){if(p.indexOf(B)!==0)return;p=p.slice(B.length)||\"/\";if(p.charAt(0)!==\"/\")return}if(M(p.split(\"/\")[1],1))return;var w;if(K)try{w=M(localStorage.getItem(K))}catch(e){}if(!w){var l=navigator.languages||[navigator.language];for(var i=0;i<l.length&&!w;i++)w=M(l[i])}if(!w||w===D)return;location.replace(B+\"/\"+w+(N&&p===\"/\"?\"\":p)+location.search+location.hash)})()";
@@ -4720,7 +5269,8 @@ async function renderSite(cfg, options = {}) {
4720
5269
  const locales = options.locales ?? cfg.locales;
4721
5270
  const attribute = options.attribute ?? cfg.render.attribute;
4722
5271
  const base = normalizeBase(options.base ?? cfg.render.base);
4723
- const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\/+$/, "");
5272
+ const wantedUrl = options.baseUrl ?? cfg.render.baseUrl;
5273
+ const baseUrl = typeof wantedUrl === "string" ? trimTrailingSlashes(wantedUrl) : void 0;
4724
5274
  const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== void 0;
4725
5275
  const patterns = options.exclude ?? cfg.render.exclude ?? [];
4726
5276
  const excluded = patterns.length > 0 ? picomatch(patterns) : () => false;
@@ -4750,7 +5300,7 @@ async function renderSite(cfg, options = {}) {
4750
5300
  ignore: locales.map((locale) => `${locale}/**`)
4751
5301
  });
4752
5302
  const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
4753
- const missing = {};
5303
+ const missing = emptyCatalog();
4754
5304
  const untranslatedHead = [];
4755
5305
  const urls = [];
4756
5306
  for (const file of files) {
@@ -4840,15 +5390,26 @@ function parseArgs$1(raw, attribute) {
4840
5390
  return;
4841
5391
  }
4842
5392
  }
4843
- function protectedRanges(html) {
4844
- const ranges = [];
4845
- const re = /<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
4846
- let m;
4847
- while ((m = re.exec(html)) !== null) {
4848
- const openEnd = m[0].startsWith("<!--") ? m.index : html.indexOf(">", m.index) + 1;
4849
- ranges.push([openEnd, m.index + m[0].length]);
5393
+ const OPAQUE_BLOCKS = [
5394
+ {
5395
+ open: "<!--",
5396
+ close: /(?<=<!--)-?>|--!?>/g
5397
+ },
5398
+ {
5399
+ open: /<script\b/gi,
5400
+ close: /<\/script(?=[\t\n\f\r />])/gi,
5401
+ closeTag: true
5402
+ },
5403
+ {
5404
+ open: /<style\b/gi,
5405
+ close: /<\/style(?=[\t\n\f\r />])/gi,
5406
+ closeTag: true
4850
5407
  }
4851
- return ranges;
5408
+ ];
5409
+ function protectedRanges(html) {
5410
+ return blocks(html, OPAQUE_BLOCKS).map(({ start, end }) => {
5411
+ return [html.startsWith("<!--", start) ? start : html.indexOf(">", start) + 1, end];
5412
+ });
4852
5413
  }
4853
5414
  function findClose(html, tagName, from, inSkip) {
4854
5415
  const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
@@ -4901,92 +5462,144 @@ function escapeAttr(text) {
4901
5462
  function decodeEntities(text) {
4902
5463
  return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
4903
5464
  }
4904
- // src/watch.ts
4905
- const NATIVE_TREE = process.platform === "darwin" || process.platform === "win32";
4906
- function watchTree(root, options, onFile) {
4907
- const watchers = /* @__PURE__ */ new Map();
4908
- const close = (name) => {
4909
- watchers.get(name)?.close();
4910
- watchers.delete(name);
4911
- };
4912
- const open = (name, recursive, listener) => {
4913
- const watcher = watch(join(root, name), {
4914
- recursive,
4915
- persistent: options.persistent ?? true
4916
- }, listener);
4917
- watcher.on("error", (error) => {
4918
- close(name);
4919
- console.warn(`[verbaly] stopped watching ${name || "the project"}:`, error);
4920
- });
4921
- watchers.set(name, watcher);
4922
- };
4923
- if (options.native ?? NATIVE_TREE) open("", true, (_event, file) => {
4924
- if (file) onFile(file);
5465
+ // src/cli/commands/render.ts
5466
+ async function renderCommand(cfg, values) {
5467
+ const result = await renderSite(cfg, {
5468
+ site: values.site,
5469
+ locales: csv(values.locales),
5470
+ attribute: values.attribute,
5471
+ base: values.base,
5472
+ baseUrl: values["base-url"],
5473
+ sitemap: values.sitemap,
5474
+ redirect: values.redirect,
5475
+ clean: values.clean
4925
5476
  });
4926
- else {
4927
- const sync = (name) => {
4928
- close(name);
4929
- if (name !== options.keep && (name === "node_modules" || name.startsWith("."))) return;
4930
- try {
4931
- if (!lstatSync(join(root, name)).isDirectory()) return;
4932
- open(name, true, (_event, file) => {
4933
- if (file) onFile(`${name}/${file}`);
4934
- });
4935
- } catch (error) {
4936
- if (error.code !== "ENOENT") console.warn(`[verbaly] could not watch ${name}:`, error);
4937
- }
4938
- };
4939
- open("", false, (event, file) => {
4940
- if (!file) return;
4941
- if (event === "rename") sync(file);
4942
- onFile(file);
4943
- });
4944
- for (const entry of readdirSync(root, { withFileTypes: true })) if (entry.isDirectory()) sync(entry.name);
5477
+ console.log(`[verbaly] ${counted(result.files, "page")} × ${counted(result.locales.length, "locale")} (${result.locales.join(", ")})`);
5478
+ for (const line of formatRenderWarnings(result, cfg.sourceLocale)) console.warn(line);
5479
+ }
5480
+ // src/cli/commands/review.ts
5481
+ async function reviewCommand(cfg, values, positionals) {
5482
+ const registry = await extractProject(cfg);
5483
+ const catalogs = loadCatalogs(cfg);
5484
+ const shipped = shippedCatalogs(cfg, catalogs, registry);
5485
+ const state = loadState(cfg);
5486
+ const only = new Set(positionals.slice(1));
5487
+ const wanted = ({ locale, key }) => (!values.locale || locale === values.locale) && (only.size === 0 || only.has(key));
5488
+ const drafts = Object.entries(effectiveDrafts(state.drafts, catalogs)).flatMap(([locale, keys]) => keys.map((key) => ({
5489
+ locale,
5490
+ key
5491
+ }))).filter(wanted);
5492
+ const outdated = outdatedTranslations(cfg, shipped, state.fingerprints).filter(wanted);
5493
+ if (drafts.length === 0 && outdated.length === 0) {
5494
+ console.log("[verbaly] nothing awaiting review ✓");
5495
+ return;
4945
5496
  }
4946
- return () => {
4947
- for (const name of [...watchers.keys()]) close(name);
5497
+ if (values.approve) {
5498
+ for (const [locale, keys] of byLocale(drafts)) {
5499
+ clearDrafts(state.drafts, locale, keys);
5500
+ console.log(` ${locale}: ${keys.length} approved`);
5501
+ }
5502
+ acceptOutdated(cfg, shipped, state.fingerprints, outdated);
5503
+ for (const [locale, keys] of byLocale(outdated)) console.log(` ${locale}: ${keys.length} kept for the new source text`);
5504
+ const lockBefore = stateFile(cfg);
5505
+ saveState(cfg, state);
5506
+ sayLockNews(cfg, lockBefore);
5507
+ const reviewed = new Set([...drafts, ...outdated].map(({ locale, key }) => `${locale}:${key}`));
5508
+ console.log(`[verbaly] ${counted(reviewed.size, "translation")} marked reviewed ✓`);
5509
+ return;
5510
+ }
5511
+ const source = shipped[cfg.sourceLocale] ?? {};
5512
+ const show = (locale, keys) => {
5513
+ console.log(` ${locale}:`);
5514
+ for (const key of keys) {
5515
+ const translated = catalogs[locale]?.[key] ?? "";
5516
+ console.log(` ${key}: "${truncate(source[key] ?? "", 60)}" → "${truncate(translated, 60)}"`);
5517
+ }
4948
5518
  };
5519
+ if (drafts.length > 0) {
5520
+ console.log(`[verbaly] ${counted(drafts.length, "machine translation")} awaiting review (--approve to accept)`);
5521
+ for (const [locale, keys] of byLocale(drafts)) show(locale, keys);
5522
+ }
5523
+ if (outdated.length > 0) {
5524
+ console.log(`[verbaly] ${counted(outdated.length, "translation")} written for an older source text (update them, or --approve keeps them)`);
5525
+ for (const [locale, keys] of byLocale(outdated)) show(locale, keys);
5526
+ }
4949
5527
  }
4950
- function watchProject(cfg, run, options = {}) {
4951
- const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
4952
- let timer;
4953
- let running = false;
4954
- let queued = false;
4955
- async function refresh() {
4956
- if (running) {
4957
- queued = true;
5528
+ // src/cli/commands/status.ts
5529
+ async function statusCommand(cfg, values) {
5530
+ const registry = await extractProject(cfg);
5531
+ const { state, problem } = readState(cfg);
5532
+ if (problem) console.warn(`[verbaly] ${problem}, so drafts and outdated translations are not counted`);
5533
+ const result = status(cfg, loadCatalogs(cfg), registry, state.drafts, state.fingerprints);
5534
+ console.log(values.json ? JSON.stringify(result) : formatStatusResult(result));
5535
+ }
5536
+ // src/cli/commands/translate.ts
5537
+ async function translateCommand(cfg, values) {
5538
+ if (!values["dry-run"]) loadState(cfg);
5539
+ const registry = await extractProject(cfg);
5540
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
5541
+ const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
5542
+ locales: csv(values.locales),
5543
+ batchSize: cfg.translate.batchSize,
5544
+ concurrency: cfg.translate.concurrency,
5545
+ retries: cfg.translate.retries,
5546
+ dryRun: values["dry-run"],
5547
+ origins: values["dry-run"] ? void 0 : await collectOrigins(cfg, registry),
5548
+ onProgress: values["dry-run"] ? void 0 : reportProgress
5549
+ });
5550
+ if (values["dry-run"]) {
5551
+ const entries = Object.entries(result.pending);
5552
+ if (entries.length === 0) {
5553
+ console.log("[verbaly] nothing to translate ✓");
4958
5554
  return;
4959
5555
  }
4960
- running = true;
4961
- try {
4962
- await run();
4963
- } catch (error) {
4964
- console.warn("[verbaly] watch run failed:", error);
4965
- } finally {
4966
- running = false;
4967
- if (queued) {
4968
- queued = false;
4969
- schedule();
4970
- }
4971
- }
5556
+ for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.length} missing: ${keys.join(", ")}`);
5557
+ return;
4972
5558
  }
4973
- function schedule() {
4974
- clearTimeout(timer);
4975
- timer = setTimeout(() => void refresh(), options.debounce ?? 150);
5559
+ const source = catalogs[cfg.sourceLocale] ?? {};
5560
+ const writes = [];
5561
+ for (const [locale, keys] of Object.entries(result.translated)) {
5562
+ const catalog = catalogs[locale] ?? {};
5563
+ const written = mergeTranslations(cfg, locale, catalog, keys);
5564
+ writes.push({
5565
+ locale,
5566
+ draft: true,
5567
+ entries: written.map((key) => ({
5568
+ key,
5569
+ text: catalog[key]
5570
+ }))
5571
+ });
5572
+ console.log(` ${locale}: +${written.length} translated (draft)`);
5573
+ const kept = keys.length - written.length;
5574
+ if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
5575
+ }
5576
+ const lockBefore = stateFile(cfg);
5577
+ if (writes.length > 0) recordTranslations(cfg, source, writes);
5578
+ sayLockNews(cfg, lockBefore);
5579
+ for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
5580
+ for (const line of formatTranslateFailures(result.failed)) console.error(line);
5581
+ if (result.failed.length > 0) process.exitCode = 1;
5582
+ if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0 && result.failed.length === 0) console.log("[verbaly] nothing to translate ✓");
5583
+ }
5584
+ function reportProgress(progress) {
5585
+ const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
5586
+ if (progress.error) console.warn(`${head}: failed (${progress.error}), continuing`);
5587
+ else console.log(`${head}: ${counted(progress.keys, "message")}`);
5588
+ }
5589
+ // src/cli/commands/typegen.ts
5590
+ async function typegenCommand(cfg) {
5591
+ const registry = await extractProject(cfg);
5592
+ const source = shippedCatalogs(cfg, loadCatalogs(cfg), registry)[cfg.sourceLocale] ?? {};
5593
+ const written = writeDts(cfg, source);
5594
+ if (!written) {
5595
+ console.log("[verbaly] no types written: dts is false in your verbaly config");
5596
+ return;
4976
5597
  }
4977
- const close = watchTree(cfg.root, {}, (filename) => {
4978
- if (!filename) return;
4979
- const file = filename.replaceAll("\\", "/");
4980
- if (file.includes("node_modules/") || file.endsWith(".d.ts")) return;
4981
- if (catalogDir && file.startsWith(`${catalogDir}/`)) return;
4982
- if (SOURCE_FILE_RE.test(file)) schedule();
4983
- });
4984
- return () => {
4985
- clearTimeout(timer);
4986
- close();
4987
- };
5598
+ const where = relative(cfg.root, written.file).replaceAll("\\", "/");
5599
+ const how = written.changed ? "written to" : "up to date in";
5600
+ console.log(`[verbaly] types ${how} ${where} (${counted(Object.keys(source).length, "message")})`);
4988
5601
  }
4989
- // src/wrap.ts
5602
+ // src/scan/wrap.ts
4990
5603
  const WRAP_ATTRS = /* @__PURE__ */ new Set([
4991
5604
  "title",
4992
5605
  "alt",
@@ -5261,7 +5874,43 @@ function trailingWs(text) {
5261
5874
  function line(node) {
5262
5875
  return node.loc?.start?.line ?? 1;
5263
5876
  }
5264
- // src/run.ts
5877
+ // src/cli/commands/wrap.ts
5878
+ function binding(cfg, client) {
5879
+ if (cfg.host !== "next") return "in the component: `const t = useT()` from @verbaly/react";
5880
+ const onClient = "`const t = useT()` from @verbaly/next/client";
5881
+ if (client) return `"use client", so ${onClient}`;
5882
+ return `no "use client": a Server Component takes \`const t = await getT()\` from @verbaly/next/server, a client one ${onClient}`;
5883
+ }
5884
+ async function wrapCommand(cfg, values) {
5885
+ const result = await wrapProject(cfg, { write: values.write });
5886
+ if (result.wrapped.length === 0 && result.skipped.length === 0) {
5887
+ console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
5888
+ return;
5889
+ }
5890
+ const blocked = new Set(result.blocked.map((entry) => entry.file));
5891
+ const done = result.changed.filter((file) => !blocked.has(file));
5892
+ const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));
5893
+ const verb = values.write ? "wrapped" : "would wrap";
5894
+ const note = values.write ? "" : " (report only, use --write to apply)";
5895
+ let counts = `${counted(texts.length, "text")} in ${counted(done.length, "file")}`;
5896
+ const waiting = result.wrapped.length - texts.length;
5897
+ if (!values.write && waiting > 0) counts += `, and ${counted(waiting, "text")} in ${counted(blocked.size, "file")} once t is in scope`;
5898
+ console.log(`[verbaly] ${verb} ${counts}${note}`);
5899
+ for (const entry of values.write ? texts : result.wrapped) {
5900
+ const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
5901
+ console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
5902
+ }
5903
+ if (result.skipped.length > 0) {
5904
+ console.log(" needs a human:");
5905
+ for (const entry of result.skipped) console.log(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
5906
+ }
5907
+ if (result.blocked.length > 0) {
5908
+ console.log(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
5909
+ for (const entry of result.blocked) console.log(` ${entry.file} ${counted(entry.texts, "text")}, ${binding(cfg, entry.client)}`);
5910
+ console.log(" next: add t there, run verbaly wrap --write again, then verbaly extract");
5911
+ } else if (values.write && done.length > 0) console.log(" next: run verbaly extract");
5912
+ }
5913
+ // src/cli/run.ts
5265
5914
  const HELP = `verbaly · i18n compiler
5266
5915
 
5267
5916
  Usage:
@@ -5313,45 +5962,23 @@ Options:
5313
5962
  Config file: verbaly.config.{js,mjs,ts,mts,json} at root (flags win).
5314
5963
  The claude provider needs @anthropic-ai/sdk installed and ANTHROPIC_API_KEY set.
5315
5964
  `;
5965
+ const COMMANDS = {
5966
+ doctor: doctorCommand,
5967
+ extract: extractCommand,
5968
+ typegen: typegenCommand,
5969
+ migrate: migrateCommand,
5970
+ wrap: wrapCommand,
5971
+ status: statusCommand,
5972
+ check: checkCommand,
5973
+ translate: translateCommand,
5974
+ review: reviewCommand,
5975
+ export: exportCommand,
5976
+ import: importCommand,
5977
+ render: renderCommand,
5978
+ pseudo: pseudoCommand
5979
+ };
5316
5980
  async function runCli(args = process.argv.slice(2)) {
5317
- const { positionals, values } = parseArgs({
5318
- args,
5319
- allowPositionals: true,
5320
- options: {
5321
- root: { type: "string" },
5322
- dir: { type: "string" },
5323
- source: { type: "string" },
5324
- locales: { type: "string" },
5325
- prune: { type: "boolean" },
5326
- watch: { type: "boolean" },
5327
- write: { type: "boolean" },
5328
- json: { type: "boolean" },
5329
- drafts: { type: "boolean" },
5330
- outdated: { type: "boolean" },
5331
- draft: { type: "boolean" },
5332
- approve: { type: "boolean" },
5333
- reporter: { type: "string" },
5334
- model: { type: "string" },
5335
- locale: { type: "string" },
5336
- site: { type: "string" },
5337
- attribute: { type: "string" },
5338
- base: { type: "string" },
5339
- "base-url": { type: "string" },
5340
- redirect: { type: "boolean" },
5341
- sitemap: { type: "boolean" },
5342
- clean: { type: "boolean" },
5343
- "dry-run": { type: "boolean" },
5344
- plurals: { type: "boolean" },
5345
- format: { type: "string" },
5346
- out: { type: "string" },
5347
- missing: { type: "boolean" },
5348
- overwrite: { type: "boolean" },
5349
- help: {
5350
- type: "boolean",
5351
- short: "h"
5352
- }
5353
- }
5354
- });
5981
+ const { positionals, values } = parseCli(args);
5355
5982
  const command = positionals[0];
5356
5983
  if (values.help || !command) {
5357
5984
  console.log(HELP);
@@ -5359,442 +5986,20 @@ async function runCli(args = process.argv.slice(2)) {
5359
5986
  return;
5360
5987
  }
5361
5988
  if (rejectStrayFlags(command, values)) return;
5362
- if (command === "init") {
5363
- const result = await init({
5364
- root: values.root,
5365
- dir: values.dir,
5366
- sourceLocale: values.source,
5367
- locales: csv(values.locales)
5368
- });
5369
- if (result.created.length) console.log(`[verbaly] created: ${result.created.join(", ")}`);
5370
- if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(", ")}`);
5371
- for (const { from, to } of result.renamed) console.log(` wrote ${to} for ${from}, since a locale tag takes a hyphen`);
5372
- for (const locale of result.refused) console.warn(` left out "${locale}": it is not a locale tag, use one like es or pt-BR`);
5373
- if (result.found) console.log(` catalogs: ${result.found}, kept where they already are`);
5374
- if (result.host) console.log(` detected: ${result.host}`);
5375
- console.log([" next steps:", ...result.next.map((step, i) => ` ${i + 1}. ${step}`)].join("\n"));
5376
- return;
5377
- }
5989
+ if (command === "init") return initCommand(values);
5378
5990
  const cfg = await loadConfig(values.root ?? process.cwd(), {
5379
5991
  dir: values.dir,
5380
5992
  sourceLocale: values.source,
5381
5993
  locales: csv(values.locales)
5382
5994
  });
5383
- if (command === "doctor") {
5384
- const result = await doctor(cfg);
5385
- console.log(`[verbaly] doctor: ${counted(result.entries.length, "check")}`);
5386
- for (const entry of result.entries) {
5387
- const line = formatDoctorEntry(entry);
5388
- if (entry.level === "error") console.error(line);
5389
- else if (entry.level === "warn") console.warn(line);
5390
- else console.log(line);
5391
- }
5392
- if (result.ok) console.log(`[verbaly] ${formatDoctorHealth(result)} ✓`);
5393
- else {
5394
- console.error("[verbaly] doctor found problems");
5395
- process.exitCode = 1;
5396
- }
5397
- return;
5398
- }
5399
- if (command === "extract") {
5400
- const dryRun = values["dry-run"];
5401
- if (values.watch && (dryRun || values.prune)) {
5402
- console.error("[verbaly] --watch runs alone: prune is a deliberate one-shot action and dry-run writes nothing");
5403
- process.exitCode = 1;
5404
- return;
5405
- }
5406
- const reporter = values.watch ? createDevReporter(cfg.root, (line) => console.warn(` ${line}`)) : void 0;
5407
- async function runExtract() {
5408
- const result = await syncProject(cfg, {
5409
- prune: values.prune,
5410
- dryRun
5411
- });
5412
- if (result.pruneBlocked) {
5413
- const unread = result.registry.parseErrors().length;
5414
- console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
5415
- }
5416
- for (const [locale, keys] of Object.entries(result.pruned)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
5417
- const origin = result.inCode === result.messages ? "" : ` (${result.inCode} in code)`;
5418
- console.log(`[verbaly] ${counted(result.messages, "message")}${origin} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
5419
- for (const [locale, keys] of Object.entries(result.added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
5420
- const warnings = result.findings.filter((finding) => {
5421
- if (finding.kind !== "replaced" && finding.kind !== "lock") return true;
5422
- console.log(` ${formatFinding(finding, cfg.root)}`);
5423
- return false;
5424
- });
5425
- if (reporter) reporter.report("extract", warnings);
5426
- else for (const finding of warnings) console.warn(` ${formatFinding(finding, cfg.root)}`);
5427
- if (result.stateProblem) console.warn(` ${result.stateProblem}, so drafts and outdated translations were not updated`);
5428
- }
5429
- await runExtract();
5430
- if (values.watch) {
5431
- watchProject(cfg, runExtract);
5432
- console.log("[verbaly] watching for source changes (ctrl+c to stop)");
5433
- }
5434
- return;
5435
- }
5436
- if (command === "typegen") {
5437
- const registry = await extractProject(cfg);
5438
- const source = shippedCatalogs(cfg, loadCatalogs(cfg), registry)[cfg.sourceLocale] ?? {};
5439
- const written = writeDts(cfg, source);
5440
- if (!written) {
5441
- console.log("[verbaly] no types written: dts is false in your verbaly config");
5442
- return;
5443
- }
5444
- const where = relative(cfg.root, written.file).replaceAll("\\", "/");
5445
- const how = written.changed ? "written to" : "up to date in";
5446
- console.log(`[verbaly] types ${how} ${where} (${counted(Object.keys(source).length, "message")})`);
5447
- return;
5448
- }
5449
- if (command === "migrate") {
5450
- const lockBefore = stateFile(cfg);
5451
- const result = migrateCatalogs(cfg, {
5452
- write: values.write,
5453
- plurals: values.plurals
5454
- });
5455
- const from = result.detected.length ? result.detected.join(", ") : "no known i18n library";
5456
- const changes = result.braces.length + result.plurals.length;
5457
- const before = result.remembered.length ? `, ${counted(result.remembered.length, "language")} converted before` : "";
5458
- if (changes === 0 && result.skipped.length === 0) {
5459
- console.log(`[verbaly] catalogs need nothing (${from}${before}) ✓`);
5460
- return;
5461
- }
5462
- const verb = values.write ? "ported" : "would port";
5463
- const note = values.write ? "" : " (report only, use --write to apply)";
5464
- console.log(`[verbaly] ${verb} ${counted(changes, "message")} from ${from}${before}${note}`);
5465
- for (const entry of result.braces) console.log(` ${entry.locale} ${entry.key} ${entry.before} → ${entry.after}`);
5466
- for (const entry of result.plurals) console.log(` ${entry.locale} ${entry.key} ${entry.from.join(" + ")} → ${entry.after}`);
5467
- if (!values.plurals && changes > 0) console.log(" --plurals also merges _one/_other into one message with variants");
5468
- if (result.skipped.length > 0) {
5469
- console.log(" needs a human:");
5470
- for (const entry of result.skipped) console.log(` ${entry.locale} ${entry.key} ${entry.reason}`);
5471
- }
5472
- if (values.write && result.braces.length > 0) console.log(` ${STATE_FILE} remembers the converted languages, so a later run never reads them as i18next again`);
5473
- sayLockNews(cfg, lockBefore);
5474
- if (values.write) console.log(" next: run verbaly check");
5475
- return;
5476
- }
5477
- if (command === "wrap") {
5478
- const result = await wrapProject(cfg, { write: values.write });
5479
- if (result.wrapped.length === 0 && result.skipped.length === 0) {
5480
- console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
5481
- return;
5482
- }
5483
- const blocked = new Set(result.blocked.map((entry) => entry.file));
5484
- const done = result.changed.filter((file) => !blocked.has(file));
5485
- const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));
5486
- const verb = values.write ? "wrapped" : "would wrap";
5487
- const note = values.write ? "" : " (report only, use --write to apply)";
5488
- const counts = values.write ? `${counted(texts.length, "text")} in ${counted(done.length, "file")}` : `${counted(result.wrapped.length, "text")} in ${counted(result.changed.length, "file")}`;
5489
- console.log(`[verbaly] ${verb} ${counts}${note}`);
5490
- for (const entry of values.write ? texts : result.wrapped) {
5491
- const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
5492
- console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
5493
- }
5494
- if (result.skipped.length > 0) {
5495
- console.log(" needs a human:");
5496
- for (const entry of result.skipped) console.log(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
5497
- }
5498
- if (result.blocked.length > 0) {
5499
- console.log(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
5500
- for (const entry of result.blocked) {
5501
- const how = entry.client ? "\"use client\", so const t = useT()" : "no \"use client\": check which side renders it before you pick the binding";
5502
- console.log(` ${entry.file} ${counted(entry.texts, "text")}, ${how}`);
5503
- }
5504
- console.log(" next: add t there, run verbaly wrap --write again, then verbaly extract");
5505
- } else if (values.write && done.length > 0) console.log(" next: run verbaly extract");
5506
- return;
5507
- }
5508
- if (command === "status") {
5509
- const registry = await extractProject(cfg);
5510
- const { state, problem } = readState(cfg);
5511
- if (problem) console.warn(`[verbaly] ${problem}, so drafts and outdated translations are not counted`);
5512
- const result = status(cfg, loadCatalogs(cfg), registry, state.drafts, state.fingerprints);
5513
- console.log(values.json ? JSON.stringify(result) : formatStatusResult(result));
5514
- return;
5515
- }
5516
- if (command === "check") {
5517
- const reporter = values.reporter ?? "text";
5518
- if (reporter !== "text" && reporter !== "github") {
5519
- console.error(`[verbaly] unknown reporter "${values.reporter}", use text or github`);
5520
- process.exitCode = 1;
5521
- return;
5522
- }
5523
- const registry = await extractProject(cfg);
5524
- const catalogs = loadCatalogs(cfg);
5525
- const state = checkState(cfg, values.drafts === true || values.outdated === true);
5526
- const result = check(cfg, catalogs, registry, state.fingerprints);
5527
- const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};
5528
- const outdated = values.outdated ? result.outdated : [];
5529
- const gated = { outdatedFails: values.outdated === true };
5530
- if (reporter === "github") for (const line of githubCheckAnnotations(result, registry, cfg, gated)) console.error(line);
5531
- else {
5532
- const warnings = formatCheckWarnings(result, cfg.root, gated);
5533
- if (warnings) console.warn(`[verbaly] warnings (the gate still passes)\n${warnings}`);
5534
- }
5535
- 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(", ")}`)];
5536
- if (result.ok && awaiting.length === 0) {
5537
- console.log("[verbaly] all translations complete ✓");
5538
- return;
5539
- }
5540
- if (!result.ok) {
5541
- const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
5542
- const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken, ${counted(result.collisions.length, "collision")}` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
5543
- console.error(`${report}\n${checkNextSteps(result)}`);
5544
- }
5545
- if (awaiting.length > 0) {
5546
- for (const line of awaiting) console.error(line);
5547
- console.error("[verbaly] check failed: translations awaiting review (run verbaly review, then --approve what holds)");
5548
- }
5549
- process.exitCode = 1;
5550
- return;
5551
- }
5552
- if (command === "translate") {
5553
- if (!values["dry-run"]) loadState(cfg);
5554
- const registry = await extractProject(cfg);
5555
- const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
5556
- const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
5557
- locales: csv(values.locales),
5558
- batchSize: cfg.translate.batchSize,
5559
- concurrency: cfg.translate.concurrency,
5560
- retries: cfg.translate.retries,
5561
- dryRun: values["dry-run"],
5562
- origins: values["dry-run"] ? void 0 : await collectOrigins(cfg, registry),
5563
- onProgress: values["dry-run"] ? void 0 : reportProgress
5564
- });
5565
- if (values["dry-run"]) {
5566
- const entries = Object.entries(result.pending);
5567
- if (entries.length === 0) {
5568
- console.log("[verbaly] nothing to translate ✓");
5569
- return;
5570
- }
5571
- for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.length} missing: ${keys.join(", ")}`);
5572
- return;
5573
- }
5574
- const source = catalogs[cfg.sourceLocale] ?? {};
5575
- const writes = [];
5576
- for (const [locale, keys] of Object.entries(result.translated)) {
5577
- const catalog = catalogs[locale] ?? {};
5578
- const written = mergeTranslations(cfg, locale, catalog, keys);
5579
- writes.push({
5580
- locale,
5581
- draft: true,
5582
- entries: written.map((key) => ({
5583
- key,
5584
- text: catalog[key]
5585
- }))
5586
- });
5587
- console.log(` ${locale}: +${written.length} translated (draft)`);
5588
- const kept = keys.length - written.length;
5589
- if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
5590
- }
5591
- const lockBefore = stateFile(cfg);
5592
- if (writes.length > 0) recordTranslations(cfg, source, writes);
5593
- sayLockNews(cfg, lockBefore);
5594
- for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
5595
- for (const line of formatTranslateFailures(result.failed)) console.error(line);
5596
- if (result.failed.length > 0) process.exitCode = 1;
5597
- if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0 && result.failed.length === 0) console.log("[verbaly] nothing to translate ✓");
5598
- return;
5599
- }
5600
- if (command === "review") {
5601
- const registry = await extractProject(cfg);
5602
- const catalogs = loadCatalogs(cfg);
5603
- const shipped = shippedCatalogs(cfg, catalogs, registry);
5604
- const state = loadState(cfg);
5605
- const only = new Set(positionals.slice(1));
5606
- const wanted = ({ locale, key }) => (!values.locale || locale === values.locale) && (only.size === 0 || only.has(key));
5607
- const drafts = Object.entries(effectiveDrafts(state.drafts, catalogs)).flatMap(([locale, keys]) => keys.map((key) => ({
5608
- locale,
5609
- key
5610
- }))).filter(wanted);
5611
- const outdated = outdatedTranslations(cfg, shipped, state.fingerprints).filter(wanted);
5612
- if (drafts.length === 0 && outdated.length === 0) {
5613
- console.log("[verbaly] nothing awaiting review ✓");
5614
- return;
5615
- }
5616
- if (values.approve) {
5617
- for (const [locale, keys] of byLocale(drafts)) {
5618
- clearDrafts(state.drafts, locale, keys);
5619
- console.log(` ${locale}: ${keys.length} approved`);
5620
- }
5621
- acceptOutdated(cfg, shipped, state.fingerprints, outdated);
5622
- for (const [locale, keys] of byLocale(outdated)) console.log(` ${locale}: ${keys.length} kept for the new source text`);
5623
- const lockBefore = stateFile(cfg);
5624
- saveState(cfg, state);
5625
- sayLockNews(cfg, lockBefore);
5626
- const reviewed = new Set([...drafts, ...outdated].map(({ locale, key }) => `${locale}:${key}`));
5627
- console.log(`[verbaly] ${counted(reviewed.size, "translation")} marked reviewed ✓`);
5628
- return;
5629
- }
5630
- const source = shipped[cfg.sourceLocale] ?? {};
5631
- const show = (locale, keys) => {
5632
- console.log(` ${locale}:`);
5633
- for (const key of keys) {
5634
- const translated = catalogs[locale]?.[key] ?? "";
5635
- console.log(` ${key}: "${truncate(source[key] ?? "", 60)}" → "${truncate(translated, 60)}"`);
5636
- }
5637
- };
5638
- if (drafts.length > 0) {
5639
- console.log(`[verbaly] ${counted(drafts.length, "machine translation")} awaiting review (--approve to accept)`);
5640
- for (const [locale, keys] of byLocale(drafts)) show(locale, keys);
5641
- }
5642
- if (outdated.length > 0) {
5643
- console.log(`[verbaly] ${counted(outdated.length, "translation")} written for an older source text (update them, or --approve keeps them)`);
5644
- for (const [locale, keys] of byLocale(outdated)) show(locale, keys);
5645
- }
5646
- return;
5647
- }
5648
- if (command === "export") {
5649
- const format = values.format ?? "xliff";
5650
- if (![
5651
- "xliff",
5652
- "csv",
5653
- "po",
5654
- "android-xml",
5655
- "ios-strings"
5656
- ].includes(format)) {
5657
- console.error(`[verbaly] unknown format "${values.format}", use xliff, csv, po, android-xml or ios-strings`);
5658
- process.exitCode = 1;
5659
- return;
5660
- }
5661
- if (values.missing && isMobileFormat(format)) {
5662
- console.error(`[verbaly] --missing is for translator formats (xliff, csv): ${format} already skips untranslated keys so the app falls back to the source locale`);
5663
- process.exitCode = 1;
5664
- return;
5665
- }
5666
- const registry = await extractProject(cfg);
5667
- const result = exportCatalogs(cfg, shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false }), {
5668
- locales: csv(values.locales),
5669
- format,
5670
- out: values.out,
5671
- missing: values.missing,
5672
- origins: isMobileFormat(format) ? void 0 : await collectOrigins(cfg, registry)
5673
- });
5674
- if (result.files.length === 0) {
5675
- console.log("[verbaly] no target locales to export (add locales to your config)");
5676
- return;
5677
- }
5678
- const note = isMobileFormat(result.format) ? "untranslated skipped" : "untranslated";
5679
- console.log(`[verbaly] exported ${counted(result.files.length, "locale")} (${result.format}) → ${result.dir}`);
5680
- for (const file of result.files) console.log(` ${file.locale}: ${counted(file.total, "message")} (${file.untranslated} ${note}) → ${file.path}`);
5681
- return;
5682
- }
5683
- if (command === "import") {
5684
- const files = positionals.slice(1);
5685
- if (files.length === 0) {
5686
- console.error("[verbaly] import needs at least one file: verbaly import verbaly-export/es.xlf");
5687
- process.exitCode = 1;
5688
- return;
5689
- }
5690
- if (!values["dry-run"]) loadState(cfg);
5691
- const registry = await extractProject(cfg);
5692
- const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
5693
- const result = importCatalogs(cfg, catalogs, files, {
5694
- locale: values.locale,
5695
- overwrite: values.overwrite,
5696
- dryRun: values["dry-run"]
5697
- });
5698
- for (const { file, from, to } of result.mapped) console.log(` ${file}: "${from}" read as ${to}`);
5699
- for (const { file, locale, reason } of result.unmatched) {
5700
- if (reason === "undeclared") {
5701
- console.warn(` ${file}: "${locale}" is not one of this project's locales (${cfg.locales.join(", ")}), so nothing was imported from it`);
5702
- console.warn(` fix: add ${locale} to locales in your verbaly config, or pass --locale with one of them`);
5703
- } else {
5704
- console.warn(` ${file}: "${locale}" is not a locale tag, so nothing was imported from it`);
5705
- console.warn(" fix: pass --locale with the tag it stands for, like pt-BR");
5706
- }
5707
- process.exitCode = 1;
5708
- }
5709
- const writes = [];
5710
- for (const [locale, keys] of Object.entries(result.imported)) {
5711
- if (!values["dry-run"]) {
5712
- const catalog = catalogs[locale] ?? {};
5713
- writeCatalog(cfg, locale, catalog);
5714
- const seen = result.sources[locale] ?? {};
5715
- const entries = keys.map((key) => ({
5716
- key,
5717
- text: catalog[key],
5718
- source: seen[key]
5719
- }));
5720
- writes.push({
5721
- locale,
5722
- entries,
5723
- draft: values.draft === true
5724
- });
5725
- }
5726
- const verb = values["dry-run"] ? "would import" : "imported";
5727
- console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? " (draft)" : ""}`);
5728
- }
5729
- const lockBefore = stateFile(cfg);
5730
- if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
5731
- sayLockNews(cfg, lockBefore);
5732
- for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
5733
- for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
5734
- 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(", ")}`);
5735
- if (Object.keys(result.imported).length === 0 && result.unmatched.length === 0) console.log("[verbaly] nothing to import ✓");
5736
- return;
5737
- }
5738
- if (command === "render") {
5739
- const result = await renderSite(cfg, {
5740
- site: values.site,
5741
- locales: csv(values.locales),
5742
- attribute: values.attribute,
5743
- base: values.base,
5744
- baseUrl: values["base-url"],
5745
- sitemap: values.sitemap,
5746
- redirect: values.redirect,
5747
- clean: values.clean
5748
- });
5749
- console.log(`[verbaly] ${counted(result.files, "page")} × ${counted(result.locales.length, "locale")} (${result.locales.join(", ")})`);
5750
- for (const line of formatRenderWarnings(result, cfg.sourceLocale)) console.warn(line);
5751
- return;
5752
- }
5753
- if (command === "pseudo") {
5754
- const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg), { newKeys: false });
5755
- const locale = values.locale ?? "en-XA";
5756
- const keys = pseudoCatalogs(cfg, catalogs, locale);
5757
- writeCatalog(cfg, locale, catalogs[locale] ?? {});
5758
- console.log(`[verbaly] ${counted(keys.length, "message")} pseudo-localized → ${locale}`);
5759
- return;
5760
- }
5995
+ if (Object.hasOwn(COMMANDS, command)) return COMMANDS[command](cfg, values, positionals);
5761
5996
  console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
5762
5997
  process.exitCode = 1;
5763
5998
  }
5764
- function csv(value) {
5765
- return value?.split(",").map((item) => item.trim()).filter(Boolean);
5766
- }
5767
- function reportProgress(progress) {
5768
- const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
5769
- if (progress.error) console.warn(`${head}: failed (${progress.error}), continuing`);
5770
- else console.log(`${head}: ${counted(progress.keys, "message")}`);
5771
- }
5772
5999
  function formatCliError(error) {
5773
6000
  const message = error instanceof Error ? error.message : String(error);
5774
6001
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
5775
6002
  }
5776
- function checkState(cfg, gating) {
5777
- if (gating) return loadState(cfg);
5778
- const { state, problem } = readState(cfg);
5779
- if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);
5780
- return state;
5781
- }
5782
- function sayLockNews(cfg, before) {
5783
- const news = lockNews(cfg, before);
5784
- if (news) console.log(` ${formatFinding({
5785
- kind: "lock",
5786
- ...news
5787
- }, cfg.root)}`);
5788
- }
5789
- function byLocale(entries) {
5790
- const out = /* @__PURE__ */ new Map();
5791
- for (const { locale, key } of entries) {
5792
- const keys = out.get(locale);
5793
- if (keys) keys.push(key);
5794
- else out.set(locale, [key]);
5795
- }
5796
- return [...out];
5797
- }
5798
6003
  const COMMON_FLAGS = /* @__PURE__ */ new Set([
5799
6004
  "root",
5800
6005
  "dir",
@@ -5844,13 +6049,12 @@ const COMMAND_FLAGS = {
5844
6049
  ]
5845
6050
  };
5846
6051
  function rejectStrayFlags(command, values) {
5847
- const own = COMMAND_FLAGS[command];
5848
- if (!own) return false;
5849
- const allowed = /* @__PURE__ */ new Set([...COMMON_FLAGS, ...own]);
6052
+ if (!Object.hasOwn(COMMAND_FLAGS, command)) return false;
6053
+ const allowed = /* @__PURE__ */ new Set([...COMMON_FLAGS, ...COMMAND_FLAGS[command]]);
5850
6054
  const stray = Object.keys(values).filter((k) => values[k] !== void 0 && !allowed.has(k));
5851
6055
  if (stray.length === 0) return false;
5852
6056
  for (const flag of stray) console.error(`[verbaly] --${flag} is not a "${command}" flag${flag === "locale" ? " (did you mean --locales?)" : ""}`);
5853
6057
  process.exitCode = 1;
5854
6058
  return true;
5855
6059
  }
5856
- export { collectOrigins as $, formatCheckWarnings as A, recordTranslations as B, loadVirtualModule as C, transformCode as D, transformSource as E, effectiveDrafts as F, formatCollision as G, updateState as H, loadState as I, generateLocaleModule as J, formatFinding as K, markDrafts as L, syncProject as M, STATE_FILE as N, check as O, clearDrafts as P, validatePair as Q, outdatedTranslations as R, isTransformTarget as S, runBuildGate as T, collisionEntries as U, saveState as V, createDevReporter as W, writeDts as X, generateRuntimeModule as Y, validateMessage as Z, reportOutsideInclude as _, parseCatalog as _t, formatRenderWarnings as a, APP_ID as at, SOURCE_FILE_RE as b, mergeTranslations as c, clientCatalogs as ct, writeDrafts as d, loadConfig as dt, extractProject as et, doctor as f, resolveConfig as ft, status as g, needsRelative as gt, formatStatusResult as h, needsIcu as ht, watchTree as i, stableKey as it, init as j, formatCheckResult as k, resolveProvider as l, counted as lt, formatDoctorHealth as m, loadCatalogs as mt, runCli as n, shippedCatalogs as nt, renderSite as o, LOCALE_IMPORT as ot, formatDoctorEntry as p, targetLocales as pt, generateDts as q, wrapProject as r, syncCatalogs as rt, formatTranslateFailures as s, MessageRegistry as st, formatCliError as t, pruneCatalogs as tt, translateCatalogs as u, isModuleNotFound as ut, LOCALE_MODULE_PREFIX as v, readCatalog as vt, resolveVirtualId as w, createSourceFilter as x, RESOLVED_VIRTUAL_ID as y, writeCatalog as yt, readState as z };
6060
+ export { validatePair as $, check as A, readState as B, isTransformTarget as C, transformSource as D, runBuildGate as E, clearDrafts as F, createDevReporter as G, saveState as H, effectiveDrafts as I, generateDts as J, formatCollision as K, loadState as L, formatCheckWarnings as M, syncProject as N, writeBuildTypes as O, STATE_FILE as P, validateMessage as Q, markDrafts as R, createSourceFilter as S, resolveVirtualId as T, updateState as U, recordTranslations as V, collisionEntries as W, generateRuntimeModule as X, generateLocaleModule as Y, writeDts as Z, status as _, isModuleNotFound as _t, renderSite as a, stableKey as at, RESOLVED_VIRTUAL_ID as b, targetLocales as bt, formatTranslateFailures as c, MessageRegistry as ct, translateCatalogs as d, loadCatalogs as dt, collectOrigins as et, writeDrafts as f, needsIcu as ft, formatStatusResult as g, writeCatalog as gt, formatDoctorHealth as h, readCatalog as ht, formatRenderWarnings as i, syncCatalogs as it, formatCheckResult as j, transformCode as k, mergeTranslations as l, clientCatalogs as lt, formatDoctorEntry as m, parseCatalog as mt, runCli as n, pruneCatalogs as nt, init as o, APP_ID as ot, doctor as p, needsRelative as pt, formatFinding as q, wrapProject as r, shippedCatalogs as rt, watchTree as s, LOCALE_IMPORT as st, formatCliError as t, extractProject as tt, resolveProvider as u, counted as ut, reportOutsideInclude as v, loadConfig as vt, loadVirtualModule as w, SOURCE_FILE_RE as x, LOCALE_MODULE_PREFIX as y, resolveConfig as yt, outdatedTranslations as z };