@verbaly/compiler 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -14,16 +14,37 @@ function catalogPath(cfg, locale) {
14
14
  return join(cfg.dir, `${locale}.json`);
15
15
  }
16
16
  function readCatalog(cfg, locale) {
17
+ const tree = readTree(cfg, locale);
18
+ const bad = badLeaf(tree);
19
+ if (bad) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} has a non-string value at "${bad}", catalog values are text (groups of text are fine): fix the value`);
20
+ return flatten(tree);
21
+ }
22
+ function badLeaf(tree, prefix = "") {
23
+ for (const [key, value] of Object.entries(tree)) {
24
+ const path = prefix ? `${prefix}.${key}` : key;
25
+ if (typeof value === "string") continue;
26
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return path;
27
+ const bad = badLeaf(value, path);
28
+ if (bad) return bad;
29
+ }
30
+ }
31
+ function readTree(cfg, locale) {
17
32
  let content;
18
33
  try {
19
34
  content = readFileSync(catalogPath(cfg, locale), "utf8");
20
35
  } catch {
21
36
  return {};
22
37
  }
38
+ const parsed = parseTree(content);
39
+ if (parsed) return parsed;
40
+ throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`);
41
+ }
42
+ function parseTree(content) {
43
+ const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
23
44
  try {
24
- return JSON.parse(content.replace(/^\uFEFF/, ""));
25
- } catch (error) {
26
- throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`, { cause: error });
45
+ return JSON.parse(body);
46
+ } catch {
47
+ return;
27
48
  }
28
49
  }
29
50
  function loadCatalogs(cfg) {
@@ -31,25 +52,57 @@ function loadCatalogs(cfg) {
31
52
  for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
32
53
  return catalogs;
33
54
  }
34
- function serializeCatalog(catalog) {
55
+ function isNested(tree) {
56
+ return Object.values(tree).some((value) => typeof value === "object" && value !== null);
57
+ }
58
+ function nest(catalog) {
59
+ const tree = {};
60
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
61
+ const parts = key.split(".");
62
+ const leaf = parts[parts.length - 1];
63
+ let node = parts.length > 1 ? tree : void 0;
64
+ for (let i = 0; node && i < parts.length - 1; i++) {
65
+ const next = node[parts[i]] ??= {};
66
+ node = typeof next === "object" && next !== null ? next : void 0;
67
+ }
68
+ if (node && typeof node[leaf] !== "object") node[leaf] = message;
69
+ else tree[key] = message;
70
+ }
71
+ return tree;
72
+ }
73
+ function sortTree(tree) {
35
74
  const sorted = {};
36
- for (const key of Object.keys(catalog).sort()) {
37
- const value = catalog[key];
38
- if (value !== void 0) sorted[key] = value;
75
+ for (const key of Object.keys(tree).sort()) {
76
+ const value = tree[key];
77
+ if (typeof value === "string") sorted[key] = value;
78
+ else if (value !== void 0) sorted[key] = sortTree(value);
39
79
  }
40
- return JSON.stringify(sorted, null, 2) + "\n";
80
+ return sorted;
81
+ }
82
+ function serializeCatalog(catalog, nested = false) {
83
+ return JSON.stringify(sortTree(nested ? nest(catalog) : catalog), null, 2) + "\n";
41
84
  }
42
85
  function writeCatalog(cfg, locale, catalog) {
43
- const serialized = serializeCatalog(catalog);
44
86
  const path = catalogPath(cfg, locale);
87
+ let existing;
45
88
  try {
46
- if (readFileSync(path, "utf8") === serialized) return serialized;
89
+ existing = readFileSync(path, "utf8");
47
90
  } catch {
48
91
  mkdirSync(cfg.dir, { recursive: true });
49
92
  }
93
+ const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing));
94
+ if (existing === serialized) return serialized;
50
95
  writeFileSync(path, serialized);
51
96
  return serialized;
52
97
  }
98
+ function wantsNesting(cfg, locale, existing) {
99
+ if (existing !== void 0) {
100
+ const tree = parseTree(existing);
101
+ return tree !== void 0 && isNested(tree);
102
+ }
103
+ if (locale === cfg.sourceLocale) return false;
104
+ return isNested(readTree(cfg, cfg.sourceLocale));
105
+ }
53
106
  //#endregion
54
107
  //#region src/validate.ts
55
108
  const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
@@ -665,6 +718,14 @@ function definedOnly(config) {
665
718
  return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
666
719
  }
667
720
  //#endregion
721
+ //#region src/warn.ts
722
+ const warned = /* @__PURE__ */ new Set();
723
+ function warnOnce(message, dedupeKey = message) {
724
+ if (warned.has(dedupeKey)) return;
725
+ warned.add(dedupeKey);
726
+ console.warn(`[verbaly] ${message}`);
727
+ }
728
+ //#endregion
668
729
  //#region src/registry.ts
669
730
  var MessageRegistry = class {
670
731
  files = /* @__PURE__ */ new Map();
@@ -679,7 +740,7 @@ var MessageRegistry = class {
679
740
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
680
741
  const existing = out.get(msg.key);
681
742
  if (existing) {
682
- if (existing.message !== msg.message) console.warn(`[verbaly] key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped.`);
743
+ if (existing.message !== msg.message) warnOnce(`key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped`, `collision:${msg.key}`);
683
744
  continue;
684
745
  }
685
746
  out.set(msg.key, msg);
@@ -1328,8 +1389,23 @@ function init(options = {}) {
1328
1389
  };
1329
1390
  }
1330
1391
  //#endregion
1392
+ //#region src/text.ts
1393
+ function counted(count, noun, many = `${noun}s`) {
1394
+ return `${count} ${count === 1 ? noun : many}`;
1395
+ }
1396
+ //#endregion
1331
1397
  //#region src/doctor.ts
1332
1398
  const PREVIEW = 5;
1399
+ const ICON = {
1400
+ ok: "✓",
1401
+ warn: "⚠",
1402
+ error: "✗"
1403
+ };
1404
+ function formatDoctorEntry(entry) {
1405
+ const head = ` ${ICON[entry.level]} ${entry.check}: ${entry.message}`;
1406
+ return entry.fix ? `${head}
1407
+ fix: ${entry.fix}` : head;
1408
+ }
1333
1409
  async function doctor(cfg) {
1334
1410
  const entries = [];
1335
1411
  const ok = (name, message) => entries.push({
@@ -1378,7 +1454,7 @@ async function doctor(cfg) {
1378
1454
  error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
1379
1455
  }
1380
1456
  }
1381
- if (catalogsHealthy) ok("catalogs", `${cfg.locales.length} locales (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/`);
1457
+ if (catalogsHealthy) ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/`);
1382
1458
  }
1383
1459
  const source = catalogs[cfg.sourceLocale];
1384
1460
  if (source && Object.keys(source).length === 0) warn("source", `source catalog ${cfg.sourceLocale}.json is empty`, "write your first t`…` message and run `npx verbaly extract`");
@@ -1401,41 +1477,40 @@ async function doctor(cfg) {
1401
1477
  const unreadable = registry.parseErrors();
1402
1478
  if (unreadable.length > 0) {
1403
1479
  const first = unreadable[0];
1404
- const one = unreadable.length === 1;
1405
- warn("sources", `${unreadable.length} ${one ? "file" : "files"} could not be parsed, so ${one ? "its" : "their"} messages are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
1480
+ warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
1406
1481
  }
1407
1482
  const stray = registry.strayImports();
1408
1483
  if (stray.length > 0) {
1409
1484
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1410
- error("imports", `${files.length} ${files.length === 1 ? "file imports" : "files import"} t from a verbaly package, which never exports it (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
1485
+ error("imports", `t is imported from a verbaly package, which never exports it, in ${counted(files.length, "file")} (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
1411
1486
  }
1412
1487
  const escaped = [...registry.messages().values()].map((msg) => ({
1413
1488
  file: rel(msg.file),
1414
1489
  slice: escapedSyntax(msg.message)
1415
1490
  })).filter((entry) => entry.slice !== void 0);
1416
- if (escaped.length > 0) warn("messages", `${escaped.length} extracted ${escaped.length === 1 ? "message keeps" : "messages keep"} a block as literal text (${escaped[0].file}: ${escaped[0].slice})`, "a tagged template takes its values from ${…}: use t(key, params) for a plural or format block");
1491
+ if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${escaped[0].slice})`, "a tagged template takes its values from ${…}: use t(key, params) for a plural or format block");
1417
1492
  }
1418
1493
  if (source && scanning) {
1419
1494
  const extracted = registry.messages();
1420
1495
  const used = registry.usedKeys();
1421
1496
  const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
1422
- if (orphans.length > 0) warn("orphans", `${orphans.length} catalog ${orphans.length === 1 ? "key is" : "keys are"} no longer referenced (${preview(orphans)})`, "run `npx verbaly extract --prune` to drop them");
1497
+ if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, "run `npx verbaly extract --prune` to drop them");
1423
1498
  else ok("orphans", "no orphan keys");
1424
1499
  }
1425
1500
  if (catalogsHealthy) {
1426
1501
  const result = check(cfg, catalogs, registry);
1427
- if (result.unknown.length > 0) error("keys", `${result.unknown.length} unknown ${result.unknown.length === 1 ? "key" : "keys"} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
1502
+ if (result.unknown.length > 0) error("keys", `${counted(result.unknown.length, "unknown key")} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
1428
1503
  if (result.missing.length > 0) {
1429
1504
  const locales = [...new Set(result.missing.map((m) => m.locale))];
1430
- warn("translations", `${result.missing.length} missing ${result.missing.length === 1 ? "translation" : "translations"} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
1505
+ warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
1431
1506
  }
1432
1507
  const broken = result.broken.filter((entry) => entry.severity === "error");
1433
1508
  if (broken.length > 0) {
1434
1509
  const locales = [...new Set(broken.map((b) => b.locale))];
1435
- error("translations", `${broken.length} broken ${broken.length === 1 ? "translation" : "translations"} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
1510
+ error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
1436
1511
  }
1437
1512
  const warnings = result.broken.filter((entry) => entry.severity === "warning");
1438
- if (warnings.length > 0) warn("translations", `${warnings.length} structural ${warnings.length === 1 ? "warning" : "warnings"} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
1513
+ if (warnings.length > 0) warn("translations", `${counted(warnings.length, "structural warning")} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
1439
1514
  if (result.ok) ok("translations", "all translations complete");
1440
1515
  }
1441
1516
  return {
@@ -1447,15 +1522,6 @@ function preview(keys) {
1447
1522
  const head = keys.slice(0, PREVIEW).join(", ");
1448
1523
  return keys.length > PREVIEW ? `${head}, …` : head;
1449
1524
  }
1450
- function badLeaf(tree, prefix = "") {
1451
- for (const [key, value] of Object.entries(tree)) {
1452
- const path = prefix ? `${prefix}.${key}` : key;
1453
- if (typeof value === "string") continue;
1454
- if (value === null || typeof value !== "object" || Array.isArray(value)) return path;
1455
- const bad = badLeaf(value, path);
1456
- if (bad) return bad;
1457
- }
1458
- }
1459
1525
  //#endregion
1460
1526
  //#region src/drafts.ts
1461
1527
  const DRAFTS_FILE = ".verbaly-drafts.json";
@@ -1864,15 +1930,56 @@ function poUnquote(text) {
1864
1930
  }
1865
1931
  //#endregion
1866
1932
  //#region src/translate.ts
1933
+ const RETRY_STATUS = /* @__PURE__ */ new Set([
1934
+ 408,
1935
+ 409,
1936
+ 425,
1937
+ 429,
1938
+ 500,
1939
+ 502,
1940
+ 503,
1941
+ 504,
1942
+ 529
1943
+ ]);
1944
+ function retryable(error) {
1945
+ const status = error?.status;
1946
+ const code = error?.statusCode;
1947
+ const value = typeof status === "number" ? status : code;
1948
+ return typeof value === "number" ? RETRY_STATUS.has(value) : true;
1949
+ }
1950
+ function reason(error) {
1951
+ return error instanceof Error ? error.message : String(error);
1952
+ }
1953
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1954
+ async function attempt(run, retries, delay) {
1955
+ for (let round = 0;; round++) try {
1956
+ return await run();
1957
+ } catch (error) {
1958
+ if (round >= retries || !retryable(error)) throw error;
1959
+ await wait(delay * 2 ** round);
1960
+ }
1961
+ }
1962
+ async function pooled(jobs, limit, run) {
1963
+ let next = 0;
1964
+ const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
1965
+ while (next < jobs.length) await run(jobs[next++]);
1966
+ });
1967
+ await Promise.all(workers);
1968
+ }
1867
1969
  async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1868
1970
  const batchSize = options.batchSize ?? 20;
1971
+ const concurrency = Math.max(1, options.concurrency ?? 4);
1972
+ const retries = Math.max(0, options.retries ?? 2);
1973
+ const retryDelay = options.retryDelay ?? 500;
1869
1974
  const targets = targetLocales(cfg, options.locales);
1870
1975
  const source = catalogs[cfg.sourceLocale] ?? {};
1871
1976
  const result = {
1872
1977
  translated: {},
1873
1978
  invalid: {},
1874
- pending: {}
1979
+ pending: {},
1980
+ failed: []
1875
1981
  };
1982
+ const jobs = [];
1876
1983
  for (const locale of targets) {
1877
1984
  const catalog = catalogs[locale] ??= {};
1878
1985
  const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
@@ -1881,31 +1988,78 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1881
1988
  result.pending[locale] = missing;
1882
1989
  continue;
1883
1990
  }
1991
+ const batches = Math.ceil(missing.length / batchSize);
1884
1992
  for (let i = 0; i < missing.length; i += batchSize) {
1885
- const keys = missing.slice(i, i + batchSize);
1886
- const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
1887
- const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins[key]).map((key) => [key, options.origins[key]])) : void 0;
1888
- const out = await provider({
1993
+ const index = Math.floor(i / batchSize) + 1;
1994
+ jobs.push({
1995
+ locale,
1996
+ index,
1997
+ batches,
1998
+ keys: missing.slice(i, i + batchSize)
1999
+ });
2000
+ }
2001
+ }
2002
+ await pooled(jobs, concurrency, async (job) => {
2003
+ const { locale, keys } = job;
2004
+ const catalog = catalogs[locale];
2005
+ const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
2006
+ const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins[key]).map((key) => [key, options.origins[key]])) : void 0;
2007
+ let out;
2008
+ try {
2009
+ out = await attempt(() => provider({
1889
2010
  sourceLocale: cfg.sourceLocale,
1890
2011
  targetLocale: locale,
1891
2012
  messages,
1892
- origins
2013
+ origins,
2014
+ instructions: cfg.translate.instructions,
2015
+ glossary: glossaryFor(cfg, locale, messages)
2016
+ }), retries, retryDelay);
2017
+ } catch (error) {
2018
+ const message = reason(error);
2019
+ result.failed.push({
2020
+ locale,
2021
+ keys,
2022
+ error: message
1893
2023
  });
1894
- for (const key of keys) {
1895
- const text = out[key];
1896
- if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
1897
- catalog[key] = text;
1898
- (result.translated[locale] ??= []).push(key);
1899
- } else (result.invalid[locale] ??= []).push(key);
1900
- }
2024
+ options.onProgress?.({
2025
+ ...progressOf(job),
2026
+ error: message
2027
+ });
2028
+ return;
1901
2029
  }
1902
- }
2030
+ for (const key of keys) {
2031
+ const text = out[key];
2032
+ if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
2033
+ catalog[key] = text;
2034
+ (result.translated[locale] ??= []).push(key);
2035
+ } else (result.invalid[locale] ??= []).push(key);
2036
+ }
2037
+ options.onProgress?.(progressOf(job));
2038
+ });
2039
+ for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
2040
+ for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
2041
+ result.failed.sort((a, b) => a.locale.localeCompare(b.locale) || compare(a.keys, b.keys));
1903
2042
  return result;
