@verbaly/compiler 0.81.0 → 0.83.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.
@@ -3,13 +3,35 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSy
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";
6
+ import { readFile } from "node:fs/promises";
6
7
  import { glob } from "tinyglobby";
7
8
  import { parse as parse$1 } from "@babel/parser";
8
9
  import { createHash } from "node:crypto";
9
10
  import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
10
11
  import picomatch from "picomatch";
11
12
  import MagicString from "magic-string";
12
- import { parseArgs } from "node:util";
13
+ import { parseArgs as parseArgs$1 } from "node:util";
14
+ // src/util/text.ts
15
+ function counted(count, noun, many = `${noun}s`) {
16
+ return `${count} ${count === 1 ? noun : many}`;
17
+ }
18
+ function truncate(text, max) {
19
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
20
+ }
21
+ function trimTrailingSlashes(text) {
22
+ let end = text.length;
23
+ while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
24
+ return text.slice(0, end);
25
+ }
26
+ function singleQuoted(text) {
27
+ return `'${text.replace(/[\\']/g, "\\$&")}'`;
28
+ }
29
+ function byCodeUnit(a, b) {
30
+ return a < b ? -1 : a > b ? 1 : 0;
31
+ }
32
+ function stripBom(text) {
33
+ return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
34
+ }
13
35
  // src/config/host.ts
