@verbaly/compiler 0.81.0 → 0.82.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.
@@ -9,7 +9,7 @@ import { createHash } from "node:crypto";
9
9
  import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
10
10
  import picomatch from "picomatch";
11
11
  import MagicString from "magic-string";
12
- import { parseArgs } from "node:util";
12
+ import { parseArgs as parseArgs$1 } from "node:util";
13
13
  // src/config/host.ts
14
14
  const HOSTS = [
15
15
  {
@@ -207,7 +207,9 @@ function resolveConfig(config = {}) {
207
207
  const sourceLocale = config.sourceLocale ?? "en";
208
208
  const host = detectHost(root)?.name;
209
209
  const localesDeclared = config.locales !== void 0;
210
- const locales = /* @__PURE__ */ new Set([sourceLocale, ...config.locales ?? []]);
210
+ const written = config.locales;
211
+ const listed = typeof written === "string" ? [written] : config.locales ?? [];
212
+ const locales = /* @__PURE__ */ new Set([sourceLocale, ...listed]);
211
213
  if (!localesDeclared && existsSync(dir)) {
212
214
  for (const file of readdirSync(dir)) if (file.endsWith(".json") && !file.startsWith(".") && file !== `en-XA.json`) locales.add(file.slice(0, -5));
213
215
  }
@@ -399,10 +401,19 @@ function isNested(tree) {
399
401
  function group() {
400
402
  return Object.create(null);
401
403
  }
402
- function nest(catalog) {
404
+ function pathsOf(tree, prefix = [], out = /* @__PURE__ */ new Map()) {
405
+ for (const [name, value] of Object.entries(tree)) {
406
+ const path = [...prefix, name];
407
+ if (typeof value === "string") out.set(path.join("."), path);
408
+ else if (isTree(value)) pathsOf(value, path, out);
409
+ }
410
+ return out;
411
+ }
412
+ function nest(catalog, shape) {
403
413
  const tree = group();
414
+ const written = shape ? pathsOf(shape) : void 0;
404
415
  for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
405
- const parts = key.split(".");
416
+ const parts = written?.get(key) ?? key.split(".");
406
417
  const leaf = parts[parts.length - 1];
407
418
  let node = parts.length > 1 ? tree : void 0;
408
419
  for (let i = 0; node && i < parts.length - 1; i++) {
@@ -445,8 +456,8 @@ function orderLike(tree, previous) {
445
456
  for (const key of Object.keys(tree).sort()) if (!Object.hasOwn(previous, key)) take(key);
446
457
  return out;
447
458
  }
448
- function serializeCatalog(catalog, nested = false, previous) {
449
- const tree = nested ? nest(catalog) : catalog;
459
+ function serializeCatalog(catalog, nested = false, previous, shape = previous) {
460
+ const tree = nested ? nest(catalog, shape) : catalog;
450
461
  return JSON.stringify(previous ? orderLike(tree, previous) : sortTree(tree), null, 2) + "\n";
451
462
  }
452
463
  function writeCatalog(cfg, locale, catalog) {
@@ -459,17 +470,20 @@ function writeCatalog(cfg, locale, catalog) {
459
470
  }
460
471
  const parsed = existing === void 0 ? void 0 : parseTree(existing);
461
472
  const previous = isTree(parsed) ? parsed : void 0;
462
- const serialized = withLineEndings(serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous), existing);
473
+ const shape = shapeFor(cfg, locale, existing, previous);
474
+ const serialized = withLineEndings(serializeCatalog(catalog, shape !== void 0 && isNested(shape), previous, shape), existing);
463
475
  if (existing === serialized) return serialized;
464
476
  writeFileSync(path, serialized);
465
477
  return serialized;
466
478
  }
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));
479
+ function shapeFor(cfg, locale, existing, previous) {
480
+ if (existing !== void 0) return previous;
481
+ return locale === cfg.sourceLocale ? void 0 : readTree(cfg, cfg.sourceLocale);
471
482
  }
472
483
  const ICU_ARG = /(^|[^{])\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
484
+ function isIcu(message) {
485
+ return ICU_ARG.test(message);
486
+ }
473
487
  function needsIcu(catalogs) {
474
488
  return someMessage(catalogs, ICU_ARG);
475
489
  }
@@ -498,6 +512,9 @@ function trimTrailingSlashes(text) {
498
512
  while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
499
513
  return text.slice(0, end);
500
514
  }
515
+ function singleQuoted(text) {
516
+ return `'${text.replace(/[\\']/g, "\\$&")}'`;
517
+ }
501
518
  function byCodeUnit(a, b) {
502
519
  return a < b ? -1 : a > b ? 1 : 0;
503
520
  }
@@ -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) {
@@ -768,9 +798,19 @@ function loadsAtRuntime(node) {
768
798
  function lineOf(node) {
769
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 = Infinity;
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) => {
@@ -902,10 +960,9 @@ function staticString(node) {
902
960
  if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
903
961
  if (node.type === "JSXExpressionContainer") return staticString(node.expression);
904
962
  }
905
- const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
906
963
  function collectStrayImports(node, file, out) {
907
964
  const source = node.source;
908
- if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
965
+ if (typeof source.value !== "string" || !VERBALY_SOURCE.test(source.value)) return;
909
966
  for (const spec of node.specifiers) {
910
967
  if (spec.type !== "ImportSpecifier") continue;
911
968
  const imported = spec.imported;
@@ -921,7 +978,7 @@ function collectStrayImports(node, file, out) {
921
978
  function handleTrans(code, node, file, tagged, usedKeys, names) {
922
979
  const opening = node.openingElement;
923
980
  const nameNode = opening.name;
924
- if (nameNode.type !== "JSXIdentifier" || nameNode.name !== "Trans") return;
981
+ if (nameNode.type !== "JSXIdentifier" || nameNode.name !== TRANS) return;
925
982
  const attrs = opening.attributes;
926
983
  const idAttr = attrs.find((a) => a.type === "JSXAttribute" && a.name.name === "id");
927
984
  const children = node.children;
@@ -1748,7 +1805,7 @@ function visit(nodes, out) {
1748
1805
  else if (key !== "other") types.add("string");
1749
1806
  visit(body, out);
1750
1807
  }
1751
- if (types.size === 0) types.add("string");
1808
+ if (types.size === 0) types.add("number").add("string");
1752
1809
  } else if (node.format && NUMBER_FORMATS.has(node.format)) types.add("number");
1753
1810
  else if (node.format && DATE_FORMATS.has(node.format)) types.add("date");
1754
1811
  else types.add("unknown");
@@ -1848,7 +1905,7 @@ function generateRuntimeModule(cfg, options = {}) {
1848
1905
  const importPath = options.localeImport ?? ((locale) => "@verbaly/app/locale/" + locale);
1849
1906
  const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
1850
1907
  const src = JSON.stringify(cfg.sourceLocale);
1851
- const loaders = others.map((locale) => ` ${loaderKey(locale)}: () => import('${importPath(locale)}'),`).join("\n");
1908
+ const loaders = others.map((locale) => ` ${loaderKey(locale)}: () => import(${singleQuoted(importPath(locale))}),`).join("\n");
1852
1909
  const icu = options.icu ? ",\n parseIcu" : "";
1853
1910
  const rel = options.relative ? ",\n relativeFormatter" : "";
1854
1911
  const slice = options.inlineCatalog ? ",\n inlineMessages" : "";
@@ -1860,7 +1917,7 @@ function generateRuntimeModule(cfg, options = {}) {
1860
1917
  persistLocale,
1861
1918
  switchLocale as runSwitch${icu}${rel}${slice},
1862
1919
  } from 'verbaly';
1863
- import source from '${importPath(cfg.sourceLocale)}';
1920
+ import source from ${singleQuoted(importPath(cfg.sourceLocale))};
1864
1921
 
1865
1922
  export const sourceLocale = ${src};
1866
1923
  export const locales = ${JSON.stringify(cfg.locales)};
@@ -2110,127 +2167,6 @@ function removeRootDts(cfg, target) {
2110
2167
  rmSync(old);
2111
2168
  warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
2112
2169
  }
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
- } };
2233
- }
2234
2170
  // src/catalog/state.ts
2235
2171
  const STATE_FILE = "verbaly.lock";
2236
2172
  const LOCK_VERSION = 1;
@@ -2565,6 +2501,155 @@ function readFingerprints(value) {
2565
2501
  }
2566
2502
  return out;
2567
2503
  }
2504
+ // src/gate/findings.ts
2505
+ function siteOf(msg) {
2506
+ return {
2507
+ file: msg.file,
2508
+ line: msg.line,
2509
+ message: msg.message
2510
+ };
2511
+ }
2512
+ function collisionEntries(registry) {
2513
+ return registry.collisions().map(({ key, kept, dropped }) => ({
2514
+ key,
2515
+ sites: [kept, ...dropped].map(siteOf)
2516
+ }));
2517
+ }
2518
+ function scanFindings(cfg, registry, replaced = []) {
2519
+ const messages = registry.messages();
2520
+ const out = [];
2521
+ for (const { key, before } of replaced) {
2522
+ const msg = messages.get(key);
2523
+ if (msg) out.push({
2524
+ kind: "replaced",
2525
+ locale: cfg.sourceLocale,
2526
+ key,
2527
+ before,
2528
+ site: siteOf(msg)
2529
+ });
2530
+ }
2531
+ for (const entry of collisionEntries(registry)) out.push({
2532
+ kind: "collision",
2533
+ ...entry
2534
+ });
2535
+ for (const { name, file, line } of registry.missed()) out.push({
2536
+ kind: "renamed",
2537
+ name,
2538
+ file,
2539
+ line
2540
+ });
2541
+ for (const msg of messages.values()) {
2542
+ const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
2543
+ if (params.length > 0) out.push({
2544
+ kind: "positional",
2545
+ params,
2546
+ site: siteOf(msg)
2547
+ });
2548
+ const slice = escapedSyntax(msg.message);
2549
+ if (slice) out.push({
2550
+ kind: "escaped",
2551
+ slice,
2552
+ site: siteOf(msg)
2553
+ });
2554
+ }
2555
+ for (const { file, message } of registry.parseErrors()) out.push({
2556
+ kind: "unparsed",
2557
+ file,
2558
+ message
2559
+ });
2560
+ return out;
2561
+ }
2562
+ function sourcePlace(at, root) {
2563
+ const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
2564
+ return at.line ? `${file}:${at.line}` : file;
2565
+ }
2566
+ function quoted(at, root) {
2567
+ return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
2568
+ }
2569
+ function formatCollision({ key, sites }, root) {
2570
+ const [kept, ...others] = sites;
2571
+ const texts = new Set(sites.map((at) => at.message)).size;
2572
+ 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`;
2573
+ }
2574
+ function formatFinding(finding, root) {
2575
+ switch (finding.kind) {
2576
+ case "collision": return formatCollision(finding, root);
2577
+ case "replaced": {
2578
+ const place = sourcePlace(finding.site, root);
2579
+ 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)}"`;
2580
+ }
2581
+ case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
2582
+ case "positional": {
2583
+ const names = finding.params.map((name) => `{${name}}`).join(", ");
2584
+ 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`;
2585
+ }
2586
+ case "escaped": return `${sourcePlace(finding.site, root)}: ${shownSlice(finding.slice)} renders as literal text: write ${inlineBlock(finding.slice)}`;
2587
+ case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
2588
+ case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
2589
+ case "lock": {
2590
+ const lock = sourcePlace(finding, root);
2591
+ 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`;
2592
+ 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`;
2593
+ }
2594
+ }
2595
+ }
2596
+ function findingId(finding) {
2597
+ switch (finding.kind) {
2598
+ case "collision":
2599
+ case "replaced": return `${finding.kind}:${finding.key}`;
2600
+ case "outdated": return `outdated:${finding.locale}:${finding.key}`;
2601
+ case "renamed": return `renamed:${finding.file}:${finding.name}`;
2602
+ case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
2603
+ case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
2604
+ case "unparsed": return `unparsed:${finding.file}`;
2605
+ case "lock": return `lock:${finding.merged ? "merged:" : ""}${finding.file}`;
2606
+ }
2607
+ }
2608
+ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
2609
+ const shown = /* @__PURE__ */ new Map();
2610
+ let stateBroken = false;
2611
+ const report = (channel, findings) => {
2612
+ const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
2613
+ const now = /* @__PURE__ */ new Set();
2614
+ const fresh = [];
2615
+ for (const finding of findings) {
2616
+ const id = findingId(finding);
2617
+ if (now.has(id)) continue;
2618
+ now.add(id);
2619
+ if (!before.has(id)) fresh.push(finding);
2620
+ }
2621
+ shown.set(channel, now);
2622
+ for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
2623
+ if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
2624
+ };
2625
+ return {
2626
+ report,
2627
+ sync(cfg, result, edited) {
2628
+ const replaced = [];
2629
+ const code = [];
2630
+ const lock = [];
2631
+ for (const finding of result.findings) if (finding.kind === "collision" || finding.kind === "renamed") code.push(finding);
2632
+ else if (finding.kind === "lock") lock.push(finding);
2633
+ else if (finding.kind === "replaced") {
2634
+ const answer = edited(finding);
2635
+ if (answer !== void 0) replaced.push({
2636
+ ...finding,
2637
+ edited: answer
2638
+ });
2639
+ }
2640
+ report("replaced", replaced);
2641
+ report("code", code);
2642
+ report("lock", lock);
2643
+ const outdated = result.state ? outdatedTranslations(cfg, result.catalogs, result.state.fingerprints) : [];
2644
+ report("outdated", outdated.map((entry) => ({
2645
+ kind: "outdated",
2646
+ ...entry
2647
+ })));
2648
+ if (result.stateProblem && !stateBroken) print(`${result.stateProblem}, so drafts are not tracked`);
2649
+ stateBroken = Boolean(result.stateProblem);
2650
+ }
2651
+ };
2652
+ }
2568
2653
  // src/project/project.ts
2569
2654
  async function syncProject(cfg, options = {}) {
2570
2655
  const registry = options.registry ?? await extractProject(cfg);
@@ -2621,10 +2706,297 @@ function confirmFromDisk(cfg, catalogs, registry) {
2621
2706
  registry.update(file, analyzeFile(code, file));
2622
2707
  }
2623
2708
  }
2624
- // src/gate/check.ts
2709
+ // src/exchange/translate.ts
2710
+ const RETRY_STATUS = /* @__PURE__ */ new Set([
2711
+ 408,
2712
+ 409,
2713
+ 425,
2714
+ 429,
2715
+ 500,
2716
+ 502,
2717
+ 503,
2718
+ 504,
2719
+ 529
2720
+ ]);
2721
+ function retryable(error) {
2722
+ const status = error?.status;
2723
+ const code = error?.statusCode;
2724
+ const value = typeof status === "number" ? status : code;
2725
+ return typeof value === "number" ? RETRY_STATUS.has(value) : true;
2726
+ }
2727
+ function reason(error) {
2728
+ return error instanceof Error ? error.message : String(error);
2729
+ }
2730
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2731
+ async function attempt(run, retries, delay) {
2732
+ for (let round = 0;; round++) try {
2733
+ return await run();
2734
+ } catch (error) {
2735
+ if (round >= retries || !retryable(error)) throw error;
2736
+ await wait(delay * 2 ** round);
2737
+ }
2738
+ }
2739
+ async function pooled(jobs, limit, run) {
2740
+ let next = 0;
2741
+ const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
2742
+ while (next < jobs.length) await run(jobs[next++]);
2743
+ });
2744
+ await Promise.all(workers);
2745
+ }
2746
+ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2747
+ const batchSize = options.batchSize ?? 20;
2748
+ const concurrency = Math.max(1, options.concurrency ?? 4);
2749
+ const retries = Math.max(0, options.retries ?? 2);
2750
+ const retryDelay = options.retryDelay ?? 500;
2751
+ const targets = targetLocales(cfg, options.locales);
2752
+ const source = catalogs[cfg.sourceLocale] ?? {};
2753
+ const result = {
2754
+ translated: emptyCatalog(),
2755
+ invalid: emptyCatalog(),
2756
+ pending: emptyCatalog(),
2757
+ failed: []
2758
+ };
2759
+ const jobs = [];
2760
+ for (const locale of targets) {
2761
+ const catalog = catalogs[locale] ??= emptyCatalog();
2762
+ const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
2763
+ if (missing.length === 0) continue;
2764
+ if (options.dryRun) {
2765
+ result.pending[locale] = missing;
2766
+ continue;
2767
+ }
2768
+ const batches = Math.ceil(missing.length / batchSize);
2769
+ for (let i = 0; i < missing.length; i += batchSize) {
2770
+ const index = Math.floor(i / batchSize) + 1;
2771
+ jobs.push({
2772
+ locale,
2773
+ index,
2774
+ batches,
2775
+ keys: missing.slice(i, i + batchSize)
2776
+ });
2777
+ }
2778
+ }
2779
+ await pooled(jobs, concurrency, async (job) => {
2780
+ const { locale, keys } = job;
2781
+ const catalog = catalogs[locale];
2782
+ const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
2783
+ const origins = options.origins ? Object.fromEntries(keys.filter((key) => Object.hasOwn(options.origins, key)).map((key) => [key, options.origins[key]])) : void 0;
2784
+ let out;
2785
+ try {
2786
+ out = await attempt(() => provider({
2787
+ sourceLocale: cfg.sourceLocale,
2788
+ targetLocale: locale,
2789
+ messages,
2790
+ origins,
2791
+ instructions: cfg.translate.instructions,
2792
+ glossary: glossaryFor(cfg, locale, messages)
2793
+ }), retries, retryDelay);
2794
+ } catch (error) {
2795
+ const message = reason(error);
2796
+ result.failed.push({
2797
+ locale,
2798
+ keys,
2799
+ error: message
2800
+ });
2801
+ options.onProgress?.({
2802
+ ...progressOf(job),
2803
+ error: message
2804
+ });
2805
+ return;
2806
+ }
2807
+ for (const key of keys) {
2808
+ const text = out[key];
2809
+ if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
2810
+ catalog[key] = text;
2811
+ (result.translated[locale] ??= []).push(key);
2812
+ } else (result.invalid[locale] ??= []).push(key);
2813
+ }
2814
+ options.onProgress?.(progressOf(job));
2815
+ });
2816
+ for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
2817
+ for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
2818
+ result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));
2819
+ return result;
2820
+ }
2821
+ function compare(a, b) {
2822
+ return byCodeUnit(a[0] ?? "", b[0] ?? "");
2823
+ }
2824
+ function mergeTranslations(cfg, locale, translated, keys) {
2825
+ const source = readCatalog(cfg, cfg.sourceLocale);
2826
+ const current = readCatalog(cfg, locale);
2827
+ const written = [];
2828
+ for (const key of keys) {
2829
+ const text = translated[key];
2830
+ if (!source[key] || current[key] || !text) continue;
2831
+ current[key] = text;
2832
+ written.push(key);
2833
+ }
2834
+ if (written.length > 0) writeCatalog(cfg, locale, current);
2835
+ return written;
2836
+ }
2837
+ function writeDrafts(cfg, locale, entries, options = {}) {
2838
+ const targets = targetLocales(cfg);
2839
+ if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
2840
+ loadState(cfg);
2841
+ const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
2842
+ const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
2843
+ const current = readCatalog(cfg, locale);
2844
+ const result = {
2845
+ written: [],
2846
+ kept: [],
2847
+ invalid: [],
2848
+ unknown: []
2849
+ };
2850
+ for (const { key, text } of entries) {
2851
+ const from = own(source, key);
2852
+ if (!from) result.unknown.push(key);
2853
+ else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);
2854
+ else if (own(current, key) && !options.overwrite) result.kept.push(key);
2855
+ else {
2856
+ current[key] = text;
2857
+ result.written.push(key);
2858
+ }
2859
+ }
2860
+ if (result.written.length > 0) {
2861
+ writeCatalog(cfg, locale, current);
2862
+ const written = result.written.map((key) => ({
2863
+ key,
2864
+ text: current[key]
2865
+ }));
2866
+ const before = stateFile(cfg);
2867
+ recordTranslations(cfg, source, [{
2868
+ locale,
2869
+ entries: written,
2870
+ draft: true
2871
+ }]);
2872
+ const lock = lockNews(cfg, before);
2873
+ if (lock) result.lock = lock;
2874
+ }
2875
+ return result;
2876
+ }
2877
+ function formatTranslateFailures(failed) {
2878
+ const grouped = [];
2879
+ for (const entry of failed) {
2880
+ const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
2881
+ if (same) same.keys = [...same.keys, ...entry.keys];
2882
+ else grouped.push({
2883
+ ...entry,
2884
+ keys: [...entry.keys]
2885
+ });
2886
+ }
2887
+ return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
2888
+ }
2889
+ async function resolveProvider(cfg, model) {
2890
+ const configured = cfg.translate.provider;
2891
+ if (typeof configured === "function") return configured;
2892
+ const { claudeProvider } = await import("./claude-D31sQLmS.js");
2893
+ return claudeProvider({ model: model ?? cfg.translate.model });
2894
+ }
2895
+ function structureMatches(source, translated) {
2896
+ try {
2897
+ return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
2898
+ } catch {
2899
+ return false;
2900
+ }
2901
+ }
2902
+ function progressOf(job) {
2903
+ return {
2904
+ locale: job.locale,
2905
+ batch: job.index,
2906
+ batches: job.batches,
2907
+ keys: job.keys.length
2908
+ };
2909
+ }
2910
+ function glossaryFor(cfg, locale, messages) {
2911
+ const entries = cfg.translate.glossary;
2912
+ if (!entries) return void 0;
2913
+ const text = Object.values(messages).join("\n").toLowerCase();
2914
+ const out = {};
2915
+ for (const [term, rendering] of Object.entries(entries)) {
2916
+ if (!text.includes(term.toLowerCase())) continue;
2917
+ const value = typeof rendering === "string" ? rendering : rendering[locale];
2918
+ if (value) out[term] = value;
2919
+ }
2920
+ return Object.keys(out).length > 0 ? out : void 0;
2921
+ }
2922
+ // src/project/translate.ts
2923
+ async function translateProject(cfg, options = {}) {
2924
+ const dryRun = options.dryRun === true;
2925
+ if (!dryRun) loadState(cfg);
2926
+ const registry = await extractProject(cfg);
2927
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
2928
+ const run = await translateCatalogs(cfg, catalogs, options.provider ?? await resolveProvider(cfg, options.model), {
2929
+ locales: options.locales,
2930
+ batchSize: cfg.translate.batchSize,
2931
+ concurrency: cfg.translate.concurrency,
2932
+ retries: cfg.translate.retries,
2933
+ dryRun,
2934
+ origins: dryRun ? void 0 : await collectOrigins(cfg, registry),
2935
+ onProgress: dryRun ? void 0 : options.onProgress
2936
+ });
2937
+ const result = {
2938
+ pending: run.pending,
2939
+ written: emptyCatalog(),
2940
+ kept: emptyCatalog(),
2941
+ invalid: run.invalid,
2942
+ failed: run.failed
2943
+ };
2944
+ if (dryRun) return result;
2945
+ const writes = [];
2946
+ for (const [locale, keys] of Object.entries(run.translated)) {
2947
+ const catalog = catalogs[locale] ?? {};
2948
+ const landed = mergeTranslations(cfg, locale, catalog, keys);
2949
+ const left = keys.filter((key) => !landed.includes(key));
2950
+ if (left.length > 0) result.kept[locale] = left;
2951
+ if (landed.length === 0) continue;
2952
+ result.written[locale] = landed;
2953
+ writes.push({
2954
+ locale,
2955
+ draft: true,
2956
+ entries: landed.map((key) => ({
2957
+ key,
2958
+ text: catalog[key]
2959
+ }))
2960
+ });
2961
+ }
2962
+ const before = stateFile(cfg);
2963
+ if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
2964
+ const lock = lockNews(cfg, before);
2965
+ if (lock) result.lock = lock;
2966
+ return result;
2967
+ }
2968
+ // src/gate/check.ts
2625
2969
  function gatePasses(result) {
2626
2970
  return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2627
2971
  }
2972
+ function relativeCheck(root, result) {
2973
+ const rel = (file) => relative(root, file).replaceAll("\\", "/");
2974
+ return {
2975
+ ...result,
2976
+ unknown: result.unknown.map((entry) => ({
2977
+ ...entry,
2978
+ files: entry.files.map(rel)
2979
+ })),
2980
+ extra: result.extra.map((entry) => ({
2981
+ ...entry,
2982
+ files: entry.files.map(rel)
2983
+ })),
2984
+ collisions: result.collisions.map((entry) => ({
2985
+ ...entry,
2986
+ sites: entry.sites.map((at) => ({
2987
+ ...at,
2988
+ file: rel(at.file)
2989
+ }))
2990
+ })),
2991
+ divergent: result.divergent.map((entry) => ({
2992
+ ...entry,
2993
+ code: {
2994
+ ...entry.code,
2995
+ file: rel(entry.code.file)
2996
+ }
2997
+ }))
2998
+ };
2999
+ }
2628
3000
  function warningCount(result) {
2629
3001
  return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.divergent.length + result.outdated.length;
2630
3002
  }
@@ -2855,8 +3227,7 @@ function escapeProperty(text) {
2855
3227
  }
2856
3228
  // src/scan/transform.ts
2857
3229
  function quote(text, single) {
2858
- if (!single) return JSON.stringify(text);
2859
- return `'${text.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
3230
+ return single ? singleQuoted(text) : JSON.stringify(text);
2860
3231
  }
2861
3232
  function transformCode(code, file, analysis, options = {}) {
2862
3233
  const own = analysis ?? analyzeFile(code, file);
@@ -2873,7 +3244,9 @@ function transformCode(code, file, analysis, options = {}) {
2873
3244
  if (msg.jsx) {
2874
3245
  const values = entries.length ? ` values={{ ${pairs} }}` : "";
2875
3246
  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} />`);
3247
+ const quoted = JSON.stringify(msg.key);
3248
+ const id = quoted === `"${msg.key}"` ? quoted : `{${quoted}}`;
3249
+ s.overwrite(msg.start, msg.end, `<${msg.jsx.name} id=${id}${values}${components} />`);
2877
3250
  continue;
2878
3251
  }
2879
3252
  const tagSource = code.slice(msg.tagStart, msg.tagEnd);
@@ -2894,14 +3267,21 @@ function resolveVirtualId(id) {
2894
3267
  if (id.startsWith("@verbaly/app/locale/")) return LOCALE_MODULE_PREFIX + id.slice(20);
2895
3268
  if (id.startsWith(`virtual:verbaly/`)) return "\0" + id;
2896
3269
  }
2897
- function loadVirtualModule(id, cfg, catalogs) {
3270
+ function clientModules(cfg, catalogs, options = {}) {
2898
3271
  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)] ?? {});
3272
+ return {
3273
+ runtime: () => generateRuntimeModule(cfg, {
3274
+ ...options,
3275
+ icu: cfg.icu ?? needsIcu(client),
3276
+ relative: cfg.relative ?? needsRelative(client),
3277
+ inlineCatalog: cfg.render.inlineCatalog === true
3278
+ }),
3279
+ locale: (locale) => generateLocaleModule(own(client, locale) ?? {})
3280
+ };
3281
+ }
3282
+ function loadVirtualModule(id, cfg, catalogs) {
3283
+ if (id === RESOLVED_VIRTUAL_ID) return clientModules(cfg, catalogs).runtime();
3284
+ if (id.startsWith(LOCALE_MODULE_PREFIX)) return clientModules(cfg, catalogs).locale(id.slice(LOCALE_MODULE_PREFIX.length));
2905
3285
  }
2906
3286
  function isTransformTarget(id) {
2907
3287
  return SOURCE_FILE_RE.test(id) && !id.includes("node_modules") && !id.startsWith("\0");
@@ -3146,7 +3526,7 @@ const OPTIONS = {
3146
3526
  }
3147
3527
  };
3148
3528
  function parseCli(args) {
3149
- return parseArgs({
3529
+ return parseArgs$1({
3150
3530
  args,
3151
3531
  allowPositionals: true,
3152
3532
  options: OPTIONS
@@ -3377,11 +3757,12 @@ async function doctor(cfg) {
3377
3757
  else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
3378
3758
  const scanning = cfg.include.length > 0;
3379
3759
  if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
3760
+ const registry = await extractProject(cfg);
3380
3761
  if (source && scanning && cfg.dts !== false) {
3381
3762
  const dtsPath = cfg.dts;
3382
3763
  const shown = rel(dtsPath);
3383
3764
  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));
3765
+ const expected = generateDts(shippedCatalogs(cfg, catalogs, registry)[cfg.sourceLocale] ?? source, projectDtsOptions(cfg));
3385
3766
  if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
3386
3767
  else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
3387
3768
  else ok("types", `${shown} is up to date`);
@@ -3392,7 +3773,6 @@ async function doctor(cfg) {
3392
3773
  const old = join(cfg.root, "verbaly.d.ts");
3393
3774
  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
3775
  }
3395
- const registry = await extractProject(cfg);
3396
3776
  if (scanning) {
3397
3777
  const unreadable = registry.parseErrors();
3398
3778
  if (unreadable.length > 0) {
@@ -3507,39 +3887,106 @@ async function doctorCommand(cfg) {
3507
3887
  process.exitCode = 1;
3508
3888
  }
3509
3889
  }
3890
+ // src/util/markup.ts
3891
+ const NAME$1 = `[^\\s=/"'<>]+`;
3892
+ const ATTRIBUTE = new RegExp(`(${NAME$1})(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`, "g");
3893
+ const ATTRIBUTE_NAME = new RegExp(`^${NAME$1}$`);
3894
+ const TAG_REST = `(?:"[^"]*"|'[^']*'|[^"'>])*`;
3895
+ function isAttributeName(name) {
3896
+ return ATTRIBUTE_NAME.test(name);
3897
+ }
3898
+ function readAttributes(chunk, lowerCase = false) {
3899
+ const attributes = /* @__PURE__ */ new Map();
3900
+ ATTRIBUTE.lastIndex = 0;
3901
+ let match;
3902
+ while ((match = ATTRIBUTE.exec(chunk)) !== null) {
3903
+ const name = lowerCase ? match[1].toLowerCase() : match[1];
3904
+ if (attributes.has(name)) continue;
3905
+ const quoted = match[2] ?? match[3];
3906
+ const value = quoted ?? match[4] ?? "";
3907
+ const end = match.index + match[0].length;
3908
+ const written = quoted !== void 0 ? value.length + 2 : value.length;
3909
+ attributes.set(name, {
3910
+ value,
3911
+ start: end - written,
3912
+ end
3913
+ });
3914
+ }
3915
+ return attributes;
3916
+ }
3917
+ const ENTITY = /&(?:(lt|gt|amp|quot|apos)|#(\d+)|#[xX]([0-9a-fA-F]+));/g;
3918
+ const NAMED = {
3919
+ lt: "<",
3920
+ gt: ">",
3921
+ amp: "&",
3922
+ quot: "\"",
3923
+ apos: "'"
3924
+ };
3925
+ function decodeEntities(text) {
3926
+ return text.replace(ENTITY, (whole, name, decimal, hex) => {
3927
+ if (name) return NAMED[name];
3928
+ const code = decimal ? parseInt(decimal, 10) : parseInt(hex, 16);
3929
+ return code <= 1114111 ? String.fromCodePoint(code) : whole;
3930
+ });
3931
+ }
3510
3932
  // src/exchange/inline.ts
3511
3933
  const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
3934
+ const PH_EMPTY = new RegExp(`^<ph\\b(${TAG_REST}?)/\\s*>`);
3935
+ const PH_PAIRED = new RegExp(`^<ph\\b(${TAG_REST})>\\s*</ph\\s*>`);
3936
+ const PC_OPEN = new RegExp(`^<pc\\b(${TAG_REST})>`);
3937
+ const PC_TAGS = `<pc\\b${TAG_REST}>|</pc\\s*>`;
3512
3938
  const BREAK = /^(?:br|wbr)$/;
3939
+ const VERBALY = {
3940
+ escape: (text, at) => text.startsWith("{{", at) || text.startsWith("}}", at) ? 2 : 0,
3941
+ translatable: hasTopLevelPipe
3942
+ };
3943
+ const ICU_BLOCK = /^\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select)\b/;
3944
+ const ICU = {
3945
+ escape(text, at) {
3946
+ if (text[at] !== "'") return 0;
3947
+ if (text[at + 1] === "'") return 2;
3948
+ if (!"{}#|".includes(text[at + 1] ?? " ")) return 0;
3949
+ for (let end = at + 1; end < text.length; end++) {
3950
+ if (text[end] !== "'") continue;
3951
+ if (text[end + 1] === "'") end += 1;
3952
+ else return end - at + 1;
3953
+ }
3954
+ return text.length - at;
3955
+ },
3956
+ translatable: (src) => ICU_BLOCK.test(src)
3957
+ };
3513
3958
  function messageToInline(text) {
3514
- return renderParts(parseParts(text, 0).parts, /* @__PURE__ */ new Map());
3959
+ return renderParts(parseParts(text, 0, isIcu(text) ? ICU : VERBALY).parts, /* @__PURE__ */ new Map());
3515
3960
  }
3516
3961
  function inlineToMessage(xml) {
3517
3962
  let out = "";
3518
3963
  let text = "";
3519
3964
  let i = 0;
3520
3965
  const flush = () => {
3521
- out += unescapeXml(text);
3966
+ out += decodeEntities(text);
3522
3967
  text = "";
3523
3968
  };
3524
3969
  while (i < xml.length) {
3525
3970
  if (xml[i] === "<") {
3526
3971
  const slice = xml.slice(i);
3527
- const ph = /^<ph\b([^>]*?)\/\s*>/.exec(slice) ?? /^<ph\b([^>]*)>\s*<\/ph\s*>/.exec(slice);
3972
+ const ph = PH_EMPTY.exec(slice) ?? PH_PAIRED.exec(slice);
3528
3973
  if (ph) {
3529
3974
  flush();
3530
- out += attr(ph[1], "disp") ?? `{${attr(ph[1], "id") ?? "ph"}}`;
3975
+ const attrs = readAttributes(ph[1]);
3976
+ out += attr(attrs, "disp") ?? `{${attr(attrs, "id") ?? "ph"}}`;
3531
3977
  i += ph[0].length;
3532
3978
  continue;
3533
3979
  }
3534
- const pc = /^<pc\b([^>]*)>/.exec(slice);
3980
+ const pc = PC_OPEN.exec(slice);
3535
3981
  if (pc) {
3536
3982
  const close = findPcClose(xml, i + pc[0].length);
3537
3983
  if (close) {
3538
3984
  flush();
3539
- const id = attr(pc[1], "id") ?? "pc";
3540
- out += attr(pc[1], "dispStart") ?? `<${id}>`;
3985
+ const attrs = readAttributes(pc[1]);
3986
+ const id = attr(attrs, "id") ?? "pc";
3987
+ out += attr(attrs, "dispStart") ?? `<${id}>`;
3541
3988
  out += inlineToMessage(xml.slice(i + pc[0].length, close.innerEnd));
3542
- out += attr(pc[1], "dispEnd") ?? `</${id}>`;
3989
+ out += attr(attrs, "dispEnd") ?? `</${id}>`;
3543
3990
  i = close.end;
3544
3991
  continue;
3545
3992
  }
@@ -3554,18 +4001,7 @@ function inlineToMessage(xml) {
3554
4001
  function escapeXml(text) {
3555
4002
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
3556
4003
  }
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) {
4004
+ function parseParts(text, pos, syntax, closeTag) {
3569
4005
  const parts = [];
3570
4006
  let plain = "";
3571
4007
  const flush = () => {
@@ -3577,21 +4013,21 @@ function parseParts(text, pos, closeTag) {
3577
4013
  };
3578
4014
  let i = pos;
3579
4015
  while (i < text.length) {
3580
- const pair = text[i] + (text[i + 1] ?? "");
3581
- if (pair === "{{" || pair === "}}") {
3582
- plain += pair;
3583
- i += 2;
4016
+ const escaped = syntax.escape(text, i);
4017
+ if (escaped > 0) {
4018
+ plain += text.slice(i, i + escaped);
4019
+ i += escaped;
3584
4020
  continue;
3585
4021
  }
3586
4022
  if (text[i] === "{") {
3587
- const end = matchBrace$1(text, i);
4023
+ const end = matchBrace$1(text, i, syntax);
3588
4024
  if (end === -1) {
3589
4025
  plain += "{";
3590
4026
  i += 1;
3591
4027
  continue;
3592
4028
  }
3593
4029
  const src = text.slice(i, end + 1);
3594
- if (hasTopLevelPipe(src)) plain += src;
4030
+ if (syntax.translatable(src)) plain += src;
3595
4031
  else {
3596
4032
  flush();
3597
4033
  parts.push({
@@ -3625,7 +4061,7 @@ function parseParts(text, pos, closeTag) {
3625
4061
  i += openSrc.length;
3626
4062
  continue;
3627
4063
  }
3628
- const inner = parseParts(text, i + openSrc.length, name);
4064
+ const inner = parseParts(text, i + openSrc.length, syntax, name);
3629
4065
  if (inner.closed) {
3630
4066
  flush();
3631
4067
  parts.push({
@@ -3653,12 +4089,12 @@ function parseParts(text, pos, closeTag) {
3653
4089
  closed: false
3654
4090
  };
3655
4091
  }
3656
- function matchBrace$1(text, start) {
4092
+ function matchBrace$1(text, start, syntax) {
3657
4093
  let depth = 0;
3658
4094
  for (let i = start; i < text.length; i++) {
3659
- const pair = text[i] + (text[i + 1] ?? "");
3660
- if (pair === "{{" || pair === "}}") {
3661
- i += 1;
4095
+ const escaped = syntax.escape(text, i);
4096
+ if (escaped > 0) {
4097
+ i += escaped - 1;
3662
4098
  continue;
3663
4099
  }
3664
4100
  if (text[i] === "{") depth += 1;
@@ -3684,7 +4120,7 @@ function hasTopLevelPipe(src) {
3684
4120
  return false;
3685
4121
  }
3686
4122
  function paramName(src) {
3687
- const name = /^\{\s*([^{}|:\s]+)/.exec(src)?.[1];
4123
+ const name = /^\{\s*([^{}|:,\s]+)/.exec(src)?.[1];
3688
4124
  return name ? idSafe(name) : "ph";
3689
4125
  }
3690
4126
  function idSafe(name) {
@@ -3708,7 +4144,7 @@ function uniqueId(name, taken) {
3708
4144
  return count === 0 ? name : `${name}${count + 1}`;
3709
4145
  }
3710
4146
  function findPcClose(xml, from) {
3711
- const tags = /<pc\b[^>]*>|<\/pc\s*>/g;
4147
+ const tags = new RegExp(PC_TAGS, "g");
3712
4148
  tags.lastIndex = from;
3713
4149
  let depth = 1;
3714
4150
  for (let match = tags.exec(xml); match; match = tags.exec(xml)) {
@@ -3720,8 +4156,8 @@ function findPcClose(xml, from) {
3720
4156
  }
3721
4157
  }
3722
4158
  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);
4159
+ const value = attrs.get(name)?.value;
4160
+ return value === void 0 ? void 0 : decodeEntities(value);
3725
4161
  }
3726
4162
  // src/exchange/mobile.ts
3727
4163
  function androidValuesDir(locale, sourceLocale) {
@@ -3756,314 +4192,105 @@ function androidName(key) {
3756
4192
  }
3757
4193
  function androidText(text) {
3758
4194
  const escaped = text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3759
- return /^[@?]/.test(escaped) ? `\\${escaped}` : escaped;
3760
- }
3761
- function iosText(text) {
3762
- return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
3763
- }
3764
- // src/exchange/po.ts
3765
- function toPo(sourceLocale, locale, entries) {
3766
- return [
3767
- [
3768
- "msgid \"\"",
3769
- "msgstr \"\"",
3770
- `${poString("Project-Id-Version: verbaly\n")}`,
3771
- `${poString("MIME-Version: 1.0\n")}`,
3772
- `${poString("Content-Type: text/plain; charset=UTF-8\n")}`,
3773
- `${poString("Content-Transfer-Encoding: 8bit\n")}`,
3774
- `${poString(`Language: ${locale}\n`)}`,
3775
- `${poString(`X-Source-Language: ${sourceLocale}\n`)}`
3776
- ].join("\n"),
3777
- ...entries.map(({ key, source, target, location }) => [
3778
- ...location?.length ? [`#: ${location.join(" ")}`] : [],
3779
- `msgctxt ${poString(key)}`,
3780
- `msgid ${poString(source)}`,
3781
- `msgstr ${poString(target)}`
3782
- ].join("\n")),
3783
- ""
3784
- ].join("\n\n");
3785
- }
3786
- function parsePo(content) {
3787
- const entries = Object.create(null);
3788
- const sources = Object.create(null);
3789
- let locale;
3790
- let msgctxt;
3791
- let msgid;
3792
- let msgstr;
3793
- let fuzzy = false;
3794
- let field;
3795
- const finish = () => {
3796
- if (msgid === "" && msgctxt === void 0) {
3797
- const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
3798
- if (lang) locale = lang;
3799
- } else if (msgctxt !== void 0 && msgid !== void 0) {
3800
- entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
3801
- sources[msgctxt] = msgid;
3802
- }
3803
- msgctxt = msgid = msgstr = field = void 0;
3804
- fuzzy = false;
3805
- };
3806
- for (const raw of content.replace(/^\uFEFF/, "").split(/\r\n|[\r\n]/)) {
3807
- const line = raw.trim();
3808
- if (line === "") {
3809
- finish();
3810
- continue;
3811
- }
3812
- if (line.startsWith("#")) {
3813
- if (/^#,.*\bfuzzy\b/.test(line)) fuzzy = true;
3814
- continue;
3815
- }
3816
- const keyword = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/.exec(line);
3817
- if (keyword) {
3818
- const [, name, rest] = keyword;
3819
- const value = poUnquote(rest);
3820
- if (value === void 0) continue;
3821
- if (name === "msgctxt") {
3822
- msgctxt = value;
3823
- field = "msgctxt";
3824
- } else if (name === "msgid") {
3825
- msgid = value;
3826
- field = "msgid";
3827
- } else if (name === "msgstr" || name === "msgstr[0]") {
3828
- msgstr = value;
3829
- field = "msgstr";
3830
- } else field = "other";
3831
- continue;
3832
- }
3833
- const continuation = poUnquote(line);
3834
- if (continuation === void 0 || field === void 0 || field === "other") continue;
3835
- if (field === "msgctxt") msgctxt = (msgctxt ?? "") + continuation;
3836
- else if (field === "msgid") msgid = (msgid ?? "") + continuation;
3837
- else msgstr = (msgstr ?? "") + continuation;
3838
- }
3839
- finish();
3840
- return {
3841
- locale,
3842
- entries,
3843
- sources
3844
- };
3845
- }
3846
- function poString(text) {
3847
- return `"${text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r")}"`;
3848
- }
3849
- function poUnquote(text) {
3850
- const match = /^"((?:[^"\\]|\\.)*)"$/.exec(text);
3851
- if (!match) return void 0;
3852
- return match[1].replace(/\\(.)/g, (_, ch) => {
3853
- if (ch === "n") return "\n";
3854
- if (ch === "t") return " ";
3855
- if (ch === "r") return "\r";
3856
- return ch;
3857
- });
3858
- }
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);
3887
- }
3888
- }
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++]);
3893
- });
3894
- await Promise.all(workers);
3895
- }
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;
3917
- }
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
- });
3927
- }
3928
- }
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;
4195
+ return /^[@?]/.test(escaped) ? `\\${escaped}` : escaped;
3970
4196
  }
3971
- function compare(a, b) {
3972
- return byCodeUnit(a[0] ?? "", b[0] ?? "");
4197
+ function iosText(text) {
4198
+ return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
3973
4199
  }
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;
4200
+ // src/exchange/po.ts
4201
+ function toPo(sourceLocale, locale, entries) {
4202
+ return [
4203
+ [
4204
+ "msgid \"\"",
4205
+ "msgstr \"\"",
4206
+ `${poString("Project-Id-Version: verbaly\n")}`,
4207
+ `${poString("MIME-Version: 1.0\n")}`,
4208
+ `${poString("Content-Type: text/plain; charset=UTF-8\n")}`,
4209
+ `${poString("Content-Transfer-Encoding: 8bit\n")}`,
4210
+ `${poString(`Language: ${locale}\n`)}`,
4211
+ `${poString(`X-Source-Language: ${sourceLocale}\n`)}`
4212
+ ].join("\n"),
4213
+ ...entries.map(({ key, source, target, location }) => [
4214
+ ...location?.length ? [`#: ${location.join(" ")}`] : [],
4215
+ `msgctxt ${poString(key)}`,
4216
+ `msgid ${poString(source)}`,
4217
+ `msgstr ${poString(target)}`
4218
+ ].join("\n")),
4219
+ ""
4220
+ ].join("\n\n");
3986
4221
  }
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: []
4222
+ function parsePo(content) {
4223
+ const entries = Object.create(null);
4224
+ const sources = Object.create(null);
4225
+ let locale;
4226
+ let msgctxt;
4227
+ let msgid;
4228
+ let msgstr;
4229
+ let fuzzy = false;
4230
+ let field;
4231
+ const finish = () => {
4232
+ if (msgid === "" && msgctxt === void 0) {
4233
+ const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
4234
+ if (lang) locale = lang;
4235
+ } else if (msgctxt !== void 0 && msgid !== void 0) {
4236
+ entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
4237
+ sources[msgctxt] = msgid;
4238
+ }
4239
+ msgctxt = msgid = msgstr = field = void 0;
4240
+ fuzzy = false;
3999
4241
  };
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);
4242
+ for (const raw of content.replace(/^\uFEFF/, "").split(/\r\n|[\r\n]/)) {
4243
+ const line = raw.trim();
4244
+ if (line === "") {
4245
+ finish();
4246
+ continue;
4008
4247
  }
4248
+ if (line.startsWith("#")) {
4249
+ if (/^#,.*\bfuzzy\b/.test(line)) fuzzy = true;
4250
+ continue;
4251
+ }
4252
+ const keyword = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/.exec(line);
4253
+ if (keyword) {
4254
+ const [, name, rest] = keyword;
4255
+ const value = poUnquote(rest);
4256
+ if (value === void 0) continue;
4257
+ if (name === "msgctxt") {
4258
+ msgctxt = value;
4259
+ field = "msgctxt";
4260
+ } else if (name === "msgid") {
4261
+ msgid = value;
4262
+ field = "msgid";
4263
+ } else if (name === "msgstr" || name === "msgstr[0]") {
4264
+ msgstr = value;
4265
+ field = "msgstr";
4266
+ } else field = "other";
4267
+ continue;
4268
+ }
4269
+ const continuation = poUnquote(line);
4270
+ if (continuation === void 0 || field === void 0 || field === "other") continue;
4271
+ if (field === "msgctxt") msgctxt = (msgctxt ?? "") + continuation;
4272
+ else if (field === "msgid") msgid = (msgid ?? "") + continuation;
4273
+ else msgstr = (msgstr ?? "") + continuation;
4009
4274
  }
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
- }]);
4020
- }
4021
- return result;
4022
- }
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
- });
4032
- }
4033
- return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
4034
- }
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 });
4040
- }
4041
- function structureMatches(source, translated) {
4042
- try {
4043
- return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
4044
- } catch {
4045
- return false;
4046
- }
4047
- }
4048
- function progressOf(job) {
4275
+ finish();
4049
4276
  return {
4050
- locale: job.locale,
4051
- batch: job.index,
4052
- batches: job.batches,
4053
- keys: job.keys.length
4277
+ locale,
4278
+ entries,
4279
+ sources
4054
4280
  };
4055
4281
  }
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;
4282
+ function poString(text) {
4283
+ return `"${text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r")}"`;
4284
+ }
4285
+ function poUnquote(text) {
4286
+ const match = /^"((?:[^"\\]|\\.)*)"$/.exec(text);
4287
+ if (!match) return void 0;
4288
+ return match[1].replace(/\\(.)/g, (_, ch) => {
4289
+ if (ch === "n") return "\n";
4290
+ if (ch === "t") return " ";
4291
+ if (ch === "r") return "\r";
4292
+ return ch;
4293
+ });
4067
4294
  }
4068
4295
  // src/exchange/exchange.ts
4069
4296
  function isMobileFormat(format) {
@@ -4243,17 +4470,25 @@ function newLocale(cfg, detected) {
4243
4470
  if (cfg.localesDeclared) return void 0;
4244
4471
  return isLocaleTag(detected) ? detected : suggestTag(detected);
4245
4472
  }
4473
+ const UNIT = `<(?:trans-)?unit\\b(${TAG_REST})>([\\s\\S]*?)</(?:trans-)?unit>`;
4474
+ const TARGET = new RegExp(`<target\\b${TAG_REST}>([\\s\\S]*?)</target>`);
4475
+ const SOURCE = new RegExp(`<source\\b${TAG_REST}>([\\s\\S]*?)</source>`);
4476
+ function tagAttribute(content, tag, name) {
4477
+ const open = new RegExp(`<${tag}\\b(${TAG_REST})>`).exec(content);
4478
+ return open && readAttributes(open[1]).get(name)?.value || void 0;
4479
+ }
4246
4480
  function parseXliff(content) {
4247
- const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
4481
+ const head = (name) => tagAttribute(content, "xliff", name) ?? tagAttribute(content, "file", name);
4482
+ const locale = head("trgLang") ?? head("target-language");
4248
4483
  const entries = Object.create(null);
4249
4484
  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];
4485
+ for (const match of content.matchAll(new RegExp(UNIT, "g"))) {
4486
+ const id = readAttributes(match[1]).get("id")?.value;
4252
4487
  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));
4488
+ const target = TARGET.exec(match[2])?.[1];
4489
+ entries[decodeEntities(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
4490
+ const source = SOURCE.exec(match[2])?.[1];
4491
+ if (source !== void 0) sources[decodeEntities(id)] = inlineToMessage(stripCdata(source));
4257
4492
  }
4258
4493
  return {
4259
4494
  locale,
@@ -4275,7 +4510,7 @@ function csvField(text) {
4275
4510
  return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
4276
4511
  }
4277
4512
  function parseCsv(content) {
4278
- const rows = csvRows(content);
4513
+ const rows = csvRows(content, csvSeparator(content));
4279
4514
  const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
4280
4515
  const keyCol = header.indexOf("key");
4281
4516
  const targetCol = header.indexOf("target");
@@ -4295,7 +4530,15 @@ function parseCsv(content) {
4295
4530
  sources
4296
4531
  };
4297
4532
  }
4298
- function csvRows(content) {
4533
+ function csvSeparator(content) {
4534
+ let quoted = false;
4535
+ const seen = /* @__PURE__ */ new Set();
4536
+ for (const char of content) if (char === "\"") quoted = !quoted;
4537
+ else if (!quoted && (char === "\n" || char === "\r")) break;
4538
+ else if (!quoted) seen.add(char);
4539
+ return seen.has(",") ? "," : seen.has(";") ? ";" : seen.has(" ") ? " " : ",";
4540
+ }
4541
+ function csvRows(content, separator) {
4299
4542
  const rows = [];
4300
4543
  let row = [];
4301
4544
  let field = "";
@@ -4310,7 +4553,7 @@ function csvRows(content) {
4310
4553
  } else quoted = false;
4311
4554
  } else field += char;
4312
4555
  } else if (char === "\"") quoted = true;
4313
- else if (char === ",") {
4556
+ else if (char === separator) {
4314
4557
  row.push(field);
4315
4558
  field = "";
4316
4559
  } else if (char === "\n" || char === "\r") {
@@ -4710,8 +4953,9 @@ function migrateCatalogs(cfg, options = {}) {
4710
4953
  const catalog = catalogs.get(locale);
4711
4954
  const out = Object.assign(emptyCatalog(), catalog);
4712
4955
  const convert = fromI18next && !done.has(locale);
4956
+ const reported = convert || done.has(locale);
4713
4957
  for (const [key, value] of Object.entries(catalog)) {
4714
- if (!convert || typeof value !== "string") continue;
4958
+ if (!reported || typeof value !== "string") continue;
4715
4959
  const problem = i18nextProblem(value);
4716
4960
  if (problem) {
4717
4961
  skipped.push({
@@ -4721,6 +4965,7 @@ function migrateCatalogs(cfg, options = {}) {
4721
4965
  });
4722
4966
  continue;
4723
4967
  }
4968
+ if (!convert) continue;
4724
4969
  const after = convertBraces(value);
4725
4970
  if (after !== value) {
4726
4971
  braces.push({
@@ -4732,7 +4977,12 @@ function migrateCatalogs(cfg, options = {}) {
4732
4977
  out[key] = after;
4733
4978
  }
4734
4979
  }
4735
- if (options.plurals) mergePlurals(locale, catalog, out, plurals, skipped, convert);
4980
+ if (options.plurals) {
4981
+ mergePlurals(locale, catalog, out, plurals, skipped, convert);
4982
+ const merged = new Set(plurals.filter((entry) => entry.locale === locale).flatMap((entry) => entry.from));
4983
+ const left = braces.filter((entry) => entry.locale !== locale || !merged.has(entry.key));
4984
+ braces.splice(0, braces.length, ...left);
4985
+ }
4736
4986
  if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
4737
4987
  writeCatalog(cfg, locale, out);
4738
4988
  written.push(locale);
@@ -4778,9 +5028,9 @@ function existingCatalogs(root) {
4778
5028
  });
4779
5029
  }
4780
5030
  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}',`);
5031
+ const fields = [` sourceLocale: ${singleQuoted(options.sourceLocale ?? "en")},`];
5032
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map(singleQuoted).join(", ")}],`);
5033
+ if (options.dir) fields.push(` dir: ${singleQuoted(options.dir)},`);
4784
5034
  const body = `export default {\n${fields.join("\n")}\n}`;
4785
5035
  if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
4786
5036
  return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
@@ -5055,7 +5305,6 @@ const REDIRECT_OPEN = "<!--verbaly:redirect-->";
5055
5305
  const REDIRECT_CLOSE = "<!--/verbaly:redirect-->";
5056
5306
  const VOID = new Set(VOID_TAGS);
5057
5307
  const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
5058
- const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
5059
5308
  function renderHtml(html, options) {
5060
5309
  const attr = options.attribute ?? "data-verbaly";
5061
5310
  const argsAttr = `${attr}-args`;
@@ -5085,34 +5334,36 @@ function renderHtml(html, options) {
5085
5334
  const tagName = rawName.toLowerCase();
5086
5335
  const openEnd = m.index + full.length;
5087
5336
  const chunkStart = m.index + 1 + rawName.length;
5337
+ const attrs = readAttributes(attrChunk, true);
5338
+ const read = (name) => attrs.get(name)?.value;
5339
+ const set = (name, value) => setAttribute(ms, html, chunkStart, openEnd, attrs, name, value);
5088
5340
  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));
5341
+ set("lang", options.locale);
5342
+ set("dir", localeDirection(options.locale));
5091
5343
  continue;
5092
5344
  }
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);
5345
+ if (rewriteUrl && tagName === "link" && read("rel")?.toLowerCase() === "canonical" && sameUrl(decodeEntities(read("href") ?? ""), sourceUrl)) set("href", selfUrl);
5346
+ if (rewriteUrl && tagName === "meta" && read("property") === "og:url" && sameUrl(decodeEntities(read("content") ?? ""), sourceUrl)) set("content", selfUrl);
5096
5347
  const mirror = options.mirror;
5097
5348
  if (mirror) {
5098
5349
  if (tagName === "a" || tagName === "area") {
5099
- const inside = mirroredHref(attrs.get("href"), mirror);
5100
- if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", inside);
5350
+ const inside = mirroredHref(read("href"), mirror);
5351
+ if (inside) set("href", inside);
5101
5352
  } else if (tagName === "form" || tagName === "button" || tagName === "input") {
5102
5353
  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") ?? "";
5354
+ const inside = mirroredHref(read(name), mirror);
5355
+ if (inside) set(name, inside);
5356
+ } else if (tagName === "meta" && read("http-equiv")?.toLowerCase() === "refresh") {
5357
+ const content = read("content") ?? "";
5107
5358
  const url = /^([^;]*;\s*url\s*=\s*)(.*)$/i.exec(decodeEntities(content));
5108
5359
  const inside = url && mirroredHref(url[2], mirror);
5109
- if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", `${url[1]}${inside}`);
5360
+ if (inside) set("content", `${url[1]}${inside}`);
5110
5361
  }
5111
5362
  }
5112
- const key = attrs.get(attr);
5113
- const attrMapRaw = attrs.get(attrsAttr);
5363
+ const key = read(attr);
5364
+ const attrMapRaw = read(attrsAttr);
5114
5365
  if (key === void 0 && attrMapRaw === void 0) continue;
5115
- const args = parseArgs$1(attrs.get(argsAttr), argsAttr);
5366
+ const args = parseArgs(read(argsAttr), argsAttr);
5116
5367
  if (key) {
5117
5368
  if (!v.has(key)) missing.add(key);
5118
5369
  else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
@@ -5120,7 +5371,7 @@ function renderHtml(html, options) {
5120
5371
  const close = findClose(html, tagName, openEnd, inSkip);
5121
5372
  if (close) {
5122
5373
  const text = t(key, args);
5123
- const own = parseArgs$1(attrs.get(linksAttr), linksAttr);
5374
+ const own = parseArgs(read(linksAttr), linksAttr);
5124
5375
  const merged = own ? globalLinks ? {
5125
5376
  ...globalLinks,
5126
5377
  ...own
@@ -5129,7 +5380,7 @@ function renderHtml(html, options) {
5129
5380
  const nodes = attrs.has(richAttr) ? parseTags(text) : [];
5130
5381
  if (mirror && links) {
5131
5382
  const carried = usedLinks(nodes, links);
5132
- if (carried && JSON.stringify(carried) !== JSON.stringify(own)) setAttribute(ms, html, chunkStart, openEnd, attrChunk, linksAttr, JSON.stringify(carried));
5383
+ if (carried && JSON.stringify(carried) !== JSON.stringify(own)) set(linksAttr, JSON.stringify(carried));
5133
5384
  }
5134
5385
  const content = attrs.has(richAttr) ? richToHtml(nodes, richTags, links) : escapeHtml(text);
5135
5386
  if (html.slice(openEnd, close.contentEnd) !== content) {
@@ -5141,16 +5392,20 @@ function renderHtml(html, options) {
5141
5392
  }
5142
5393
  }
5143
5394
  if (attrMapRaw !== void 0) {
5144
- const map = parseArgs$1(attrMapRaw, attrsAttr);
5395
+ const map = parseArgs(attrMapRaw, attrsAttr);
5145
5396
  if (map) for (const [name, attrKey] of Object.entries(map)) {
5146
5397
  if (typeof attrKey !== "string") continue;
5398
+ if (!isAttributeName(name)) {
5399
+ warnOnce(`${attrsAttr} names "${name}", which is not an attribute name`);
5400
+ continue;
5401
+ }
5147
5402
  if (!v.has(attrKey)) {
5148
5403
  missing.add(attrKey);
5149
5404
  continue;
5150
5405
  }
5151
5406
  used.add(attrKey);
5152
5407
  const value = safeAttribute(name, t(attrKey, args));
5153
- if (value !== void 0) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value);
5408
+ if (value !== void 0) set(name, value);
5154
5409
  }
5155
5410
  }
5156
5411
  }
@@ -5412,14 +5667,7 @@ function buildSitemap(urls) {
5412
5667
  return alternates.filter((a) => a.hreflang !== "x-default").map((self) => `<url><loc>${escapeAttr(self.href)}</loc>${alts}</url>`);
5413
5668
  }).join("")}</urlset>\n`;
5414
5669
  }
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) {
5670
+ function parseArgs(raw, attribute) {
5423
5671
  if (!raw) return void 0;
5424
5672
  try {
5425
5673
  return JSON.parse(decodeEntities(raw));
@@ -5463,17 +5711,18 @@ function findClose(html, tagName, from, inSkip) {
5463
5711
  }
5464
5712
  return null;
5465
5713
  }
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);
5714
+ function setAttribute(ms, html, chunkStart, openEnd, attrs, name, value) {
5715
+ const written = `"${escapeAttr(value)}"`;
5716
+ const existing = attrs.get(name.toLowerCase());
5469
5717
  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}"`);
5718
+ const from = chunkStart + existing.start;
5719
+ const to = chunkStart + existing.end;
5720
+ if (from === to) ms.appendLeft(from, `=${written}`);
5721
+ else if (html.slice(from, to) !== written) ms.overwrite(from, to, written);
5473
5722
  return;
5474
5723
  }
5475
5724
  const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
5476
- ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
5725
+ ms.appendLeft(insertAt, ` ${name}=${written}`);
5477
5726
  }
5478
5727
  function richToHtml(nodes, allowed, links) {
5479
5728
  let out = "";
@@ -5497,9 +5746,6 @@ function escapeHtml(text) {
5497
5746
  function escapeAttr(text) {
5498
5747
  return escapeHtml(text).replace(/"/g, "&quot;");
5499
5748
  }
5500
- function decodeEntities(text) {
5501
- return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
5502
- }
5503
5749
  // src/cli/commands/render.ts
5504
5750
  async function renderCommand(cfg, values) {
5505
5751
  const result = await renderSite(cfg, {
@@ -5573,19 +5819,14 @@ async function statusCommand(cfg, values) {
5573
5819
  }
5574
5820
  // src/cli/commands/translate.ts
5575
5821
  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), {
5822
+ const dryRun = values["dry-run"];
5823
+ const result = await translateProject(cfg, {
5580
5824
  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
5825
+ dryRun,
5826
+ model: values.model,
5827
+ onProgress: reportProgress
5587
5828
  });
5588
- if (values["dry-run"]) {
5829
+ if (dryRun) {
5589
5830
  const entries = Object.entries(result.pending);
5590
5831
  if (entries.length === 0) {
5591
5832
  console.log("[verbaly] nothing to translate ✓");
@@ -5594,30 +5835,20 @@ async function translateCommand(cfg, values) {
5594
5835
  for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.length} missing: ${keys.join(", ")}`);
5595
5836
  return;
5596
5837
  }
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);
5838
+ for (const [locale, keys] of Object.entries(result.written)) console.log(` ${locale}: +${keys.length} translated (draft)`);
5839
+ for (const [locale, keys] of Object.entries(result.kept)) console.log(` ${locale}: ${counted(keys.length, "message")} kept as written while this ran`);
5840
+ if (result.lock) console.log(` ${formatFinding({
5841
+ kind: "lock",
5842
+ ...result.lock
5843
+ }, cfg.root)}`);
5617
5844
  for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
5618
5845
  for (const line of formatTranslateFailures(result.failed)) console.error(line);
5619
5846
  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 ✓");
5847
+ if ([
5848
+ result.written,
5849
+ result.kept,
5850
+ result.invalid
5851
+ ].every((record) => Object.keys(record).length === 0) && result.failed.length === 0) console.log("[verbaly] nothing to translate ✓");
5621
5852
  }
5622
5853
  function reportProgress(progress) {
5623
5854
  const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
@@ -5720,16 +5951,23 @@ function wrapCode(code, file) {
5720
5951
  client: false
5721
5952
  };
5722
5953
  }
5723
- const hasT = declaresT(ast);
5954
+ const scopes = tScopes(ast);
5724
5955
  const client = hasDirective(ast, "use client");
5725
5956
  const s = new MagicString(code);
5726
5957
  const visited = /* @__PURE__ */ new Set();
5727
5958
  let changed = false;
5959
+ let reached = true;
5960
+ const write = (start, end, template) => {
5961
+ s.overwrite(start, end, "{t`" + template + "`}");
5962
+ changed = true;
5963
+ if (!tReaches(scopes, start)) reached = false;
5964
+ };
5728
5965
  walk$1(ast, (node) => {
5729
5966
  if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
5730
5967
  if (visited.has(node)) return;
5731
5968
  processElement(node);
5732
5969
  });
5970
+ const hasT = changed ? reached : scopes.some((scope) => scope.bound);
5733
5971
  return changed ? {
5734
5972
  code: s.toString(),
5735
5973
  wrapped,
@@ -5810,8 +6048,7 @@ function wrapCode(code, file) {
5810
6048
  if (isIdentifierLike(report)) return;
5811
6049
  const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
5812
6050
  const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
5813
- s.overwrite(start, end, "{t`" + template + "`}");
5814
- changed = true;
6051
+ write(start, end, template);
5815
6052
  wrapped.push({
5816
6053
  file,
5817
6054
  line: line(first),
@@ -5828,8 +6065,7 @@ function wrapCode(code, file) {
5828
6065
  if (value?.type !== "StringLiteral") continue;
5829
6066
  const raw = value.value;
5830
6067
  if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;
5831
- s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
5832
- changed = true;
6068
+ write(value.start, value.end, escapeTemplate(raw));
5833
6069
  wrapped.push({
5834
6070
  file,
5835
6071
  line: line(value),
@@ -5868,19 +6104,59 @@ function isIdentifierLike(text) {
5868
6104
  function hasDirective(program, value) {
5869
6105
  return (program.directives ?? []).some((d) => d.value?.value === value);
5870
6106
  }
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;
6107
+ const CALLS = /* @__PURE__ */ new Set([
6108
+ "CallExpression",
6109
+ "NewExpression",
6110
+ "OptionalCallExpression"
6111
+ ]);
6112
+ function tScopes(program) {
6113
+ const scopes = [];
6114
+ const mark = (scope, bound) => {
6115
+ scopes.push({
6116
+ start: scope.start,
6117
+ end: scope.end,
6118
+ bound
6119
+ });
6120
+ };
6121
+ const visit = (node, scope, argument) => {
6122
+ let inner = scope;
6123
+ if (FUNCTIONS.has(node.type)) {
6124
+ inner = node;
6125
+ if (node.type === "FunctionDeclaration" && isTName(node.id?.name)) mark(scope, true);
6126
+ for (const param of node.params ?? []) {
6127
+ if (!bindsT(param)) continue;
6128
+ mark(node, !(argument && namesT(param)));
6129
+ }
6130
+ } else if (node.type === "ImportDeclaration") {
6131
+ if (node.specifiers.map((spec) => spec.local).some((local) => isTName(local?.name))) mark(program, true);
5877
6132
  return;
6133
+ } else if (node.type === "VariableDeclarator" && bindsT(node.id)) mark(scope, true);
6134
+ const args = CALLS.has(node.type) ? node.arguments : void 0;
6135
+ for (const key in node) {
6136
+ if (key === "loc" || key.endsWith("Comments") || key === "extra") continue;
6137
+ const value = node[key];
6138
+ for (const child of Array.isArray(value) ? value : [value]) if (isAstNode(child)) visit(child, inner, args?.includes(child) ?? false);
5878
6139
  }
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;
6140
+ };
6141
+ visit(program, program, false);
6142
+ return scopes;
6143
+ }
6144
+ function tReaches(scopes, position) {
6145
+ let nearest;
6146
+ for (const scope of scopes) {
6147
+ if (position < scope.start || position >= scope.end) continue;
6148
+ const size = scope.end - scope.start;
6149
+ const best = nearest ? nearest.end - nearest.start : Infinity;
6150
+ if (size < best || size === best && scope.bound) nearest = scope;
6151
+ }
6152
+ return nearest?.bound ?? false;
6153
+ }
6154
+ function isAstNode(value) {
6155
+ return typeof value?.type === "string";
6156
+ }
6157
+ function namesT(param) {
6158
+ const target = param.type === "AssignmentPattern" ? param.left : param;
6159
+ return target.type === "Identifier" && isTName(target.name);
5884
6160
  }
5885
6161
  function bindsT(pattern) {
5886
6162
  if (!pattern) return false;
@@ -5927,35 +6203,46 @@ function trailingWs(text) {
5927
6203
  function line(node) {
5928
6204
  return node.loc?.start?.line ?? 1;
5929
6205
  }
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
- }
6206
+ function formatWrapResult(result, write) {
5937
6207
  const blocked = new Set(result.blocked.map((entry) => entry.file));
5938
6208
  const done = result.changed.filter((file) => !blocked.has(file));
5939
6209
  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")}`;
6210
+ let counts = `${write ? "wrapped" : "would wrap"} ${counted(texts.length, "text")} in ${counted(done.length, "file")}`;
5943
6211
  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) {
6212
+ if (!write && waiting > 0) counts += `, and ${counted(waiting, "text")} in ${counted(blocked.size, "file")} once t is in scope`;
6213
+ const lines = [];
6214
+ for (const entry of write ? texts : result.wrapped) {
5947
6215
  const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
5948
- console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
6216
+ lines.push(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
5949
6217
  }
5950
6218
  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})`);
6219
+ lines.push(" needs a human:");
6220
+ for (const entry of result.skipped) lines.push(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
5953
6221
  }
5954
6222
  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");
6223
+ lines.push(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
6224
+ for (const entry of result.blocked) lines.push(` ${entry.file} ${counted(entry.texts, "text")}, ${entry.binding}`);
6225
+ }
6226
+ return {
6227
+ counts,
6228
+ lines,
6229
+ files: done.length
6230
+ };
6231
+ }
6232
+ // src/cli/commands/wrap.ts
6233
+ async function wrapCommand(cfg, values) {
6234
+ const write = values.write === true;
6235
+ const result = await wrapProject(cfg, { write });
6236
+ if (result.wrapped.length === 0 && result.skipped.length === 0) {
6237
+ console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
6238
+ return;
6239
+ }
6240
+ const report = formatWrapResult(result, write);
6241
+ const note = write ? "" : " (report only, use --write to apply)";
6242
+ console.log(`[verbaly] ${report.counts}${note}`);
6243
+ for (const line of report.lines) console.log(line);
6244
+ if (result.blocked.length > 0) console.log(" next: add t there, run verbaly wrap --write again, then verbaly extract");
6245
+ else if (write && report.files > 0) console.log(" next: run verbaly extract");
5959
6246
  }
5960
6247
  // src/cli/run.ts
5961
6248
  const HELP = `verbaly · i18n compiler
@@ -6034,14 +6321,38 @@ async function runCli(args = process.argv.slice(2)) {
6034
6321
  }
6035
6322
  if (rejectStrayFlags(command, values)) return;
6036
6323
  if (command === "init") return initCommand(values);
6037
- const cfg = await loadConfig(values.root ?? process.cwd(), {
6324
+ if (!Object.hasOwn(COMMANDS, command)) {
6325
+ console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
6326
+ process.exitCode = 1;
6327
+ return;
6328
+ }
6329
+ const root = values.root ?? process.cwd();
6330
+ const project = {
6038
6331
  dir: values.dir,
6039
- sourceLocale: values.source,
6040
- locales: csv(values.locales)
6332
+ sourceLocale: values.source
6333
+ };
6334
+ const narrowed = csv(values.locales);
6335
+ if (narrowed || command === "review" && values.locale) {
6336
+ const whole = await loadConfig(root, project);
6337
+ const typo = narrowed ? strangers(whole, "locales", narrowed) : strangers(whole, "locale", [values.locale]);
6338
+ if (typo) {
6339
+ console.error(typo);
6340
+ process.exitCode = 1;
6341
+ return;
6342
+ }
6343
+ }
6344
+ const cfg = await loadConfig(root, {
6345
+ ...project,
6346
+ locales: narrowed
6041
6347
  });
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;
6348
+ return COMMANDS[command](cfg, values, positionals);
6349
+ }
6350
+ function strangers(cfg, flag, named) {
6351
+ const unknown = named.filter((locale) => !cfg.locales.includes(locale));
6352
+ if (unknown.length === 0) return void 0;
6353
+ const dir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
6354
+ const start = cfg.localesDeclared ? `add ${unknown.join(", ")} to locales in your verbaly config` : `create ${unknown.map((locale) => `${dir}/${locale}.json`).join(", ")} holding {}`;
6355
+ 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
6356
  }
6046
6357
  function formatCliError(error) {
6047
6358
  const message = error instanceof Error ? error.message : String(error);
@@ -6104,4 +6415,4 @@ function rejectStrayFlags(command, values) {
6104
6415
  process.exitCode = 1;
6105
6416
  return true;
6106
6417
  }
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 };
6418
+ export { generateLocaleModule as $, relativeCheck as A, formatCollision as B, runBuildGate as C, resolveConfig as Ct, check as D, transformCode as E, translateCatalogs as F, loadState as G, STATE_FILE as H, writeDrafts as I, readState as J, markDrafts as K, syncProject as L, formatTranslateFailures as M, mergeTranslations as N, formatCheckResult as O, resolveProvider as P, generateDts as Q, collisionEntries as R, resolveVirtualId as S, loadConfig as St, writeBuildTypes as T, clearDrafts as U, formatFinding as V, effectiveDrafts as W, saveState as X, recordTranslations as Y, updateState as Z, SOURCE_FILE_RE as _, needsRelative as _t, formatRenderWarnings as a, extractProject as at, isTransformTarget as b, writeCatalog as bt, watchTree as c, syncCatalogs as ct, formatDoctorHealth as d, LOCALE_IMPORT as dt, generateRuntimeModule as et, formatStatusResult as f, MessageRegistry as ft, RESOLVED_VIRTUAL_ID as g, needsIcu as gt, LOCALE_MODULE_PREFIX as h, loadCatalogs as ht, wrapProject as i, collectOrigins as it, translateProject as j, formatCheckWarnings as k, doctor as l, stableKey as lt, reportOutsideInclude as m, counted as mt, runCli as n, validateMessage as nt, renderSite as o, pruneCatalogs as ot, status as p, clientCatalogs as pt, outdatedTranslations as q, formatWrapResult as r, validatePair as rt, init as s, shippedCatalogs as st, formatCliError as t, writeDts as tt, formatDoctorEntry as u, APP_ID as ut, clientModules as v, parseCatalog as vt, transformSource as w, targetLocales as wt, loadVirtualModule as x, isModuleNotFound as xt, createSourceFilter as y, readCatalog as yt, createDevReporter as z };