1904
2043
  }
2044
+ function compare(a, b) {
2045
+ return (a[0] ?? "").localeCompare(b[0] ?? "");
2046
+ }
2047
+ function formatTranslateFailures(failed) {
2048
+ const grouped = [];
2049
+ for (const entry of failed) {
2050
+ const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
2051
+ if (same) same.keys = [...same.keys, ...entry.keys];
2052
+ else grouped.push({
2053
+ ...entry,
2054
+ keys: [...entry.keys]
2055
+ });
2056
+ }
2057
+ return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
2058
+ }
1905
2059
  async function resolveProvider(cfg, model) {
1906
2060
  const configured = cfg.translate.provider;
1907
2061
  if (typeof configured === "function") return configured;
1908
- const { claudeProvider } = await import("./claude-h9WA0ppg.js");
2062
+ const { claudeProvider } = await import("./claude-ByRATJ03.js");
1909
2063
  return claudeProvider({ model: model ?? cfg.translate.model });
1910
2064
  }
1911
2065
  function structureMatches(source, translated) {
@@ -1915,6 +2069,26 @@ function structureMatches(source, translated) {
1915
2069
  return false;
1916
2070
  }
1917
2071
  }
2072
+ function progressOf(job) {
2073
+ return {
2074
+ locale: job.locale,
2075
+ batch: job.index,
2076
+ batches: job.batches,
2077
+ keys: job.keys.length
2078
+ };
2079
+ }
2080
+ function glossaryFor(cfg, locale, messages) {
2081
+ const entries = cfg.translate.glossary;
2082
+ if (!entries) return void 0;
2083
+ const text = Object.values(messages).join("\n").toLowerCase();
2084
+ const out = {};
2085
+ for (const [term, rendering] of Object.entries(entries)) {
2086
+ if (!text.includes(term.toLowerCase())) continue;
2087
+ const value = typeof rendering === "string" ? rendering : rendering[locale];
2088
+ if (value) out[term] = value;
2089
+ }
2090
+ return Object.keys(out).length > 0 ? out : void 0;
2091
+ }
1918
2092
  //#endregion