14
36
  const HOSTS = [
15
37
  {
@@ -95,19 +117,21 @@ const HOSTS = [
95
117
  }
96
118
  ];
97
119
  const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
98
- function readDependencies(root) {
99
- const path = join(root, "package.json");
100
- if (!existsSync(path)) return {};
120
+ function readManifest(root) {
101
121
  try {
102
- const pkg = JSON.parse(readFileSync(path, "utf8"));
103
- return {
104
- ...pkg.dependencies,
105
- ...pkg.devDependencies
106
- };
122
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
123
+ return typeof manifest === "object" && manifest !== null ? manifest : void 0;
107
124
  } catch {
108
- return {};
125
+ return;
109
126
  }
110
127
  }
128
+ function readDependencies(root) {
129
+ const manifest = readManifest(root);
130
+ return {
131
+ ...manifest?.dependencies,
132
+ ...manifest?.devDependencies
133
+ };
134
+ }
111
135
  const ADAPTERS = [
112
136
  ["@verbaly/react", [
113
137
  "react",
@@ -153,11 +177,9 @@ const LOCKFILES = [
153
177
  ["package-lock.json", "npm"]
154
178
  ];
155
179
  function packageManager(root) {
156
- try {
157
- const declared = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).packageManager;
158
- const name = typeof declared === "string" ? declared.split("@")[0] : void 0;
159
- if (name === "pnpm" || name === "npm" || name === "yarn" || name === "bun") return name;
160
- } catch {}
180
+ const declared = readManifest(root)?.packageManager;
181
+ const name = typeof declared === "string" ? declared.split("@")[0] : void 0;
182
+ if (name === "pnpm" || name === "npm" || name === "yarn" || name === "bun") return name;
161
183
  for (let dir = root;; dir = dirname(dir)) {
162
184
  const found = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
163
185
  if (found) return found[1];
@@ -200,6 +222,7 @@ function warnParseError(file, message) {
200
222
  }
201
223
  // src/config/config.ts
202
224
  const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}";
225
+ const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
203
226
  const PSEUDO_LOCALE = "en-XA";
204
227
  function resolveConfig(config = {}) {
205
228
  const root = resolve(config.root ?? process.cwd());
@@ -207,7 +230,9 @@ function resolveConfig(config = {}) {
207
230
  const sourceLocale = config.sourceLocale ?? "en";
208
231
  const host = detectHost(root)?.name;
209
232
  const localesDeclared = config.locales !== void 0;
210
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
233
+ const written = config.locales;
234
+ const listed = typeof written === "string" ? [written] : config.locales ?? [];
235
+ const locales = /* @__PURE__ */ new Set([sourceLocale, ...listed]);
211
236
  if (!localesDeclared && existsSync(dir)) {
212
237
  for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
213
238
  }
@@ -241,27 +266,19 @@ function findConfigFile(root) {
241
266
  return CONFIG_FILES.find((name) => existsSync(join(root, name)));
242
267
  }
243
268
  async function loadConfigFile(root) {
244
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
245
- const path = join(root, name);
246
- if (existsSync(path)) {
247
- const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
248
- const cache = createRequire(import.meta.url).cache;
249
- delete cache[realpathSync(path)];
250
- delete cache[resolve(path)];
251
- return (await import(url)).default ?? {};
252
- }
253
- }
254
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
255
- const path = join(root, name);
256
- if (existsSync(path)) return loadTsConfig(path);
257
- }
258
- const jsonPath = join(root, "verbaly.config.json");
259
- if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
260
- return {};
269
+ const name = findConfigFile(root);
270
+ if (!name) return {};
271
+ const path = join(root, name);
272
+ if (name.endsWith(".json")) return readJsonConfig(path);
273
+ if (name.endsWith("ts")) return loadTsConfig(path);
274
+ const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
275
+ const cache = createRequire(import.meta.url).cache;
276
+ delete cache[realpathSync(path)];
277
+ delete cache[resolve(path)];
278
+ return (await import(url)).default ?? {};
261
279
  }
262
280
  function readJsonConfig(path) {
263
- const content = readFileSync(path, "utf8");
264
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
281
+ const body = stripBom(readFileSync(path, "utf8"));
265
282
  try {
266
283
  return JSON.parse(body);
267
284
  } catch (error) {
@@ -378,16 +395,19 @@ function parseCatalog(content) {
378
395
  return tree === void 0 ? void 0 : flatten(tree);
379
396
  }
380
397
  function parseTree(content) {
381
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
398
+ const body = stripBom(content);
382
399
  try {
383
400
  return JSON.parse(body);
384
401
  } catch {
385
402
  return;
386
403
  }
387
404
  }
388
- function isTree(value) {
405
+ function isRecord(value) {
389
406
  return typeof value === "object" && value !== null && !Array.isArray(value);
390
407
  }
408
+ function isTree(value) {
409
+ return isRecord(value);
410
+ }
391
411
  function loadCatalogs(cfg) {
392
412
  const catalogs = emptyCatalog();
393
413
  for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
@@ -399,10 +419,19 @@ function isNested(tree) {
399
419
  function group() {
400
420
  return Object.create(null);
401
421
  }
402
- function nest(catalog) {
422
+ function pathsOf(tree, prefix = [], out = /* @__PURE__ */ new Map()) {
423
+ for (const [name, value] of Object.entries(tree)) {
424
+ const path = [...prefix, name];
425
+ if (typeof value === "string") out.set(path.join("."), path);
426
+ else if (isTree(value)) pathsOf(value, path, out);
427
+ }
428
+ return out;
429
+ }
430
+ function nest(catalog, shape) {
403
431
  const tree = group();
404
- for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
405
- const parts = key.split(".");
432
+ const written = shape ? pathsOf(shape) : void 0;
433
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => byCodeUnit(a, b))) {
434
+ const parts = written?.get(key) ?? key.split(".");
406
435
  const leaf = parts[parts.length - 1];
407
436
  let node = parts.length > 1 ? tree : void 0;
408
437
  for (let i = 0; node && i < parts.length - 1; i++) {
@@ -445,8 +474,8 @@ function orderLike(tree, previous) {
445
474
  for (const key of Object.keys(tree).sort()) if (!Object.hasOwn(previous, key)) take(key);
446
475
  return out;
447
476
  }
448
- function serializeCatalog(catalog, nested = false, previous) {
449
- const tree = nested ? nest(catalog) : catalog;
477
+ function serializeCatalog(catalog, nested = false, previous, shape = previous) {
478
+ const tree = nested ? nest(catalog, shape) : catalog;
450
479
  return JSON.stringify(previous ? orderLike(tree, previous) : sortTree(tree), null, 2) + "\n";
451
480
  }
452
481
  function writeCatalog(cfg, locale, catalog) {
@@ -459,17 +488,20 @@ function writeCatalog(cfg, locale, catalog) {
459
488
  }
460
489
  const parsed = existing === void 0 ? void 0 : parseTree(existing);
461
490
  const previous = isTree(parsed) ? parsed : void 0;
462
- const serialized = withLineEndings(serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous), existing);
491
+ const shape = shapeFor(cfg, locale, existing, previous);
492
+ const serialized = withLineEndings(serializeCatalog(catalog, shape !== void 0 && isNested(shape), previous, shape), existing);
463
493
  if (existing === serialized) return serialized;
464
494
  writeFileSync(path, serialized);
465
495
  return serialized;
466
496
  }
467
- function wantsNesting(cfg, locale, existing, previous) {
468
- if (existing !== void 0) return previous !== void 0 && isNested(previous);
469
- if (locale === cfg.sourceLocale) return false;
470
- return isNested(readTree(cfg, cfg.sourceLocale));
497
+ function shapeFor(cfg, locale, existing, previous) {
498
+ if (existing !== void 0) return previous;
499
+ return locale === cfg.sourceLocale ? void 0 : readTree(cfg, cfg.sourceLocale);
471
500
  }
472
501
  const ICU_ARG = /(^|[^{])\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
502
+ function isIcu(message) {
503
+ return ICU_ARG.test(message);
504
+ }
473
505
  function needsIcu(catalogs) {
474
506
  return someMessage(catalogs, ICU_ARG);
475
507
  }
@@ -486,21 +518,6 @@ function someLeaf(tree, pattern) {
486
518
  } else if (isTree(value) && someLeaf(value, pattern)) return true;
487
519
  return false;
488
520
  }
489
- // src/util/text.ts
490
- function counted(count, noun, many = `${noun}s`) {
491
- return `${count} ${count === 1 ? noun : many}`;
492
- }
493
- function truncate(text, max) {
494
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
495
- }
496
- function trimTrailingSlashes(text) {
497
- let end = text.length;
498
- while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
499
- return text.slice(0, end);
500
- }
501
- function byCodeUnit(a, b) {
502
- return a < b ? -1 : a > b ? 1 : 0;
503
- }
504
521
  // src/emit/bundle.ts
505
522
  function isExcluded(key, prefixes) {
506
523
  return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
@@ -665,13 +682,21 @@ function analyzeScript(code, file, options = {}) {
665
682
  if (isAppModule(source)) appImported = true;
666
683
  else if (ADAPTER_SOURCE.test(source)) adapterImport ??= node.start;
667
684
  };
668
- walk$1(ast.program, (node) => {
669
- if (node.type === "ImportDeclaration") {
670
- collectStrayImports(node, file, strayImports);
671
- bindings.addImport(node);
672
- noteLoad(node);
673
- } else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") noteLoad(node);
674
- else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
685
+ for (const node of ast.program.body) if (node.type === "ImportDeclaration") {
686
+ collectStrayImports(node, file, strayImports);
687
+ bindings.addImport(node);
688
+ noteLoad(node);
689
+ } else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") noteLoad(node);
690
+ const ownTrans = !bindings.other(TRANS);
691
+ const program = ast.program;
692
+ const functions = [];
693
+ const scopeOf = (node) => {
694
+ for (let i = functions.length - 1; i >= 0; i--) if (node.start >= functions[i].start && node.end <= functions[i].end) return functions[i];
695
+ return program;
696
+ };
697
+ walk$1(program, (node) => {
698
+ if (FUNCTIONS.has(node.type)) functions.push(node);
699
+ if (node.type === "VariableDeclarator") bindings.addDeclarator(node, scopeOf(node));
675
700
  else if (node.type === "TaggedTemplateExpression") {
676
701
  const tag = node.tag;
677
702
  const explicit = explicitId(tag, names);
@@ -717,8 +742,13 @@ function analyzeScript(code, file, options = {}) {
717
742
  key,
718
743
  file
719
744
  });
720
- } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
745
+ } else if (ownTrans && node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
746
+ });
747
+ const kept = tagged.filter((entry) => {
748
+ const name = code.slice(entry.tagStart, entry.tagEnd);
749
+ return entry.jsx || !names.has(name) || !bindings.foreign(name, entry.tagStart);
721
750
  });
751
+ if (kept.length < tagged.length) tagged.splice(0, tagged.length, ...kept);
722
752
  const renamed = bindings.renamed(options.renamed);
723
753
  const missed = [];
724
754
  for (const candidate of candidates) {
@@ -766,11 +796,21 @@ function loadsAtRuntime(node) {
766
796
  return specifiers.some((spec) => spec.importKind !== "type" && spec.exportKind !== "type");
767
797
  }
768
798
  function lineOf(node) {
769
- return node.loc?.start.line ?? 1;
799
+ return node.loc?.start?.line ?? 1;
770
800
  }
801
+ const OTHER_I18N = /^(?:react-i18next|next-i18next|next-translate|ttag|@lingui\/[\w-]+)(?:\/.*)?$/;
802
+ const TRANS = "Trans";
771
803
  const VERBALY_SOURCE = /^(?:verbaly|@verbaly\/[\w-]+(?:\/[\w-]+)*)$/;
772
804
  const T_FACTORIES = /* @__PURE__ */ new Map([["useT", "call"], ["getT", "await"]]);
773
805
  const INSTANCE_FACTORIES = /* @__PURE__ */ new Set(["useVerbaly", "getVerbaly"]);
806
+ const FUNCTIONS = /* @__PURE__ */ new Set([
807
+ "FunctionDeclaration",
808
+ "FunctionExpression",
809
+ "ArrowFunctionExpression",
810
+ "ObjectMethod",
811
+ "ClassMethod",
812
+ "ClassPrivateMethod"
813
+ ]);
774
814
  var Bindings = class {
775
815
  names;
776
816
  imports = /* @__PURE__ */ new Map();
@@ -794,14 +834,15 @@ var Bindings = class {
794
834
  if (isAppModule(source) && imported === "t") this.direct.add(local);
795
835
  }
796
836
  }
797
- addDeclarator(node) {
837
+ addDeclarator(node, scope) {
798
838
  const id = node.id;
799
839
  const init = node.init;
800
840
  if (!init) return;
801
841
  if (id.type === "Identifier") {
802
842
  this.declared.push({
803
843
  name: id.name,
804
- init
844
+ init,
845
+ scope
805
846
  });
806
847
  return;
807
848
  }
@@ -813,10 +854,27 @@ var Bindings = class {
813
854
  const name = identifierName(value.type === "AssignmentPattern" ? value.left : value);
814
855
  if (name) this.destructured.push({
815
856
  name,
816
- init
857
+ init,
858
+ scope
817
859
  });
818
860
  }
819
861
  }
862
+ other(local) {
863
+ return OTHER_I18N.test(this.imports.get(local)?.source ?? "");
864
+ }
865
+ foreign(name, at) {
866
+ let theirs = this.other(name);
867
+ let reach = 1e400;
868
+ for (const { name: bound, init, scope } of [...this.declared, ...this.destructured]) {
869
+ if (bound !== name || at < scope.start || at >= scope.end) continue;
870
+ if (scope.end - scope.start >= reach) continue;
871
+ reach = scope.end - scope.start;
872
+ const inner = init.type === "AwaitExpression" ? init.argument : init;
873
+ const read = inner.type === "CallExpression" ? inner.callee : inner;
874
+ theirs = this.other(identifierName(read));
875
+ }
876
+ return theirs;
877
+ }
820
878
  renamed(seed = []) {
821
879
  const out = new Set(seed);
822
880
  const add = (name) => {
@@ -866,19 +924,25 @@ function renamedTag(tag, renamed) {
866
924
  if (renamed.size === 0) return void 0;
867
925
  const name = identifierName(tag);
868
926
  if (renamed.has(name)) return name;
927
+ const call = idCall(tag);
928
+ if (!call) return void 0;
929
+ const object = identifierName(call.object);
930
+ return renamed.has(object) ? object : void 0;
931
+ }
932
+ function idCall(tag) {
869
933
  if (tag.type !== "CallExpression") return void 0;
870
934
  const callee = tag.callee;
871
935
  if (callee.type !== "MemberExpression" || callee.computed) return void 0;
872
936
  if (identifierName(callee.property) !== "id") return void 0;
873
- const object = identifierName(callee.object);
874
- return renamed.has(object) ? object : void 0;
937
+ const args = tag.arguments;
938
+ return {
939
+ object: callee.object,
940
+ key: args.length === 1 ? staticString(args[0]) : void 0
941
+ };
875
942
  }
876
943
  function missedKey(code, node, names) {
877
944
  const tag = node.tag;
878
- if (tag.type === "CallExpression") {
879
- const args = tag.arguments;
880
- return args.length === 1 ? staticString(args[0]) : void 0;
881
- }
945
+ if (tag.type === "CallExpression") return idCall(tag)?.key;
882
946
  const message = buildMessage(code, node.quasi, names);
883
947
  return message ? stableKey(message.text) : void 0;
884
948
  }
@@ -902,10 +966,9 @@ function staticString(node) {
902
966
  if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
903
967
  if (node.type === "JSXExpressionContainer") return staticString(node.expression);
904
968
  }
905
- const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
906
969
  function collectStrayImports(node, file, out) {
907
970
  const source = node.source;
908
- if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
971
+ if (typeof source.value !== "string" || !VERBALY_SOURCE.test(source.value)) return;
909
972
  for (const spec of node.specifiers) {
910
973
  if (spec.type !== "ImportSpecifier") continue;
911
974
  const imported = spec.imported;
@@ -921,7 +984,7 @@ function collectStrayImports(node, file, out) {
921
984
  function handleTrans(code, node, file, tagged, usedKeys, names) {
922
985
  const opening = node.openingElement;
923
986
  const nameNode = opening.name;
924
- if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
987
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name !== TRANS) return;
925
988
  const attrs = opening.attributes;
926
989
  const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
927
990
  const children = node.children;
@@ -964,20 +1027,12 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
964
1027
  push(stableKey(built.text), built);
965
1028
  }
966
1029
  function explicitId(tag, names) {
967
- if (tag.type !== "CallExpression") return void 0;
968
- const callee = tag.callee;
969
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
970
- const prop = callee.property;
971
- if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
972
- const obj = callee.object;
973
- if (!isTReference(obj, names)) return void 0;
974
- const args = tag.arguments;
975
- const key = args.length === 1 ? staticString(args[0]) : void 0;
976
- if (key === void 0) return void 0;
1030
+ const call = idCall(tag);
1031
+ if (!call || !isTReference(call.object, names) || call.key === void 0) return void 0;
977
1032
  return {
978
- key,
979
- refStart: obj.start,
980
- refEnd: obj.end
1033
+ key: call.key,
1034
+ refStart: call.object.start,
1035
+ refEnd: call.object.end
981
1036
  };
982
1037
  }
983
1038
  function buildTransMessage(code, children, names) {
@@ -1431,8 +1486,26 @@ function stringEnd(code, start) {
1431
1486
  else i += 1;
1432
1487
  return code.length;
1433
1488
  }
1489
+ // src/util/path.ts
1490
+ function slashed(path) {
1491
+ return path.replaceAll("\\", "/");
1492
+ }
1493
+ function relativePath(root, file) {
1494
+ return slashed(relative(root, file));
1495
+ }
1434
1496
  // src/scan/extract.ts
1435
1497
  const kept = /* @__PURE__ */ new WeakMap();
1498
+ async function readSources(files, each, platform = process.platform) {
1499
+ if (platform !== "win32") {
1500
+ for (const file of files) each(file, readFileSync(file, "utf8"));
1501
+ return;
1502
+ }
1503
+ for (let at = 0; at < files.length; at += 64) {
1504
+ const window = files.slice(at, at + 64);
1505
+ const read = await Promise.all(window.map(async (file) => [file, await readFile(file, "utf8")]));
1506
+ for (const [file, code] of read) each(file, code);
1507
+ }
1508
+ }
1436
1509
  async function extractProject(cfg, options = {}) {
1437
1510
  const files = await glob(cfg.include, {
1438
1511
  cwd: cfg.root,
@@ -1441,31 +1514,31 @@ async function extractProject(cfg, options = {}) {
1441
1514
  });
1442
1515
  const registry = new MessageRegistry();
1443
1516
  const read = options.keepSource ? /* @__PURE__ */ new Map() : null;
1444
- for (const file of files.sort()) {
1445
- const code = readFileSync(file, "utf8");
1517
+ await readSources(files.sort(), (file, code) => {
1446
1518
  const analysis = analyzeFile(code, file);
1447
1519
  registry.update(file, analysis);
1448
- read?.set(file.replaceAll("\\", "/"), {
1520
+ read?.set(slashed(file), {
1449
1521
  code,
1450
1522
  analysis
1451
1523
  });
1452
- }
1524
+ });
1453
1525
  if (read) kept.set(registry, read);
1454
1526
  return registry;
1455
1527
  }
1456
1528
  function scannedAnalysis(scan, file, code) {
1457
1529
  const read = kept.get(scan);
1458
- const key = file.replaceAll("\\", "/");
1530
+ const key = slashed(file);
1459
1531
  const entry = read?.get(key);
1460
1532
  read?.delete(key);
1461
1533
  return entry?.code === code ? entry.analysis : void 0;
1462
1534
  }
1463
1535
  async function collectOrigins(cfg, reuse) {
1464
1536
  const registry = reuse ?? await extractProject(cfg);
1465
- const origins = Object.create(null);
1466
- for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
1537
+ const origins = emptyCatalog();
1538
+ for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relativePath(cfg.root, file));
1467
1539
  return origins;
1468
1540
  }
1541
+ // src/scan/sync.ts
1469
1542
  function syncCatalogs(cfg, catalogs, registry) {
1470
1543
  const added = emptyCatalog();
1471
1544
  const replaced = [];
@@ -1526,12 +1599,14 @@ function read(message) {
1526
1599
  return tree;
1527
1600
  }
1528
1601
  function gatePass(run) {
1529
- reading = /* @__PURE__ */ new Map();
1602
+ const outer = reading;
1603
+ const pass = /* @__PURE__ */ new Map();
1604
+ reading = pass;
1530
1605
  try {
1531
1606
  return run();
1532
1607
  } finally {
1533
- remembered = reading;
1534
- reading = void 0;
1608
+ remembered = pass;
1609
+ reading = outer;
1535
1610
  }
1536
1611
  }
1537
1612
  const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
@@ -1724,6 +1799,13 @@ function reachableCategories(locale, ordinal) {
1724
1799
  reachable.set(cacheKey, out);
1725
1800
  return out;
1726
1801
  }
1802
+ function structureMatches(source, translated) {
1803
+ try {
1804
+ return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
1805
+ } catch {
1806
+ return false;
1807
+ }
1808
+ }
1727
1809
  // src/emit/params.ts
1728
1810
  const NUMBER_FORMATS = /* @__PURE__ */ new Set([
1729
1811
  "number",
@@ -1748,7 +1830,7 @@ function visit(nodes, out) {
1748
1830
  else if (key !== "other") types.add("string");
1749
1831
  visit(body, out);
1750
1832
  }
1751
- if (types.size === 0) types.add("string");
1833
+ if (types.size === 0) types.add("number").add("string");
1752
1834
  } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
1753
1835
  else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
1754
1836
  else types.add("unknown");
@@ -1803,7 +1885,7 @@ function formatting(text) {
1803
1885
  function typesIncluded(root, file) {
1804
1886
  const read = readTsconfig(root);
1805
1887
  if (typeof read === "string") return read;
1806
- const entry = relative(root, file).replaceAll("\\", "/");
1888
+ const entry = relativePath(root, file);
1807
1889
  const { include, files } = read.json;
1808
1890
  if (covered(include, entry) || covered(files, entry)) return "present";
1809
1891
  return "missing";
@@ -1811,7 +1893,7 @@ function typesIncluded(root, file) {
1811
1893
  function includeTypes(root, file) {
1812
1894
  const read = readTsconfig(root);
1813
1895
  if (typeof read === "string") return read;
1814
- const entry = relative(root, file).replaceAll("\\", "/");
1896
+ const entry = relativePath(root, file);
1815
1897
  const { include, files } = read.json;
1816
1898
  if (covered(include, entry) || covered(files, entry)) return "present";
1817
1899
  const options = { formattingOptions: formatting(read.text) };
@@ -1848,7 +1930,7 @@ function generateRuntimeModule(cfg, options = {}) {
1848
1930
  const importPath = options.localeImport ?? ((locale) => "@verbaly/app/locale/" + locale);
1849
1931
  const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
1850
1932
  const src = JSON.stringify(cfg.sourceLocale);
1851
- const loaders = others.map((locale) => ` ${loaderKey(locale)}: () => import('${importPath(locale)}'),`).join("\n");
1933
+ const loaders = others.map((locale) => ` ${loaderKey(locale)}: () => import(${singleQuoted(importPath(locale))}),`).join("\n");
1852
1934
  const icu = options.icu ? ",\n parseIcu" : "";
1853
1935
  const rel = options.relative ? ",\n relativeFormatter" : "";
1854
1936
  const slice = options.inlineCatalog ? ",\n inlineMessages" : "";
@@ -1860,7 +1942,7 @@ function generateRuntimeModule(cfg, options = {}) {
1860
1942
  persistLocale,
1861
1943
  switchLocale as runSwitch${icu}${rel}${slice},
1862
1944
  } from 'verbaly';
1863
- import source from '${importPath(cfg.sourceLocale)}';
1945
+ import source from ${singleQuoted(importPath(cfg.sourceLocale))};
1864
1946
 
1865
1947
  export const sourceLocale = ${src};
1866
1948
  export const locales = ${JSON.stringify(cfg.locales)};
@@ -2088,7 +2170,7 @@ function writeDts(cfg, catalog, file) {
2088
2170
  const ignore = join(cfg.root, ".verbaly", ".gitignore");
2089
2171
  if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
2090
2172
  const state = includeTypes(cfg.root, target);
2091
- const entry = relative(cfg.root, target).replaceAll("\\", "/");
2173
+ const entry = relativePath(cfg.root, target);
2092
2174
  if (state === "added") warnOnce(`added "${entry}" to the include of tsconfig.json, so TypeScript reads the types`);
2093
2175
  else if (state === "unreadable") warnOnce(`tsconfig.json could not be read, so add "${entry}" to its include yourself`);
2094
2176
  }
@@ -2108,130 +2190,9 @@ function removeRootDts(cfg, target) {
2108
2190
  }
2109
2191
  if (head !== "// generated by verbaly: do not edit") return;
2110
2192
  rmSync(old);
2111
- warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
2112
- }
2113
- // src/gate/findings.ts
2114
- function siteOf(msg) {
2115
- return {
2116
- file: msg.file,
2117
- line: msg.line,
2118
- message: msg.message
2119
- };
2120
- }
2121
- function collisionEntries(registry) {
2122
- return registry.collisions().map(({ key, kept, dropped }) => ({
2123
- key,
2124
- sites: [kept, ...dropped].map(siteOf)
2125
- }));
2126
- }
2127
- function scanFindings(cfg, registry, replaced = []) {
2128
- const messages = registry.messages();
2129
- const out = [];
2130
- for (const { key, before } of replaced) {
2131
- const msg = messages.get(key);
2132
- if (msg) out.push({
2133
- kind: "replaced",
2134
- locale: cfg.sourceLocale,
2135
- key,
2136
- before,
2137
- site: siteOf(msg)
2138
- });
2139
- }
2140
- for (const entry of collisionEntries(registry)) out.push({
2141
- kind: "collision",
2142
- ...entry
2143
- });
2144
- for (const { name, file, line } of registry.missed()) out.push({
2145
- kind: "renamed",
2146
- name,
2147
- file,
2148
- line
2149
- });
2150
- for (const msg of messages.values()) {
2151
- const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
2152
- if (params.length > 0) out.push({
2153
- kind: "positional",
2154
- params,
2155
- site: siteOf(msg)
2156
- });
2157
- const slice = escapedSyntax(msg.message);
2158
- if (slice) out.push({
2159
- kind: "escaped",
2160
- slice,
2161
- site: siteOf(msg)
2162
- });
2163
- }
2164
- for (const { file, message } of registry.parseErrors()) out.push({
2165
- kind: "unparsed",
2166
- file,
2167
- message
2168
- });
2169
- return out;
2170
- }
2171
- function sourcePlace(at, root) {
2172
- const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
2173
- return at.line ? `${file}:${at.line}` : file;
2174
- }
2175
- function quoted(at, root) {
2176
- return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
2177
- }
2178
- function formatCollision({ key, sites }, root) {
2179
- const [kept, ...others] = sites;
2180
- const texts = new Set(sites.map((at) => at.message)).size;
2181
- return `${key}: one key with ${counted(texts, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
2182
- }
2183
- function formatFinding(finding, root) {
2184
- switch (finding.kind) {
2185
- case "collision": return formatCollision(finding, root);
2186
- case "replaced": {
2187
- const place = sourcePlace(finding.site, root);
2188
- return finding.edited ? `${finding.locale}.json: your edit of "${finding.key}" was replaced, its text lives in ${place}: change it there` : `${finding.locale}: ${finding.key} follows the code (${place}): "${truncate(finding.site.message, 40)}", was "${truncate(finding.before, 40)}"`;
2189
- }
2190
- case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
2191
- case "positional": {
2192
- const names = finding.params.map((name) => `{${name}}`).join(", ");
2193
- return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
2194
- }
2195
- case "escaped": return `${sourcePlace(finding.site, root)}: ${shownSlice(finding.slice)} renders as literal text: write ${inlineBlock(finding.slice)}`;
2196
- case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
2197
- case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
2198
- case "lock": {
2199
- const lock = sourcePlace(finding, root);
2200
- if (finding.merged) return `${lock} had a merge conflict and now holds both sides, drafts and stamps included: add it to the commit that resolves the merge`;
2201
- return finding.from ? `${sourcePlace({ file: finding.from }, root)} moved to ${lock}, next to your config: commit both changes` : `${lock} now keeps the source text each translation was made for and which ones are drafts: commit it with your catalogs`;
2202
- }
2203
- }
2204
- }
2205
- function findingId(finding) {
2206
- switch (finding.kind) {
2207
- case "collision":
2208
- case "replaced": return `${finding.kind}:${finding.key}`;
2209
- case "outdated": return `outdated:${finding.locale}:${finding.key}`;
2210
- case "renamed": return `renamed:${finding.file}:${finding.name}`;
2211
- case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
2212
- case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
2213
- case "unparsed": return `unparsed:${finding.file}`;
2214
- case "lock": return `lock:${finding.merged ? "merged:" : ""}${finding.file}`;
2215
- }
2216
- }
2217
- function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
2218
- const shown = /* @__PURE__ */ new Map();
2219
- return { report(channel, findings) {
2220
- const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
2221
- const now = /* @__PURE__ */ new Set();
2222
- const fresh = [];
2223
- for (const finding of findings) {
2224
- const id = findingId(finding);
2225
- if (now.has(id)) continue;
2226
- now.add(id);
2227
- if (!before.has(id)) fresh.push(finding);
2228
- }
2229
- shown.set(channel, now);
2230
- for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
2231
- if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
2232
- } };
2193
+ warnOnce(`the types live in ${relativePath(cfg.root, target)} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
2233
2194
  }
2234
- // src/catalog/state.ts
2195
+ // src/catalog/lock.ts
2235
2196
  const STATE_FILE = "verbaly.lock";
2236
2197
  const LOCK_VERSION = 1;
2237
2198
  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.";
@@ -2342,27 +2303,142 @@ function readText(path) {
2342
2303
  return;
2343
2304
  }
2344
2305
  }
2345
- function updateState(cfg, catalogs) {
2346
- const next = refreshState(cfg, catalogs, loadState(cfg));
2347
- saveState(cfg, next);
2348
- return next;
2306
+ function markDrafts(drafts, locale, keys) {
2307
+ if (!keys.length) return;
2308
+ drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
2349
2309
  }
2350
- function refreshState(cfg, catalogs, previous) {
2351
- const flat = flatCatalogs(catalogs);
2352
- const source = flat[cfg.sourceLocale] ?? {};
2353
- const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
2310
+ function clearDrafts(drafts, locale, keys) {
2311
+ if (!drafts[locale]) return;
2312
+ if (!keys) {
2313
+ delete drafts[locale];
2314
+ return;
2315
+ }
2316
+ const drop = new Set(keys);
2317
+ drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
2318
+ if (!drafts[locale].length) delete drafts[locale];
2319
+ }
2320
+ function fingerprint(text) {
2321
+ return stableKey(text);
2322
+ }
2323
+ function stamp(source, translated) {
2324
+ return `${fingerprint(source)}.${fingerprint(translated)}`;
2325
+ }
2326
+ function sourceOf(stamped) {
2327
+ return stamped.slice(0, stamped.indexOf("."));
2328
+ }
2329
+ function translationOf(stamped) {
2330
+ return stamped.slice(stamped.indexOf(".") + 1);
2331
+ }
2332
+ function serializeState(state) {
2354
2333
  const drafts = emptyCatalog();
2355
- for (const [locale, keys] of Object.entries(previous.drafts)) {
2356
- if (!shown.has(locale)) {
2357
- drafts[locale] = keys;
2358
- continue;
2359
- }
2360
- const live = keys.filter((key) => own(flat[locale], key));
2361
- if (live.length) drafts[locale] = live;
2334
+ for (const locale of Object.keys(state.drafts).sort()) {
2335
+ const keys = [...new Set(state.drafts[locale])].sort();
2336
+ if (keys.length) drafts[locale] = keys;
2362
2337
  }
2363
2338
  const fingerprints = emptyCatalog();
2364
- for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
2365
- for (const locale of shown) {
2339
+ for (const locale of Object.keys(state.fingerprints).sort()) {
2340
+ const entries = state.fingerprints[locale] ?? {};
2341
+ const keys = Object.keys(entries).sort();
2342
+ if (!keys.length) continue;
2343
+ fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
2344
+ }
2345
+ const migrated = [...new Set(state.migrated ?? [])].sort();
2346
+ if (!Object.keys(drafts).length && !Object.keys(fingerprints).length && !migrated.length) return;
2347
+ const out = {
2348
+ _readme: README,
2349
+ version: LOCK_VERSION
2350
+ };
2351
+ if (Object.keys(drafts).length) out.drafts = drafts;
2352
+ if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
2353
+ if (migrated.length) out.migrated = migrated;
2354
+ return JSON.stringify(out, null, 2) + "\n";
2355
+ }
2356
+ function readSides(path) {
2357
+ const content = readText(path);
2358
+ if (content === void 0) return void 0;
2359
+ const body = stripBom(content);
2360
+ const sides = conflictSides(body);
2361
+ return (sides ?? [body]).map((text) => parseObject(path, text, sides !== void 0));
2362
+ }
2363
+ function parseObject(path, text, conflicted) {
2364
+ let value;
2365
+ try {
2366
+ value = JSON.parse(text);
2367
+ } catch (error) {
2368
+ throw corrupt(path, conflicted, error);
2369
+ }
2370
+ if (!isRecord(value)) throw corrupt(path, conflicted);
2371
+ return value;
2372
+ }
2373
+ const CONFLICT = {
2374
+ start: /^<{7}(?: |$)/,
2375
+ base: /^\|{7}(?: |$)/,
2376
+ split: /^={7}$/,
2377
+ end: /^>{7}(?: |$)/
2378
+ };
2379
+ function conflictSides(text) {
2380
+ const lines = text.split(/\r?\n/);
2381
+ if (!lines.some((line) => CONFLICT.start.test(line))) return void 0;
2382
+ const ours = [];
2383
+ const theirs = [];
2384
+ let at = "both";
2385
+ for (const line of lines) if (at === "both" && CONFLICT.start.test(line)) at = "ours";
2386
+ else if (at === "ours" && CONFLICT.base.test(line)) at = "base";
2387
+ else if ((at === "ours" || at === "base") && CONFLICT.split.test(line)) at = "theirs";
2388
+ else if (at === "theirs" && CONFLICT.end.test(line)) at = "both";
2389
+ else if (at !== "base") {
2390
+ if (at !== "theirs") ours.push(line);
2391
+ if (at !== "ours") theirs.push(line);
2392
+ }
2393
+ return at === "both" ? [ours.join("\n"), theirs.join("\n")] : void 0;
2394
+ }
2395
+ function corrupt(path, conflicted, cause) {
2396
+ return new Error(conflicted ? `[verbaly] ${path} has a merge conflict Verbaly cannot read: resolve it by hand and keep the entries of both sides (dropping a side, or the file, approves its drafts)` : `[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
2397
+ }
2398
+ function readDrafts(value) {
2399
+ const out = emptyCatalog();
2400
+ if (!isRecord(value)) return out;
2401
+ for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
2402
+ return out;
2403
+ }
2404
+ function readMigrated(value) {
2405
+ if (!Array.isArray(value)) return void 0;
2406
+ const locales = value.filter((locale) => typeof locale === "string");
2407
+ return locales.length ? locales : void 0;
2408
+ }
2409
+ function readFingerprints(value) {
2410
+ const out = emptyCatalog();
2411
+ if (!isRecord(value)) return out;
2412
+ for (const [locale, entries] of Object.entries(value)) {
2413
+ if (!isRecord(entries)) continue;
2414
+ const kept = emptyCatalog();
2415
+ for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
2416
+ out[locale] = kept;
2417
+ }
2418
+ return out;
2419
+ }
2420
+ // src/catalog/state.ts
2421
+ function updateState(cfg, catalogs) {
2422
+ const next = refreshState(cfg, catalogs, loadState(cfg));
2423
+ saveState(cfg, next);
2424
+ return next;
2425
+ }
2426
+ function refreshState(cfg, catalogs, previous) {
2427
+ const flat = flatCatalogs(catalogs);
2428
+ const source = flat[cfg.sourceLocale] ?? {};
2429
+ const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
2430
+ const drafts = emptyCatalog();
2431
+ for (const [locale, keys] of Object.entries(previous.drafts)) {
2432
+ if (!shown.has(locale)) {
2433
+ drafts[locale] = keys;
2434
+ continue;
2435
+ }
2436
+ const live = keys.filter((key) => own(flat[locale], key));
2437
+ if (live.length) drafts[locale] = live;
2438
+ }
2439
+ const fingerprints = emptyCatalog();
2440
+ for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
2441
+ for (const locale of shown) {
2366
2442
  const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
2367
2443
  if (Object.keys(stamps).length) fingerprints[locale] = stamps;
2368
2444
  }
@@ -2413,29 +2489,9 @@ function effectiveDrafts(drafts, catalogs) {
2413
2489
  }
2414
2490
  return out;
2415
2491
  }
2416
- function markDrafts(drafts, locale, keys) {
2417
- if (!keys.length) return;
2418
- drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
2419
- }
2420
- function clearDrafts(drafts, locale, keys) {
2421
- if (!drafts[locale]) return;
2422
- if (!keys) {
2423
- delete drafts[locale];
2424
- return;
2425
- }
2426
- const drop = new Set(keys);
2427
- drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
2428
- if (!drafts[locale].length) delete drafts[locale];
2429
- }
2430
- function fingerprint(text) {
2431
- return stableKey(text);
2432
- }
2433
2492
  function tracked(key, text) {
2434
2493
  return stableKey(text) !== key;
2435
2494
  }
2436
- function stamp(source, translated) {
2437
- return `${fingerprint(source)}.${fingerprint(translated)}`;
2438
- }
2439
2495
  function outdatedTranslations(cfg, catalogs, fingerprints) {
2440
2496
  const source = catalogs[cfg.sourceLocale] ?? {};
2441
2497
  const out = [];
@@ -2463,109 +2519,161 @@ function acceptOutdated(cfg, catalogs, fingerprints, entries) {
2463
2519
  (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
2464
2520
  }
2465
2521
  }
2466
- function sourceOf(stamped) {
2467
- return stamped.slice(0, stamped.indexOf("."));
2468
- }
2469
- function translationOf(stamped) {
2470
- return stamped.slice(stamped.indexOf(".") + 1);
2471
- }
2472
2522
  function flatCatalogs(catalogs) {
2473
2523
  const out = emptyCatalog();
2474
2524
  for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
2475
2525
  return out;
2476
2526
  }
2477
- function serializeState(state) {
2478
- const drafts = emptyCatalog();
2479
- for (const locale of Object.keys(state.drafts).sort()) {
2480
- const keys = [...new Set(state.drafts[locale])].sort();
2481
- if (keys.length) drafts[locale] = keys;
2482
- }
2483
- const fingerprints = emptyCatalog();
2484
- for (const locale of Object.keys(state.fingerprints).sort()) {
2485
- const entries = state.fingerprints[locale] ?? {};
2486
- const keys = Object.keys(entries).sort();
2487
- if (!keys.length) continue;
2488
- fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
2489
- }
2490
- const migrated = [...new Set(state.migrated ?? [])].sort();
2491
- if (!Object.keys(drafts).length && !Object.keys(fingerprints).length && !migrated.length) return;
2492
- const out = {
2493
- _readme: README,
2494
- version: LOCK_VERSION
2527
+ // src/gate/findings.ts
2528
+ function siteOf(msg) {
2529
+ return {
2530
+ file: msg.file,
2531
+ line: msg.line,
2532
+ message: msg.message
2495
2533
  };
2496
- if (Object.keys(drafts).length) out.drafts = drafts;
2497
- if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
2498
- if (migrated.length) out.migrated = migrated;
2499
- return JSON.stringify(out, null, 2) + "\n";
2500
2534
  }
2501
- function readSides(path) {
2502
- const content = readText(path);
2503
- if (content === void 0) return void 0;
2504
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
2505
- const sides = conflictSides(body);
2506
- return (sides ?? [body]).map((text) => parseObject(path, text, sides !== void 0));
2535
+ function collisionEntries(registry) {
2536
+ return registry.collisions().map(({ key, kept, dropped }) => ({
2537
+ key,
2538
+ sites: [kept, ...dropped].map(siteOf)
2539
+ }));
2507
2540
  }
2508
- function parseObject(path, text, conflicted) {
2509
- let value;
2510
- try {
2511
- value = JSON.parse(text);
2512
- } catch (error) {
2513
- throw corrupt(path, conflicted, error);
2541
+ function scanFindings(cfg, registry, replaced = []) {
2542
+ const messages = registry.messages();
2543
+ const out = [];
2544
+ for (const { key, before } of replaced) {
2545
+ const msg = messages.get(key);
2546
+ if (msg) out.push({
2547
+ kind: "replaced",
2548
+ locale: cfg.sourceLocale,
2549
+ key,
2550
+ before,
2551
+ site: siteOf(msg)
2552
+ });
2514
2553
  }
2515
- if (!isObject(value)) throw corrupt(path, conflicted);
2516
- return value;
2517
- }
2518
- const CONFLICT = {
2519
- start: /^<{7}(?: |$)/,
2520
- base: /^\|{7}(?: |$)/,
2521
- split: /^={7}$/,
2522
- end: /^>{7}(?: |$)/
2523
- };
2524
- function conflictSides(text) {
2525
- const lines = text.split(/\r?\n/);
2526
- if (!lines.some((line) => CONFLICT.start.test(line))) return void 0;
2527
- const ours = [];
2528
- const theirs = [];
2529
- let at = "both";
2530
- for (const line of lines) if (at === "both" && CONFLICT.start.test(line)) at = "ours";
2531
- else if (at === "ours" && CONFLICT.base.test(line)) at = "base";
2532
- else if ((at === "ours" || at === "base") && CONFLICT.split.test(line)) at = "theirs";
2533
- else if (at === "theirs" && CONFLICT.end.test(line)) at = "both";
2534
- else if (at !== "base") {
2535
- if (at !== "theirs") ours.push(line);
2536
- if (at !== "ours") theirs.push(line);
2554
+ for (const entry of collisionEntries(registry)) out.push({
2555
+ kind: "collision",
2556
+ ...entry
2557
+ });
2558
+ for (const { name, file, line } of registry.missed()) out.push({
2559
+ kind: "renamed",
2560
+ name,
2561
+ file,
2562
+ line
2563
+ });
2564
+ for (const msg of messages.values()) {
2565
+ const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
2566
+ if (params.length > 0) out.push({
2567
+ kind: "positional",
2568
+ params,
2569
+ site: siteOf(msg)
2570
+ });
2571
+ const slice = escapedSyntax(msg.message);
2572
+ if (slice) out.push({
2573
+ kind: "escaped",
2574
+ slice,
2575
+ site: siteOf(msg)
2576
+ });
2537
2577
  }
2538
- return at === "both" ? [ours.join("\n"), theirs.join("\n")] : void 0;
2539
- }
2540
- function corrupt(path, conflicted, cause) {
2541
- return new Error(conflicted ? `[verbaly] ${path} has a merge conflict Verbaly cannot read: resolve it by hand and keep the entries of both sides (dropping a side, or the file, approves its drafts)` : `[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
2542
- }
2543
- function isObject(value) {
2544
- return typeof value === "object" && value !== null && !Array.isArray(value);
2545
- }
2546
- function readDrafts(value) {
2547
- const out = emptyCatalog();
2548
- if (!isObject(value)) return out;
2549
- for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
2578
+ for (const { file, message } of registry.parseErrors()) out.push({
2579
+ kind: "unparsed",
2580
+ file,
2581
+ message
2582
+ });
2550
2583
  return out;
2551
2584
  }
2552
- function readMigrated(value) {
2553
- if (!Array.isArray(value)) return void 0;
2554
- const locales = value.filter((locale) => typeof locale === "string");
2555
- return locales.length ? locales : void 0;
2585
+ function sourcePlace(at, root) {
2586
+ const file = root ? relativePath(root, at.file) : at.file;
2587
+ return at.line ? `${file}:${at.line}` : file;
2556
2588
  }
2557
- function readFingerprints(value) {
2558
- const out = emptyCatalog();
2559
- if (!isObject(value)) return out;
2560
- for (const [locale, entries] of Object.entries(value)) {
2561
- if (!isObject(entries)) continue;
2562
- const kept = emptyCatalog();
2563
- for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
2564
- out[locale] = kept;
2565
- }
2566
- return out;
2589
+ function quoted(at, root) {
2590
+ return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
2567
2591
  }
2568
- // src/project/project.ts
2592
+ function formatCollision({ key, sites }, root) {
2593
+ const [kept, ...others] = sites;
2594
+ const texts = new Set(sites.map((at) => at.message)).size;
2595
+ return `${key}: one key with ${counted(texts, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
2596
+ }
2597
+ function formatFinding(finding, root) {
2598
+ switch (finding.kind) {
2599
+ case "collision": return formatCollision(finding, root);
2600
+ case "replaced": {
2601
+ const place = sourcePlace(finding.site, root);
2602
+ return finding.edited ? `${finding.locale}.json: your edit of "${finding.key}" was replaced, its text lives in ${place}: change it there` : `${finding.locale}: ${finding.key} follows the code (${place}): "${truncate(finding.site.message, 40)}", was "${truncate(finding.before, 40)}"`;
2603
+ }
2604
+ case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
2605
+ case "positional": {
2606
+ const names = finding.params.map((name) => `{${name}}`).join(", ");
2607
+ return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
2608
+ }
2609
+ case "escaped": return `${sourcePlace(finding.site, root)}: ${shownSlice(finding.slice)} renders as literal text: write ${inlineBlock(finding.slice)}`;
2610
+ case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
2611
+ case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
2612
+ case "lock": {
2613
+ const lock = sourcePlace(finding, root);
2614
+ if (finding.merged) return `${lock} had a merge conflict and now holds both sides, drafts and stamps included: add it to the commit that resolves the merge`;
2615
+ return finding.from ? `${sourcePlace({ file: finding.from }, root)} moved to ${lock}, next to your config: commit both changes` : `${lock} now keeps the source text each translation was made for and which ones are drafts: commit it with your catalogs`;
2616
+ }
2617
+ }
2618
+ }
2619
+ function findingId(finding) {
2620
+ switch (finding.kind) {
2621
+ case "collision":
2622
+ case "replaced": return `${finding.kind}:${finding.key}`;
2623
+ case "outdated": return `outdated:${finding.locale}:${finding.key}`;
2624
+ case "renamed": return `renamed:${finding.file}:${finding.name}`;
2625
+ case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
2626
+ case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
2627
+ case "unparsed": return `unparsed:${finding.file}`;
2628
+ case "lock": return `lock:${finding.merged ? "merged:" : ""}${finding.file}`;
2629
+ }
2630
+ }
2631
+ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
2632
+ const shown = /* @__PURE__ */ new Map();
2633
+ let stateBroken = false;
2634
+ const report = (channel, findings) => {
2635
+ const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
2636
+ const now = /* @__PURE__ */ new Set();
2637
+ const fresh = [];
2638
+ for (const finding of findings) {
2639
+ const id = findingId(finding);
2640
+ if (now.has(id)) continue;
2641
+ now.add(id);
2642
+ if (!before.has(id)) fresh.push(finding);
2643
+ }
2644
+ shown.set(channel, now);
2645
+ for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
2646
+ if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
2647
+ };
2648
+ return {
2649
+ report,
2650
+ sync(cfg, result, edited) {
2651
+ const replaced = [];
2652
+ const code = [];
2653
+ const lock = [];
2654
+ for (const finding of result.findings) if (finding.kind === "collision" || finding.kind === "renamed") code.push(finding);
2655
+ else if (finding.kind === "lock") lock.push(finding);
2656
+ else if (finding.kind === "replaced") {
2657
+ const answer = edited(finding);
2658
+ if (answer !== void 0) replaced.push({
2659
+ ...finding,
2660
+ edited: answer
2661
+ });
2662
+ }
2663
+ report("replaced", replaced);
2664
+ report("code", code);
2665
+ report("lock", lock);
2666
+ const outdated = result.state ? outdatedTranslations(cfg, result.catalogs, result.state.fingerprints) : [];
2667
+ report("outdated", outdated.map((entry) => ({
2668
+ kind: "outdated",
2669
+ ...entry
2670
+ })));
2671
+ if (result.stateProblem && !stateBroken) print(`${result.stateProblem}, so drafts are not tracked`);
2672
+ stateBroken = Boolean(result.stateProblem);
2673
+ }
2674
+ };
2675
+ }
2676
+ // src/project/project.ts
2569
2677
  async function syncProject(cfg, options = {}) {
2570
2678
  const registry = options.registry ?? await extractProject(cfg);
2571
2679
  const catalogs = options.catalogs ?? loadCatalogs(cfg);
@@ -2576,7 +2684,7 @@ async function syncProject(cfg, options = {}) {
2576
2684
  const result = {
2577
2685
  registry,
2578
2686
  catalogs,
2579
- messages: Object.keys(catalogs[cfg.sourceLocale] ?? {}).length,
2687
+ messages: Object.keys(catalogs[cfg.sourceLocale] ?? emptyCatalog()).length,
2580
2688
  inCode: registry.messages().size,
2581
2689
  added,
2582
2690
  replaced,
@@ -2590,9 +2698,9 @@ async function syncProject(cfg, options = {}) {
2590
2698
  if (replaced.length > 0) changed.add(cfg.sourceLocale);
2591
2699
  for (const locale of cfg.locales) {
2592
2700
  if (options.write === "changed" && !changed.has(locale)) continue;
2593
- result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
2701
+ result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? emptyCatalog());
2594
2702
  }
2595
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
2703
+ writeDts(cfg, catalogs[cfg.sourceLocale] ?? emptyCatalog());
2596
2704
  const before = stateFile(cfg);
2597
2705
  try {
2598
2706
  result.state = updateState(cfg, catalogs);
@@ -2607,7 +2715,7 @@ async function syncProject(cfg, options = {}) {
2607
2715
  return result;
2608
2716
  }
2609
2717
  function confirmFromDisk(cfg, catalogs, registry) {
2610
- const source = catalogs[cfg.sourceLocale] ?? {};
2718
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
2611
2719
  const stale = /* @__PURE__ */ new Set();
2612
2720
  for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
2613
2721
  for (const file of stale) {
@@ -2621,23 +2729,316 @@ function confirmFromDisk(cfg, catalogs, registry) {
2621
2729
  registry.update(file, analyzeFile(code, file));
2622
2730
  }
2623
2731
  }
2732
+ // src/exchange/translate.ts
2733
+ const RETRY_STATUS = /* @__PURE__ */ new Set([
2734
+ 408,
2735
+ 409,
2736
+ 425,
2737
+ 429,
2738
+ 500,
2739
+ 502,
2740
+ 503,
2741
+ 504,
2742
+ 529
2743
+ ]);
2744
+ function retryable(error) {
2745
+ const status = error?.status;
2746
+ const code = error?.statusCode;
2747
+ const value = typeof status === "number" ? status : code;
2748
+ return typeof value === "number" ? RETRY_STATUS.has(value) : true;
2749
+ }
2750
+ function reason(error) {
2751
+ return error instanceof Error ? error.message : String(error);
2752
+ }
2753
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2754
+ async function attempt(run, retries, delay) {
2755
+ for (let round = 0;; round++) try {
2756
+ return await run();
2757
+ } catch (error) {
2758
+ if (round >= retries || !retryable(error)) throw error;
2759
+ await wait(delay * 2 ** round);
2760
+ }
2761
+ }
2762
+ async function pooled(jobs, limit, run) {
2763
+ let next = 0;
2764
+ const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
2765
+ while (next < jobs.length) await run(jobs[next++]);
2766
+ });
2767
+ await Promise.all(workers);
2768
+ }
2769
+ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2770
+ const batchSize = options.batchSize ?? 20;
2771
+ const concurrency = Math.max(1, options.concurrency ?? 4);
2772
+ const retries = Math.max(0, options.retries ?? 2);
2773
+ const retryDelay = options.retryDelay ?? 500;
2774
+ const targets = targetLocales(cfg, options.locales);
2775
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
2776
+ const result = {
2777
+ translated: emptyCatalog(),
2778
+ invalid: emptyCatalog(),
2779
+ pending: emptyCatalog(),
2780
+ failed: []
2781
+ };
2782
+ const jobs = [];
2783
+ for (const locale of targets) {
2784
+ const catalog = catalogs[locale] ??= emptyCatalog();
2785
+ const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
2786
+ if (missing.length === 0) continue;
2787
+ if (options.dryRun) {
2788
+ result.pending[locale] = missing;
2789
+ continue;
2790
+ }
2791
+ const batches = Math.ceil(missing.length / batchSize);
2792
+ for (let i = 0; i < missing.length; i += batchSize) {
2793
+ const index = Math.floor(i / batchSize) + 1;
2794
+ jobs.push({
2795
+ locale,
2796
+ index,
2797
+ batches,
2798
+ keys: missing.slice(i, i + batchSize)
2799
+ });
2800
+ }
2801
+ }
2802
+ await pooled(jobs, concurrency, async (job) => {
2803
+ const { locale, keys } = job;
2804
+ const catalog = catalogs[locale];
2805
+ const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
2806
+ const origins = options.origins ? Object.fromEntries(keys.filter((key) => Object.hasOwn(options.origins, key)).map((key) => [key, options.origins[key]])) : void 0;
2807
+ let out;
2808
+ try {
2809
+ out = await attempt(() => provider({
2810
+ sourceLocale: cfg.sourceLocale,
2811
+ targetLocale: locale,
2812
+ messages,
2813
+ origins,
2814
+ instructions: cfg.translate.instructions,
2815
+ glossary: glossaryFor(cfg, locale, messages)
2816
+ }), retries, retryDelay);
2817
+ } catch (error) {
2818
+ const message = reason(error);
2819
+ result.failed.push({
2820
+ locale,
2821
+ keys,
2822
+ error: message
2823
+ });
2824
+ options.onProgress?.({
2825
+ ...progressOf(job),
2826
+ error: message
2827
+ });
2828
+ return;
2829
+ }
2830
+ for (const key of keys) {
2831
+ const text = out[key];
2832
+ if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
2833
+ catalog[key] = text;
2834
+ (result.translated[locale] ??= []).push(key);
2835
+ } else (result.invalid[locale] ??= []).push(key);
2836
+ }
2837
+ options.onProgress?.(progressOf(job));
2838
+ });
2839
+ for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
2840
+ for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
2841
+ result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));
2842
+ return result;
2843
+ }
2844
+ function compare(a, b) {
2845
+ return byCodeUnit(a[0] ?? "", b[0] ?? "");
2846
+ }
2847
+ function mergeTranslations(cfg, locale, translated, keys) {
2848
+ const source = readCatalog(cfg, cfg.sourceLocale);
2849
+ const current = readCatalog(cfg, locale);
2850
+ const written = [];
2851
+ for (const key of keys) {
2852
+ const text = own(translated, key);
2853
+ if (!source[key] || current[key] || !text) continue;
2854
+ current[key] = text;
2855
+ written.push(key);
2856
+ }
2857
+ if (written.length > 0) writeCatalog(cfg, locale, current);
2858
+ return written;
2859
+ }
2860
+ function writeDrafts(cfg, locale, entries, options = {}) {
2861
+ const targets = targetLocales(cfg);
2862
+ if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
2863
+ loadState(cfg);
2864
+ const catalogs = emptyCatalog();
2865
+ catalogs[cfg.sourceLocale] = readCatalog(cfg, cfg.sourceLocale);
2866
+ const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
2867
+ const current = readCatalog(cfg, locale);
2868
+ const result = {
2869
+ written: [],
2870
+ kept: [],
2871
+ invalid: [],
2872
+ unknown: []
2873
+ };
2874
+ for (const { key, text } of entries) {
2875
+ const from = own(source, key);
2876
+ if (!from) result.unknown.push(key);
2877
+ else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);
2878
+ else if (own(current, key) && !options.overwrite) result.kept.push(key);
2879
+ else {
2880
+ current[key] = text;
2881
+ result.written.push(key);
2882
+ }
2883
+ }
2884
+ if (result.written.length > 0) {
2885
+ writeCatalog(cfg, locale, current);
2886
+ const written = result.written.map((key) => ({
2887
+ key,
2888
+ text: current[key]
2889
+ }));
2890
+ const before = stateFile(cfg);
2891
+ recordTranslations(cfg, source, [{
2892
+ locale,
2893
+ entries: written,
2894
+ draft: true
2895
+ }]);
2896
+ const lock = lockNews(cfg, before);
2897
+ if (lock) result.lock = lock;
2898
+ }
2899
+ return result;
2900
+ }
2901
+ function formatTranslateFailures(failed) {
2902
+ const grouped = [];
2903
+ for (const entry of failed) {
2904
+ const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
2905
+ if (same) same.keys = [...same.keys, ...entry.keys];
2906
+ else grouped.push({
2907
+ ...entry,
2908
+ keys: [...entry.keys]
2909
+ });
2910
+ }
2911
+ return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
2912
+ }
2913
+ async function resolveProvider(cfg, model) {
2914
+ const configured = cfg.translate.provider;
2915
+ if (typeof configured === "function") return configured;
2916
+ const { claudeProvider } = await import("./claude-DvjHi7np.js");
2917
+ return claudeProvider({ model: model ?? cfg.translate.model });
2918
+ }
2919
+ function progressOf(job) {
2920
+ return {
2921
+ locale: job.locale,
2922
+ batch: job.index,
2923
+ batches: job.batches,
2924
+ keys: job.keys.length
2925
+ };
2926
+ }
2927
+ function glossaryFor(cfg, locale, messages) {
2928
+ const entries = cfg.translate.glossary;
2929
+ if (!entries) return void 0;
2930
+ const text = Object.values(messages).join("\n").toLowerCase();
2931
+ const out = {};
2932
+ for (const [term, rendering] of Object.entries(entries)) {
2933
+ if (!text.includes(term.toLowerCase())) continue;
2934
+ const value = typeof rendering === "string" ? rendering : rendering[locale];
2935
+ if (value) out[term] = value;
2936
+ }
2937
+ return Object.keys(out).length > 0 ? out : void 0;
2938
+ }
2939
+ // src/project/translate.ts
2940
+ async function translateProject(cfg, options = {}) {
2941
+ const dryRun = options.dryRun === true;
2942
+ if (!dryRun) loadState(cfg);
2943
+ const registry = await extractProject(cfg);
2944
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
2945
+ const run = await translateCatalogs(cfg, catalogs, options.provider ?? await resolveProvider(cfg, options.model), {
2946
+ locales: options.locales,
2947
+ batchSize: cfg.translate.batchSize,
2948
+ concurrency: cfg.translate.concurrency,
2949
+ retries: cfg.translate.retries,
2950
+ dryRun,
2951
+ origins: dryRun ? void 0 : await collectOrigins(cfg, registry),
2952
+ onProgress: dryRun ? void 0 : options.onProgress
2953
+ });
2954
+ const result = {
2955
+ pending: run.pending,
2956
+ written: emptyCatalog(),
2957
+ kept: emptyCatalog(),
2958
+ invalid: run.invalid,
2959
+ failed: run.failed
2960
+ };
2961
+ if (dryRun) return result;
2962
+ const writes = [];
2963
+ for (const [locale, keys] of Object.entries(run.translated)) {
2964
+ const catalog = catalogs[locale] ?? {};
2965
+ const landed = mergeTranslations(cfg, locale, catalog, keys);
2966
+ const left = keys.filter((key) => !landed.includes(key));
2967
+ if (left.length > 0) result.kept[locale] = left;
2968
+ if (landed.length === 0) continue;
2969
+ result.written[locale] = landed;
2970
+ writes.push({
2971
+ locale,
2972
+ draft: true,
2973
+ entries: landed.map((key) => ({
2974
+ key,
2975
+ text: catalog[key]
2976
+ }))
2977
+ });
2978
+ }
2979
+ const before = stateFile(cfg);
2980
+ if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
2981
+ const lock = lockNews(cfg, before);
2982
+ if (lock) result.lock = lock;
2983
+ return result;
2984
+ }
2624
2985
  // src/gate/check.ts
2625
2986
  function gatePasses(result) {
2626
2987
  return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2627
2988
  }
2989
+ function relativeCheck(root, result) {
2990
+ const rel = (file) => relativePath(root, file);
2991
+ return {
2992
+ ...result,
2993
+ unknown: result.unknown.map((entry) => ({
2994
+ ...entry,
2995
+ files: entry.files.map(rel)
2996
+ })),
2997
+ extra: result.extra.map((entry) => ({
2998
+ ...entry,
2999
+ files: entry.files.map(rel)
3000
+ })),
3001
+ collisions: result.collisions.map((entry) => ({
3002
+ ...entry,
3003
+ sites: entry.sites.map((at) => ({
3004
+ ...at,
3005
+ file: rel(at.file)
3006
+ }))
3007
+ })),
3008
+ divergent: result.divergent.map((entry) => ({
3009
+ ...entry,
3010
+ code: {
3011
+ ...entry.code,
3012
+ file: rel(entry.code.file)
3013
+ }
3014
+ }))
3015
+ };
3016
+ }
2628
3017
  function warningCount(result) {
2629
3018
  return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.divergent.length + result.outdated.length;
2630
3019
  }
2631
3020
  function check(cfg, catalogs, registry, fingerprints = emptyCatalog()) {
2632
3021
  return gatePass(() => checkPass(cfg, catalogs, registry, fingerprints));
2633
3022
  }
2634
- function checkPass(cfg, catalogs, registry, fingerprints) {
2635
- const extracted = registry.messages();
3023
+ function gateViews(cfg, catalogs, registry) {
2636
3024
  const flat = emptyCatalog();
2637
3025
  for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
2638
3026
  const source = flat[cfg.sourceLocale] ?? {};
2639
3027
  const shipped = shippedCatalogs(cfg, flat, registry);
2640
- const sourceText = shipped[cfg.sourceLocale];
3028
+ return {
3029
+ flat,
3030
+ source,
3031
+ shipped,
3032
+ sourceText: shipped[cfg.sourceLocale]
3033
+ };
3034
+ }
3035
+ function translationIssues(locale, translated, text) {
3036
+ const issues = validateMessage(translated, locale);
3037
+ return text ? [...issues, ...validatePair(text, translated)] : issues;
3038
+ }
3039
+ function checkPass(cfg, catalogs, registry, fingerprints) {
3040
+ const extracted = registry.messages();
3041
+ const { flat, source, shipped, sourceText } = gateViews(cfg, catalogs, registry);
2641
3042
  const used = registry.usedKeys();
2642
3043
  const unknown = [];
2643
3044
  for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
@@ -2682,9 +3083,7 @@ function checkPass(cfg, catalogs, registry, fingerprints) {
2682
3083
  if (locale === cfg.sourceLocale) continue;
2683
3084
  for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
2684
3085
  if (!translated) continue;
2685
- add(locale, key, validateMessage(translated, locale));
2686
- const text = sourceText[key];
2687
- if (text) add(locale, key, validatePair(text, translated));
3086
+ add(locale, key, translationIssues(locale, translated, sourceText[key]));
2688
3087
  }
2689
3088
  }
2690
3089
  const extra = [];
@@ -2716,8 +3115,9 @@ function checkPass(cfg, catalogs, registry, fingerprints) {
2716
3115
  outdated: outdatedTranslations(cfg, shipped, fingerprints)
2717
3116
  };
2718
3117
  }
3118
+ // src/gate/report.ts
2719
3119
  function formatCheckResult(result, root) {
2720
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
3120
+ const show = (file) => root ? relativePath(root, file) : file;
2721
3121
  const lines = [];
2722
3122
  if (result.missing.length > 0) {
2723
3123
  lines.push("missing translations:");
@@ -2742,7 +3142,7 @@ function formatCheckResult(result, root) {
2742
3142
  return lines.join("\n");
2743
3143
  }
2744
3144
  function formatBuildReport(result, sourceLocale, root, cap = 5) {
2745
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
3145
+ const show = (file) => root ? relativePath(root, file) : file;
2746
3146
  const lines = [];
2747
3147
  const list = (entries, line) => {
2748
3148
  for (const entry of entries.slice(0, cap)) lines.push(` ${line(entry)}`);
@@ -2792,7 +3192,7 @@ function formatCheckWarnings(result, root, options = {}) {
2792
3192
  }
2793
3193
  function githubCheckAnnotations(result, registry, cfg, options = {}) {
2794
3194
  const messages = registry.messages();
2795
- const rel = (file) => escapeProperty(relative(cfg.root, file).replaceAll("\\", "/"));
3195
+ const rel = (file) => escapeProperty(relativePath(cfg.root, file));
2796
3196
  const at = (file, line) => `file=${rel(file)}${line ? `,line=${line}` : ""}`;
2797
3197
  const lines = [];
2798
3198
  const byKey = /* @__PURE__ */ new Map();
@@ -2853,140 +3253,6 @@ function escapeData(text) {
2853
3253
  function escapeProperty(text) {
2854
3254
  return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
2855
3255
  }
2856
- // src/scan/transform.ts
2857
- function quote(text, single) {
2858
- if (!single) return JSON.stringify(text);
2859
- return `'${text.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
2860
- }
2861
- function transformCode(code, file, analysis, options = {}) {
2862
- const own = analysis ?? analyzeFile(code, file);
2863
- if (!analysis && own.parseError) warnParseError(file, own.parseError);
2864
- const { tagged } = own;
2865
- const appAt = options.appImport && !own.appImported ? own.adapterImport : void 0;
2866
- if (tagged.length === 0 && appAt === void 0) return null;
2867
- const s = new MagicString(code);
2868
- if (appAt !== void 0) s.appendLeft(appAt, `import '${APP_ID}'; `);
2869
- for (const msg of tagged) {
2870
- const seen = /* @__PURE__ */ new Set();
2871
- const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));
2872
- const pairs = entries.map((p) => `${quote(p.name, msg.singleQuote)}: ${code.slice(p.start, p.end)}`).join(", ");
2873
- if (msg.jsx) {
2874
- const values = entries.length ? ` values={{ ${pairs} }}` : "";
2875
- const components = msg.jsx.components.length ? ` components={{ ${msg.jsx.components.map((c) => `${JSON.stringify(c.name)}: ${c.source}`).join(", ")} }}` : "";
2876
- s.overwrite(msg.start, msg.end, `<${msg.jsx.name} id=${JSON.stringify(msg.key)}${values}${components} />`);
2877
- continue;
2878
- }
2879
- const tagSource = code.slice(msg.tagStart, msg.tagEnd);
2880
- const args = entries.length ? `, { ${pairs} }` : "";
2881
- s.overwrite(msg.start, msg.end, `${tagSource}(${quote(msg.key, msg.singleQuote)}${args})`);
2882
- }
2883
- return {
2884
- code: s.toString(),
2885
- map: s.generateMap({ hires: true })
2886
- };
2887
- }
2888
- // src/emit/plugin.ts
2889
- const RESOLVED_VIRTUAL_ID = "\0" + VIRTUAL_ID;
2890
- const LOCALE_MODULE_PREFIX = `${RESOLVED_VIRTUAL_ID}/locale/`;
2891
- const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
2892
- function resolveVirtualId(id) {
2893
- if (isAppModule(id)) return RESOLVED_VIRTUAL_ID;
2894
- if (id.startsWith("@verbaly/app/locale/")) return LOCALE_MODULE_PREFIX + id.slice(20);
2895
- if (id.startsWith(`virtual:verbaly/`)) return "\0" + id;
2896
- }
2897
- function loadVirtualModule(id, cfg, catalogs) {
2898
- const client = clientCatalogs(cfg, catalogs);
2899
- if (id === RESOLVED_VIRTUAL_ID) return generateRuntimeModule(cfg, {
2900
- icu: cfg.icu ?? needsIcu(client),
2901
- relative: cfg.relative ?? needsRelative(client),
2902
- inlineCatalog: cfg.render.inlineCatalog === true
2903
- });
2904
- if (id.startsWith(LOCALE_MODULE_PREFIX)) return generateLocaleModule(client[id.slice(LOCALE_MODULE_PREFIX.length)] ?? {});
2905
- }
2906
- function isTransformTarget(id) {
2907
- return SOURCE_FILE_RE.test(id) && !id.includes("node_modules") && !id.startsWith("\0");
2908
- }
2909
- function createSourceFilter(cfg) {
2910
- if (cfg.include.length === 0) return () => false;
2911
- const matches = picomatch(cfg.include, { ignore: cfg.exclude });
2912
- return (id) => {
2913
- const rel = relative(cfg.root, id).replaceAll("\\", "/");
2914
- return !rel.startsWith("..") && matches(rel);
2915
- };
2916
- }
2917
- function transformSource(code, id, registry, scan) {
2918
- const analysis = (scan && scannedAnalysis(scan, id, code)) ?? analyzeFile(code, id);
2919
- registry.update(id, analysis);
2920
- if (analysis.parseError) warnParseError(id, analysis.parseError);
2921
- const messages = emptyCatalog();
2922
- for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
2923
- return {
2924
- messages,
2925
- result: transformCode(code, id, analysis, { appImport: true }) ?? null
2926
- };
2927
- }
2928
- function writeBuildTypes(cfg, catalogs) {
2929
- try {
2930
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
2931
- } catch (error) {
2932
- const code = error?.code;
2933
- if (typeof code !== "string") throw error;
2934
- 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}`);
2935
- }
2936
- }
2937
- function runBuildGate(cfg, registry, failOnMissing) {
2938
- const catalogs = loadCatalogs(cfg);
2939
- for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
2940
- const found = check(cfg, catalogs, registry, buildFingerprints(cfg));
2941
- if (failOnMissing === true && !gatePasses(found)) throw new Error(`[verbaly] build blocked\n${formatCheckResult(found, cfg.root)}\n${checkNextSteps(found, cliReachable(cfg.root))}`);
2942
- reportGate(cfg, found);
2943
- const warnings = warningCount(found);
2944
- if (warnings > 0) {
2945
- const once = onceMoved(cfg.root);
2946
- const read = once ? `\`npx verbaly check\` reads them${once}` : "run `npx verbaly check` to read them";
2947
- warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: ${read}`, "gate:warnings");
2948
- }
2949
- }
2950
- function onceMoved(root) {
2951
- const moved = pluginOnlyOptions(root);
2952
- if (!moved) return "";
2953
- return ` once ${moved} ${moved.includes(" and ") ? "move" : "moves"} to verbaly.config`;
2954
- }
2955
- const reported = /* @__PURE__ */ new Map();
2956
- function reportGate(cfg, found) {
2957
- const before = reported.get(cfg.root) ?? /* @__PURE__ */ new Set();
2958
- const now = /* @__PURE__ */ new Set();
2959
- const fresh = (entries, id) => entries.filter((entry) => {
2960
- const key = id(entry);
2961
- now.add(key);
2962
- return !before.has(key);
2963
- });
2964
- const report = {
2965
- broken: fresh(found.broken.filter((entry) => entry.severity === "error"), (entry) => `broken:${entry.locale}:${entry.key}:${entry.issue}`),
2966
- missing: fresh(found.missing, (entry) => `missing:${entry.locale}:${entry.key}`),
2967
- unknown: fresh(found.unknown, (entry) => `unknown:${entry.key}`),
2968
- collisions: fresh(found.collisions, (entry) => `collision:${entry.key}`)
2969
- };
2970
- reported.set(cfg.root, now);
2971
- const lines = formatBuildReport(report, cfg.sourceLocale, cfg.root);
2972
- if (lines.length === 0) return;
2973
- const steps = checkNextSteps({
2974
- ...found,
2975
- ...report
2976
- }, cliReachable(cfg.root));
2977
- const block = [
2978
- ...lines.map((line) => line.startsWith(" ") ? line : `[verbaly] ${line}`),
2979
- "[verbaly] to fix them:",
2980
- ...steps.split("\n").map((step) => ` ${step}`),
2981
- `[verbaly] \`npx verbaly check\` lists every one${onceMoved(cfg.root)}, and in your CI it stops a release on them`
2982
- ];
2983
- console.warn(block.join("\n"));
2984
- }
2985
- function buildFingerprints(cfg) {
2986
- const { state, problem } = readState(cfg);
2987
- if (problem) warnOnce(`${problem}, so outdated translations are not reported`, "gate:state");
2988
- return state.fingerprints;
2989
- }
2990
3256
  // src/scan/scope.ts
2991
3257
  const TAGGED_HINT = /(?<![\w$.])\$?t(?:\.id\s*\([^)]*\))?\s*`/;
2992
3258
  const NOT_SOURCE = [
@@ -2997,7 +3263,7 @@ const NOT_SOURCE = [
2997
3263
  "**/coverage/**"
2998
3264
  ];
2999
3265
  function relativeId(cfg, id) {
3000
- return relative(cfg.root, id).replaceAll("\\", "/");
3266
+ return relativePath(cfg.root, id);
3001
3267
  }
3002
3268
  function suggestedPattern(rel) {
3003
3269
  const slash = rel.indexOf("/");
@@ -3056,13 +3322,9 @@ async function filesOutsideInclude(cfg) {
3056
3322
  // src/gate/status.ts
3057
3323
  function status(cfg, catalogs, registry, drafts = emptyCatalog(), fingerprints = emptyCatalog()) {
3058
3324
  const extracted = registry.messages();
3059
- const flat = emptyCatalog();
3060
- for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
3061
- const source = flat[cfg.sourceLocale] ?? {};
3325
+ const { flat, source, shipped, sourceText } = gateViews(cfg, catalogs, registry);
3062
3326
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
3063
3327
  const live = effectiveDrafts(drafts, flat);
3064
- const shipped = shippedCatalogs(cfg, flat, registry);
3065
- const sourceText = shipped[cfg.sourceLocale];
3066
3328
  const outdated = outdatedTranslations(cfg, shipped, fingerprints);
3067
3329
  const locales = [];
3068
3330
  for (const locale of cfg.locales) {
@@ -3073,8 +3335,7 @@ function status(cfg, catalogs, registry, drafts = emptyCatalog(), fingerprints =
3073
3335
  let broken = 0;
3074
3336
  for (const [key, text] of Object.entries(catalog)) {
3075
3337
  if (!text) continue;
3076
- const from = sourceText[key];
3077
- if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
3338
+ if (translationIssues(locale, text, sourceText[key]).some((issue) => issue.severity === "error")) broken += 1;
3078
3339
  }
3079
3340
  locales.push({
3080
3341
  locale,
@@ -3146,7 +3407,7 @@ const OPTIONS = {
3146
3407
  }
3147
3408
  };
3148
3409
  function parseCli(args) {
3149
- return parseArgs({
3410
+ return parseArgs$1({
3150
3411
  args,
3151
3412
  allowPositionals: true,
3152
3413
  options: OPTIONS
@@ -3182,7 +3443,7 @@ async function checkCommand(cfg, values) {
3182
3443
  }
3183
3444
  const registry = await extractProject(cfg);
3184
3445
  const catalogs = loadCatalogs(cfg);
3185
- const state = checkState(cfg, values.drafts === true || values.outdated === true);
3446
+ const state = checkState$1(cfg, values.drafts === true || values.outdated === true);
3186
3447
  const result = check(cfg, catalogs, registry, state.fingerprints);
3187
3448
  const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};
3188
3449
  const outdated = values.outdated ? result.outdated : [];
@@ -3208,7 +3469,7 @@ async function checkCommand(cfg, values) {
3208
3469
  }
3209
3470
  process.exitCode = 1;
3210
3471
  }
3211
- function checkState(cfg, gating) {
3472
+ function checkState$1(cfg, gating) {
3212
3473
  if (gating) return loadState(cfg);
3213
3474
  const { state, problem } = readState(cfg);
3214
3475
  if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);
@@ -3286,31 +3547,63 @@ function formatDoctorHealth(result) {
3286
3547
  const warnings = result.entries.filter((entry) => entry.level === "warn").length;
3287
3548
  return warnings > 0 ? `setup works, with ${counted(warnings, "warning")} to read` : "setup looks healthy";
3288
3549
  }
3289
- async function doctor(cfg) {
3550
+ function createReport(cfg) {
3290
3551
  const entries = [];
3291
- const ok = (name, message) => entries.push({
3292
- level: "ok",
3293
- check: name,
3294
- message
3295
- });
3296
- const warn = (name, message, fix) => entries.push({
3297
- level: "warn",
3298
- check: name,
3299
- message,
3300
- fix
3301
- });
3302
- const error = (name, message, fix) => entries.push({
3303
- level: "error",
3304
- check: name,
3305
- message,
3306
- fix
3307
- });
3308
- const rel = (path) => relative(cfg.root, path).replaceAll("\\", "/");
3552
+ return {
3553
+ entries,
3554
+ ok: (name, message) => void entries.push({
3555
+ level: "ok",
3556
+ check: name,
3557
+ message
3558
+ }),
3559
+ warn: (name, message, fix) => void entries.push({
3560
+ level: "warn",
3561
+ check: name,
3562
+ message,
3563
+ fix
3564
+ }),
3565
+ error: (name, message, fix) => void entries.push({
3566
+ level: "error",
3567
+ check: name,
3568
+ message,
3569
+ fix
3570
+ }),
3571
+ rel: (path) => relativePath(cfg.root, path)
3572
+ };
3573
+ }
3574
+ async function doctor(cfg) {
3575
+ const report = createReport(cfg);
3576
+ const { ok } = report;
3577
+ const configFile = checkSetup(report, cfg);
3578
+ const { catalogs, catalogsHealthy, source } = checkCatalogs(report, cfg);
3579
+ checkRouting(report, cfg, configFile);
3580
+ const host = checkPlugin(report, cfg);
3581
+ const scanning = cfg.include.length > 0;
3582
+ if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
3583
+ const registry = await extractProject(cfg);
3584
+ const messages = registry.messages();
3585
+ if (source && scanning) checkTypes(report, cfg, host, catalogs, registry, source);
3586
+ if (scanning) await checkSources(report, cfg, registry, messages);
3587
+ if (source && scanning) checkOrphans(report, source, registry, messages);
3588
+ if (catalogsHealthy) checkBundle(report, cfg, catalogs, registry);
3589
+ const state = checkState(report, cfg, catalogs, catalogsHealthy);
3590
+ if (catalogsHealthy) mirrorGate(report, cfg, catalogs, registry, state, scanning);
3591
+ return {
3592
+ ok: report.entries.every((entry) => entry.level !== "error"),
3593
+ entries: report.entries
3594
+ };
3595
+ }
3596
+ function checkSetup(report, cfg) {
3597
+ const { ok, warn } = report;
3309
3598
  const configFile = findConfigFile(cfg.root);
3310
3599
  if (configFile) ok("config", `${configFile} found`);
3311
3600
  else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
3312
3601
  if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
3313
3602
  else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
3603
+ return configFile;
3604
+ }
3605
+ function checkCatalogs(report, cfg) {
3606
+ const { ok, warn, error, rel } = report;
3314
3607
  const catalogs = emptyCatalog();
3315
3608
  let catalogsHealthy = true;
3316
3609
  if (!existsSync(cfg.dir)) {
@@ -3354,7 +3647,15 @@ async function doctor(cfg) {
3354
3647
  }
3355
3648
  const source = catalogs[cfg.sourceLocale];
3356
3649
  if (source && Object.keys(source).length === 0) warn("source", `source catalog ${cfg.sourceLocale}.json is empty`, "write your first t`…` message and run `npx verbaly extract`");
3357
- const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
3650
+ return {
3651
+ catalogs,
3652
+ catalogsHealthy,
3653
+ source
3654
+ };
3655
+ }
3656
+ function checkRouting(report, cfg, configFile) {
3657
+ const { ok, warn } = report;
3658
+ const mirrors = Object.keys(cfg.render).length > 0;
3358
3659
  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");
3359
3660
  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");
3360
3661
  else {
@@ -3366,80 +3667,89 @@ async function doctor(cfg) {
3366
3667
  ok("routing", `${astro.mode}${how}: ${ROUTING_SAYS[astro.mode]}`);
3367
3668
  } else {
3368
3669
  const how = named ? "" : " (from your setup, no routing set)";
3369
- ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
3370
- }
3371
- }
3372
- const deps = readDependencies(cfg.root);
3373
- const host = detectHost(cfg.root);
3374
- const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
3375
- if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
3376
- else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
3377
- else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
3378
- const scanning = cfg.include.length > 0;
3379
- if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
3380
- if (source && scanning && cfg.dts !== false) {
3381
- const dtsPath = cfg.dts;
3382
- const shown = rel(dtsPath);
3383
- const regenerate = host?.name === "astro" ? "run `npx astro sync`, which writes the types and links them" : host?.name === "nuxt" ? "run `npx nuxi prepare`, which writes the types and links them" : "run `npx verbaly typegen`";
3384
- const expected = generateDts(source, projectDtsOptions(cfg));
3385
- if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
3386
- else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
3387
- else ok("types", `${shown} is up to date`);
3388
- if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
3389
- const state = typesIncluded(cfg.root, dtsPath);
3390
- if (state === "missing" || state === "unreadable") warn("types", state === "missing" ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types` : `tsconfig.json could not be read, so it may not include ${shown}`, `run \`npx verbaly typegen\`, which adds the line, or add "${shown}" to include`);
3391
- }
3392
- const old = join(cfg.root, "verbaly.d.ts");
3393
- if (dtsPath !== old && existsSync(old) && readFileSync(old, "utf8").startsWith("// generated by verbaly: do not edit")) warn("types", `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`, "run `npx verbaly typegen`, which removes it");
3394
- }
3395
- const registry = await extractProject(cfg);
3396
- if (scanning) {
3397
- const unreadable = registry.parseErrors();
3398
- if (unreadable.length > 0) {
3399
- const first = unreadable[0];
3400
- warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
3401
- }
3402
- const outside = await filesOutsideInclude(cfg);
3403
- if (outside.length > 0) {
3404
- const files = outside.map((entry) => rel(entry.file));
3405
- const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
3406
- warn("sources", `t\`…\` is written in ${counted(outside.length, "file")} outside include, and those texts are never extracted or translated (${preview(files)})`, `add ${patterns.join(" and ")} to include in your verbaly config, or the files to exclude if they are not app code`);
3407
- }
3408
- const stray = registry.strayImports();
3409
- if (stray.length > 0) {
3410
- const files = [...new Set(stray.map((entry) => rel(entry.file)))];
3411
- error("imports", `t is imported from a verbaly package, which never exports it, in ${counted(files.length, "file")} (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from verbaly/app");
3412
- }
3413
- const missed = registry.missed();
3414
- if (missed.length > 0) {
3415
- const first = missed[0];
3416
- warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
3417
- }
3418
- const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
3419
- if (positional.length > 0) {
3420
- const first = positional[0];
3421
- warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
3670
+ ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
3422
3671
  }
3423
- const escaped = [...registry.messages().values()].map((msg) => ({
3424
- file: rel(msg.file),
3425
- slice: escapedSyntax(msg.message)
3426
- })).filter((entry) => entry.slice !== void 0);
3427
- if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${shownSlice(escaped[0].slice)})`, `in a tagged template, write ${inlineBlock(escaped[0].slice)}`);
3428
- }
3429
- if (source && scanning) {
3430
- const extracted = registry.messages();
3431
- const used = registry.usedKeys();
3432
- const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
3433
- const unread = registry.parseErrors().length > 0;
3434
- if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
3435
- else ok("orphans", "no orphan keys");
3436
3672
  }
3437
- const excluded = cfg.bundle.exclude ?? [];
3438
- if (excluded.length > 0 && catalogsHealthy) {
3439
- const issues = auditBundle(cfg, catalogs, registry);
3440
- for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
3441
- if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
3673
+ }
3674
+ function checkPlugin(report, cfg) {
3675
+ const { ok, warn } = report;
3676
+ const deps = readDependencies(cfg.root);
3677
+ const host = detectHost(cfg.root);
3678
+ const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
3679
+ if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
3680
+ else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
3681
+ else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
3682
+ return host;
3683
+ }
3684
+ function checkTypes(report, cfg, host, catalogs, registry, source) {
3685
+ const { ok, warn, rel } = report;
3686
+ if (cfg.dts === false) return;
3687
+ const dtsPath = cfg.dts;
3688
+ const shown = rel(dtsPath);
3689
+ const regenerate = host?.name === "astro" ? "run `npx astro sync`, which writes the types and links them" : host?.name === "nuxt" ? "run `npx nuxi prepare`, which writes the types and links them" : "run `npx verbaly typegen`";
3690
+ const expected = generateDts(shippedCatalogs(cfg, catalogs, registry)[cfg.sourceLocale] ?? source, projectDtsOptions(cfg));
3691
+ if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
3692
+ else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
3693
+ else ok("types", `${shown} is up to date`);
3694
+ if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
3695
+ const state = typesIncluded(cfg.root, dtsPath);
3696
+ if (state === "missing" || state === "unreadable") warn("types", state === "missing" ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types` : `tsconfig.json could not be read, so it may not include ${shown}`, `run \`npx verbaly typegen\`, which adds the line, or add "${shown}" to include`);
3442
3697
  }
3698
+ const old = join(cfg.root, "verbaly.d.ts");
3699
+ if (dtsPath !== old && existsSync(old) && readFileSync(old, "utf8").startsWith("// generated by verbaly: do not edit")) warn("types", `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`, "run `npx verbaly typegen`, which removes it");
3700
+ }
3701
+ async function checkSources(report, cfg, registry, messages) {
3702
+ const { warn, error, rel } = report;
3703
+ const unreadable = registry.parseErrors();
3704
+ if (unreadable.length > 0) {
3705
+ const first = unreadable[0];
3706
+ warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
3707
+ }
3708
+ const outside = await filesOutsideInclude(cfg);
3709
+ if (outside.length > 0) {
3710
+ const files = outside.map((entry) => rel(entry.file));
3711
+ const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
3712
+ warn("sources", `t\`…\` is written in ${counted(outside.length, "file")} outside include, and those texts are never extracted or translated (${preview(files)})`, `add ${patterns.join(" and ")} to include in your verbaly config, or the files to exclude if they are not app code`);
3713
+ }
3714
+ const stray = registry.strayImports();
3715
+ if (stray.length > 0) {
3716
+ const files = [...new Set(stray.map((entry) => rel(entry.file)))];
3717
+ error("imports", `t is imported from a verbaly package, which never exports it, in ${counted(files.length, "file")} (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from verbaly/app");
3718
+ }
3719
+ const missed = registry.missed();
3720
+ if (missed.length > 0) {
3721
+ const first = missed[0];
3722
+ warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
3723
+ }
3724
+ const positional = [...messages.values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
3725
+ if (positional.length > 0) {
3726
+ const first = positional[0];
3727
+ warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
3728
+ }
3729
+ const escaped = [...messages.values()].map((msg) => ({
3730
+ file: rel(msg.file),
3731
+ slice: escapedSyntax(msg.message)
3732
+ })).filter((entry) => entry.slice !== void 0);
3733
+ if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${shownSlice(escaped[0].slice)})`, `in a tagged template, write ${inlineBlock(escaped[0].slice)}`);
3734
+ }
3735
+ function checkOrphans(report, source, registry, extracted) {
3736
+ const { ok, warn } = report;
3737
+ const used = registry.usedKeys();
3738
+ const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
3739
+ const unread = registry.parseErrors().length > 0;
3740
+ if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
3741
+ else ok("orphans", "no orphan keys");
3742
+ }
3743
+ function checkBundle(report, cfg, catalogs, registry) {
3744
+ const { ok, warn } = report;
3745
+ const excluded = cfg.bundle.exclude ?? [];
3746
+ if (excluded.length === 0) return;
3747
+ const issues = auditBundle(cfg, catalogs, registry);
3748
+ for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
3749
+ if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
3750
+ }
3751
+ function checkState(report, cfg, catalogs, catalogsHealthy) {
3752
+ const { warn } = report;
3443
3753
  const { state, problem, conflict } = readState(cfg);
3444
3754
  if (problem) warn("state", problem, conflict ? "resolve it by hand, keeping the entries of both sides: taking one side approves the drafts of the other" : `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
3445
3755
  else if (conflict) warn("state", `${STATE_FILE} has a merge conflict, and both sides were read`, "run `npx verbaly extract`, which writes both sides into it, then commit it");
@@ -3450,42 +3760,40 @@ async function doctor(cfg) {
3450
3760
  });
3451
3761
  if (stale.length > 0) warn("drafts", `${STATE_FILE} lists ${counted(stale.length, "draft")} whose translation is gone (${preview(stale)})`, "run `npx verbaly extract`, which drops them");
3452
3762
  }
3453
- if (catalogsHealthy) {
3454
- const result = check(cfg, catalogs, registry, state.fingerprints);
3455
- if (result.unknown.length > 0) error("keys", `${counted(result.unknown.length, "unknown key")} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
3456
- if (result.missing.length > 0) {
3457
- const locales = [...new Set(result.missing.map((m) => m.locale))];
3458
- warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
3459
- }
3460
- const broken = result.broken.filter((entry) => entry.severity === "error");
3461
- if (broken.length > 0) {
3462
- const locales = [...new Set(broken.map((b) => b.locale))];
3463
- error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
3464
- }
3465
- if (result.extra.length > 0) {
3466
- const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);
3467
- warn("extras", `a translation has ${counted(result.extra.length, "key")} the source catalog does not (${preview(shown)})`, scanning ? "add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest" : "add them to the source catalog if your code uses them, or delete them from the translations");
3468
- }
3469
- const warnings = result.broken.filter((entry) => entry.severity === "warning");
3470
- if (warnings.length > 0) warn("translations", `${counted(warnings.length, "structural warning")} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
3471
- if (result.collisions.length > 0) {
3472
- const first = result.collisions[0];
3473
- error("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
3474
- }
3475
- if (result.divergent.length > 0) {
3476
- const first = result.divergent[0];
3477
- warn("source texts", `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, "text")}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`, "edit those texts in the code; `npx verbaly extract` writes them into the catalog");
3478
- }
3479
- if (result.outdated.length > 0) {
3480
- const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
3481
- warn("outdated", `${counted(result.outdated.length, "translation")} written for an older source text (${preview(shown)})`, "update them, or keep them with `npx verbaly review --approve`");
3482
- }
3483
- if (result.ok) ok("translations", "all translations complete");
3763
+ return state;
3764
+ }
3765
+ function mirrorGate(report, cfg, catalogs, registry, state, scanning) {
3766
+ const { ok, warn, error } = report;
3767
+ const result = check(cfg, catalogs, registry, state.fingerprints);
3768
+ if (result.unknown.length > 0) error("keys", `${counted(result.unknown.length, "unknown key")} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
3769
+ if (result.missing.length > 0) {
3770
+ const locales = [...new Set(result.missing.map((m) => m.locale))];
3771
+ warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
3484
3772
  }
3485
- return {
3486
- ok: entries.every((entry) => entry.level !== "error"),
3487
- entries
3488
- };
3773
+ const broken = result.broken.filter((entry) => entry.severity === "error");
3774
+ if (broken.length > 0) {
3775
+ const locales = [...new Set(broken.map((b) => b.locale))];
3776
+ error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
3777
+ }
3778
+ if (result.extra.length > 0) {
3779
+ const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);
3780
+ warn("extras", `a translation has ${counted(result.extra.length, "key")} the source catalog does not (${preview(shown)})`, scanning ? "add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest" : "add them to the source catalog if your code uses them, or delete them from the translations");
3781
+ }
3782
+ const warnings = result.broken.filter((entry) => entry.severity === "warning");
3783
+ if (warnings.length > 0) warn("translations", `${counted(warnings.length, "structural warning")} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
3784
+ if (result.collisions.length > 0) {
3785
+ const first = result.collisions[0];
3786
+ error("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
3787
+ }
3788
+ if (result.divergent.length > 0) {
3789
+ const first = result.divergent[0];
3790
+ warn("source texts", `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, "text")}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`, "edit those texts in the code; `npx verbaly extract` writes them into the catalog");
3791
+ }
3792
+ if (result.outdated.length > 0) {
3793
+ const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
3794
+ warn("outdated", `${counted(result.outdated.length, "translation")} written for an older source text (${preview(shown)})`, "update them, or keep them with `npx verbaly review --approve`");
3795
+ }
3796
+ if (result.ok) ok("translations", "all translations complete");
3489
3797
  }
3490
3798
  function preview(keys) {
3491
3799
  const head = keys.slice(0, PREVIEW).join(", ");
@@ -3507,222 +3815,6 @@ async function doctorCommand(cfg) {
3507
3815
  process.exitCode = 1;
3508
3816
  }
3509
3817
  }
3510
- // src/exchange/inline.ts
3511
- const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
3512
- const BREAK = /^(?:br|wbr)$/;
3513
- function messageToInline(text) {
3514
- return renderParts(parseParts(text, 0).parts, /* @__PURE__ */ new Map());
3515
- }
3516
- function inlineToMessage(xml) {
3517
- let out = "";
3518
- let text = "";
3519
- let i = 0;
3520
- const flush = () => {
3521
- out += unescapeXml(text);
3522
- text = "";
3523
- };
3524
- while (i < xml.length) {
3525
- if (xml[i] === "<") {
3526
- const slice = xml.slice(i);
3527
- const ph = /^<ph\b([^>]*?)\/\s*>/.exec(slice) ?? /^<ph\b([^>]*)>\s*<\/ph\s*>/.exec(slice);
3528
- if (ph) {
3529
- flush();
3530
- out += attr(ph[1], "disp") ?? `{${attr(ph[1], "id") ?? "ph"}}`;
3531
- i += ph[0].length;
3532
- continue;
3533
- }
3534
- const pc = /^<pc\b([^>]*)>/.exec(slice);
3535
- if (pc) {
3536
- const close = findPcClose(xml, i + pc[0].length);
3537
- if (close) {
3538
- flush();
3539
- const id = attr(pc[1], "id") ?? "pc";
3540
- out += attr(pc[1], "dispStart") ?? `<${id}>`;
3541
- out += inlineToMessage(xml.slice(i + pc[0].length, close.innerEnd));
3542
- out += attr(pc[1], "dispEnd") ?? `</${id}>`;
3543
- i = close.end;
3544
- continue;
3545
- }
3546
- }
3547
- }
3548
- text += xml[i];
3549
- i += 1;
3550
- }
3551
- flush();
3552
- return out;
3553
- }
3554
- function escapeXml(text) {
3555
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
3556
- }
3557
- function unescapeXml(text) {
3558
- return text.replace(/&(lt|gt|amp|quot|apos|#x?[0-9a-fA-F]+);/g, (_, entity) => {
3559
- if (entity === "lt") return "<";
3560
- if (entity === "gt") return ">";
3561
- if (entity === "amp") return "&";
3562
- if (entity === "quot") return "\"";
3563
- if (entity === "apos") return "'";
3564
- const code = entity.startsWith("#x") ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);
3565
- return String.fromCodePoint(code);
3566
- });
3567
- }
3568
- function parseParts(text, pos, closeTag) {
3569
- const parts = [];
3570
- let plain = "";
3571
- const flush = () => {
3572
- if (plain) parts.push({
3573
- kind: "text",
3574
- text: plain
3575
- });
3576
- plain = "";
3577
- };
3578
- let i = pos;
3579
- while (i < text.length) {
3580
- const pair = text[i] + (text[i + 1] ?? "");
3581
- if (pair === "{{" || pair === "}}") {
3582
- plain += pair;
3583
- i += 2;
3584
- continue;
3585
- }
3586
- if (text[i] === "{") {
3587
- const end = matchBrace$1(text, i);
3588
- if (end === -1) {
3589
- plain += "{";
3590
- i += 1;
3591
- continue;
3592
- }
3593
- const src = text.slice(i, end + 1);
3594
- if (hasTopLevelPipe(src)) plain += src;
3595
- else {
3596
- flush();
3597
- parts.push({
3598
- kind: "ph",
3599
- name: paramName(src),
3600
- src
3601
- });
3602
- }
3603
- i = end + 1;
3604
- continue;
3605
- }
3606
- if (text[i] === "<") {
3607
- if (closeTag && text.startsWith(`</${closeTag}>`, i)) {
3608
- flush();
3609
- return {
3610
- parts,
3611
- end: i + closeTag.length + 3,
3612
- closed: true
3613
- };
3614
- }
3615
- const open = OPEN_TAG.exec(text.slice(i));
3616
- if (open) {
3617
- const [openSrc, name, selfClose] = open;
3618
- if (selfClose || BREAK.test(name)) {
3619
- flush();
3620
- parts.push({
3621
- kind: "ph",
3622
- name: idSafe(name),
3623
- src: openSrc
3624
- });
3625
- i += openSrc.length;
3626
- continue;
3627
- }
3628
- const inner = parseParts(text, i + openSrc.length, name);
3629
- if (inner.closed) {
3630
- flush();
3631
- parts.push({
3632
- kind: "pc",
3633
- name: idSafe(name),
3634
- openSrc,
3635
- closeSrc: `</${name}>`,
3636
- children: inner.parts
3637
- });
3638
- i = inner.end;
3639
- continue;
3640
- }
3641
- }
3642
- plain += "<";
3643
- i += 1;
3644
- continue;
3645
- }
3646
- plain += text[i];
3647
- i += 1;
3648
- }
3649
- flush();
3650
- return {
3651
- parts,
3652
- end: i,
3653
- closed: false
3654
- };
3655
- }
3656
- function matchBrace$1(text, start) {
3657
- let depth = 0;
3658
- for (let i = start; i < text.length; i++) {
3659
- const pair = text[i] + (text[i + 1] ?? "");
3660
- if (pair === "{{" || pair === "}}") {
3661
- i += 1;
3662
- continue;
3663
- }
3664
- if (text[i] === "{") depth += 1;
3665
- else if (text[i] === "}") {
3666
- depth -= 1;
3667
- if (depth === 0) return i;
3668
- }
3669
- }
3670
- return -1;
3671
- }
3672
- function hasTopLevelPipe(src) {
3673
- let depth = 0;
3674
- for (let i = 0; i < src.length; i++) {
3675
- const pair = src[i] + (src[i + 1] ?? "");
3676
- if (pair === "{{" || pair === "}}" || pair === "||") {
3677
- i += 1;
3678
- continue;
3679
- }
3680
- if (src[i] === "{") depth += 1;
3681
- else if (src[i] === "}") depth -= 1;
3682
- else if (src[i] === "|" && depth === 1) return true;
3683
- }
3684
- return false;
3685
- }
3686
- function paramName(src) {
3687
- const name = /^\{\s*([^{}|:\s]+)/.exec(src)?.[1];
3688
- return name ? idSafe(name) : "ph";
3689
- }
3690
- function idSafe(name) {
3691
- return name.replace(/[^a-zA-Z0-9._-]/g, "_") || "ph";
3692
- }
3693
- function renderParts(parts, taken) {
3694
- let out = "";
3695
- for (const part of parts) if (part.kind === "text") out += escapeXml(part.text);
3696
- else if (part.kind === "ph") out += `<ph id="${uniqueId(part.name, taken)}" disp="${escapeXml(part.src)}"/>`;
3697
- else {
3698
- const id = uniqueId(part.name, taken);
3699
- out += `<pc id="${id}" dispStart="${escapeXml(part.openSrc)}" dispEnd="${escapeXml(part.closeSrc)}">`;
3700
- out += renderParts(part.children, taken);
3701
- out += "</pc>";
3702
- }
3703
- return out;
3704
- }
3705
- function uniqueId(name, taken) {
3706
- const count = taken.get(name) ?? 0;
3707
- taken.set(name, count + 1);
3708
- return count === 0 ? name : `${name}${count + 1}`;
3709
- }
3710
- function findPcClose(xml, from) {
3711
- const tags = /<pc\b[^>]*>|<\/pc\s*>/g;
3712
- tags.lastIndex = from;
3713
- let depth = 1;
3714
- for (let match = tags.exec(xml); match; match = tags.exec(xml)) {
3715
- depth += match[0].startsWith("</") ? -1 : 1;
3716
- if (depth === 0) return {
3717
- innerEnd: match.index,
3718
- end: tags.lastIndex
3719
- };
3720
- }
3721
- }
3722
- function attr(attrs, name) {
3723
- const value = new RegExp(`\\b${name}\\s*=\\s*"([^"]*)"`).exec(attrs)?.[1];
3724
- return value === void 0 ? void 0 : unescapeXml(value);
3725
- }
3726
3818
  // src/exchange/mobile.ts
3727
3819
  function androidValuesDir(locale, sourceLocale) {
3728
3820
  if (locale === sourceLocale) return "values";
@@ -3739,7 +3831,7 @@ function toAndroidXml(entries) {
3739
3831
  ...entries.map(({ key, text }) => {
3740
3832
  const name = androidName(key);
3741
3833
  const clash = names.get(name);
3742
- if (clash !== void 0) throw new Error(`[verbaly] android-xml: keys "${clash}" and "${key}" both become resource name "${name}", rename one of them.`);
3834
+ if (clash !== void 0) throw new Error(`[verbaly] android-xml: keys "${clash}" and "${key}" both become resource name "${name}", rename one of them`);
3743
3835
  names.set(name, key);
3744
3836
  return ` <string name="${name}">${androidText(text)}</string>`;
3745
3837
  }),
@@ -3761,6 +3853,76 @@ function androidText(text) {
3761
3853
  function iosText(text) {
3762
3854
  return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
3763
3855
  }
3856
+ // src/exchange/csv.ts
3857
+ function toCsv(entries) {
3858
+ return [
3859
+ "key,source,target,location",
3860
+ ...entries.map(({ key, source, target, location }) => `${csvField(key)},${csvField(source)},${csvField(target)},${csvField(location?.join("; ") ?? "")}`),
3861
+ ""
3862
+ ].join("\r\n");
3863
+ }
3864
+ function csvField(text) {
3865
+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
3866
+ }
3867
+ function parseCsv(content) {
3868
+ const rows = csvRows(content, csvSeparator(content));
3869
+ const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
3870
+ const keyCol = header.indexOf("key");
3871
+ const targetCol = header.indexOf("target");
3872
+ const sourceCol = header.indexOf("source");
3873
+ if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns");
3874
+ const entries = emptyCatalog();
3875
+ const sources = emptyCatalog();
3876
+ for (const row of rows.slice(1)) {
3877
+ const key = row[keyCol];
3878
+ if (!key) continue;
3879
+ entries[key] = row[targetCol] ?? "";
3880
+ const source = sourceCol === -1 ? void 0 : row[sourceCol];
3881
+ if (source) sources[key] = source;
3882
+ }
3883
+ return {
3884
+ entries,
3885
+ sources
3886
+ };
3887
+ }
3888
+ function csvSeparator(content) {
3889
+ let quoted = false;
3890
+ const seen = /* @__PURE__ */ new Set();
3891
+ for (const char of content) if (char === "\"") quoted = !quoted;
3892
+ else if (!quoted && (char === "\n" || char === "\r")) break;
3893
+ else if (!quoted) seen.add(char);
3894
+ return seen.has(",") ? "," : seen.has(";") ? ";" : seen.has(" ") ? " " : ",";
3895
+ }
3896
+ function csvRows(content, separator) {
3897
+ const rows = [];
3898
+ let row = [];
3899
+ let field = "";
3900
+ let quoted = false;
3901
+ for (let i = 0; i < content.length; i++) {
3902
+ const char = content[i];
3903
+ if (quoted) {
3904
+ if (char === "\"") {
3905
+ if (content[i + 1] === "\"") {
3906
+ field += "\"";
3907
+ i++;
3908
+ } else quoted = false;
3909
+ } else field += char;
3910
+ } else if (char === "\"") quoted = true;
3911
+ else if (char === separator) {
3912
+ row.push(field);
3913
+ field = "";
3914
+ } else if (char === "\n" || char === "\r") {
3915
+ if (char === "\r" && content[i + 1] === "\n") i++;
3916
+ row.push(field);
3917
+ field = "";
3918
+ if (row.some((cell) => cell !== "")) rows.push(row);
3919
+ row = [];
3920
+ } else field += char;
3921
+ }
3922
+ row.push(field);
3923
+ if (row.some((cell) => cell !== "")) rows.push(row);
3924
+ return rows;
3925
+ }
3764
3926
  // src/exchange/po.ts
3765
3927
  function toPo(sourceLocale, locale, entries) {
3766
3928
  return [
@@ -3784,8 +3946,8 @@ function toPo(sourceLocale, locale, entries) {
3784
3946
  ].join("\n\n");
3785
3947
  }
3786
3948
  function parsePo(content) {
3787
- const entries = Object.create(null);
3788
- const sources = Object.create(null);
3949
+ const entries = emptyCatalog();
3950
+ const sources = emptyCatalog();
3789
3951
  let locale;
3790
3952
  let msgctxt;
3791
3953
  let msgid;
@@ -3803,7 +3965,7 @@ function parsePo(content) {
3803
3965
  msgctxt = msgid = msgstr = field = void 0;
3804
3966
  fuzzy = false;
3805
3967
  };
3806
- for (const raw of content.replace(/^\uFEFF/, "").split(/\r\n|[\r\n]/)) {
3968
+ for (const raw of stripBom(content).split(/\r\n|[\r\n]/)) {
3807
3969
  const line = raw.trim();
3808
3970
  if (line === "") {
3809
3971
  finish();
@@ -3856,214 +4018,331 @@ function poUnquote(text) {
3856
4018
  return ch;
3857
4019
  });
3858
4020
  }
3859
- // src/exchange/translate.ts
3860
- const RETRY_STATUS = /* @__PURE__ */ new Set([
3861
- 408,
3862
- 409,
3863
- 425,
3864
- 429,
3865
- 500,
3866
- 502,
3867
- 503,
3868
- 504,
3869
- 529
3870
- ]);
3871
- function retryable(error) {
3872
- const status = error?.status;
3873
- const code = error?.statusCode;
3874
- const value = typeof status === "number" ? status : code;
3875
- return typeof value === "number" ? RETRY_STATUS.has(value) : true;
3876
- }
3877
- function reason(error) {
3878
- return error instanceof Error ? error.message : String(error);
3879
- }
3880
- const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
3881
- async function attempt(run, retries, delay) {
3882
- for (let round = 0;; round++) try {
3883
- return await run();
3884
- } catch (error) {
3885
- if (round >= retries || !retryable(error)) throw error;
3886
- await wait(delay * 2 ** round);
4021
+ // src/util/markup.ts
4022
+ const NAME$1 = `[^\\s=/"'<>]+`;
4023
+ const ATTRIBUTE = new RegExp(`(${NAME$1})(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`, "g");
4024
+ const ATTRIBUTE_NAME = new RegExp(`^${NAME$1}$`);
4025
+ const TAG_REST = `(?:"[^"]*"|'[^']*'|[^"'>])*`;
4026
+ function isAttributeName(name) {
4027
+ return ATTRIBUTE_NAME.test(name);
4028
+ }
4029
+ function readAttributes(chunk, lowerCase = false) {
4030
+ const attributes = /* @__PURE__ */ new Map();
4031
+ ATTRIBUTE.lastIndex = 0;
4032
+ let match;
4033
+ while ((match = ATTRIBUTE.exec(chunk)) !== null) {
4034
+ const name = lowerCase ? match[1].toLowerCase() : match[1];
4035
+ if (attributes.has(name)) continue;
4036
+ const quoted = match[2] ?? match[3];
4037
+ const value = quoted ?? match[4] ?? "";
4038
+ const end = match.index + match[0].length;
4039
+ const written = quoted !== void 0 ? value.length + 2 : value.length;
4040
+ attributes.set(name, {
4041
+ value,
4042
+ start: end - written,
4043
+ end
4044
+ });
3887
4045
  }
4046
+ return attributes;
3888
4047
  }
3889
- async function pooled(jobs, limit, run) {
3890
- let next = 0;
3891
- const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
3892
- while (next < jobs.length) await run(jobs[next++]);
4048
+ const ENTITY = /&(?:(lt|gt|amp|quot|apos)|#(\d+)|#[xX]([0-9a-fA-F]+));/g;
4049
+ const NAMED = {
4050
+ lt: "<",
4051
+ gt: ">",
4052
+ amp: "&",
4053
+ quot: "\"",
4054
+ apos: "'"
4055
+ };
4056
+ function decodeEntities(text) {
4057
+ return text.replace(ENTITY, (whole, name, decimal, hex) => {
4058
+ if (name) return NAMED[name];
4059
+ const code = decimal ? parseInt(decimal, 10) : parseInt(hex, 16);
4060
+ return code <= 1114111 ? String.fromCodePoint(code) : whole;
3893
4061
  });
3894
- await Promise.all(workers);
3895
4062
  }
3896
- async function translateCatalogs(cfg, catalogs, provider, options = {}) {
3897
- const batchSize = options.batchSize ?? 20;
3898
- const concurrency = Math.max(1, options.concurrency ?? 4);
3899
- const retries = Math.max(0, options.retries ?? 2);
3900
- const retryDelay = options.retryDelay ?? 500;
3901
- const targets = targetLocales(cfg, options.locales);
3902
- const source = catalogs[cfg.sourceLocale] ?? {};
3903
- const result = {
3904
- translated: emptyCatalog(),
3905
- invalid: emptyCatalog(),
3906
- pending: emptyCatalog(),
3907
- failed: []
3908
- };
3909
- const jobs = [];
3910
- for (const locale of targets) {
3911
- const catalog = catalogs[locale] ??= emptyCatalog();
3912
- const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
3913
- if (missing.length === 0) continue;
3914
- if (options.dryRun) {
3915
- result.pending[locale] = missing;
3916
- continue;
4063
+ // src/exchange/inline.ts
4064
+ const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
4065
+ const PH_EMPTY = new RegExp(`^<ph\\b(${TAG_REST}?)/\\s*>`);
4066
+ const PH_PAIRED = new RegExp(`^<ph\\b(${TAG_REST})>\\s*</ph\\s*>`);
4067
+ const PC_OPEN = new RegExp(`^<pc\\b(${TAG_REST})>`);
4068
+ const PC_TAGS = `<pc\\b${TAG_REST}>|</pc\\s*>`;
4069
+ const BREAK = /^(?:br|wbr)$/;
4070
+ const VERBALY = {
4071
+ escape: (text, at) => text.startsWith("{{", at) || text.startsWith("}}", at) ? 2 : 0,
4072
+ translatable: hasTopLevelPipe
4073
+ };
4074
+ const ICU_BLOCK = /^\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select)\b/;
4075
+ const ICU = {
4076
+ escape(text, at) {
4077
+ if (text[at] !== "'") return 0;
4078
+ if (text[at + 1] === "'") return 2;
4079
+ if (!"{}#|".includes(text[at + 1] ?? " ")) return 0;
4080
+ for (let end = at + 1; end < text.length; end++) {
4081
+ if (text[end] !== "'") continue;
4082
+ if (text[end + 1] === "'") end += 1;
4083
+ else return end - at + 1;
3917
4084
  }
3918
- const batches = Math.ceil(missing.length / batchSize);
3919
- for (let i = 0; i < missing.length; i += batchSize) {
3920
- const index = Math.floor(i / batchSize) + 1;
3921
- jobs.push({
3922
- locale,
3923
- index,
3924
- batches,
3925
- keys: missing.slice(i, i + batchSize)
3926
- });
4085
+ return text.length - at;
4086
+ },
4087
+ translatable: (src) => ICU_BLOCK.test(src)
4088
+ };
4089
+ function messageToInline(text) {
4090
+ return renderParts(parseParts(text, 0, isIcu(text) ? ICU : VERBALY).parts, /* @__PURE__ */ new Map());
4091
+ }
4092
+ function inlineToMessage(xml) {
4093
+ let out = "";
4094
+ let text = "";
4095
+ let i = 0;
4096
+ const flush = () => {
4097
+ out += decodeEntities(text);
4098
+ text = "";
4099
+ };
4100
+ while (i < xml.length) {
4101
+ if (xml[i] === "<") {
4102
+ const slice = xml.slice(i);
4103
+ const ph = PH_EMPTY.exec(slice) ?? PH_PAIRED.exec(slice);
4104
+ if (ph) {
4105
+ flush();
4106
+ const attrs = readAttributes(ph[1]);
4107
+ out += attr(attrs, "disp") ?? `{${attr(attrs, "id") ?? "ph"}}`;
4108
+ i += ph[0].length;
4109
+ continue;
4110
+ }
4111
+ const pc = PC_OPEN.exec(slice);
4112
+ if (pc) {
4113
+ const close = findPcClose(xml, i + pc[0].length);
4114
+ if (close) {
4115
+ flush();
4116
+ const attrs = readAttributes(pc[1]);
4117
+ const id = attr(attrs, "id") ?? "pc";
4118
+ out += attr(attrs, "dispStart") ?? `<${id}>`;
4119
+ out += inlineToMessage(xml.slice(i + pc[0].length, close.innerEnd));
4120
+ out += attr(attrs, "dispEnd") ?? `</${id}>`;
4121
+ i = close.end;
4122
+ continue;
4123
+ }
4124
+ }
3927
4125
  }
4126
+ text += xml[i];
4127
+ i += 1;
3928
4128
  }
3929
- await pooled(jobs, concurrency, async (job) => {
3930
- const { locale, keys } = job;
3931
- const catalog = catalogs[locale];
3932
- const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
3933
- const origins = options.origins ? Object.fromEntries(keys.filter((key) => Object.hasOwn(options.origins, key)).map((key) => [key, options.origins[key]])) : void 0;
3934
- let out;
3935
- try {
3936
- out = await attempt(() => provider({
3937
- sourceLocale: cfg.sourceLocale,
3938
- targetLocale: locale,
3939
- messages,
3940
- origins,
3941
- instructions: cfg.translate.instructions,
3942
- glossary: glossaryFor(cfg, locale, messages)
3943
- }), retries, retryDelay);
3944
- } catch (error) {
3945
- const message = reason(error);
3946
- result.failed.push({
3947
- locale,
3948
- keys,
3949
- error: message
3950
- });
3951
- options.onProgress?.({
3952
- ...progressOf(job),
3953
- error: message
3954
- });
3955
- return;
3956
- }
3957
- for (const key of keys) {
3958
- const text = out[key];
3959
- if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
3960
- catalog[key] = text;
3961
- (result.translated[locale] ??= []).push(key);
3962
- } else (result.invalid[locale] ??= []).push(key);
3963
- }
3964
- options.onProgress?.(progressOf(job));
3965
- });
3966
- for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
3967
- for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
3968
- result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));
3969
- return result;
3970
- }
3971
- function compare(a, b) {
3972
- return byCodeUnit(a[0] ?? "", b[0] ?? "");
4129
+ flush();
4130
+ return out;
3973
4131
  }
3974
- function mergeTranslations(cfg, locale, translated, keys) {
3975
- const source = readCatalog(cfg, cfg.sourceLocale);
3976
- const current = readCatalog(cfg, locale);
3977
- const written = [];
3978
- for (const key of keys) {
3979
- const text = translated[key];
3980
- if (!source[key] || current[key] || !text) continue;
3981
- current[key] = text;
3982
- written.push(key);
3983
- }
3984
- if (written.length > 0) writeCatalog(cfg, locale, current);
3985
- return written;
4132
+ function escapeXml(text) {
4133
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
3986
4134
  }
3987
- function writeDrafts(cfg, locale, entries, options = {}) {
3988
- const targets = targetLocales(cfg);
3989
- if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
3990
- loadState(cfg);
3991
- const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
3992
- const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
3993
- const current = readCatalog(cfg, locale);
3994
- const result = {
3995
- written: [],
3996
- kept: [],
3997
- invalid: [],
3998
- unknown: []
4135
+ function parseParts(text, pos, syntax, closeTag) {
4136
+ const parts = [];
4137
+ let plain = "";
4138
+ const flush = () => {
4139
+ if (plain) parts.push({
4140
+ kind: "text",
4141
+ text: plain
4142
+ });
4143
+ plain = "";
4144
+ };
4145
+ let i = pos;
4146
+ while (i < text.length) {
4147
+ const escaped = syntax.escape(text, i);
4148
+ if (escaped > 0) {
4149
+ plain += text.slice(i, i + escaped);
4150
+ i += escaped;
4151
+ continue;
4152
+ }
4153
+ if (text[i] === "{") {
4154
+ const end = matchBrace$1(text, i, syntax);
4155
+ if (end === -1) {
4156
+ plain += "{";
4157
+ i += 1;
4158
+ continue;
4159
+ }
4160
+ const src = text.slice(i, end + 1);
4161
+ if (syntax.translatable(src)) plain += src;
4162
+ else {
4163
+ flush();
4164
+ parts.push({
4165
+ kind: "ph",
4166
+ name: paramName(src),
4167
+ src
4168
+ });
4169
+ }
4170
+ i = end + 1;
4171
+ continue;
4172
+ }
4173
+ if (text[i] === "<") {
4174
+ if (closeTag && text.startsWith(`</${closeTag}>`, i)) {
4175
+ flush();
4176
+ return {
4177
+ parts,
4178
+ end: i + closeTag.length + 3,
4179
+ closed: true
4180
+ };
4181
+ }
4182
+ const open = OPEN_TAG.exec(text.slice(i));
4183
+ if (open) {
4184
+ const [openSrc, name, selfClose] = open;
4185
+ if (selfClose || BREAK.test(name)) {
4186
+ flush();
4187
+ parts.push({
4188
+ kind: "ph",
4189
+ name: idSafe(name),
4190
+ src: openSrc
4191
+ });
4192
+ i += openSrc.length;
4193
+ continue;
4194
+ }
4195
+ const inner = parseParts(text, i + openSrc.length, syntax, name);
4196
+ if (inner.closed) {
4197
+ flush();
4198
+ parts.push({
4199
+ kind: "pc",
4200
+ name: idSafe(name),
4201
+ openSrc,
4202
+ closeSrc: `</${name}>`,
4203
+ children: inner.parts
4204
+ });
4205
+ i = inner.end;
4206
+ continue;
4207
+ }
4208
+ }
4209
+ plain += "<";
4210
+ i += 1;
4211
+ continue;
4212
+ }
4213
+ plain += text[i];
4214
+ i += 1;
4215
+ }
4216
+ flush();
4217
+ return {
4218
+ parts,
4219
+ end: i,
4220
+ closed: false
3999
4221
  };
4000
- for (const { key, text } of entries) {
4001
- const from = own(source, key);
4002
- if (!from) result.unknown.push(key);
4003
- else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);
4004
- else if (own(current, key) && !options.overwrite) result.kept.push(key);
4005
- else {
4006
- current[key] = text;
4007
- result.written.push(key);
4222
+ }
4223
+ function matchBrace$1(text, start, syntax) {
4224
+ let depth = 0;
4225
+ for (let i = start; i < text.length; i++) {
4226
+ const escaped = syntax.escape(text, i);
4227
+ if (escaped > 0) {
4228
+ i += escaped - 1;
4229
+ continue;
4230
+ }
4231
+ if (text[i] === "{") depth += 1;
4232
+ else if (text[i] === "}") {
4233
+ depth -= 1;
4234
+ if (depth === 0) return i;
4008
4235
  }
4009
4236
  }
4010
- if (result.written.length > 0) {
4011
- writeCatalog(cfg, locale, current);
4012
- recordTranslations(cfg, source, [{
4013
- locale,
4014
- entries: result.written.map((key) => ({
4015
- key,
4016
- text: current[key]
4017
- })),
4018
- draft: true
4019
- }]);
4237
+ return -1;
4238
+ }
4239
+ function hasTopLevelPipe(src) {
4240
+ let depth = 0;
4241
+ for (let i = 0; i < src.length; i++) {
4242
+ const pair = src[i] + (src[i + 1] ?? "");
4243
+ if (pair === "{{" || pair === "}}" || pair === "||") {
4244
+ i += 1;
4245
+ continue;
4246
+ }
4247
+ if (src[i] === "{") depth += 1;
4248
+ else if (src[i] === "}") depth -= 1;
4249
+ else if (src[i] === "|" && depth === 1) return true;
4020
4250
  }
4021
- return result;
4251
+ return false;
4022
4252
  }
4023
- function formatTranslateFailures(failed) {
4024
- const grouped = [];
4025
- for (const entry of failed) {
4026
- const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
4027
- if (same) same.keys = [...same.keys, ...entry.keys];
4028
- else grouped.push({
4029
- ...entry,
4030
- keys: [...entry.keys]
4031
- });
4253
+ function paramName(src) {
4254
+ const name = /^\{\s*([^{}|:,\s]+)/.exec(src)?.[1];
4255
+ return name ? idSafe(name) : "ph";
4256
+ }
4257
+ function idSafe(name) {
4258
+ return name.replace(/[^a-zA-Z0-9._-]/g, "_") || "ph";
4259
+ }
4260
+ function renderParts(parts, taken) {
4261
+ let out = "";
4262
+ for (const part of parts) if (part.kind === "text") out += escapeXml(part.text);
4263
+ else if (part.kind === "ph") out += `<ph id="${uniqueId(part.name, taken)}" disp="${escapeXml(part.src)}"/>`;
4264
+ else {
4265
+ const id = uniqueId(part.name, taken);
4266
+ out += `<pc id="${id}" dispStart="${escapeXml(part.openSrc)}" dispEnd="${escapeXml(part.closeSrc)}">`;
4267
+ out += renderParts(part.children, taken);
4268
+ out += "</pc>";
4032
4269
  }
4033
- return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
4270
+ return out;
4034
4271
  }
4035
- async function resolveProvider(cfg, model) {
4036
- const configured = cfg.translate.provider;
4037
- if (typeof configured === "function") return configured;
4038
- const { claudeProvider } = await import("./claude-XvHG5Neu.js");
4039
- return claudeProvider({ model: model ?? cfg.translate.model });
4272
+ function uniqueId(name, taken) {
4273
+ const count = taken.get(name) ?? 0;
4274
+ taken.set(name, count + 1);
4275
+ return count === 0 ? name : `${name}${count + 1}`;
4040
4276
  }
4041
- function structureMatches(source, translated) {
4042
- try {
4043
- return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
4044
- } catch {
4045
- return false;
4277
+ function findPcClose(xml, from) {
4278
+ const tags = new RegExp(PC_TAGS, "g");
4279
+ tags.lastIndex = from;
4280
+ let depth = 1;
4281
+ for (let match = tags.exec(xml); match; match = tags.exec(xml)) {
4282
+ depth += match[0].startsWith("</") ? -1 : 1;
4283
+ if (depth === 0) return {
4284
+ innerEnd: match.index,
4285
+ end: tags.lastIndex
4286
+ };
4046
4287
  }
4047
4288
  }
4048
- function progressOf(job) {
4289
+ function attr(attrs, name) {
4290
+ const value = attrs.get(name)?.value;
4291
+ return value === void 0 ? void 0 : decodeEntities(value);
4292
+ }
4293
+ // src/exchange/xliff.ts
4294
+ function toXliff(sourceLocale, locale, entries) {
4295
+ const units = entries.map(({ key, source, target, location }) => [
4296
+ ` <unit id="${escapeXml(key)}">`,
4297
+ ...location?.length ? [
4298
+ " <notes>",
4299
+ ...location.map((file) => ` <note category="location">${escapeXml(file)}</note>`),
4300
+ " </notes>"
4301
+ ] : [],
4302
+ ` <segment state="${target ? "translated" : "initial"}">`,
4303
+ ` <source>${messageToInline(source)}</source>`,
4304
+ ` <target>${messageToInline(target)}</target>`,
4305
+ " </segment>",
4306
+ " </unit>"
4307
+ ].join("\n")).join("\n");
4308
+ return [
4309
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
4310
+ `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
4311
+ ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
4312
+ units,
4313
+ " </file>",
4314
+ "</xliff>",
4315
+ ""
4316
+ ].join("\n");
4317
+ }
4318
+ const UNIT = `<(?:trans-)?unit\\b(${TAG_REST})>([\\s\\S]*?)</(?:trans-)?unit>`;
4319
+ const TARGET = new RegExp(`<target\\b${TAG_REST}>([\\s\\S]*?)</target>`);
4320
+ const SOURCE = new RegExp(`<source\\b${TAG_REST}>([\\s\\S]*?)</source>`);
4321
+ function tagAttribute(content, tag, name) {
4322
+ const open = new RegExp(`<${tag}\\b(${TAG_REST})>`).exec(content);
4323
+ return open && readAttributes(open[1]).get(name)?.value || void 0;
4324
+ }
4325
+ function parseXliff(content) {
4326
+ const head = (name) => tagAttribute(content, "xliff", name) ?? tagAttribute(content, "file", name);
4327
+ const locale = head("trgLang") ?? head("target-language");
4328
+ const entries = emptyCatalog();
4329
+ const sources = emptyCatalog();
4330
+ for (const match of content.matchAll(new RegExp(UNIT, "g"))) {
4331
+ const id = readAttributes(match[1]).get("id")?.value;
4332
+ if (!id) continue;
4333
+ const target = TARGET.exec(match[2])?.[1];
4334
+ entries[decodeEntities(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
4335
+ const source = SOURCE.exec(match[2])?.[1];
4336
+ if (source !== void 0) sources[decodeEntities(id)] = inlineToMessage(stripCdata(source));
4337
+ }
4049
4338
  return {
4050
- locale: job.locale,
4051
- batch: job.index,
4052
- batches: job.batches,
4053
- keys: job.keys.length
4339
+ locale,
4340
+ entries,
4341
+ sources
4054
4342
  };
4055
4343
  }
4056
- function glossaryFor(cfg, locale, messages) {
4057
- const entries = cfg.translate.glossary;
4058
- if (!entries) return void 0;
4059
- const text = Object.values(messages).join("\n").toLowerCase();
4060
- const out = {};
4061
- for (const [term, rendering] of Object.entries(entries)) {
4062
- if (!text.includes(term.toLowerCase())) continue;
4063
- const value = typeof rendering === "string" ? rendering : rendering[locale];
4064
- if (value) out[term] = value;
4065
- }
4066
- return Object.keys(out).length > 0 ? out : void 0;
4344
+ function stripCdata(text) {
4345
+ return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
4067
4346
  }
4068
4347
  // src/exchange/exchange.ts
4069
4348
  function isMobileFormat(format) {
@@ -4072,7 +4351,7 @@ function isMobileFormat(format) {
4072
4351
  function exportCatalogs(cfg, catalogs, options = {}) {
4073
4352
  const format = options.format ?? "xliff";
4074
4353
  const dir = resolve(cfg.root, options.out ?? "verbaly-export");
4075
- const source = catalogs[cfg.sourceLocale] ?? {};
4354
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
4076
4355
  const targets = targetLocales(cfg, options.locales);
4077
4356
  if (isMobileFormat(format)) return exportMobile(cfg, catalogs, format, dir, source, targets);
4078
4357
  const files = [];
@@ -4080,7 +4359,7 @@ function exportCatalogs(cfg, catalogs, options = {}) {
4080
4359
  mkdirSync(dir, { recursive: true });
4081
4360
  for (const locale of targets) {
4082
4361
  const catalog = catalogs[locale] ?? emptyCatalog();
4083
- const all = Object.keys(source).filter((key) => source[key]).sort().map((key) => ({
4362
+ const all = translatable(source).map((key) => ({
4084
4363
  key,
4085
4364
  source: source[key],
4086
4365
  target: own(catalog, key) ?? "",
@@ -4104,11 +4383,14 @@ function exportCatalogs(cfg, catalogs, options = {}) {
4104
4383
  files
4105
4384
  };
4106
4385
  }
4386
+ function translatable(source) {
4387
+ return Object.keys(source).filter((key) => source[key]).sort();
4388
+ }
4107
4389
  function exportMobile(cfg, catalogs, format, dir, source, targets) {
4108
- const keys = Object.keys(source).filter((key) => source[key]).sort();
4390
+ const keys = translatable(source);
4109
4391
  const files = [];
4110
4392
  for (const locale of [cfg.sourceLocale, ...targets]) {
4111
- const catalog = locale === cfg.sourceLocale ? source : catalogs[locale] ?? {};
4393
+ const catalog = locale === cfg.sourceLocale ? source : catalogs[locale] ?? emptyCatalog();
4112
4394
  const entries = keys.map((key) => ({
4113
4395
  key,
4114
4396
  text: own(catalog, key) ?? ""
@@ -4131,7 +4413,7 @@ function exportMobile(cfg, catalogs, format, dir, source, targets) {
4131
4413
  };
4132
4414
  }
4133
4415
  function importCatalogs(cfg, catalogs, files, options = {}) {
4134
- const source = catalogs[cfg.sourceLocale] ?? {};
4416
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
4135
4417
  const result = {
4136
4418
  imported: emptyCatalog(),
4137
4419
  rejected: emptyCatalog(),
@@ -4144,9 +4426,9 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
4144
4426
  for (const file of files) {
4145
4427
  const parsed = parseExchangeFile(file, options.locale);
4146
4428
  const detected = parsed.locale;
4147
- if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(detected)) throw new Error(`[verbaly] ${file}: "${detected}" doesn't look like a locale, pass --locale <id>.`);
4429
+ if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(detected)) throw new Error(`[verbaly] ${file}: "${detected}" doesn't look like a locale, pass --locale <id>`);
4148
4430
  const locale = projectLocale(detected, cfg.locales) ?? newLocale(cfg, detected);
4149
- if (locale === cfg.sourceLocale) throw new Error(`[verbaly] ${file} targets the source locale "${locale}": import fills translations, not the source. Pass --locale if the detection is wrong.`);
4431
+ if (locale === cfg.sourceLocale) throw new Error(`[verbaly] ${file} targets the source locale "${locale}": import fills translations, not the source, so pass --locale if the detection is wrong`);
4150
4432
  if (locale === void 0) {
4151
4433
  const near = isLocaleTag(detected) ? detected : suggestTag(detected);
4152
4434
  result.unmatched.push(near ? {
@@ -4194,7 +4476,7 @@ function parseExchangeFile(file, localeOverride) {
4194
4476
  if (/\.(xlf|xliff)$/i.test(file)) {
4195
4477
  const parsed = parseXliff(content);
4196
4478
  const locale = localeOverride ?? parsed.locale;
4197
- if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>.`);
4479
+ if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>`);
4198
4480
  return {
4199
4481
  locale,
4200
4482
  entries: parsed.entries,
@@ -4204,126 +4486,20 @@ function parseExchangeFile(file, localeOverride) {
4204
4486
  if (/\.csv$/i.test(file)) return {
4205
4487
  locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
4206
4488
  ...parseCsv(content)
4207
- };
4208
- if (/\.po$/i.test(file)) {
4209
- const parsed = parsePo(content);
4210
- return {
4211
- locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
4212
- entries: parsed.entries,
4213
- sources: parsed.sources
4214
- };
4215
- }
4216
- throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po.`);
4217
- }
4218
- function toXliff(sourceLocale, locale, entries) {
4219
- const units = entries.map(({ key, source, target, location }) => [
4220
- ` <unit id="${escapeXml(key)}">`,
4221
- ...location?.length ? [
4222
- " <notes>",
4223
- ...location.map((file) => ` <note category="location">${escapeXml(file)}</note>`),
4224
- " </notes>"
4225
- ] : [],
4226
- ` <segment state="${target ? "translated" : "initial"}">`,
4227
- ` <source>${messageToInline(source)}</source>`,
4228
- ` <target>${messageToInline(target)}</target>`,
4229
- " </segment>",
4230
- " </unit>"
4231
- ].join("\n")).join("\n");
4232
- return [
4233
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
4234
- `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
4235
- ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
4236
- units,
4237
- " </file>",
4238
- "</xliff>",
4239
- ""
4240
- ].join("\n");
4241
- }
4242
- function newLocale(cfg, detected) {
4243
- if (cfg.localesDeclared) return void 0;
4244
- return isLocaleTag(detected) ? detected : suggestTag(detected);
4245
- }
4246
- function parseXliff(content) {
4247
- const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
4248
- const entries = Object.create(null);
4249
- const sources = Object.create(null);
4250
- for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
4251
- const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
4252
- if (!id) continue;
4253
- const target = /<target\b[^>]*>([\s\S]*?)<\/target>/.exec(match[2])?.[1];
4254
- entries[unescapeXml(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
4255
- const source = /<source\b[^>]*>([\s\S]*?)<\/source>/.exec(match[2])?.[1];
4256
- if (source !== void 0) sources[unescapeXml(id)] = inlineToMessage(stripCdata(source));
4257
- }
4258
- return {
4259
- locale,
4260
- entries,
4261
- sources
4262
- };
4263
- }
4264
- function stripCdata(text) {
4265
- return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
4266
- }
4267
- function toCsv(entries) {
4268
- return [
4269
- "key,source,target,location",
4270
- ...entries.map(({ key, source, target, location }) => `${csvField(key)},${csvField(source)},${csvField(target)},${csvField(location?.join("; ") ?? "")}`),
4271
- ""
4272
- ].join("\r\n");
4273
- }
4274
- function csvField(text) {
4275
- return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
4276
- }
4277
- function parseCsv(content) {
4278
- const rows = csvRows(content);
4279
- const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
4280
- const keyCol = header.indexOf("key");
4281
- const targetCol = header.indexOf("target");
4282
- const sourceCol = header.indexOf("source");
4283
- if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
4284
- const entries = Object.create(null);
4285
- const sources = Object.create(null);
4286
- for (const row of rows.slice(1)) {
4287
- const key = row[keyCol];
4288
- if (!key) continue;
4289
- entries[key] = row[targetCol] ?? "";
4290
- const source = sourceCol === -1 ? void 0 : row[sourceCol];
4291
- if (source) sources[key] = source;
4292
- }
4293
- return {
4294
- entries,
4295
- sources
4296
- };
4297
- }
4298
- function csvRows(content) {
4299
- const rows = [];
4300
- let row = [];
4301
- let field = "";
4302
- let quoted = false;
4303
- for (let i = 0; i < content.length; i++) {
4304
- const char = content[i];
4305
- if (quoted) {
4306
- if (char === "\"") {
4307
- if (content[i + 1] === "\"") {
4308
- field += "\"";
4309
- i++;
4310
- } else quoted = false;
4311
- } else field += char;
4312
- } else if (char === "\"") quoted = true;
4313
- else if (char === ",") {
4314
- row.push(field);
4315
- field = "";
4316
- } else if (char === "\n" || char === "\r") {
4317
- if (char === "\r" && content[i + 1] === "\n") i++;
4318
- row.push(field);
4319
- field = "";
4320
- if (row.some((cell) => cell !== "")) rows.push(row);
4321
- row = [];
4322
- } else field += char;
4489
+ };
4490
+ if (/\.po$/i.test(file)) {
4491
+ const parsed = parsePo(content);
4492
+ return {
4493
+ locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
4494
+ entries: parsed.entries,
4495
+ sources: parsed.sources
4496
+ };
4323
4497
  }
4324
- row.push(field);
4325
- if (row.some((cell) => cell !== "")) rows.push(row);
4326
- return rows;
4498
+ throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po`);
4499
+ }
4500
+ function newLocale(cfg, detected) {
4501
+ if (cfg.localesDeclared) return void 0;
4502
+ return isLocaleTag(detected) ? detected : suggestTag(detected);
4327
4503
  }
4328
4504
  // src/cli/commands/export.ts
4329
4505
  async function exportCommand(cfg, values) {
@@ -4407,7 +4583,7 @@ function watchTree(root, options, onFile) {
4407
4583
  };
4408
4584
  }
4409
4585
  function watchProject(cfg, run, options = {}) {
4410
- const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
4586
+ const catalogDir = relativePath(cfg.root, cfg.dir);
4411
4587
  let timer;
4412
4588
  let running = false;
4413
4589
  let queued = false;
@@ -4435,7 +4611,7 @@ function watchProject(cfg, run, options = {}) {
4435
4611
  }
4436
4612
  const close = watchTree(cfg.root, {}, (filename) => {
4437
4613
  if (!filename) return;
4438
- const file = filename.replaceAll("\\", "/");
4614
+ const file = slashed(filename);
4439
4615
  if (file.includes("node_modules/") || file.endsWith(".d.ts")) return;
4440
4616
  if (catalogDir && file.startsWith(`${catalogDir}/`)) return;
4441
4617
  if (SOURCE_FILE_RE.test(file)) schedule();
@@ -4547,18 +4723,7 @@ const KNOWN = [
4547
4723
  "svelte-i18n"
4548
4724
  ];
4549
4725
  function detectLibraries(root) {
4550
- const path = join(root, "package.json");
4551
- if (!existsSync(path)) return [];
4552
- let manifest;
4553
- try {
4554
- manifest = JSON.parse(readFileSync(path, "utf8"));
4555
- } catch {
4556
- return [];
4557
- }
4558
- const deps = {
4559
- ...manifest.dependencies,
4560
- ...manifest.devDependencies
4561
- };
4726
+ const deps = readDependencies(root);
4562
4727
  return KNOWN.filter((name) => deps[name] !== void 0);
4563
4728
  }
4564
4729
  const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
@@ -4710,8 +4875,9 @@ function migrateCatalogs(cfg, options = {}) {
4710
4875
  const catalog = catalogs.get(locale);
4711
4876
  const out = Object.assign(emptyCatalog(), catalog);
4712
4877
  const convert = fromI18next && !done.has(locale);
4878
+ const reported = convert || done.has(locale);
4713
4879
  for (const [key, value] of Object.entries(catalog)) {
4714
- if (!convert || typeof value !== "string") continue;
4880
+ if (!reported || typeof value !== "string") continue;
4715
4881
  const problem = i18nextProblem(value);
4716
4882
  if (problem) {
4717
4883
  skipped.push({
@@ -4721,6 +4887,7 @@ function migrateCatalogs(cfg, options = {}) {
4721
4887
  });
4722
4888
  continue;
4723
4889
  }
4890
+ if (!convert) continue;
4724
4891
  const after = convertBraces(value);
4725
4892
  if (after !== value) {
4726
4893
  braces.push({
@@ -4732,7 +4899,12 @@ function migrateCatalogs(cfg, options = {}) {
4732
4899
  out[key] = after;
4733
4900
  }
4734
4901
  }
4735
- if (options.plurals) mergePlurals(locale, catalog, out, plurals, skipped, convert);
4902
+ if (options.plurals) {
4903
+ mergePlurals(locale, catalog, out, plurals, skipped, convert);
4904
+ const merged = new Set(plurals.filter((entry) => entry.locale === locale).flatMap((entry) => entry.from));
4905
+ const left = braces.filter((entry) => entry.locale !== locale || !merged.has(entry.key));
4906
+ braces.splice(0, braces.length, ...left);
4907
+ }
4736
4908
  if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
4737
4909
  writeCatalog(cfg, locale, out);
4738
4910
  written.push(locale);
@@ -4778,9 +4950,9 @@ function existingCatalogs(root) {
4778
4950
  });
4779
4951
  }
4780
4952
  function configSource(options, typescript) {
4781
- const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
4782
- if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
4783
- if (options.dir) fields.push(` dir: '${options.dir}',`);
4953
+ const fields = [` sourceLocale: ${singleQuoted(options.sourceLocale ?? "en")},`];
4954
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map(singleQuoted).join(", ")}],`);
4955
+ if (options.dir) fields.push(` dir: ${singleQuoted(options.dir)},`);
4784
4956
  const body = `export default {\n${fields.join("\n")}\n}`;
4785
4957
  if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
4786
4958
  return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
@@ -4840,7 +5012,7 @@ async function init(input = {}) {
4840
5012
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
4841
5013
  for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
4842
5014
  const file = join(dir, `${locale}.json`);
4843
- const label = relative(root, file).replaceAll("\\", "/");
5015
+ const label = relativePath(root, file);
4844
5016
  if (existsSync(file)) skipped.push(label);
4845
5017
  else {
4846
5018
  writeFileSync(file, "{}\n");
@@ -5055,7 +5227,6 @@ const REDIRECT_OPEN = "<!--verbaly:redirect-->";
5055
5227
  const REDIRECT_CLOSE = "<!--/verbaly:redirect-->";
5056
5228
  const VOID = new Set(VOID_TAGS);
5057
5229
  const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
5058
- const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
5059
5230
  function renderHtml(html, options) {
5060
5231
  const attr = options.attribute ?? "data-verbaly";
5061
5232
  const argsAttr = `${attr}-args`;
@@ -5085,34 +5256,36 @@ function renderHtml(html, options) {
5085
5256
  const tagName = rawName.toLowerCase();
5086
5257
  const openEnd = m.index + full.length;
5087
5258
  const chunkStart = m.index + 1 + rawName.length;
5259
+ const attrs = readAttributes(attrChunk, true);
5260
+ const read = (name) => attrs.get(name)?.value;
5261
+ const set = (name, value) => setAttribute(ms, html, chunkStart, openEnd, attrs, name, value);
5088
5262
  if (tagName === "html" && options.setLang !== false) {
5089
- setAttribute(ms, html, chunkStart, openEnd, attrChunk, "lang", options.locale);
5090
- setAttribute(ms, html, chunkStart, openEnd, attrChunk, "dir", localeDirection(options.locale));
5263
+ set("lang", options.locale);
5264
+ set("dir", localeDirection(options.locale));
5091
5265
  continue;
5092
5266
  }
5093
- const attrs = parseAttrs(attrChunk);
5094
- if (rewriteUrl && tagName === "link" && attrs.get("rel")?.toLowerCase() === "canonical" && sameUrl(decodeEntities(attrs.get("href") ?? ""), sourceUrl)) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", selfUrl);
5095
- if (rewriteUrl && tagName === "meta" && attrs.get("property") === "og:url" && sameUrl(decodeEntities(attrs.get("content") ?? ""), sourceUrl)) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", selfUrl);
5267
+ if (rewriteUrl && tagName === "link" && read("rel")?.toLowerCase() === "canonical" && sameUrl(decodeEntities(read("href") ?? ""), sourceUrl)) set("href", selfUrl);
5268
+ if (rewriteUrl && tagName === "meta" && read("property") === "og:url" && sameUrl(decodeEntities(read("content") ?? ""), sourceUrl)) set("content", selfUrl);
5096
5269
  const mirror = options.mirror;
5097
5270
  if (mirror) {
5098
5271
  if (tagName === "a" || tagName === "area") {
5099
- const inside = mirroredHref(attrs.get("href"), mirror);
5100
- if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", inside);
5272
+ const inside = mirroredHref(read("href"), mirror);
5273
+ if (inside) set("href", inside);
5101
5274
  } else if (tagName === "form" || tagName === "button" || tagName === "input") {
5102
5275
  const name = tagName === "form" ? "action" : "formaction";
5103
- const inside = mirroredHref(attrs.get(name), mirror);
5104
- if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, inside);
5105
- } else if (tagName === "meta" && attrs.get("http-equiv")?.toLowerCase() === "refresh") {
5106
- const content = attrs.get("content") ?? "";
5276
+ const inside = mirroredHref(read(name), mirror);
5277
+ if (inside) set(name, inside);
5278
+ } else if (tagName === "meta" && read("http-equiv")?.toLowerCase() === "refresh") {
5279
+ const content = read("content") ?? "";
5107
5280
  const url = /^([^;]*;\s*url\s*=\s*)(.*)$/i.exec(decodeEntities(content));
5108
5281
  const inside = url && mirroredHref(url[2], mirror);
5109
- if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", `${url[1]}${inside}`);
5282
+ if (inside) set("content", `${url[1]}${inside}`);
5110
5283
  }
5111
5284
  }
5112
- const key = attrs.get(attr);
5113
- const attrMapRaw = attrs.get(attrsAttr);
5285
+ const key = read(attr);
5286
+ const attrMapRaw = read(attrsAttr);
5114
5287
  if (key === void 0 && attrMapRaw === void 0) continue;
5115
- const args = parseArgs$1(attrs.get(argsAttr), argsAttr);
5288
+ const args = parseArgs(read(argsAttr), argsAttr);
5116
5289
  if (key) {
5117
5290
  if (!v.has(key)) missing.add(key);
5118
5291
  else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
@@ -5120,7 +5293,7 @@ function renderHtml(html, options) {
5120
5293
  const close = findClose(html, tagName, openEnd, inSkip);
5121
5294
  if (close) {
5122
5295
  const text = t(key, args);
5123
- const own = parseArgs$1(attrs.get(linksAttr), linksAttr);
5296
+ const own = parseArgs(read(linksAttr), linksAttr);
5124
5297
  const merged = own ? globalLinks ? {
5125
5298
  ...globalLinks,
5126
5299
  ...own
@@ -5129,7 +5302,7 @@ function renderHtml(html, options) {
5129
5302
  const nodes = attrs.has(richAttr) ? parseTags(text) : [];
5130
5303
  if (mirror && links) {
5131
5304
  const carried = usedLinks(nodes, links);
5132
- if (carried && JSON.stringify(carried) !== JSON.stringify(own)) setAttribute(ms, html, chunkStart, openEnd, attrChunk, linksAttr, JSON.stringify(carried));
5305
+ if (carried && JSON.stringify(carried) !== JSON.stringify(own)) set(linksAttr, JSON.stringify(carried));
5133
5306
  }
5134
5307
  const content = attrs.has(richAttr) ? richToHtml(nodes, richTags, links) : escapeHtml(text);
5135
5308
  if (html.slice(openEnd, close.contentEnd) !== content) {
@@ -5141,16 +5314,20 @@ function renderHtml(html, options) {
5141
5314
  }
5142
5315
  }
5143
5316
  if (attrMapRaw !== void 0) {
5144
- const map = parseArgs$1(attrMapRaw, attrsAttr);
5317
+ const map = parseArgs(attrMapRaw, attrsAttr);
5145
5318
  if (map) for (const [name, attrKey] of Object.entries(map)) {
5146
5319
  if (typeof attrKey !== "string") continue;
5320
+ if (!isAttributeName(name)) {
5321
+ warnOnce(`${attrsAttr} names "${name}", which is not an attribute name`);
5322
+ continue;
5323
+ }
5147
5324
  if (!v.has(attrKey)) {
5148
5325
  missing.add(attrKey);
5149
5326
  continue;
5150
5327
  }
5151
5328
  used.add(attrKey);
5152
5329
  const value = safeAttribute(name, t(attrKey, args));
5153
- if (value !== void 0) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value);
5330
+ if (value !== void 0) set(name, value);
5154
5331
  }
5155
5332
  }
5156
5333
  }
@@ -5167,7 +5344,7 @@ function renderHtml(html, options) {
5167
5344
  };
5168
5345
  }
5169
5346
  function pageSlice(v, locale, used) {
5170
- const slice = Object.create(null);
5347
+ const slice = emptyCatalog();
5171
5348
  for (const key of used) {
5172
5349
  const found = v.inspect(key);
5173
5350
  slice[key] = found?.from === locale ? found.source : "";
@@ -5185,7 +5362,7 @@ function linkFor(links, name) {
5185
5362
  return links && Object.hasOwn(links, name) ? links[name] : void 0;
5186
5363
  }
5187
5364
  function usedLinks(nodes, links) {
5188
- const out = {};
5365
+ const out = emptyCatalog();
5189
5366
  const walk = (list) => {
5190
5367
  for (const node of list) {
5191
5368
  if (typeof node === "string") continue;
@@ -5199,7 +5376,7 @@ function usedLinks(nodes, links) {
5199
5376
  }
5200
5377
  function mirroredLinks(links, mirror) {
5201
5378
  if (!links) return links;
5202
- const out = {};
5379
+ const out = emptyCatalog();
5203
5380
  for (const [name, link] of Object.entries(links)) {
5204
5381
  const inside = mirroredHref(typeof link === "string" ? link : link.href, mirror);
5205
5382
  if (inside === void 0) out[name] = link;
@@ -5246,51 +5423,114 @@ function redirectScript(options) {
5246
5423
  `N=${options.trailingSlash === "never" ? 1 : 0}`
5247
5424
  ].join(",")};${REDIRECT_BODY};<\/script>`;
5248
5425
  }
5249
- function injectRedirect(ms, html, options) {
5250
- const block = `${REDIRECT_OPEN}${redirectScript(options)}${REDIRECT_CLOSE}`;
5251
- const from = html.indexOf(REDIRECT_OPEN);
5252
- if (from !== -1) {
5253
- const to = html.indexOf(REDIRECT_CLOSE, from);
5254
- if (to !== -1) {
5255
- const end = to + 24;
5256
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5257
- return;
5258
- }
5426
+ const HEAD_OPEN = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i;
5427
+ const HEAD_CLOSE = /<\/head\s*>/i;
5428
+ function betweenMarkers(ms, html, [open, close], content, where) {
5429
+ const block = `${open}${content}${close}`;
5430
+ const from = html.indexOf(open);
5431
+ const to = from === -1 ? -1 : html.indexOf(close, from);
5432
+ if (to !== -1) {
5433
+ const end = to + close.length;
5434
+ if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5435
+ return;
5259
5436
  }
5260
- const head = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i.exec(html);
5261
- if (head) ms.appendRight(head.index + head[0].length, block);
5437
+ const head = (where === "first" ? HEAD_OPEN : HEAD_CLOSE).exec(html);
5438
+ if (!head) return;
5439
+ if (where === "first") ms.appendRight(head.index + head[0].length, block);
5440
+ else ms.appendLeft(head.index, block);
5441
+ }
5442
+ function injectRedirect(ms, html, options) {
5443
+ betweenMarkers(ms, html, [REDIRECT_OPEN, REDIRECT_CLOSE], redirectScript(options), "first");
5262
5444
  }
5263
5445
  function injectAlternates(ms, html, alternates) {
5264
5446
  const links = alternates.map((a) => `<link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}">`).join("");
5265
- const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;
5266
- const from = html.indexOf(HREFLANG_OPEN);
5267
- if (from !== -1) {
5268
- const to = html.indexOf(HREFLANG_CLOSE, from);
5269
- if (to !== -1) {
5270
- const end = to + 24;
5271
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5272
- return;
5273
- }
5274
- }
5275
- const head = /<\/head\s*>/i.exec(html);
5276
- if (head) ms.appendLeft(head.index, block);
5447
+ betweenMarkers(ms, html, [HREFLANG_OPEN, HREFLANG_CLOSE], links, "last");
5277
5448
  }
5278
5449
  function injectCatalog(ms, html, messages) {
5279
5450
  const json = JSON.stringify(messages).replace(/<\//g, "<\\/").replace(/<!--/g, "\\u003c!--");
5280
5451
  const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
5281
- const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
5282
- const from = html.indexOf(CATALOG_OPEN);
5283
- if (from !== -1) {
5284
- const to = html.indexOf(CATALOG_CLOSE, from);
5285
- if (to !== -1) {
5286
- const end = to + 23;
5287
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5288
- return;
5289
- }
5452
+ betweenMarkers(ms, html, [CATALOG_OPEN, CATALOG_CLOSE], tag, "last");
5453
+ }
5454
+ function parseArgs(raw, attribute) {
5455
+ if (!raw) return void 0;
5456
+ try {
5457
+ return JSON.parse(decodeEntities(raw));
5458
+ } catch {
5459
+ warnOnce(`invalid JSON in ${attribute}: ${raw}`, `${attribute}:${raw}`);
5460
+ return;
5461
+ }
5462
+ }
5463
+ const OPAQUE_BLOCKS = [
5464
+ {
5465
+ open: "<!--",
5466
+ close: /(?<=<!--)-?>|--!?>/g
5467
+ },
5468
+ {
5469
+ open: /<script\b/gi,
5470
+ close: /<\/script(?=[\t\n\f\r />])/gi,
5471
+ closeTag: true
5472
+ },
5473
+ {
5474
+ open: /<style\b/gi,
5475
+ close: /<\/style(?=[\t\n\f\r />])/gi,
5476
+ closeTag: true
5477
+ }
5478
+ ];
5479
+ function protectedRanges(html) {
5480
+ return blocks(html, OPAQUE_BLOCKS).map(({ start, end }) => {
5481
+ return [html.startsWith("<!--", start) ? start : html.indexOf(">", start) + 1, end];
5482
+ });
5483
+ }
5484
+ function findClose(html, tagName, from, inSkip) {
5485
+ const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
5486
+ re.lastIndex = from;
5487
+ let depth = 1;
5488
+ let m;
5489
+ while ((m = re.exec(html)) !== null) {
5490
+ if (inSkip(m.index)) continue;
5491
+ if (m[0][1] === "/") {
5492
+ depth -= 1;
5493
+ if (depth === 0) return { contentEnd: m.index };
5494
+ } else if (!m[0].endsWith("/>")) depth += 1;
5495
+ }
5496
+ return null;
5497
+ }
5498
+ function setAttribute(ms, html, chunkStart, openEnd, attrs, name, value) {
5499
+ const written = `"${escapeAttr(value)}"`;
5500
+ const existing = attrs.get(name.toLowerCase());
5501
+ if (existing) {
5502
+ const from = chunkStart + existing.start;
5503
+ const to = chunkStart + existing.end;
5504
+ if (from === to) ms.appendLeft(from, `=${written}`);
5505
+ else if (html.slice(from, to) !== written) ms.overwrite(from, to, written);
5506
+ return;
5507
+ }
5508
+ const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
5509
+ ms.appendLeft(insertAt, ` ${name}=${written}`);
5510
+ }
5511
+ function richToHtml(nodes, allowed, links) {
5512
+ let out = "";
5513
+ for (const node of nodes) {
5514
+ const link = typeof node === "string" ? void 0 : linkFor(links, node.name);
5515
+ if (typeof node === "string") out += escapeHtml(node);
5516
+ else if (link !== void 0) {
5517
+ const { href, target, rel } = normalizeLink(link);
5518
+ let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
5519
+ if (target) attrs += ` target="${escapeAttr(target)}"`;
5520
+ if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
5521
+ out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
5522
+ } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
5523
+ else out += richToHtml(node.children, allowed, links);
5290
5524
  }
5291
- const head = /<\/head\s*>/i.exec(html);
5292
- if (head) ms.appendLeft(head.index, block);
5525
+ return out;
5526
+ }
5527
+ function escapeHtml(text) {
5528
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5293
5529
  }
5530
+ function escapeAttr(text) {
5531
+ return escapeHtml(text).replace(/"/g, "&quot;");
5532
+ }
5533
+ // src/emit/site.ts
5294
5534
  const TITLE_TAG = /<title\b([^>]*)>/i;
5295
5535
  const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
5296
5536
  const NOINDEX_META = /<meta\b[^>]*name\s*=\s*["']?robots["']?[^>]*content\s*=\s*["'][^"']*noindex/i;
@@ -5337,13 +5577,13 @@ async function renderSite(cfg, options = {}) {
5337
5577
  absolute: true,
5338
5578
  ignore: locales.map((locale) => `${locale}/**`)
5339
5579
  });
5340
- const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
5341
- const missing = emptyCatalog();
5580
+ const pages = new Set(files.map((file) => publicPath(relativePath(site, file))));
5581
+ const unfilled = emptyCatalog();
5342
5582
  const untranslatedHead = [];
5343
5583
  const urls = [];
5344
5584
  for (const file of files) {
5345
5585
  const html = readFileSync(file, "utf8");
5346
- const rel = relative(site, file).replace(/\\/g, "/");
5586
+ const rel = relativePath(site, file);
5347
5587
  if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
5348
5588
  const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale, cfg.trailingSlash) : [];
5349
5589
  if (wantHreflang && isIndexable(html) && !excluded(rel)) urls.push({
@@ -5369,16 +5609,15 @@ async function renderSite(cfg, options = {}) {
5369
5609
  redirect: routed && locale === cfg.sourceLocale ? script : void 0,
5370
5610
  inlineCatalog: cfg.render.inlineCatalog === true
5371
5611
  });
5372
- for (const key of result.missing) {
5373
- const list = missing[locale] ??= [];
5374
- if (!list.includes(key)) list.push(key);
5375
- }
5612
+ for (const key of result.missing) (unfilled[locale] ??= /* @__PURE__ */ new Set()).add(key);
5376
5613
  const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);
5377
5614
  mkdirSync(dirname(out), { recursive: true });
5378
5615
  writeFileSync(out, result.html);
5379
5616
  }
5380
5617
  }
5381
5618
  if (wantSitemap && urls.length) writeFileSync(join(site, typeof sitemap === "string" ? sitemap : "sitemap-i18n.xml"), buildSitemap(urls));
5619
+ const missing = emptyCatalog();
5620
+ for (const [locale, keys] of Object.entries(unfilled)) missing[locale] = [...keys];
5382
5621
  return {
5383
5622
  files: files.length,
5384
5623
  locales: [...locales],
@@ -5408,98 +5647,10 @@ function pageAlternates(baseUrl, rel, locales, sourceLocale, trailingSlash) {
5408
5647
  }
5409
5648
  function buildSitemap(urls) {
5410
5649
  return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls.flatMap(({ alternates }) => {
5411
- const alts = alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${a.hreflang}" href="${escapeAttr(a.href)}"/>`).join("");
5650
+ const alts = alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}"/>`).join("");
5412
5651
  return alternates.filter((a) => a.hreflang !== "x-default").map((self) => `<url><loc>${escapeAttr(self.href)}</loc>${alts}</url>`);
5413
5652
  }).join("")}</urlset>\n`;
5414
5653
  }
5415
- function parseAttrs(chunk) {
5416
- const attrs = /* @__PURE__ */ new Map();
5417
- ATTR.lastIndex = 0;
5418
- let m;
5419
- while ((m = ATTR.exec(chunk)) !== null) attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
5420
- return attrs;
5421
- }
5422
- function parseArgs$1(raw, attribute) {
5423
- if (!raw) return void 0;
5424
- try {
5425
- return JSON.parse(decodeEntities(raw));
5426
- } catch {
5427
- warnOnce(`invalid JSON in ${attribute}: ${raw}`, `${attribute}:${raw}`);
5428
- return;
5429
- }
5430
- }
5431
- const OPAQUE_BLOCKS = [
5432
- {
5433
- open: "<!--",
5434
- close: /(?<=<!--)-?>|--!?>/g
5435
- },
5436
- {
5437
- open: /<script\b/gi,
5438
- close: /<\/script(?=[\t\n\f\r />])/gi,
5439
- closeTag: true
5440
- },
5441
- {
5442
- open: /<style\b/gi,
5443
- close: /<\/style(?=[\t\n\f\r />])/gi,
5444
- closeTag: true
5445
- }
5446
- ];
5447
- function protectedRanges(html) {
5448
- return blocks(html, OPAQUE_BLOCKS).map(({ start, end }) => {
5449
- return [html.startsWith("<!--", start) ? start : html.indexOf(">", start) + 1, end];
5450
- });
5451
- }
5452
- function findClose(html, tagName, from, inSkip) {
5453
- const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
5454
- re.lastIndex = from;
5455
- let depth = 1;
5456
- let m;
5457
- while ((m = re.exec(html)) !== null) {
5458
- if (inSkip(m.index)) continue;
5459
- if (m[0][1] === "/") {
5460
- depth -= 1;
5461
- if (depth === 0) return { contentEnd: m.index };
5462
- } else if (!m[0].endsWith("/>")) depth += 1;
5463
- }
5464
- return null;
5465
- }
5466
- function setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value) {
5467
- const escaped = escapeAttr(value);
5468
- const existing = new RegExp(`(\\s${name}\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s>]+)`, "i").exec(attrChunk);
5469
- if (existing) {
5470
- const valueStart = chunkStart + existing.index + existing[1].length;
5471
- const valueEnd = valueStart + existing[2].length;
5472
- if (html.slice(valueStart, valueEnd) !== `"${escaped}"`) ms.overwrite(valueStart, valueEnd, `"${escaped}"`);
5473
- return;
5474
- }
5475
- const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
5476
- ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
5477
- }
5478
- function richToHtml(nodes, allowed, links) {
5479
- let out = "";
5480
- for (const node of nodes) {
5481
- const link = typeof node === "string" ? void 0 : linkFor(links, node.name);
5482
- if (typeof node === "string") out += escapeHtml(node);
5483
- else if (link !== void 0) {
5484
- const { href, target, rel } = normalizeLink(link);
5485
- let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
5486
- if (target) attrs += ` target="${escapeAttr(target)}"`;
5487
- if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
5488
- out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
5489
- } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
5490
- else out += richToHtml(node.children, allowed, links);
5491
- }
5492
- return out;
5493
- }
5494
- function escapeHtml(text) {
5495
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5496
- }
5497
- function escapeAttr(text) {
5498
- return escapeHtml(text).replace(/"/g, "&quot;");
5499
- }
5500
- function decodeEntities(text) {
5501
- return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
5502
- }
5503
5654
  // src/cli/commands/render.ts
5504
5655
  async function renderCommand(cfg, values) {
5505
5656
  const result = await renderSite(cfg, {
@@ -5573,19 +5724,14 @@ async function statusCommand(cfg, values) {
5573
5724
  }
5574
5725
  // src/cli/commands/translate.ts
5575
5726
  async function translateCommand(cfg, values) {
5576
- if (!values["dry-run"]) loadState(cfg);
5577
- const registry = await extractProject(cfg);
5578
- const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
5579
- const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
5727
+ const dryRun = values["dry-run"];
5728
+ const result = await translateProject(cfg, {
5580
5729
  locales: csv(values.locales),
5581
- batchSize: cfg.translate.batchSize,
5582
- concurrency: cfg.translate.concurrency,
5583
- retries: cfg.translate.retries,
5584
- dryRun: values["dry-run"],
5585
- origins: values["dry-run"] ? void 0 : await collectOrigins(cfg, registry),
5586
- onProgress: values["dry-run"] ? void 0 : reportProgress
5730
+ dryRun,
5731
+ model: values.model,
5732
+ onProgress: reportProgress
5587
5733
  });
5588
- if (values["dry-run"]) {
5734
+ if (dryRun) {
5589
5735
  const entries = Object.entries(result.pending);
5590
5736
  if (entries.length === 0) {
5591
5737
  console.log("[verbaly] nothing to translate ✓");
@@ -5594,30 +5740,20 @@ async function translateCommand(cfg, values) {
5594
5740
  for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.length} missing: ${keys.join(", ")}`);
5595
5741
  return;
5596
5742
  }
5597
- const source = catalogs[cfg.sourceLocale] ?? {};
5598
- const writes = [];
5599
- for (const [locale, keys] of Object.entries(result.translated)) {
5600
- const catalog = catalogs[locale] ?? {};
5601
- const written = mergeTranslations(cfg, locale, catalog, keys);
5602
- writes.push({
5603
- locale,
5604
- draft: true,
5605
- entries: written.map((key) => ({
5606
- key,
5607
- text: catalog[key]
5608
- }))
5609
- });
5610
- console.log(` ${locale}: +${written.length} translated (draft)`);
5611
- const kept = keys.length - written.length;
5612
- if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
5613
- }
5614
- const lockBefore = stateFile(cfg);
5615
- if (writes.length > 0) recordTranslations(cfg, source, writes);
5616
- sayLockNews(cfg, lockBefore);
5743
+ for (const [locale, keys] of Object.entries(result.written)) console.log(` ${locale}: +${keys.length} translated (draft)`);
5744
+ for (const [locale, keys] of Object.entries(result.kept)) console.log(` ${locale}: ${counted(keys.length, "message")} kept as written while this ran`);
5745
+ if (result.lock) console.log(` ${formatFinding({
5746
+ kind: "lock",
5747
+ ...result.lock
5748
+ }, cfg.root)}`);
5617
5749
  for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
5618
5750
  for (const line of formatTranslateFailures(result.failed)) console.error(line);
5619
5751
  if (result.failed.length > 0) process.exitCode = 1;
5620
- if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0 && result.failed.length === 0) console.log("[verbaly] nothing to translate ✓");
5752
+ if ([
5753
+ result.written,
5754
+ result.kept,
5755
+ result.invalid
5756
+ ].every((record) => Object.keys(record).length === 0) && result.failed.length === 0) console.log("[verbaly] nothing to translate ✓");
5621
5757
  }
5622
5758
  function reportProgress(progress) {
5623
5759
  const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
@@ -5633,7 +5769,7 @@ async function typegenCommand(cfg) {
5633
5769
  console.log("[verbaly] no types written: dts is false in your verbaly config");
5634
5770
  return;
5635
5771
  }
5636
- const where = relative(cfg.root, written.file).replaceAll("\\", "/");
5772
+ const where = relativePath(cfg.root, written.file);
5637
5773
  const how = written.changed ? "written to" : "up to date in";
5638
5774
  console.log(`[verbaly] types ${how} ${where} (${counted(Object.keys(source).length, "message")})`);
5639
5775
  }
@@ -5682,7 +5818,7 @@ async function wrapProject(cfg, options = {}) {
5682
5818
  const adapters = () => found ??= jsxAdapters(cfg.root);
5683
5819
  for (const file of files) {
5684
5820
  const code = readFileSync(file, "utf8");
5685
- const label = relative(cfg.root, file).replaceAll("\\", "/");
5821
+ const label = relativePath(cfg.root, file);
5686
5822
  const out = wrapCode(code, label);
5687
5823
  result.wrapped.push(...out.wrapped);
5688
5824
  result.skipped.push(...out.skipped);
@@ -5720,16 +5856,23 @@ function wrapCode(code, file) {
5720
5856
  client: false
5721
5857
  };
5722
5858
  }
5723
- const hasT = declaresT(ast);
5859
+ const scopes = tScopes(ast);
5724
5860
  const client = hasDirective(ast, "use client");
5725
5861
  const s = new MagicString(code);
5726
5862
  const visited = /* @__PURE__ */ new Set();
5727
5863
  let changed = false;
5864
+ let reached = true;
5865
+ const write = (start, end, template) => {
5866
+ s.overwrite(start, end, "{t`" + template + "`}");
5867
+ changed = true;
5868
+ if (!tReaches(scopes, start)) reached = false;
5869
+ };
5728
5870
  walk$1(ast, (node) => {
5729
5871
  if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
5730
5872
  if (visited.has(node)) return;
5731
5873
  processElement(node);
5732
5874
  });
5875
+ const hasT = changed ? reached : scopes.some((scope) => scope.bound);
5733
5876
  return changed ? {
5734
5877
  code: s.toString(),
5735
5878
  wrapped,
@@ -5810,11 +5953,10 @@ function wrapCode(code, file) {
5810
5953
  if (isIdentifierLike(report)) return;
5811
5954
  const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
5812
5955
  const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
5813
- s.overwrite(start, end, "{t`" + template + "`}");
5814
- changed = true;
5956
+ write(start, end, template);
5815
5957
  wrapped.push({
5816
5958
  file,
5817
- line: line(first),
5959
+ line: lineOf(first),
5818
5960
  text: report,
5819
5961
  kind: "text"
5820
5962
  });
@@ -5828,11 +5970,10 @@ function wrapCode(code, file) {
5828
5970
  if (value?.type !== "StringLiteral") continue;
5829
5971
  const raw = value.value;
5830
5972
  if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;
5831
- s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
5832
- changed = true;
5973
+ write(value.start, value.end, escapeTemplate(raw));
5833
5974
  wrapped.push({
5834
5975
  file,
5835
- line: line(value),
5976
+ line: lineOf(value),
5836
5977
  text: raw,
5837
5978
  kind: "attribute",
5838
5979
  attribute: name.name
@@ -5842,7 +5983,7 @@ function wrapCode(code, file) {
5842
5983
  function skip(node, text, reason) {
5843
5984
  skipped.push({
5844
5985
  file,
5845
- line: line(node),
5986
+ line: lineOf(node),
5846
5987
  text,
5847
5988
  reason
5848
5989
  });
@@ -5868,19 +6009,59 @@ function isIdentifierLike(text) {
5868
6009
  function hasDirective(program, value) {
5869
6010
  return (program.directives ?? []).some((d) => d.value?.value === value);
5870
6011
  }
5871
- function declaresT(program) {
5872
- let found = false;
5873
- walk$1(program, (node) => {
5874
- if (found) return;
5875
- if (node.type === "ImportDeclaration") {
5876
- for (const spec of node.specifiers) if (isTName(spec.local?.name)) found = true;
6012
+ const CALLS = /* @__PURE__ */ new Set([
6013
+ "CallExpression",
6014
+ "NewExpression",
6015
+ "OptionalCallExpression"
6016
+ ]);
6017
+ function tScopes(program) {
6018
+ const scopes = [];
6019
+ const mark = (scope, bound) => {
6020
+ scopes.push({
6021
+ start: scope.start,
6022
+ end: scope.end,
6023
+ bound
6024
+ });
6025
+ };
6026
+ const visit = (node, scope, argument) => {
6027
+ let inner = scope;
6028
+ if (FUNCTIONS.has(node.type)) {
6029
+ inner = node;
6030
+ if (node.type === "FunctionDeclaration" && isTName(node.id?.name)) mark(scope, true);
6031
+ for (const param of node.params ?? []) {
6032
+ if (!bindsT(param)) continue;
6033
+ mark(node, !(argument && namesT(param)));
6034
+ }
6035
+ } else if (node.type === "ImportDeclaration") {
6036
+ if (node.specifiers.map((spec) => spec.local).some((local) => isTName(local?.name))) mark(program, true);
5877
6037
  return;
6038
+ } else if (node.type === "VariableDeclarator" && bindsT(node.id)) mark(scope, true);
6039
+ const args = CALLS.has(node.type) ? node.arguments : void 0;
6040
+ for (const key in node) {
6041
+ if (key === "loc" || key.endsWith("Comments") || key === "extra") continue;
6042
+ const value = node[key];
6043
+ for (const child of Array.isArray(value) ? value : [value]) if (isAstNode(child)) visit(child, inner, args?.includes(child) ?? false);
5878
6044
  }
5879
- if (node.type === "VariableDeclarator" && bindsT(node.id)) found = true;
5880
- if (node.type === "FunctionDeclaration" && isTName(node.id?.name)) found = true;
5881
- if (node.params?.some((param) => bindsT(param))) found = true;
5882
- });
5883
- return found;
6045
+ };
6046
+ visit(program, program, false);
6047
+ return scopes;
6048
+ }
6049
+ function tReaches(scopes, position) {
6050
+ let nearest;
6051
+ for (const scope of scopes) {
6052
+ if (position < scope.start || position >= scope.end) continue;
6053
+ const size = scope.end - scope.start;
6054
+ const best = nearest ? nearest.end - nearest.start : 1e400;
6055
+ if (size < best || size === best && scope.bound) nearest = scope;
6056
+ }
6057
+ return nearest?.bound ?? false;
6058
+ }
6059
+ function isAstNode(value) {
6060
+ return typeof value?.type === "string";
6061
+ }
6062
+ function namesT(param) {
6063
+ const target = param.type === "AssignmentPattern" ? param.left : param;
6064
+ return target.type === "Identifier" && isTName(target.name);
5884
6065
  }
5885
6066
  function bindsT(pattern) {
5886
6067
  if (!pattern) return false;
@@ -5924,38 +6105,46 @@ function leadingWs(text) {
5924
6105
  function trailingWs(text) {
5925
6106
  return text.length - text.trimEnd().length;
5926
6107
  }
5927
- function line(node) {
5928
- return node.loc?.start?.line ?? 1;
5929
- }
5930
- // src/cli/commands/wrap.ts
5931
- async function wrapCommand(cfg, values) {
5932
- const result = await wrapProject(cfg, { write: values.write });
5933
- if (result.wrapped.length === 0 && result.skipped.length === 0) {
5934
- console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
5935
- return;
5936
- }
6108
+ function formatWrapResult(result, write) {
5937
6109
  const blocked = new Set(result.blocked.map((entry) => entry.file));
5938
6110
  const done = result.changed.filter((file) => !blocked.has(file));
5939
6111
  const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));
5940
- const verb = values.write ? "wrapped" : "would wrap";
5941
- const note = values.write ? "" : " (report only, use --write to apply)";
5942
- let counts = `${counted(texts.length, "text")} in ${counted(done.length, "file")}`;
6112
+ let counts = `${write ? "wrapped" : "would wrap"} ${counted(texts.length, "text")} in ${counted(done.length, "file")}`;
5943
6113
  const waiting = result.wrapped.length - texts.length;
5944
- if (!values.write && waiting > 0) counts += `, and ${counted(waiting, "text")} in ${counted(blocked.size, "file")} once t is in scope`;
5945
- console.log(`[verbaly] ${verb} ${counts}${note}`);
5946
- for (const entry of values.write ? texts : result.wrapped) {
6114
+ if (!write && waiting > 0) counts += `, and ${counted(waiting, "text")} in ${counted(blocked.size, "file")} once t is in scope`;
6115
+ const lines = [];
6116
+ for (const entry of write ? texts : result.wrapped) {
5947
6117
  const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
5948
- console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
6118
+ lines.push(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
5949
6119
  }
5950
6120
  if (result.skipped.length > 0) {
5951
- console.log(" needs a human:");
5952
- for (const entry of result.skipped) console.log(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
6121
+ lines.push(" needs a human:");
6122
+ for (const entry of result.skipped) lines.push(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
5953
6123
  }
5954
6124
  if (result.blocked.length > 0) {
5955
- console.log(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
5956
- for (const entry of result.blocked) console.log(` ${entry.file} ${counted(entry.texts, "text")}, ${entry.binding}`);
5957
- console.log(" next: add t there, run verbaly wrap --write again, then verbaly extract");
5958
- } else if (values.write && done.length > 0) console.log(" next: run verbaly extract");
6125
+ lines.push(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
6126
+ for (const entry of result.blocked) lines.push(` ${entry.file} ${counted(entry.texts, "text")}, ${entry.binding}`);
6127
+ }
6128
+ return {
6129
+ counts,
6130
+ lines,
6131
+ files: done.length
6132
+ };
6133
+ }
6134
+ // src/cli/commands/wrap.ts
6135
+ async function wrapCommand(cfg, values) {
6136
+ const write = values.write === true;
6137
+ const result = await wrapProject(cfg, { write });
6138
+ if (result.wrapped.length === 0 && result.skipped.length === 0) {
6139
+ console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
6140
+ return;
6141
+ }
6142
+ const report = formatWrapResult(result, write);
6143
+ const note = write ? "" : " (report only, use --write to apply)";
6144
+ console.log(`[verbaly] ${report.counts}${note}`);
6145
+ for (const line of report.lines) console.log(line);
6146
+ if (result.blocked.length > 0) console.log(" next: add t there, run verbaly wrap --write again, then verbaly extract");
6147
+ else if (write && report.files > 0) console.log(" next: run verbaly extract");
5959
6148
  }
5960
6149
  // src/cli/run.ts
5961
6150
  const HELP = `verbaly · i18n compiler
@@ -6034,14 +6223,38 @@ async function runCli(args = process.argv.slice(2)) {
6034
6223
  }
6035
6224
  if (rejectStrayFlags(command, values)) return;
6036
6225
  if (command === "init") return initCommand(values);
6037
- const cfg = await loadConfig(values.root ?? process.cwd(), {
6226
+ if (!Object.hasOwn(COMMANDS, command)) {
6227
+ console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
6228
+ process.exitCode = 1;
6229
+ return;
6230
+ }
6231
+ const root = values.root ?? process.cwd();
6232
+ const project = {
6038
6233
  dir: values.dir,
6039
- sourceLocale: values.source,
6040
- locales: csv(values.locales)
6234
+ sourceLocale: values.source
6235
+ };
6236
+ const narrowed = csv(values.locales);
6237
+ if (narrowed || command === "review" && values.locale) {
6238
+ const whole = await loadConfig(root, project);
6239
+ const typo = narrowed ? strangers(whole, "locales", narrowed) : strangers(whole, "locale", [values.locale]);
6240
+ if (typo) {
6241
+ console.error(typo);
6242
+ process.exitCode = 1;
6243
+ return;
6244
+ }
6245
+ }
6246
+ const cfg = await loadConfig(root, {
6247
+ ...project,
6248
+ locales: narrowed
6041
6249
  });
6042
- if (Object.hasOwn(COMMANDS, command)) return COMMANDS[command](cfg, values, positionals);
6043
- console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
6044
- process.exitCode = 1;
6250
+ return COMMANDS[command](cfg, values, positionals);
6251
+ }
6252
+ function strangers(cfg, flag, named) {
6253
+ const unknown = named.filter((locale) => !cfg.locales.includes(locale));
6254
+ if (unknown.length === 0) return void 0;
6255
+ const dir = relativePath(cfg.root, cfg.dir);
6256
+ const start = cfg.localesDeclared ? `add ${unknown.join(", ")} to locales in your verbaly config` : `create ${unknown.map((locale) => `${dir}/${locale}.json`).join(", ")} holding {}`;
6257
+ return `[verbaly] --${flag} names ${unknown.map((locale) => `"${locale}"`).join(", ")}, and this project has ${cfg.locales.join(", ")}\n fix: check the spelling, or ${start} to start a new language`;
6045
6258
  }
6046
6259
  function formatCliError(error) {
6047
6260
  const message = error instanceof Error ? error.message : String(error);
@@ -6104,4 +6317,4 @@ function rejectStrayFlags(command, values) {
6104
6317
  process.exitCode = 1;
6105
6318
  return true;
6106
6319
  }
6107
- 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 };
6320
+ export { collectOrigins as $, collisionEntries as A, counted as At, loadState as B, translateProject as C, loadConfig as Ct, translateCatalogs as D, warnOnce as Dt, resolveProvider as E, targetLocales as Et, outdatedTranslations as F, generateLocaleModule as G, readState as H, recordTranslations as I, validateMessage as J, generateRuntimeModule as K, updateState as L, formatCollision as M, formatFinding as N, writeDrafts as O, warnParseError as Ot, effectiveDrafts as P, syncCatalogs as Q, STATE_FILE as R, warningCount as S, isModuleNotFound as St, mergeTranslations as T, resolveConfig as Tt, saveState as U, markDrafts as V, generateDts as W, pruneCatalogs as X, validatePair as Y, shippedCatalogs as Z, formatCheckResult as _, own as _t, formatRenderWarnings as a, APP_ID as at, gatePasses as b, writeCatalog as bt, watchTree as c, isAppModule as ct, formatDoctorHealth as d, clientCatalogs as dt, extractProject as et, formatStatusResult as f, formatBundleIssue as ft, formatBuildReport as g, needsRelative as gt, checkNextSteps as h, needsIcu as ht, wrapProject as i, stableKey as it, createDevReporter as j, singleQuoted as jt, syncProject as k, cliReachable as kt, doctor as l, MessageRegistry as lt, reportOutsideInclude as m, loadCatalogs as mt, runCli as n, relativePath as nt, renderSite as o, LOCALE_IMPORT as ot, status as p, emptyCatalog as pt, writeDts as q, formatWrapResult as r, analyzeFile as rt, init as s, VIRTUAL_ID as st, formatCliError as t, scannedAnalysis as tt, formatDoctorEntry as u, auditBundle as ut, formatCheckWarnings as v, parseCatalog as vt, formatTranslateFailures as w, pluginOnlyOptions as wt, relativeCheck as x, SOURCE_FILE_RE as xt, check as y, readCatalog as yt, clearDrafts as z };