@verbaly/compiler 0.69.1 → 0.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
2
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
3
4
  import { parseArgs } from "node:util";
4
5
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
@@ -300,7 +301,10 @@ function analyzeScript(code, file, options = {}) {
300
301
  return;
301
302
  }
302
303
  const key = staticString(args[0]);
303
- if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
304
+ if (key !== void 0) usedKeys.push({
305
+ key,
306
+ file
307
+ });
304
308
  } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
305
309
  });
306
310
  const renamed = bindings.renamed(options.renamed);
@@ -309,8 +313,7 @@ function analyzeScript(code, file, options = {}) {
309
313
  if (candidate.kind === "call") {
310
314
  if (renamed.has(candidate.name)) usedKeys.push({
311
315
  key: candidate.key,
312
- file,
313
- loose: true
316
+ file
314
317
  });
315
318
  continue;
316
319
  }
@@ -452,8 +455,7 @@ function missedKey(code, node, names) {
452
455
  const tag = node.tag;
453
456
  if (tag.type === "CallExpression") {
454
457
  const args = tag.arguments;
455
- const first = args[0];
456
- return args.length === 1 && first?.type === "StringLiteral" ? first.value : void 0;
458
+ return args.length === 1 ? staticString(args[0]) : void 0;
457
459
  }
458
460
  const message = buildMessage(code, node.quasi, names);
459
461
  return message ? stableKey(message.text) : void 0;
@@ -465,20 +467,13 @@ function collectDeclaredKeys(node, file, out) {
465
467
  const value = property.value;
466
468
  const key = staticString(value);
467
469
  if (key !== void 0) {
468
- if (key !== "") out.push(usedKey(key, file, value));
470
+ if (key !== "") out.push({
471
+ key,
472
+ file
473
+ });
469
474
  } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
470
475
  }
471
476
  }
472
- function usedKey(key, file, node) {
473
- return node?.type === "StringLiteral" ? {
474
- key,
475
- file
476
- } : {
477
- key,
478
- file,
479
- loose: true
480
- };
481
- }
482
477
  function staticString(node) {
483
478
  if (!node) return void 0;
484
479
  if (node.type === "StringLiteral") return node.value;
@@ -527,14 +522,17 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
527
522
  const value = idAttr.value;
528
523
  const id = staticString(value);
529
524
  if (id === void 0) return;
530
- if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
525
+ if (attrs.length === 1 && children?.length) {
531
526
  const built = buildTransMessage(code, children, names);
532
527
  if (built?.text.trim()) {
533
528
  push(id, built);
534
529
  return;
535
530
  }
536
531
  }
537
- usedKeys.push(usedKey(id, file, value));
532
+ usedKeys.push({
533
+ key: id,
534
+ file
535
+ });
538
536
  return;
539
537
  }
540
538
  if (attrs.length > 0) return;
@@ -552,10 +550,10 @@ function explicitId(tag, names) {
552
550
  const obj = callee.object;
553
551
  if (!isTReference(obj, names)) return void 0;
554
552
  const args = tag.arguments;
555
- const first = args[0];
556
- if (args.length !== 1 || first?.type !== "StringLiteral") return void 0;
553
+ const key = args.length === 1 ? staticString(args[0]) : void 0;
554
+ if (key === void 0) return void 0;
557
555
  return {
558
- key: first.value,
556
+ key,
559
557
  refStart: obj.start,
560
558
  refEnd: obj.end
561
559
  };
@@ -1227,6 +1225,10 @@ function formatFinding(finding, root) {
1227
1225
  case "escaped": return `${sourcePlace(finding.site, root)}: ${finding.slice} renders as literal text, a tagged template has no params (use t(key, params) for a plural or format block, or pass a \${…} value)`;
1228
1226
  case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
1229
1227
  case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
1228
+ case "lock": {
1229
+ const lock = sourcePlace(finding, root);
1230
+ 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`;
1231
+ }
1230
1232
  }
1231
1233
  }
1232
1234
  function findingId(finding) {
@@ -1238,6 +1240,7 @@ function findingId(finding) {
1238
1240
  case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1239
1241
  case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1240
1242
  case "unparsed": return `unparsed:${finding.file}`;
1243
+ case "lock": return `lock:${finding.file}`;
1241
1244
  }
1242
1245
  }
1243
1246
  function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
@@ -1554,7 +1557,11 @@ function findConfigFile(root) {
1554
1557
  async function loadConfigFile(root) {
1555
1558
  for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
1556
1559
  const path = join(root, name);
1557
- if (existsSync(path)) return (await import(`${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`)).default ?? {};
1560
+ if (existsSync(path)) {
1561
+ const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
1562
+ delete createRequire(import.meta.url).cache[resolve(path)];
1563
+ return (await import(url)).default ?? {};
1564
+ }
1558
1565
  }
1559
1566
  for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
1560
1567
  const path = join(root, name);
@@ -1600,130 +1607,53 @@ function definedOnly(config) {
1600
1607
  return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
1601
1608
  }
1602
1609
  //#endregion
1603
- //#region src/tag.ts
1604
- function isLocaleTag(tag) {
1605
- try {
1606
- Intl.getCanonicalLocales(tag);
1607
- return true;
1608
- } catch {
1609
- return false;
1610
- }
1611
- }
1612
- function suggestTag(tag) {
1613
- const near = tag.replace(/_/g, "-");
1614
- return near !== tag && isLocaleTag(near) ? near : void 0;
1615
- }
1616
- function projectLocale(tag, locales) {
1617
- if (locales.includes(tag)) return tag;
1618
- const plain = (value) => value.replace(/_/g, "-").toLowerCase();
1619
- return locales.find((locale) => plain(locale) === plain(tag));
1620
- }
1621
- //#endregion
1622
- //#region src/init.ts
1623
- function cliReachable(root) {
1624
- const bin = join(root, "node_modules", ".bin");
1625
- return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
1626
- }
1627
- const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
1628
- function configSource(options, typescript) {
1629
- const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
1630
- if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
1631
- if (options.dir) fields.push(` dir: '${options.dir}',`);
1632
- const body = `export default {\n${fields.join("\n")}\n}`;
1633
- if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
1634
- return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
1635
- }
1636
- async function init(input = {}) {
1637
- const root = input.root ?? process.cwd();
1638
- const created = [];
1639
- const skipped = [];
1640
- const renamed = [];
1641
- const refused = [];
1642
- const typed = input.locales?.flatMap((locale) => {
1643
- if (isLocaleTag(locale)) return [locale];
1644
- const near = suggestTag(locale);
1645
- if (near) renamed.push({
1646
- from: locale,
1647
- to: near
1648
- });
1649
- else refused.push(locale);
1650
- return near ? [near] : [];
1651
- });
1652
- const locales = typed && [...new Set(typed)];
1653
- let sourceLocale = input.sourceLocale;
1654
- if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
1655
- const near = suggestTag(sourceLocale);
1656
- if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
1657
- renamed.push({
1658
- from: sourceLocale,
1659
- to: near
1660
- });
1661
- sourceLocale = near;
1662
- }
1663
- const options = {
1664
- ...input,
1665
- locales,
1666
- sourceLocale
1667
- };
1668
- const existing = findConfigFile(root);
1669
- const typescript = existsSync(join(root, "tsconfig.json"));
1670
- const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
1671
- if (existing) skipped.push(existing);
1672
- else {
1673
- writeFileSync(join(root, configFile), configSource(options, typescript));
1674
- created.push(configFile);
1675
- }
1676
- const fromFile = existing ? await loadConfigFile(root) : {};
1677
- const scaffold = {
1678
- dir: options.dir ?? fromFile.dir,
1679
- sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
1680
- locales: options.locales ?? fromFile.locales
1681
- };
1682
- const dir = join(root, scaffold.dir ?? "locales");
1683
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1684
- for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
1685
- const file = join(dir, `${locale}.json`);
1686
- const label = relative(root, file).replaceAll("\\", "/");
1687
- if (existsSync(file)) skipped.push(label);
1688
- else {
1689
- writeFileSync(file, "{}\n");
1690
- created.push(label);
1691
- }
1692
- }
1693
- const host = detectHost(root);
1694
- const next = host ? [installCommand(root, host.install), host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1695
- return {
1696
- created,
1697
- skipped,
1698
- host: host?.name,
1699
- configFile,
1700
- next,
1701
- renamed,
1702
- refused
1703
- };
1704
- }
1705
- //#endregion
1706
1610
  //#region src/state.ts
1707
- const STATE_FILE = ".verbaly-state.json";
1611
+ const STATE_FILE = "verbaly.lock";
1612
+ const LOCK_VERSION = 1;
1613
+ const README = "Written by Verbaly: the source text each translation was made for, which ones are drafts, and which languages migrate converted. Commit it with your catalogs and never edit it: deleting it marks every draft as reviewed.";
1614
+ const LEGACY_STATE_FILE = ".verbaly-state.json";
1708
1615
  const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1709
- function statePath(cfg, file = STATE_FILE) {
1710
- return join(cfg.dir, file);
1616
+ function statePath(cfg) {
1617
+ return join(cfg.root, STATE_FILE);
1618
+ }
1619
+ function legacyPaths(cfg) {
1620
+ return [join(cfg.dir, LEGACY_STATE_FILE), join(cfg.dir, LEGACY_DRAFTS_FILE)];
1711
1621
  }
1712
1622
  function loadState(cfg) {
1713
- const current = readJson(statePath(cfg));
1714
- if (current !== void 0 && !isObject(current)) throw corrupt(statePath(cfg));
1715
- const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1716
- if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1717
- const state = isObject(current) ? {
1718
- drafts: readDrafts(current.drafts),
1719
- fingerprints: readFingerprints(current.fingerprints)
1720
- } : {
1623
+ const lock = readObject(statePath(cfg));
1624
+ if (lock) checkVersion(statePath(cfg), lock.version);
1625
+ const [legacyState, legacyDrafts] = legacyPaths(cfg).map(readObject);
1626
+ const state = {
1721
1627
  drafts: {},
1722
1628
  fingerprints: {}
1723
1629
  };
1724
- if (legacy !== void 0) for (const [locale, keys] of Object.entries(readDrafts(legacy))) markDrafts(state.drafts, locale, keys);
1630
+ for (const source of [lock, legacyState]) {
1631
+ if (!source) continue;
1632
+ for (const [locale, keys] of Object.entries(readDrafts(source.drafts))) markDrafts(state.drafts, locale, keys);
1633
+ for (const [locale, stamps] of Object.entries(readFingerprints(source.fingerprints))) {
1634
+ const into = state.fingerprints[locale] ??= emptyCatalog();
1635
+ for (const [key, stamped] of Object.entries(stamps)) if (own(into, key) === void 0) into[key] = stamped;
1636
+ }
1637
+ const migrated = readMigrated(source.migrated);
1638
+ if (migrated) state.migrated = [.../* @__PURE__ */ new Set([...state.migrated ?? [], ...migrated])];
1639
+ }
1640
+ if (legacyDrafts) for (const [locale, keys] of Object.entries(readDrafts(legacyDrafts))) markDrafts(state.drafts, locale, keys);
1725
1641
  return state;
1726
1642
  }
1643
+ function stateFile(cfg) {
1644
+ return [statePath(cfg), ...legacyPaths(cfg)].find((path) => existsSync(path));
1645
+ }
1646
+ function lockNews(cfg, before) {
1647
+ const lock = statePath(cfg);
1648
+ if (before === lock || !existsSync(lock)) return void 0;
1649
+ return before ? {
1650
+ file: lock,
1651
+ from: before
1652
+ } : { file: lock };
1653
+ }
1654
+ function checkVersion(path, version) {
1655
+ if (typeof version === "number" && version > LOCK_VERSION) throw new Error(`[verbaly] ${path} was written by a newer Verbaly (format ${version}): update @verbaly/compiler to read it`);
1656
+ }
1727
1657
  function readState(cfg) {
1728
1658
  try {
1729
1659
  return { state: loadState(cfg) };
@@ -1740,21 +1670,23 @@ function readState(cfg) {
1740
1670
  function saveState(cfg, state) {
1741
1671
  const fresh = serializeState(state);
1742
1672
  const path = statePath(cfg);
1743
- const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1673
+ const legacy = legacyPaths(cfg);
1744
1674
  if (fresh === void 0) {
1745
- rmSync(path, { force: true });
1746
- rmSync(legacy, { force: true });
1675
+ for (const file of [path, ...legacy]) rmSync(file, { force: true });
1747
1676
  return;
1748
1677
  }
1749
- let existing;
1678
+ const existing = readText(path);
1679
+ if (existing === void 0) mkdirSync(cfg.root, { recursive: true });
1680
+ const serialized = withLineEndings(fresh, existing ?? legacy.map(readText).find((text) => text !== void 0));
1681
+ if (existing !== serialized) writeFileSync(path, serialized);
1682
+ for (const file of legacy) rmSync(file, { force: true });
1683
+ }
1684
+ function readText(path) {
1750
1685
  try {
1751
- existing = readFileSync(path, "utf8");
1686
+ return readFileSync(path, "utf8");
1752
1687
  } catch {
1753
- mkdirSync(cfg.dir, { recursive: true });
1688
+ return;
1754
1689
  }
1755
- const serialized = withLineEndings(fresh, existing);
1756
- if (existing !== serialized) writeFileSync(path, serialized);
1757
- if (existsSync(legacy)) rmSync(legacy);
1758
1690
  }
1759
1691
  function updateState(cfg, catalogs) {
1760
1692
  const next = refreshState(cfg, catalogs, loadState(cfg));
@@ -1782,7 +1714,8 @@ function refreshState(cfg, catalogs, previous) {
1782
1714
  }
1783
1715
  return {
1784
1716
  drafts,
1785
- fingerprints
1717
+ fingerprints,
1718
+ migrated: previous.migrated
1786
1719
  };
1787
1720
  }
1788
1721
  function refreshStamps(source, catalog, before) {
@@ -1900,52 +1833,414 @@ function serializeState(state) {
1900
1833
  if (!keys.length) continue;
1901
1834
  fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1902
1835
  }
1903
- const out = {};
1836
+ const migrated = [...new Set(state.migrated ?? [])].sort();
1837
+ if (!Object.keys(drafts).length && !Object.keys(fingerprints).length && !migrated.length) return;
1838
+ const out = {
1839
+ _readme: README,
1840
+ version: LOCK_VERSION
1841
+ };
1904
1842
  if (Object.keys(drafts).length) out.drafts = drafts;
1905
1843
  if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1906
- if (!out.drafts && !out.fingerprints) return void 0;
1844
+ if (migrated.length) out.migrated = migrated;
1907
1845
  return JSON.stringify(out, null, 2) + "\n";
1908
1846
  }
1909
- function readJson(path) {
1910
- let content;
1911
- try {
1912
- content = readFileSync(path, "utf8");
1913
- } catch {
1914
- return;
1915
- }
1847
+ function readObject(path) {
1848
+ const content = readText(path);
1849
+ if (content === void 0) return void 0;
1850
+ let value;
1916
1851
  try {
1917
- return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1852
+ value = JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1918
1853
  } catch (error) {
1919
1854
  throw corrupt(path, error);
1920
1855
  }
1856
+ if (!isObject(value)) throw corrupt(path);
1857
+ return value;
1921
1858
  }
1922
1859
  function corrupt(path, cause) {
1923
1860
  return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
1924
1861
  }
1925
- function isObject(value) {
1926
- return typeof value === "object" && value !== null && !Array.isArray(value);
1862
+ function isObject(value) {
1863
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1864
+ }
1865
+ function readDrafts(value) {
1866
+ const out = {};
1867
+ if (!isObject(value)) return out;
1868
+ for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1869
+ return out;
1870
+ }
1871
+ function readMigrated(value) {
1872
+ if (!Array.isArray(value)) return void 0;
1873
+ const locales = value.filter((locale) => typeof locale === "string");
1874
+ return locales.length ? locales : void 0;
1875
+ }
1876
+ function readFingerprints(value) {
1877
+ const out = {};
1878
+ if (!isObject(value)) return out;
1879
+ for (const [locale, entries] of Object.entries(value)) {
1880
+ if (!isObject(entries)) continue;
1881
+ const kept = emptyCatalog();
1882
+ for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
1883
+ out[locale] = kept;
1884
+ }
1885
+ return out;
1886
+ }
1887
+ //#endregion
1888
+ //#region src/migrate.ts
1889
+ const KNOWN = [
1890
+ "i18next",
1891
+ "react-i18next",
1892
+ "vue-i18n",
1893
+ "react-intl",
1894
+ "next-intl",
1895
+ "svelte-i18n"
1896
+ ];
1897
+ function detectLibraries(root) {
1898
+ const path = join(root, "package.json");
1899
+ if (!existsSync(path)) return [];
1900
+ let manifest;
1901
+ try {
1902
+ manifest = JSON.parse(readFileSync(path, "utf8"));
1903
+ } catch {
1904
+ return [];
1905
+ }
1906
+ const deps = {
1907
+ ...manifest.dependencies,
1908
+ ...manifest.devDependencies
1909
+ };
1910
+ return KNOWN.filter((name) => deps[name] !== void 0);
1911
+ }
1912
+ const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
1913
+ const FORMATTED = /\{\{\s*-?\s*[A-Za-z_$][\w$]*\s*,[^}]*\}\}/;
1914
+ const UNESCAPED = /\{\{\s*-\s*[A-Za-z_$][\w$]*\s*\}\}/;
1915
+ const NESTED = /\$t\(/;
1916
+ const DOUBLE = /\{\{[^{}]*\}\}/;
1917
+ const DOUBLES = new RegExp(DOUBLE.source, "g");
1918
+ const ONE_PLAIN = new RegExp(`^${PLAIN.source}$`);
1919
+ const NAME = /^\s*([A-Za-z_$][\w$]*)\s*$/;
1920
+ const CATEGORIES = [
1921
+ "zero",
1922
+ "one",
1923
+ "two",
1924
+ "few",
1925
+ "many",
1926
+ "other"
1927
+ ];
1928
+ const SUFFIX = new RegExp(`^(.*)_(${[...CATEGORIES, "plural"].join("|")})$`);
1929
+ function i18nextProblem(text) {
1930
+ if (NESTED.test(text)) return "uses $t() nesting, which has no direct equivalent";
1931
+ if (UNESCAPED.test(text)) return "uses {{- name}}, so decide whether the message is rich";
1932
+ if (FORMATTED.test(text)) return "uses an i18next format, which needs the matching Verbaly one";
1933
+ for (const [double] of text.matchAll(DOUBLES)) if (!ONE_PLAIN.test(double)) return "uses {{…}} with more than a name, which needs a Verbaly param";
1934
+ }
1935
+ function convertBraces(text) {
1936
+ let out = "";
1937
+ let last = 0;
1938
+ for (const match of text.matchAll(PLAIN)) {
1939
+ out += escapeBraces(text.slice(last, match.index)) + `{${match[1]}}`;
1940
+ last = match.index + match[0].length;
1941
+ }
1942
+ return out + escapeBraces(text.slice(last));
1943
+ }
1944
+ function escapeBraces(text) {
1945
+ return text.replace(/[{}]/g, (brace) => brace + brace);
1946
+ }
1947
+ function toVariant(text) {
1948
+ let out = "";
1949
+ let i = 0;
1950
+ while (i < text.length) {
1951
+ const ch = text[i];
1952
+ if ((ch === "{" || ch === "}") && text[i + 1] === ch) {
1953
+ out += ch + ch;
1954
+ i += 2;
1955
+ } else if (ch === "{") {
1956
+ const close = text.indexOf("}", i);
1957
+ const name = close < 0 ? void 0 : NAME.exec(text.slice(i + 1, close))?.[1];
1958
+ if (name === void 0) return void 0;
1959
+ out += name === "count" ? "#" : `{${name}}`;
1960
+ i = close + 1;
1961
+ } else {
1962
+ out += ch === "#" || ch === "|" || ch === "}" ? ch + ch : ch;
1963
+ i += 1;
1964
+ }
1965
+ }
1966
+ return out;
1967
+ }
1968
+ function order(a, b) {
1969
+ return CATEGORIES.indexOf(a) - CATEGORIES.indexOf(b);
1970
+ }
1971
+ function mergePlurals(locale, catalog, out, plurals, skipped, fromI18next) {
1972
+ const groups = /* @__PURE__ */ new Map();
1973
+ const legacy = /* @__PURE__ */ new Set();
1974
+ for (const [key, value] of Object.entries(catalog)) {
1975
+ const match = SUFFIX.exec(key);
1976
+ if (!match || typeof value !== "string") continue;
1977
+ const [, base, suffix] = match;
1978
+ if (suffix === "plural") legacy.add(base);
1979
+ const category = suffix === "plural" ? "other" : suffix;
1980
+ if (!groups.has(base)) groups.set(base, /* @__PURE__ */ new Map());
1981
+ groups.get(base).set(category, {
1982
+ key,
1983
+ value
1984
+ });
1985
+ }
1986
+ for (const [base, forms] of groups) {
1987
+ const bare = catalog[base];
1988
+ if (legacy.has(base) && typeof bare === "string" && !forms.has("one")) forms.set("one", {
1989
+ key: base,
1990
+ value: bare
1991
+ });
1992
+ else if (bare !== void 0) {
1993
+ skipped.push({
1994
+ locale,
1995
+ key: base,
1996
+ reason: `"${base}" already exists, so merging would overwrite it`
1997
+ });
1998
+ continue;
1999
+ }
2000
+ if (!forms.has("other")) {
2001
+ skipped.push({
2002
+ locale,
2003
+ key: base,
2004
+ reason: "no _other form, so the block would have no catch-all"
2005
+ });
2006
+ continue;
2007
+ }
2008
+ if (forms.size === 1) {
2009
+ skipped.push({
2010
+ locale,
2011
+ key: base,
2012
+ reason: "only a plural form, so add the singular before merging"
2013
+ });
2014
+ continue;
2015
+ }
2016
+ const sorted = [...forms.entries()].sort((a, b) => order(a[0], b[0]));
2017
+ const cases = [];
2018
+ let problem;
2019
+ for (const [category, form] of sorted) {
2020
+ problem = fromI18next ? i18nextProblem(form.value) : void 0;
2021
+ const body = problem ? void 0 : toVariant(fromI18next ? convertBraces(form.value) : form.value);
2022
+ if (body === void 0) {
2023
+ problem ??= "a form holds more than a name in braces, so merge it by hand";
2024
+ break;
2025
+ }
2026
+ cases.push(`${category}: ${body}`);
2027
+ }
2028
+ if (problem) {
2029
+ skipped.push({
2030
+ locale,
2031
+ key: base,
2032
+ reason: problem
2033
+ });
2034
+ continue;
2035
+ }
2036
+ const merged = `{count | ${cases.join(" | ")}}`;
2037
+ for (const [, form] of sorted) delete out[form.key];
2038
+ out[base] = merged;
2039
+ plurals.push({
2040
+ locale,
2041
+ key: base,
2042
+ from: sorted.map(([, form]) => form.key),
2043
+ after: merged
2044
+ });
2045
+ }
2046
+ }
2047
+ function migrateCatalogs(cfg, options = {}) {
2048
+ const braces = [];
2049
+ const plurals = [];
2050
+ const skipped = [];
2051
+ const written = [];
2052
+ const state = loadState(cfg);
2053
+ const done = new Set(state.migrated ?? []);
2054
+ const catalogs = new Map(cfg.locales.map((locale) => [locale, readCatalog(cfg, locale)]));
2055
+ const pending = cfg.locales.filter((locale) => !done.has(locale));
2056
+ const fromI18next = pending.some((locale) => Object.values(catalogs.get(locale)).some((value) => typeof value === "string" && (DOUBLE.test(value) || NESTED.test(value))));
2057
+ for (const locale of cfg.locales) {
2058
+ const catalog = catalogs.get(locale);
2059
+ const out = Object.assign(emptyCatalog(), catalog);
2060
+ const convert = fromI18next && !done.has(locale);
2061
+ for (const [key, value] of Object.entries(catalog)) {
2062
+ if (!convert || typeof value !== "string") continue;
2063
+ const problem = i18nextProblem(value);
2064
+ if (problem) {
2065
+ skipped.push({
2066
+ locale,
2067
+ key,
2068
+ reason: problem
2069
+ });
2070
+ continue;
2071
+ }
2072
+ const after = convertBraces(value);
2073
+ if (after !== value) {
2074
+ braces.push({
2075
+ locale,
2076
+ key,
2077
+ before: value,
2078
+ after
2079
+ });
2080
+ out[key] = after;
2081
+ }
2082
+ }
2083
+ if (options.plurals) mergePlurals(locale, catalog, out, plurals, skipped, convert);
2084
+ if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
2085
+ writeCatalog(cfg, locale, out);
2086
+ written.push(locale);
2087
+ }
2088
+ }
2089
+ if (options.write && fromI18next) {
2090
+ const converted = pending.filter((locale) => existsSync(catalogPath(cfg, locale)));
2091
+ if (converted.length) saveState(cfg, {
2092
+ ...state,
2093
+ migrated: [...done, ...converted]
2094
+ });
2095
+ }
2096
+ const remembered = cfg.locales.filter((locale) => done.has(locale));
2097
+ return {
2098
+ detected: detectLibraries(cfg.root),
2099
+ braces,
2100
+ plurals,
2101
+ skipped,
2102
+ written,
2103
+ remembered
2104
+ };
2105
+ }
2106
+ //#endregion
2107
+ //#region src/tag.ts
2108
+ function isLocaleTag(tag) {
2109
+ try {
2110
+ Intl.getCanonicalLocales(tag);
2111
+ return true;
2112
+ } catch {
2113
+ return false;
2114
+ }
2115
+ }
2116
+ function suggestTag(tag) {
2117
+ const near = tag.replace(/_/g, "-");
2118
+ return near !== tag && isLocaleTag(near) ? near : void 0;
2119
+ }
2120
+ function projectLocale(tag, locales) {
2121
+ if (locales.includes(tag)) return tag;
2122
+ const plain = (value) => value.replace(/_/g, "-").toLowerCase();
2123
+ return locales.find((locale) => plain(locale) === plain(tag));
2124
+ }
2125
+ //#endregion
2126
+ //#region src/init.ts
2127
+ const CATALOG_DIRS = [
2128
+ "locales",
2129
+ "src/locales",
2130
+ "src/i18n/locales",
2131
+ "src/i18n",
2132
+ "i18n",
2133
+ "lang",
2134
+ "src/lang",
2135
+ "translations",
2136
+ "src/translations",
2137
+ "messages"
2138
+ ];
2139
+ function existingCatalogs(root) {
2140
+ return CATALOG_DIRS.find((dir) => {
2141
+ try {
2142
+ return readdirSync(join(root, dir)).some((file) => file.endsWith(".json") && isLocaleTag(file.slice(0, -5)));
2143
+ } catch {
2144
+ return false;
2145
+ }
2146
+ });
2147
+ }
2148
+ function cliReachable(root) {
2149
+ const bin = join(root, "node_modules", ".bin");
2150
+ return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
1927
2151
  }
1928
- function readDrafts(value) {
1929
- const out = {};
1930
- if (!isObject(value)) return out;
1931
- for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1932
- return out;
2152
+ const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
2153
+ function configSource(options, typescript) {
2154
+ const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
2155
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
2156
+ if (options.dir) fields.push(` dir: '${options.dir}',`);
2157
+ const body = `export default {\n${fields.join("\n")}\n}`;
2158
+ if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
2159
+ return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
1933
2160
  }
1934
- function readFingerprints(value) {
1935
- const out = {};
1936
- if (!isObject(value)) return out;
1937
- for (const [locale, entries] of Object.entries(value)) {
1938
- if (!isObject(entries)) continue;
1939
- const kept = emptyCatalog();
1940
- for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
1941
- out[locale] = kept;
2161
+ async function init(input = {}) {
2162
+ const root = input.root ?? process.cwd();
2163
+ const created = [];
2164
+ const skipped = [];
2165
+ const renamed = [];
2166
+ const refused = [];
2167
+ const typed = input.locales?.flatMap((locale) => {
2168
+ if (isLocaleTag(locale)) return [locale];
2169
+ const near = suggestTag(locale);
2170
+ if (near) renamed.push({
2171
+ from: locale,
2172
+ to: near
2173
+ });
2174
+ else refused.push(locale);
2175
+ return near ? [near] : [];
2176
+ });
2177
+ const locales = typed && [...new Set(typed)];
2178
+ let sourceLocale = input.sourceLocale;
2179
+ if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
2180
+ const near = suggestTag(sourceLocale);
2181
+ if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
2182
+ renamed.push({
2183
+ from: sourceLocale,
2184
+ to: near
2185
+ });
2186
+ sourceLocale = near;
1942
2187
  }
1943
- return out;
2188
+ const options = {
2189
+ ...input,
2190
+ locales,
2191
+ sourceLocale
2192
+ };
2193
+ const existing = findConfigFile(root);
2194
+ const typescript = existsSync(join(root, "tsconfig.json"));
2195
+ const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
2196
+ const found = existing || options.dir ? void 0 : existingCatalogs(root);
2197
+ if (existing) skipped.push(existing);
2198
+ else {
2199
+ const dir = found === "locales" ? void 0 : found;
2200
+ writeFileSync(join(root, configFile), configSource({
2201
+ ...options,
2202
+ dir: options.dir ?? dir
2203
+ }, typescript));
2204
+ created.push(configFile);
2205
+ }
2206
+ const fromFile = existing ? await loadConfigFile(root) : {};
2207
+ const scaffold = {
2208
+ dir: options.dir ?? fromFile.dir ?? found,
2209
+ sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
2210
+ locales: options.locales ?? fromFile.locales
2211
+ };
2212
+ const dir = join(root, scaffold.dir ?? "locales");
2213
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
2214
+ for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
2215
+ const file = join(dir, `${locale}.json`);
2216
+ const label = relative(root, file).replaceAll("\\", "/");
2217
+ if (existsSync(file)) skipped.push(label);
2218
+ else {
2219
+ writeFileSync(file, "{}\n");
2220
+ created.push(label);
2221
+ }
2222
+ }
2223
+ const host = detectHost(root);
2224
+ const deps = readDependencies(root);
2225
+ const missing = host?.install.filter((pkg) => !deps[pkg]) ?? [];
2226
+ const next = host ? [...missing.length ? [installCommand(root, missing)] : [], host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
2227
+ const others = detectLibraries(root);
2228
+ if (found && others.length) next.push(`port the ${others.join(" and ")} catalogs: npx verbaly migrate reports, --write applies`);
2229
+ return {
2230
+ created,
2231
+ skipped,
2232
+ host: host?.name,
2233
+ configFile,
2234
+ next,
2235
+ renamed,
2236
+ refused,
2237
+ found
2238
+ };
1944
2239
  }
1945
2240
  //#endregion
1946
2241
  //#region src/check.ts
1947
2242
  function gatePasses(result) {
1948
- return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2243
+ return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
1949
2244
  }
1950
2245
  function check(cfg, catalogs, registry, fingerprints = {}) {
1951
2246
  const extracted = registry.messages();
@@ -2015,17 +2310,19 @@ function check(cfg, catalogs, registry, fingerprints = {}) {
2015
2310
  });
2016
2311
  }
2017
2312
  }
2313
+ const collisions = collisionEntries(registry);
2018
2314
  return {
2019
2315
  ok: gatePasses({
2020
2316
  missing,
2021
2317
  unknown,
2022
- broken
2318
+ broken,
2319
+ collisions
2023
2320
  }),
2024
2321
  missing,
2025
2322
  unknown,
2026
2323
  broken,
2027
2324
  extra,
2028
- collisions: collisionEntries(registry),
2325
+ collisions,
2029
2326
  divergent,
2030
2327
  outdated: outdatedTranslations(cfg, shipped, fingerprints)
2031
2328
  };
@@ -2049,6 +2346,10 @@ function formatCheckResult(result, root) {
2049
2346
  lines.push("broken translations:");
2050
2347
  for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2051
2348
  }
2349
+ if (result.collisions.length > 0) {
2350
+ lines.push("keys written with more than one text:");
2351
+ for (const entry of result.collisions) lines.push(` ${formatCollision(entry, root)}`);
2352
+ }
2052
2353
  return lines.join("\n");
2053
2354
  }
2054
2355
  function checkNextSteps(result, cliReachable = true) {
@@ -2056,16 +2357,13 @@ function checkNextSteps(result, cliReachable = true) {
2056
2357
  if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
2057
2358
  if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
2058
2359
  if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
2360
+ if (result.collisions.length > 0) steps.push("collisions: give each text its own key in t.id(…), or write the same text in every place");
2059
2361
  if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
2060
2362
  return steps.join("\n");
2061
2363
  }
2062
2364
  function formatCheckWarnings(result, root, options = {}) {
2063
2365
  const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
2064
2366
  for (const entry of result.extra) lines.push(entry.files.length > 0 ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself` : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`);
2065
- for (const entry of result.collisions) lines.push(` ${formatFinding({
2066
- kind: "collision",
2067
- ...entry
2068
- }, root)}`);
2069
2367
  for (const { key, catalog, code } of result.divergent) lines.push(` ${key}: the source catalog says "${truncate(catalog, 40)}" and the code says "${truncate(code.message, 40)}" (${sourcePlace(code, root)}): the code wins, so edit the text there (extract writes it into the catalog)`);
2070
2368
  if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
2071
2369
  kind: "outdated",
@@ -2117,7 +2415,7 @@ function githubCheckAnnotations(result, registry, cfg, options = {}) {
2117
2415
  for (const { key, sites } of result.collisions) {
2118
2416
  const texts = new Set(sites.map((place) => place.message)).size;
2119
2417
  const text = escapeData(`"${key}" has ${counted(texts, "text")}, and every place shows the first one`);
2120
- for (const place of sites) lines.push(`::warning ${at(place.file, place.line)}::${text}`);
2418
+ for (const place of sites) lines.push(`::error ${at(place.file, place.line)}::${text}`);
2121
2419
  }
2122
2420
  for (const { key, code } of result.divergent) {
2123
2421
  const text = escapeData(`"${key}": the source catalog has another text, the code's one ships`);
@@ -2260,6 +2558,9 @@ function generateDts(catalog, options = {}) {
2260
2558
  }
2261
2559
  }
2262
2560
  return `${DTS_HEADER}
2561
+ // biome-ignore-all lint: generated by verbaly
2562
+ // biome-ignore-all format: generated by verbaly
2563
+ // prettier-ignore
2263
2564
  declare module 'virtual:verbaly' {
2264
2565
  export interface VerbalyMessages {
2265
2566
  ${lines.join("\n")}
@@ -2289,28 +2590,28 @@ ${lines.join("\n")}
2289
2590
  ): import('verbaly').Verbaly;
2290
2591
  export function createRequestInstance(locale: string): Promise<import('verbaly').Verbaly>;
2291
2592
 
2292
- // a key written as a literal must exist; string, or a template with a part from data, is data
2293
- export function t<K extends VerbalyKey | TemplateStringsArray | (string & {})>(
2294
- first: K extends TemplateStringsArray
2295
- ? K
2296
- : {} extends Record<K & string, 1>
2593
+ // a literal key must exist; a string, a template with data in it or a union of keys is data
2594
+ export const t: {
2595
+ <K extends VerbalyKey | TemplateStringsArray | (string & {})>(
2596
+ first: K extends TemplateStringsArray
2297
2597
  ? K
2298
- : K extends VerbalyKey ? K : VerbalyKey,
2299
- ...rest: [K] extends [never]
2300
- ? [params?: import('verbaly').Params]
2301
- : K extends TemplateStringsArray
2302
- ? unknown[]
2303
2598
  : {} extends Record<K & string, 1>
2304
- ? [params?: import('verbaly').Params]
2305
- : K extends VerbalyKey
2306
- ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
2307
- : unknown[]
2308
- ): string;
2309
- export namespace t {
2310
- export function id(
2311
- key: string,
2312
- ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
2313
- }
2599
+ ? K
2600
+ : K extends VerbalyKey ? K : VerbalyKey,
2601
+ ...rest: [K] extends [never]
2602
+ ? [params?: import('verbaly').Params]
2603
+ : [K] extends [(K extends unknown ? (key: K) => void : never) extends (key: infer One) => void ? One : never]
2604
+ ? K extends TemplateStringsArray
2605
+ ? unknown[]
2606
+ : {} extends Record<K & string, 1>
2607
+ ? [params?: import('verbaly').Params]
2608
+ : K extends VerbalyKey
2609
+ ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
2610
+ : unknown[]
2611
+ : [params?: import('verbaly').Params]
2612
+ ): string;
2613
+ id(key: string): (strings: TemplateStringsArray, ...values: unknown[]) => string;
2614
+ };
2314
2615
 
2315
2616
  export function setLocale(locale: string): Promise<void>;
2316
2617
  export function switchLocale(
@@ -2332,6 +2633,7 @@ ${lines.join("\n")}
2332
2633
  }
2333
2634
  }
2334
2635
 
2636
+ // prettier-ignore
2335
2637
  declare module 'virtual:verbaly/locale/*' {
2336
2638
  const messages: Record<string, string>;
2337
2639
  export default messages;
@@ -2495,6 +2797,11 @@ function formatDoctorEntry(entry) {
2495
2797
  return entry.fix ? `${head}
2496
2798
  fix: ${entry.fix}` : head;
2497
2799
  }
2800
+ function formatDoctorHealth(result) {
2801
+ if (!result.ok) return "problems found";
2802
+ const warnings = result.entries.filter((entry) => entry.level === "warn").length;
2803
+ return warnings > 0 ? `setup works, with ${counted(warnings, "warning")} to read` : "setup looks healthy";
2804
+ }
2498
2805
  async function doctor(cfg) {
2499
2806
  const entries = [];
2500
2807
  const ok = (name, message) => entries.push({
@@ -2670,7 +2977,7 @@ async function doctor(cfg) {
2670
2977
  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");
2671
2978
  if (result.collisions.length > 0) {
2672
2979
  const first = result.collisions[0];
2673
- warn("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
2980
+ error("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
2674
2981
  }
2675
2982
  if (result.divergent.length > 0) {
2676
2983
  const first = result.divergent[0];
@@ -3478,169 +3785,6 @@ function csvRows(content) {
3478
3785
  return rows;
3479
3786
  }
3480
3787
  //#endregion
3481
- //#region src/migrate.ts
3482
- const KNOWN = [
3483
- "i18next",
3484
- "react-i18next",
3485
- "vue-i18n",
3486
- "react-intl",
3487
- "next-intl",
3488
- "svelte-i18n"
3489
- ];
3490
- function detectLibraries(root) {
3491
- const path = join(root, "package.json");
3492
- if (!existsSync(path)) return [];
3493
- let manifest;
3494
- try {
3495
- manifest = JSON.parse(readFileSync(path, "utf8"));
3496
- } catch {
3497
- return [];
3498
- }
3499
- const deps = {
3500
- ...manifest.dependencies,
3501
- ...manifest.devDependencies
3502
- };
3503
- return KNOWN.filter((name) => deps[name] !== void 0);
3504
- }
3505
- const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
3506
- const FORMATTED = /\{\{\s*-?\s*[A-Za-z_$][\w$]*\s*,[^}]*\}\}/;
3507
- const UNESCAPED = /\{\{\s*-\s*[A-Za-z_$][\w$]*\s*\}\}/;
3508
- const NESTED = /\$t\(/;
3509
- const CATEGORIES = [
3510
- "zero",
3511
- "one",
3512
- "two",
3513
- "few",
3514
- "many",
3515
- "other"
3516
- ];
3517
- const SUFFIX = new RegExp(`^(.*)_(${[...CATEGORIES, "plural"].join("|")})$`);
3518
- function convertBraces(text) {
3519
- return text.replace(PLAIN, "{$1}");
3520
- }
3521
- function toHash(text) {
3522
- return text.replaceAll("{count}", "#");
3523
- }
3524
- function order(a, b) {
3525
- return CATEGORIES.indexOf(a) - CATEGORIES.indexOf(b);
3526
- }
3527
- function mergePlurals(locale, catalog, out, plurals, skipped) {
3528
- const groups = /* @__PURE__ */ new Map();
3529
- const legacy = /* @__PURE__ */ new Set();
3530
- for (const [key, value] of Object.entries(catalog)) {
3531
- const match = SUFFIX.exec(key);
3532
- if (!match || typeof value !== "string") continue;
3533
- const [, base, suffix] = match;
3534
- if (suffix === "plural") legacy.add(base);
3535
- const category = suffix === "plural" ? "other" : suffix;
3536
- if (!groups.has(base)) groups.set(base, /* @__PURE__ */ new Map());
3537
- groups.get(base).set(category, {
3538
- key,
3539
- value
3540
- });
3541
- }
3542
- for (const [base, forms] of groups) {
3543
- const bare = catalog[base];
3544
- if (legacy.has(base) && typeof bare === "string" && !forms.has("one")) forms.set("one", {
3545
- key: base,
3546
- value: bare
3547
- });
3548
- else if (bare !== void 0) {
3549
- skipped.push({
3550
- locale,
3551
- key: base,
3552
- reason: `"${base}" already exists, so merging would overwrite it`
3553
- });
3554
- continue;
3555
- }
3556
- if (!forms.has("other")) {
3557
- skipped.push({
3558
- locale,
3559
- key: base,
3560
- reason: "no _other form, so the block would have no catch-all"
3561
- });
3562
- continue;
3563
- }
3564
- if (forms.size === 1) {
3565
- skipped.push({
3566
- locale,
3567
- key: base,
3568
- reason: "only a plural form, so add the singular before merging"
3569
- });
3570
- continue;
3571
- }
3572
- const sorted = [...forms.entries()].sort((a, b) => order(a[0], b[0]));
3573
- const merged = `{count | ${sorted.map(([category, form]) => `${category}: ${toHash(convertBraces(form.value))}`).join(" | ")}}`;
3574
- for (const [, form] of sorted) delete out[form.key];
3575
- out[base] = merged;
3576
- plurals.push({
3577
- locale,
3578
- key: base,
3579
- from: sorted.map(([, form]) => form.key),
3580
- after: merged
3581
- });
3582
- }
3583
- }
3584
- function migrateCatalogs(cfg, options = {}) {
3585
- const braces = [];
3586
- const plurals = [];
3587
- const skipped = [];
3588
- const written = [];
3589
- for (const locale of cfg.locales) {
3590
- const catalog = readCatalog(cfg, locale);
3591
- const out = Object.assign(emptyCatalog(), catalog);
3592
- for (const [key, value] of Object.entries(catalog)) {
3593
- if (typeof value !== "string") continue;
3594
- if (NESTED.test(value)) {
3595
- skipped.push({
3596
- locale,
3597
- key,
3598
- reason: "uses $t() nesting, which has no direct equivalent"
3599
- });
3600
- continue;
3601
- }
3602
- if (UNESCAPED.test(value)) {
3603
- skipped.push({
3604
- locale,
3605
- key,
3606
- reason: "uses {{- name}}, so decide whether the message is rich"
3607
- });
3608
- continue;
3609
- }
3610
- if (FORMATTED.test(value)) {
3611
- skipped.push({
3612
- locale,
3613
- key,
3614
- reason: "uses an i18next format, which needs the matching Verbaly one"
3615
- });
3616
- continue;
3617
- }
3618
- const after = convertBraces(value);
3619
- if (after !== value) {
3620
- braces.push({
3621
- locale,
3622
- key,
3623
- before: value,
3624
- after
3625
- });
3626
- out[key] = after;
3627
- }
3628
- }
3629
- if (options.plurals) mergePlurals(locale, catalog, out, plurals, skipped);
3630
- if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
3631
- writeCatalog(cfg, locale, out);
3632
- written.push(locale);
3633
- }
3634
- }
3635
- return {
3636
- detected: detectLibraries(cfg.root),
3637
- braces,
3638
- plurals,
3639
- skipped,
3640
- written
3641
- };
3642
- }
3643
- //#endregion
3644
3788
  //#region src/project.ts
3645
3789
  async function syncProject(cfg, options = {}) {
3646
3790
  const registry = options.registry ?? await extractProject(cfg);
@@ -3667,11 +3811,17 @@ async function syncProject(cfg, options = {}) {
3667
3811
  result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
3668
3812
  }
3669
3813
  writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
3814
+ const before = stateFile(cfg);
3670
3815
  try {
3671
3816
  result.state = updateState(cfg, catalogs);
3672
3817
  } catch (error) {
3673
3818
  result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
3674
3819
  }
3820
+ const news = lockNews(cfg, before);
3821
+ if (news) result.findings.push({
3822
+ kind: "lock",
3823
+ ...news
3824
+ });
3675
3825
  return result;
3676
3826
  }
3677
3827
  function confirmFromDisk(cfg, catalogs, registry) {
@@ -4662,6 +4812,7 @@ async function runCli(args = process.argv.slice(2)) {
4662
4812
  if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(", ")}`);
4663
4813
  for (const { from, to } of result.renamed) console.log(` wrote ${to} for ${from}, since a locale tag takes a hyphen`);
4664
4814
  for (const locale of result.refused) console.warn(` left out "${locale}": it is not a locale tag, use one like es or pt-BR`);
4815
+ if (result.found) console.log(` catalogs: ${result.found}, kept where they already are`);
4665
4816
  if (result.host) console.log(` detected: ${result.host}`);
4666
4817
  console.log([" next steps:", ...result.next.map((step, i) => ` ${i + 1}. ${step}`)].join("\n"));
4667
4818
  return;
@@ -4680,7 +4831,7 @@ async function runCli(args = process.argv.slice(2)) {
4680
4831
  else if (entry.level === "warn") console.warn(line);
4681
4832
  else console.log(line);
4682
4833
  }
4683
- if (result.ok) console.log("[verbaly] setup looks healthy ✓");
4834
+ if (result.ok) console.log(`[verbaly] ${formatDoctorHealth(result)} ✓`);
4684
4835
  else {
4685
4836
  console.error("[verbaly] doctor found problems");
4686
4837
  process.exitCode = 1;
@@ -4709,7 +4860,7 @@ async function runCli(args = process.argv.slice(2)) {
4709
4860
  console.log(`[verbaly] ${counted(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
4710
4861
  for (const [locale, keys] of Object.entries(result.added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
4711
4862
  const warnings = result.findings.filter((finding) => {
4712
- if (finding.kind !== "replaced") return true;
4863
+ if (finding.kind !== "replaced" && finding.kind !== "lock") return true;
4713
4864
  console.log(` ${formatFinding(finding, cfg.root)}`);
4714
4865
  return false;
4715
4866
  });
@@ -4738,19 +4889,21 @@ async function runCli(args = process.argv.slice(2)) {
4738
4889
  return;
4739
4890
  }
4740
4891
  if (command === "migrate") {
4892
+ const lockBefore = stateFile(cfg);
4741
4893
  const result = migrateCatalogs(cfg, {
4742
4894
  write: values.write,
4743
4895
  plurals: values.plurals
4744
4896
  });
4745
4897
  const from = result.detected.length ? result.detected.join(", ") : "no known i18n library";
4746
4898
  const changes = result.braces.length + result.plurals.length;
4899
+ const before = result.remembered.length ? `, ${counted(result.remembered.length, "language")} converted before` : "";
4747
4900
  if (changes === 0 && result.skipped.length === 0) {
4748
- console.log(`[verbaly] catalogs need nothing (${from}) ✓`);
4901
+ console.log(`[verbaly] catalogs need nothing (${from}${before}) ✓`);
4749
4902
  return;
4750
4903
  }
4751
4904
  const verb = values.write ? "ported" : "would port";
4752
4905
  const note = values.write ? "" : " (report only, use --write to apply)";
4753
- console.log(`[verbaly] ${verb} ${counted(changes, "message")} from ${from}${note}`);
4906
+ console.log(`[verbaly] ${verb} ${counted(changes, "message")} from ${from}${before}${note}`);
4754
4907
  for (const entry of result.braces) console.log(` ${entry.locale} ${entry.key} ${entry.before} → ${entry.after}`);
4755
4908
  for (const entry of result.plurals) console.log(` ${entry.locale} ${entry.key} ${entry.from.join(" + ")} → ${entry.after}`);
4756
4909
  if (!values.plurals && changes > 0) console.log(" --plurals also merges _one/_other into one message with variants");
@@ -4758,6 +4911,8 @@ async function runCli(args = process.argv.slice(2)) {
4758
4911
  console.log(" needs a human:");
4759
4912
  for (const entry of result.skipped) console.log(` ${entry.locale} ${entry.key} ${entry.reason}`);
4760
4913
  }
4914
+ if (values.write && result.braces.length > 0) console.log(` ${STATE_FILE} remembers the converted languages, so a later run never reads them as i18next again`);
4915
+ sayLockNews(cfg, lockBefore);
4761
4916
  if (values.write) console.log(" next: run verbaly check");
4762
4917
  return;
4763
4918
  }
@@ -4826,7 +4981,7 @@ async function runCli(args = process.argv.slice(2)) {
4826
4981
  }
4827
4982
  if (!result.ok) {
4828
4983
  const brokenCount = result.broken.filter((entry) => entry.severity === "error").length;
4829
- const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
4984
+ const report = reporter === "github" ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken, ${counted(result.collisions.length, "collision")}` : `[verbaly] check failed\n${formatCheckResult(result, cfg.root)}`;
4830
4985
  console.error(`${report}\n${checkNextSteps(result)}`);
4831
4986
  }
4832
4987
  if (awaiting.length > 0) {
@@ -4875,7 +5030,9 @@ async function runCli(args = process.argv.slice(2)) {
4875
5030
  const kept = keys.length - written.length;
4876
5031
  if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
4877
5032
  }
5033
+ const lockBefore = stateFile(cfg);
4878
5034
  if (writes.length > 0) recordTranslations(cfg, source, writes);
5035
+ sayLockNews(cfg, lockBefore);
4879
5036
  for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
4880
5037
  for (const line of formatTranslateFailures(result.failed)) console.error(line);
4881
5038
  if (result.failed.length > 0) process.exitCode = 1;
@@ -4905,7 +5062,9 @@ async function runCli(args = process.argv.slice(2)) {
4905
5062
  }
4906
5063
  acceptOutdated(cfg, shipped, state.fingerprints, outdated);
4907
5064
  for (const [locale, keys] of byLocale(outdated)) console.log(` ${locale}: ${keys.length} kept for the new source text`);
5065
+ const lockBefore = stateFile(cfg);
4908
5066
  saveState(cfg, state);
5067
+ sayLockNews(cfg, lockBefore);
4909
5068
  const reviewed = new Set([...drafts, ...outdated].map(({ locale, key }) => `${locale}:${key}`));
4910
5069
  console.log(`[verbaly] ${counted(reviewed.size, "translation")} marked reviewed ✓`);
4911
5070
  return;
@@ -5009,7 +5168,9 @@ async function runCli(args = process.argv.slice(2)) {
5009
5168
  const verb = values["dry-run"] ? "would import" : "imported";
5010
5169
  console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? " (draft)" : ""}`);
5011
5170
  }
5171
+ const lockBefore = stateFile(cfg);
5012
5172
  if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
5173
+ sayLockNews(cfg, lockBefore);
5013
5174
  for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
5014
5175
  for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
5015
5176
  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(", ")}`);
@@ -5060,6 +5221,13 @@ function checkState(cfg, gating) {
5060
5221
  if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);
5061
5222
  return state;
5062
5223
  }
5224
+ function sayLockNews(cfg, before) {
5225
+ const news = lockNews(cfg, before);
5226
+ if (news) console.log(` ${formatFinding({
5227
+ kind: "lock",
5228
+ ...news
5229
+ }, cfg.root)}`);
5230
+ }
5063
5231
  function byLocale(entries) {
5064
5232
  const out = /* @__PURE__ */ new Map();
5065
5233
  for (const { locale, key } of entries) {