1919
2093
  //#region src/exchange.ts
1920
2094
  function isMobileFormat(format) {
@@ -1939,7 +2113,8 @@ function exportCatalogs(cfg, catalogs, options = {}) {
1939
2113
  const untranslated = all.filter((entry) => !entry.target);
1940
2114
  const entries = options.missing ? untranslated : all;
1941
2115
  const path = join(dir, `${locale}.${format === "xliff" ? "xlf" : format}`);
1942
- writeFileSync(path, format === "csv" ? toCsv(entries) : format === "po" ? toPo(cfg.sourceLocale, locale, entries) : toXliff(cfg.sourceLocale, locale, entries));
2116
+ const content = format === "csv" ? toCsv(entries) : format === "po" ? toPo(cfg.sourceLocale, locale, entries) : toXliff(cfg.sourceLocale, locale, entries);
2117
+ writeFileSync(path, content);
1943
2118
  files.push({
1944
2119
  locale,
1945
2120
  path,
@@ -1962,7 +2137,8 @@ function exportMobile(cfg, catalogs, format, dir, source, targets) {
1962
2137
  key,
1963
2138
  text: catalog[key] ?? ""
1964
2139
  })).filter((entry) => entry.text);
1965
- const path = join(dir, format === "android-xml" ? join(androidValuesDir(locale, cfg.sourceLocale), "strings.xml") : join(`${locale}.lproj`, "Localizable.strings"));
2140
+ const relative = format === "android-xml" ? join(androidValuesDir(locale, cfg.sourceLocale), "strings.xml") : join(`${locale}.lproj`, "Localizable.strings");
2141
+ const path = join(dir, relative);
1966
2142
  mkdirSync(dirname(path), { recursive: true });
1967
2143
  writeFileSync(path, format === "android-xml" ? toAndroidXml(entries) : toIosStrings(entries));
1968
2144
  files.push({
@@ -2107,12 +2283,14 @@ function csvRows(content) {
2107
2283
  let quoted = false;
2108
2284
  for (let i = 0; i < content.length; i++) {
2109
2285
  const char = content[i];
2110
- if (quoted) if (char === "\"") if (content[i + 1] === "\"") {
2111
- field += "\"";
2112
- i++;
2113
- } else quoted = false;
2114
- else field += char;
2115
- else if (char === "\"") quoted = true;
2286
+ if (quoted) {
2287
+ if (char === "\"") {
2288
+ if (content[i + 1] === "\"") {
2289
+ field += "\"";
2290
+ i++;
2291
+ } else quoted = false;
2292
+ } else field += char;
2293
+ } else if (char === "\"") quoted = true;
2116
2294
  else if (char === ",") {
2117
2295
  row.push(field);
2118
2296
  field = "";
@@ -2130,6 +2308,13 @@ function csvRows(content) {
2130
2308
  }
2131
2309
  //#endregion
2132
2310
  //#region src/render.ts
2311
+ function localeInstance(catalogs, locale, sourceLocale) {
2312
+ return createVerbaly({
2313
+ locale,
2314
+ fallback: sourceLocale,
2315
+ messages: catalogs
2316
+ });
2317
+ }
2133
2318
  const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
2134
2319
  const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
2135
2320
  const REDIRECT_OPEN = "<!--verbaly:redirect-->";
@@ -2146,11 +2331,7 @@ function renderHtml(html, options) {
2146
2331
  const richTags = new Set(options.richTags ?? RICH_TAGS);
2147
2332
  const globalLinks = options.richLinks;
2148
2333
  const sourceLocale = options.sourceLocale ?? "en";
2149
- const v = createVerbaly({
2150
- locale: options.locale,
2151
- fallback: sourceLocale,
2152
- messages: options.catalogs
2153
- });
2334
+ const v = options.instance ?? localeInstance(options.catalogs, options.locale, sourceLocale);
2154
2335
  const t = v.t;
2155
2336
  const ms = new MagicString(html);
2156
2337
  const missing = /* @__PURE__ */ new Set();
@@ -2205,8 +2386,10 @@ function renderHtml(html, options) {
2205
2386
  ...own
2206
2387
  } : own : globalLinks;
2207
2388
  const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
2208
- if (html.slice(openEnd, close.contentEnd) !== content) if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
2209
- else ms.overwrite(openEnd, close.contentEnd, content);
2389
+ if (html.slice(openEnd, close.contentEnd) !== content) {
2390
+ if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
2391
+ else ms.overwrite(openEnd, close.contentEnd, content);
2392
+ }
2210
2393
  filled.push([openEnd, close.contentEnd]);
2211
2394
  }
2212
2395
  }
@@ -2317,6 +2500,7 @@ async function renderSite(cfg, options = {}) {
2317
2500
  storageKey: redirect.storageKey
2318
2501
  };
2319
2502
  const catalogs = loadCatalogs(cfg);
2503
+ const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
2320
2504
  if (clean) {
2321
2505
  for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
2322
2506
  recursive: true,
@@ -2343,7 +2527,7 @@ async function renderSite(cfg, options = {}) {
2343
2527
  for (const locale of locales) {
2344
2528
  const result = renderHtml(html, {
2345
2529
  locale,
2346
- catalogs,
2530
+ instance: instances.get(locale),
2347
2531
  sourceLocale: cfg.sourceLocale,
2348
2532
  attribute,
2349
2533
  richTags: options.richTags,
@@ -2507,7 +2691,7 @@ function status(cfg, catalogs, registry, drafts = {}) {
2507
2691
  };
2508
2692
  }
2509
2693
  function formatStatusResult(result) {
2510
- const lines = [`[verbaly] ${result.messages} messages · source: ${result.source}`];
2694
+ const lines = [`[verbaly] ${counted(result.messages, "message")} · source: ${result.source}`];
2511
2695
  if (result.locales.length === 0) {
2512
2696
  lines.push(" no target locales (add locales to your config)");
2513
2697
  return lines.join("\n");
@@ -2886,18 +3070,12 @@ async function runCli(args = process.argv.slice(2)) {
2886
3070
  });
2887
3071
  if (command === "doctor") {
2888
3072
  const result = await doctor(cfg);
2889
- const icon = {
2890
- ok: "✓",
2891
- warn: "⚠",
2892
- error: "✗"
2893
- };
2894
- console.log(`[verbaly] doctor: ${plural(result.entries.length, "check")}`);
3073
+ console.log(`[verbaly] doctor: ${counted(result.entries.length, "check")}`);
2895
3074
  for (const entry of result.entries) {
2896
- const line = ` ${icon[entry.level]} ${entry.check}: ${entry.message}`;
3075
+ const line = formatDoctorEntry(entry);
2897
3076
  if (entry.level === "error") console.error(line);
2898
3077
  else if (entry.level === "warn") console.warn(line);
2899
3078
  else console.log(line);
2900
- if (entry.fix) console.log(` fix: ${entry.fix}`);
2901
3079
  }
2902
3080
  if (result.ok) console.log("[verbaly] setup looks healthy ✓");
2903
3081
  else {
@@ -2926,7 +3104,7 @@ async function runCli(args = process.argv.slice(2)) {
2926
3104
  if (cfg.dts !== false) writeDts(cfg, catalogs[cfg.sourceLocale] ?? {}, cfg.dts);
2927
3105
  }
2928
3106
  const total = registry.messages().size;
2929
- console.log(`[verbaly] ${plural(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
3107
+ console.log(`[verbaly] ${counted(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
2930
3108
  for (const [locale, keys] of Object.entries(added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
2931
3109
  reportParseErrors(cfg, registry);
2932
3110
  reportEscapedSyntax(cfg, registry);
@@ -2941,12 +3119,12 @@ async function runCli(args = process.argv.slice(2)) {
2941
3119
  if (command === "wrap") {
2942
3120
  const result = await wrapProject(cfg, { write: values.write });
2943
3121
  if (result.wrapped.length === 0 && result.skipped.length === 0) {
2944
- console.log(`[verbaly] nothing to wrap (${plural(result.files, "file")} scanned) ✓`);
3122
+ console.log(`[verbaly] nothing to wrap (${counted(result.files, "file")} scanned) ✓`);
2945
3123
  return;
2946
3124
  }
2947
3125
  const verb = values.write ? "wrapped" : "would wrap";
2948
3126
  const note = values.write ? "" : " (report only, use --write to apply)";
2949
- console.log(`[verbaly] ${verb} ${plural(result.wrapped.length, "text")} in ${plural(result.changed.length, "file")}${note}`);
3127
+ console.log(`[verbaly] ${verb} ${counted(result.wrapped.length, "text")} in ${counted(result.changed.length, "file")}${note}`);
2950
3128
  for (const entry of result.wrapped) {
2951
3129
  const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
2952
3130
  console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
@@ -3002,8 +3180,11 @@ async function runCli(args = process.argv.slice(2)) {
3002
3180
  const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
3003
3181
  locales: values.locales?.split(","),
3004
3182
  batchSize: cfg.translate.batchSize,
3183
+ concurrency: cfg.translate.concurrency,
3184
+ retries: cfg.translate.retries,
3005
3185
  dryRun: values["dry-run"],
3006
- origins: values["dry-run"] ? void 0 : await collectOrigins(cfg)
3186
+ origins: values["dry-run"] ? void 0 : await collectOrigins(cfg),
3187
+ onProgress: values["dry-run"] ? void 0 : reportProgress
3007
3188
  });
3008
3189
  if (values["dry-run"]) {
3009
3190
  const entries = Object.entries(result.pending);
@@ -3022,7 +3203,9 @@ async function runCli(args = process.argv.slice(2)) {
3022
3203
  }
3023
3204
  if (Object.keys(result.translated).length > 0) saveDrafts(cfg, drafts);
3024
3205
  for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
3025
- if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0) console.log("[verbaly] nothing to translate ✓");
3206
+ for (const line of formatTranslateFailures(result.failed)) console.error(line);
3207
+ if (result.failed.length > 0) process.exitCode = 1;
3208
+ if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0 && result.failed.length === 0) console.log("[verbaly] nothing to translate ✓");
3026
3209
  return;
3027
3210
  }
3028
3211
  if (command === "review") {
@@ -3043,11 +3226,11 @@ async function runCli(args = process.argv.slice(2)) {
3043
3226
  console.log(` ${locale}: ${keys.length} approved`);
3044
3227
  }
3045
3228
  saveDrafts(cfg, drafts);
3046
- console.log(`[verbaly] ${count} translations marked reviewed ✓`);
3229
+ console.log(`[verbaly] ${counted(count, "translation")} marked reviewed ✓`);
3047
3230
  return;
3048
3231
  }
3049
3232
  const total = entries.reduce((sum, [, keys]) => sum + keys.length, 0);
3050
- console.log(`[verbaly] ${total} machine translations awaiting review (--approve to accept)`);
3233
+ console.log(`[verbaly] ${counted(total, "machine translation")} awaiting review (--approve to accept)`);
3051
3234
  for (const [locale, keys] of entries) console.log(` ${locale}: ${keys.join(", ")}`);
3052
3235
  return;
3053
3236
  }
@@ -3081,8 +3264,8 @@ async function runCli(args = process.argv.slice(2)) {
3081
3264
  return;
3082
3265
  }
3083
3266
  const note = isMobileFormat(result.format) ? "untranslated skipped" : "untranslated";
3084
- console.log(`[verbaly] exported ${result.files.length} locales (${result.format}) → ${result.dir}`);
3085
- for (const file of result.files) console.log(` ${file.locale}: ${file.total} messages (${file.untranslated} ${note}) → ${file.path}`);
3267
+ console.log(`[verbaly] exported ${counted(result.files.length, "locale")} (${result.format}) → ${result.dir}`);
3268
+ for (const file of result.files) console.log(` ${file.locale}: ${counted(file.total, "message")} (${file.untranslated} ${note}) → ${file.path}`);
3086
3269
  return;
3087
3270
  }
3088
3271
  if (command === "import") {
@@ -3112,7 +3295,7 @@ async function runCli(args = process.argv.slice(2)) {
3112
3295
  if (draftsChanged) saveDrafts(cfg, drafts);
3113
3296
  for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
3114
3297
  for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
3115
- for (const [locale, keys] of Object.entries(result.unknown)) console.warn(` ${locale}: ${keys.length} unknown keys ignored (not in the source catalog): ${keys.join(", ")}`);
3298
+ for (const [locale, keys] of Object.entries(result.unknown)) console.warn(` ${locale}: ${counted(keys.length, "unknown key")} ignored (not in the source catalog): ${keys.join(", ")}`);
3116
3299
  if (Object.keys(result.imported).length === 0) console.log("[verbaly] nothing to import ✓");
3117
3300
  return;
3118
3301
  }
@@ -3127,8 +3310,8 @@ async function runCli(args = process.argv.slice(2)) {
3127
3310
  redirect: values.redirect,
3128
3311
  clean: values.clean
3129
3312
  });
3130
- console.log(`[verbaly] ${plural(result.files, "page")} × ${plural(result.locales.length, "locale")} (${result.locales.join(", ")})`);
3131
- for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${plural(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
3313
+ console.log(`[verbaly] ${counted(result.files, "page")} × ${counted(result.locales.length, "locale")} (${result.locales.join(", ")})`);
3314
+ for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
3132
3315
  return;
3133
3316
  }
3134
3317
  if (command === "pseudo") {
@@ -3136,19 +3319,21 @@ async function runCli(args = process.argv.slice(2)) {
3136
3319
  const locale = values.locale ?? "en-XA";
3137
3320
  const keys = pseudoCatalogs(cfg, catalogs, locale);
3138
3321
  writeCatalog(cfg, locale, catalogs[locale] ?? {});
3139
- console.log(`[verbaly] ${plural(keys.length, "message")} pseudo-localized → ${locale}`);
3322
+ console.log(`[verbaly] ${counted(keys.length, "message")} pseudo-localized → ${locale}`);
3140
3323
  return;
3141
3324
  }
3142
3325
  console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
3143
3326
  process.exitCode = 1;
3144
3327
  }
3328
+ function reportProgress(progress) {
3329
+ const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
3330
+ if (progress.error) console.warn(`${head}: failed (${progress.error}), continuing`);
3331
+ else console.log(`${head}: ${counted(progress.keys, "message")}`);
3332
+ }
3145
3333
  function formatCliError(error) {
3146
3334
  const message = error instanceof Error ? error.message : String(error);
3147
3335
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
3148
3336
  }
3149
- function plural(count, noun) {
3150
- return `${count} ${noun}${count === 1 ? "" : "s"}`;
3151
- }
3152
3337
  function reportParseErrors(cfg, registry) {
3153
3338
  for (const { file, message } of registry.parseErrors()) {
3154
3339
  const rel = relative(cfg.root, file).replaceAll("\\", "/");