@verbaly/compiler 0.69.0 → 0.70.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
  };
@@ -1554,7 +1552,11 @@ function findConfigFile(root) {
1554
1552
  async function loadConfigFile(root) {
1555
1553
  for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
1556
1554
  const path = join(root, name);
1557
- if (existsSync(path)) return (await import(`${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`)).default ?? {};
1555
+ if (existsSync(path)) {
1556
+ const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
1557
+ delete createRequire(import.meta.url).cache[resolve(path)];
1558
+ return (await import(url)).default ?? {};
1559
+ }
1558
1560
  }
1559
1561
  for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
1560
1562
  const path = join(root, name);
@@ -1600,109 +1602,6 @@ function definedOnly(config) {
1600
1602
  return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
1601
1603
  }
1602
1604
  //#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
1605
  //#region src/state.ts
1707
1606
  const STATE_FILE = ".verbaly-state.json";
1708
1607
  const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
@@ -1716,7 +1615,8 @@ function loadState(cfg) {
1716
1615
  if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1717
1616
  const state = isObject(current) ? {
1718
1617
  drafts: readDrafts(current.drafts),
1719
- fingerprints: readFingerprints(current.fingerprints)
1618
+ fingerprints: readFingerprints(current.fingerprints),
1619
+ migrated: readMigrated(current.migrated)
1720
1620
  } : {
1721
1621
  drafts: {},
1722
1622
  fingerprints: {}
@@ -1782,7 +1682,8 @@ function refreshState(cfg, catalogs, previous) {
1782
1682
  }
1783
1683
  return {
1784
1684
  drafts,
1785
- fingerprints
1685
+ fingerprints,
1686
+ migrated: previous.migrated
1786
1687
  };
1787
1688
  }
1788
1689
  function refreshStamps(source, catalog, before) {
@@ -1900,10 +1801,12 @@ function serializeState(state) {
1900
1801
  if (!keys.length) continue;
1901
1802
  fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1902
1803
  }
1804
+ const migrated = [...new Set(state.migrated ?? [])].sort();
1903
1805
  const out = {};
1904
1806
  if (Object.keys(drafts).length) out.drafts = drafts;
1905
1807
  if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1906
- if (!out.drafts && !out.fingerprints) return void 0;
1808
+ if (migrated.length) out.migrated = migrated;
1809
+ if (!out.drafts && !out.fingerprints && !out.migrated) return void 0;
1907
1810
  return JSON.stringify(out, null, 2) + "\n";
1908
1811
  }
1909
1812
  function readJson(path) {
@@ -1931,6 +1834,11 @@ function readDrafts(value) {
1931
1834
  for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1932
1835
  return out;
1933
1836
  }
1837
+ function readMigrated(value) {
1838
+ if (!Array.isArray(value)) return void 0;
1839
+ const locales = value.filter((locale) => typeof locale === "string");
1840
+ return locales.length ? locales : void 0;
1841
+ }
1934
1842
  function readFingerprints(value) {
1935
1843
  const out = {};
1936
1844
  if (!isObject(value)) return out;
@@ -1943,75 +1851,428 @@ function readFingerprints(value) {
1943
1851
  return out;
1944
1852
  }
1945
1853
  //#endregion
1946
- //#region src/check.ts
1947
- function gatePasses(result) {
1948
- return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
1949
- }
1950
- function check(cfg, catalogs, registry, fingerprints = {}) {
1951
- const extracted = registry.messages();
1952
- const flat = {};
1953
- for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1954
- const source = flat[cfg.sourceLocale] ?? {};
1955
- const shipped = shippedCatalogs(cfg, flat, registry);
1956
- const sourceText = shipped[cfg.sourceLocale];
1957
- const used = registry.usedKeys();
1958
- const unknown = [];
1959
- for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
1960
- key,
1961
- files
1962
- });
1963
- const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
1964
- const missing = [];
1965
- for (const key of extracted.keys()) if (!source[key]) missing.push({
1966
- locale: cfg.sourceLocale,
1967
- key,
1968
- source: extracted.get(key)?.message
1969
- });
1970
- for (const locale of cfg.locales) {
1971
- if (locale === cfg.sourceLocale) continue;
1972
- for (const key of needed) if (!flat[locale]?.[key]) missing.push({
1973
- locale,
1974
- key,
1975
- source: source[key] ?? extracted.get(key)?.message
1976
- });
1854
+ //#region src/migrate.ts
1855
+ const KNOWN = [
1856
+ "i18next",
1857
+ "react-i18next",
1858
+ "vue-i18n",
1859
+ "react-intl",
1860
+ "next-intl",
1861
+ "svelte-i18n"
1862
+ ];
1863
+ function detectLibraries(root) {
1864
+ const path = join(root, "package.json");
1865
+ if (!existsSync(path)) return [];
1866
+ let manifest;
1867
+ try {
1868
+ manifest = JSON.parse(readFileSync(path, "utf8"));
1869
+ } catch {
1870
+ return [];
1977
1871
  }
1978
- const broken = [];
1979
- const add = (locale, key, issues) => {
1980
- for (const issue of issues) broken.push({
1981
- locale,
1982
- key,
1983
- severity: issue.severity,
1984
- issue: issue.message
1985
- });
1872
+ const deps = {
1873
+ ...manifest.dependencies,
1874
+ ...manifest.devDependencies
1986
1875
  };
1987
- const divergent = [];
1988
- for (const [key, entry] of extracted) {
1989
- const written = source[key];
1990
- if (written && written !== entry.message) divergent.push({
1991
- key,
1992
- catalog: written,
1993
- code: siteOf(entry)
1994
- });
1876
+ return KNOWN.filter((name) => deps[name] !== void 0);
1877
+ }
1878
+ const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
1879
+ const FORMATTED = /\{\{\s*-?\s*[A-Za-z_$][\w$]*\s*,[^}]*\}\}/;
1880
+ const UNESCAPED = /\{\{\s*-\s*[A-Za-z_$][\w$]*\s*\}\}/;
1881
+ const NESTED = /\$t\(/;
1882
+ const DOUBLE = /\{\{[^{}]*\}\}/;
1883
+ const DOUBLES = new RegExp(DOUBLE.source, "g");
1884
+ const ONE_PLAIN = new RegExp(`^${PLAIN.source}$`);
1885
+ const NAME = /^\s*([A-Za-z_$][\w$]*)\s*$/;
1886
+ const CATEGORIES = [
1887
+ "zero",
1888
+ "one",
1889
+ "two",
1890
+ "few",
1891
+ "many",
1892
+ "other"
1893
+ ];
1894
+ const SUFFIX = new RegExp(`^(.*)_(${[...CATEGORIES, "plural"].join("|")})$`);
1895
+ function i18nextProblem(text) {
1896
+ if (NESTED.test(text)) return "uses $t() nesting, which has no direct equivalent";
1897
+ if (UNESCAPED.test(text)) return "uses {{- name}}, so decide whether the message is rich";
1898
+ if (FORMATTED.test(text)) return "uses an i18next format, which needs the matching Verbaly one";
1899
+ for (const [double] of text.matchAll(DOUBLES)) if (!ONE_PLAIN.test(double)) return "uses {{…}} with more than a name, which needs a Verbaly param";
1900
+ }
1901
+ function convertBraces(text) {
1902
+ let out = "";
1903
+ let last = 0;
1904
+ for (const match of text.matchAll(PLAIN)) {
1905
+ out += escapeBraces(text.slice(last, match.index)) + `{${match[1]}}`;
1906
+ last = match.index + match[0].length;
1995
1907
  }
1996
- for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
1997
- for (const locale of cfg.locales) {
1998
- if (locale === cfg.sourceLocale) continue;
1999
- for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
2000
- if (!translated) continue;
2001
- add(locale, key, validateMessage(translated, locale));
2002
- const text = sourceText[key];
2003
- if (text) add(locale, key, validatePair(text, translated));
1908
+ return out + escapeBraces(text.slice(last));
1909
+ }
1910
+ function escapeBraces(text) {
1911
+ return text.replace(/[{}]/g, (brace) => brace + brace);
1912
+ }
1913
+ function toVariant(text) {
1914
+ let out = "";
1915
+ let i = 0;
1916
+ while (i < text.length) {
1917
+ const ch = text[i];
1918
+ if ((ch === "{" || ch === "}") && text[i + 1] === ch) {
1919
+ out += ch + ch;
1920
+ i += 2;
1921
+ } else if (ch === "{") {
1922
+ const close = text.indexOf("}", i);
1923
+ const name = close < 0 ? void 0 : NAME.exec(text.slice(i + 1, close))?.[1];
1924
+ if (name === void 0) return void 0;
1925
+ out += name === "count" ? "#" : `{${name}}`;
1926
+ i = close + 1;
1927
+ } else {
1928
+ out += ch === "#" || ch === "|" || ch === "}" ? ch + ch : ch;
1929
+ i += 1;
2004
1930
  }
2005
1931
  }
2006
- const extra = [];
2007
- for (const locale of cfg.locales) {
2008
- if (locale === cfg.sourceLocale) continue;
2009
- for (const key of Object.keys(flat[locale] ?? {})) {
2010
- if (source[key] !== void 0 || extracted.has(key)) continue;
2011
- extra.push({
1932
+ return out;
1933
+ }
1934
+ function order(a, b) {
1935
+ return CATEGORIES.indexOf(a) - CATEGORIES.indexOf(b);
1936
+ }
1937
+ function mergePlurals(locale, catalog, out, plurals, skipped, fromI18next) {
1938
+ const groups = /* @__PURE__ */ new Map();
1939
+ const legacy = /* @__PURE__ */ new Set();
1940
+ for (const [key, value] of Object.entries(catalog)) {
1941
+ const match = SUFFIX.exec(key);
1942
+ if (!match || typeof value !== "string") continue;
1943
+ const [, base, suffix] = match;
1944
+ if (suffix === "plural") legacy.add(base);
1945
+ const category = suffix === "plural" ? "other" : suffix;
1946
+ if (!groups.has(base)) groups.set(base, /* @__PURE__ */ new Map());
1947
+ groups.get(base).set(category, {
1948
+ key,
1949
+ value
1950
+ });
1951
+ }
1952
+ for (const [base, forms] of groups) {
1953
+ const bare = catalog[base];
1954
+ if (legacy.has(base) && typeof bare === "string" && !forms.has("one")) forms.set("one", {
1955
+ key: base,
1956
+ value: bare
1957
+ });
1958
+ else if (bare !== void 0) {
1959
+ skipped.push({
2012
1960
  locale,
2013
- key,
2014
- files: used.get(key) ?? []
1961
+ key: base,
1962
+ reason: `"${base}" already exists, so merging would overwrite it`
1963
+ });
1964
+ continue;
1965
+ }
1966
+ if (!forms.has("other")) {
1967
+ skipped.push({
1968
+ locale,
1969
+ key: base,
1970
+ reason: "no _other form, so the block would have no catch-all"
1971
+ });
1972
+ continue;
1973
+ }
1974
+ if (forms.size === 1) {
1975
+ skipped.push({
1976
+ locale,
1977
+ key: base,
1978
+ reason: "only a plural form, so add the singular before merging"
1979
+ });
1980
+ continue;
1981
+ }
1982
+ const sorted = [...forms.entries()].sort((a, b) => order(a[0], b[0]));
1983
+ const cases = [];
1984
+ let problem;
1985
+ for (const [category, form] of sorted) {
1986
+ problem = fromI18next ? i18nextProblem(form.value) : void 0;
1987
+ const body = problem ? void 0 : toVariant(fromI18next ? convertBraces(form.value) : form.value);
1988
+ if (body === void 0) {
1989
+ problem ??= "a form holds more than a name in braces, so merge it by hand";
1990
+ break;
1991
+ }
1992
+ cases.push(`${category}: ${body}`);
1993
+ }
1994
+ if (problem) {
1995
+ skipped.push({
1996
+ locale,
1997
+ key: base,
1998
+ reason: problem
1999
+ });
2000
+ continue;
2001
+ }
2002
+ const merged = `{count | ${cases.join(" | ")}}`;
2003
+ for (const [, form] of sorted) delete out[form.key];
2004
+ out[base] = merged;
2005
+ plurals.push({
2006
+ locale,
2007
+ key: base,
2008
+ from: sorted.map(([, form]) => form.key),
2009
+ after: merged
2010
+ });
2011
+ }
2012
+ }
2013
+ function migrateCatalogs(cfg, options = {}) {
2014
+ const braces = [];
2015
+ const plurals = [];
2016
+ const skipped = [];
2017
+ const written = [];
2018
+ const state = loadState(cfg);
2019
+ const done = new Set(state.migrated ?? []);
2020
+ const catalogs = new Map(cfg.locales.map((locale) => [locale, readCatalog(cfg, locale)]));
2021
+ const pending = cfg.locales.filter((locale) => !done.has(locale));
2022
+ const fromI18next = pending.some((locale) => Object.values(catalogs.get(locale)).some((value) => typeof value === "string" && (DOUBLE.test(value) || NESTED.test(value))));
2023
+ for (const locale of cfg.locales) {
2024
+ const catalog = catalogs.get(locale);
2025
+ const out = Object.assign(emptyCatalog(), catalog);
2026
+ const convert = fromI18next && !done.has(locale);
2027
+ for (const [key, value] of Object.entries(catalog)) {
2028
+ if (!convert || typeof value !== "string") continue;
2029
+ const problem = i18nextProblem(value);
2030
+ if (problem) {
2031
+ skipped.push({
2032
+ locale,
2033
+ key,
2034
+ reason: problem
2035
+ });
2036
+ continue;
2037
+ }
2038
+ const after = convertBraces(value);
2039
+ if (after !== value) {
2040
+ braces.push({
2041
+ locale,
2042
+ key,
2043
+ before: value,
2044
+ after
2045
+ });
2046
+ out[key] = after;
2047
+ }
2048
+ }
2049
+ if (options.plurals) mergePlurals(locale, catalog, out, plurals, skipped, convert);
2050
+ if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
2051
+ writeCatalog(cfg, locale, out);
2052
+ written.push(locale);
2053
+ }
2054
+ }
2055
+ if (options.write && fromI18next) {
2056
+ const converted = pending.filter((locale) => existsSync(catalogPath(cfg, locale)));
2057
+ if (converted.length) saveState(cfg, {
2058
+ ...state,
2059
+ migrated: [...done, ...converted]
2060
+ });
2061
+ }
2062
+ const remembered = cfg.locales.filter((locale) => done.has(locale));
2063
+ return {
2064
+ detected: detectLibraries(cfg.root),
2065
+ braces,
2066
+ plurals,
2067
+ skipped,
2068
+ written,
2069
+ remembered
2070
+ };
2071
+ }
2072
+ //#endregion
2073
+ //#region src/tag.ts
2074
+ function isLocaleTag(tag) {
2075
+ try {
2076
+ Intl.getCanonicalLocales(tag);
2077
+ return true;
2078
+ } catch {
2079
+ return false;
2080
+ }
2081
+ }
2082
+ function suggestTag(tag) {
2083
+ const near = tag.replace(/_/g, "-");
2084
+ return near !== tag && isLocaleTag(near) ? near : void 0;
2085
+ }
2086
+ function projectLocale(tag, locales) {
2087
+ if (locales.includes(tag)) return tag;
2088
+ const plain = (value) => value.replace(/_/g, "-").toLowerCase();
2089
+ return locales.find((locale) => plain(locale) === plain(tag));
2090
+ }
2091
+ //#endregion
2092
+ //#region src/init.ts
2093
+ const CATALOG_DIRS = [
2094
+ "locales",
2095
+ "src/locales",
2096
+ "src/i18n/locales",
2097
+ "src/i18n",
2098
+ "i18n",
2099
+ "lang",
2100
+ "src/lang",
2101
+ "translations",
2102
+ "src/translations",
2103
+ "messages"
2104
+ ];
2105
+ function existingCatalogs(root) {
2106
+ return CATALOG_DIRS.find((dir) => {
2107
+ try {
2108
+ return readdirSync(join(root, dir)).some((file) => file.endsWith(".json") && isLocaleTag(file.slice(0, -5)));
2109
+ } catch {
2110
+ return false;
2111
+ }
2112
+ });
2113
+ }
2114
+ function cliReachable(root) {
2115
+ const bin = join(root, "node_modules", ".bin");
2116
+ return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
2117
+ }
2118
+ const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
2119
+ function configSource(options, typescript) {
2120
+ const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
2121
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
2122
+ if (options.dir) fields.push(` dir: '${options.dir}',`);
2123
+ const body = `export default {\n${fields.join("\n")}\n}`;
2124
+ if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
2125
+ return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
2126
+ }
2127
+ async function init(input = {}) {
2128
+ const root = input.root ?? process.cwd();
2129
+ const created = [];
2130
+ const skipped = [];
2131
+ const renamed = [];
2132
+ const refused = [];
2133
+ const typed = input.locales?.flatMap((locale) => {
2134
+ if (isLocaleTag(locale)) return [locale];
2135
+ const near = suggestTag(locale);
2136
+ if (near) renamed.push({
2137
+ from: locale,
2138
+ to: near
2139
+ });
2140
+ else refused.push(locale);
2141
+ return near ? [near] : [];
2142
+ });
2143
+ const locales = typed && [...new Set(typed)];
2144
+ let sourceLocale = input.sourceLocale;
2145
+ if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
2146
+ const near = suggestTag(sourceLocale);
2147
+ if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
2148
+ renamed.push({
2149
+ from: sourceLocale,
2150
+ to: near
2151
+ });
2152
+ sourceLocale = near;
2153
+ }
2154
+ const options = {
2155
+ ...input,
2156
+ locales,
2157
+ sourceLocale
2158
+ };
2159
+ const existing = findConfigFile(root);
2160
+ const typescript = existsSync(join(root, "tsconfig.json"));
2161
+ const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
2162
+ const found = existing || options.dir ? void 0 : existingCatalogs(root);
2163
+ if (existing) skipped.push(existing);
2164
+ else {
2165
+ const dir = found === "locales" ? void 0 : found;
2166
+ writeFileSync(join(root, configFile), configSource({
2167
+ ...options,
2168
+ dir: options.dir ?? dir
2169
+ }, typescript));
2170
+ created.push(configFile);
2171
+ }
2172
+ const fromFile = existing ? await loadConfigFile(root) : {};
2173
+ const scaffold = {
2174
+ dir: options.dir ?? fromFile.dir ?? found,
2175
+ sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
2176
+ locales: options.locales ?? fromFile.locales
2177
+ };
2178
+ const dir = join(root, scaffold.dir ?? "locales");
2179
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
2180
+ for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
2181
+ const file = join(dir, `${locale}.json`);
2182
+ const label = relative(root, file).replaceAll("\\", "/");
2183
+ if (existsSync(file)) skipped.push(label);
2184
+ else {
2185
+ writeFileSync(file, "{}\n");
2186
+ created.push(label);
2187
+ }
2188
+ }
2189
+ const host = detectHost(root);
2190
+ const deps = readDependencies(root);
2191
+ const missing = host?.install.filter((pkg) => !deps[pkg]) ?? [];
2192
+ const next = host ? [...missing.length ? [installCommand(root, missing)] : [], host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
2193
+ const others = detectLibraries(root);
2194
+ if (found && others.length) next.push(`port the ${others.join(" and ")} catalogs: npx verbaly migrate reports, --write applies`);
2195
+ return {
2196
+ created,
2197
+ skipped,
2198
+ host: host?.name,
2199
+ configFile,
2200
+ next,
2201
+ renamed,
2202
+ refused,
2203
+ found
2204
+ };
2205
+ }
2206
+ //#endregion
2207
+ //#region src/check.ts
2208
+ function gatePasses(result) {
2209
+ return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2210
+ }
2211
+ function check(cfg, catalogs, registry, fingerprints = {}) {
2212
+ const extracted = registry.messages();
2213
+ const flat = {};
2214
+ for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
2215
+ const source = flat[cfg.sourceLocale] ?? {};
2216
+ const shipped = shippedCatalogs(cfg, flat, registry);
2217
+ const sourceText = shipped[cfg.sourceLocale];
2218
+ const used = registry.usedKeys();
2219
+ const unknown = [];
2220
+ for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
2221
+ key,
2222
+ files
2223
+ });
2224
+ const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
2225
+ const missing = [];
2226
+ for (const key of extracted.keys()) if (!source[key]) missing.push({
2227
+ locale: cfg.sourceLocale,
2228
+ key,
2229
+ source: extracted.get(key)?.message
2230
+ });
2231
+ for (const locale of cfg.locales) {
2232
+ if (locale === cfg.sourceLocale) continue;
2233
+ for (const key of needed) if (!flat[locale]?.[key]) missing.push({
2234
+ locale,
2235
+ key,
2236
+ source: source[key] ?? extracted.get(key)?.message
2237
+ });
2238
+ }
2239
+ const broken = [];
2240
+ const add = (locale, key, issues) => {
2241
+ for (const issue of issues) broken.push({
2242
+ locale,
2243
+ key,
2244
+ severity: issue.severity,
2245
+ issue: issue.message
2246
+ });
2247
+ };
2248
+ const divergent = [];
2249
+ for (const [key, entry] of extracted) {
2250
+ const written = source[key];
2251
+ if (written && written !== entry.message) divergent.push({
2252
+ key,
2253
+ catalog: written,
2254
+ code: siteOf(entry)
2255
+ });
2256
+ }
2257
+ for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
2258
+ for (const locale of cfg.locales) {
2259
+ if (locale === cfg.sourceLocale) continue;
2260
+ for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
2261
+ if (!translated) continue;
2262
+ add(locale, key, validateMessage(translated, locale));
2263
+ const text = sourceText[key];
2264
+ if (text) add(locale, key, validatePair(text, translated));
2265
+ }
2266
+ }
2267
+ const extra = [];
2268
+ for (const locale of cfg.locales) {
2269
+ if (locale === cfg.sourceLocale) continue;
2270
+ for (const key of Object.keys(flat[locale] ?? {})) {
2271
+ if (source[key] !== void 0 || extracted.has(key)) continue;
2272
+ extra.push({
2273
+ locale,
2274
+ key,
2275
+ files: used.get(key) ?? []
2015
2276
  });
2016
2277
  }
2017
2278
  }
@@ -2260,6 +2521,9 @@ function generateDts(catalog, options = {}) {
2260
2521
  }
2261
2522
  }
2262
2523
  return `${DTS_HEADER}
2524
+ // biome-ignore-all lint: generated by verbaly
2525
+ // biome-ignore-all format: generated by verbaly
2526
+ // prettier-ignore
2263
2527
  declare module 'virtual:verbaly' {
2264
2528
  export interface VerbalyMessages {
2265
2529
  ${lines.join("\n")}
@@ -2289,17 +2553,28 @@ ${lines.join("\n")}
2289
2553
  ): import('verbaly').Verbaly;
2290
2554
  export function createRequestInstance(locale: string): Promise<import('verbaly').Verbaly>;
2291
2555
 
2292
- export function t<K extends VerbalyKey | TemplateStringsArray>(
2293
- first: K,
2294
- ...rest: K extends VerbalyKey
2295
- ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
2296
- : unknown[]
2297
- ): string;
2298
- export namespace t {
2299
- export function id(
2300
- key: string,
2301
- ): (strings: TemplateStringsArray, ...values: unknown[]) => string;
2302
- }
2556
+ // a literal key must exist; a string, a template with data in it or a union of keys is data
2557
+ export const t: {
2558
+ <K extends VerbalyKey | TemplateStringsArray | (string & {})>(
2559
+ first: K extends TemplateStringsArray
2560
+ ? K
2561
+ : {} extends Record<K & string, 1>
2562
+ ? K
2563
+ : K extends VerbalyKey ? K : VerbalyKey,
2564
+ ...rest: [K] extends [never]
2565
+ ? [params?: import('verbaly').Params]
2566
+ : [K] extends [(K extends unknown ? (key: K) => void : never) extends (key: infer One) => void ? One : never]
2567
+ ? K extends TemplateStringsArray
2568
+ ? unknown[]
2569
+ : {} extends Record<K & string, 1>
2570
+ ? [params?: import('verbaly').Params]
2571
+ : K extends VerbalyKey
2572
+ ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
2573
+ : unknown[]
2574
+ : [params?: import('verbaly').Params]
2575
+ ): string;
2576
+ id(key: string): (strings: TemplateStringsArray, ...values: unknown[]) => string;
2577
+ };
2303
2578
 
2304
2579
  export function setLocale(locale: string): Promise<void>;
2305
2580
  export function switchLocale(
@@ -2321,6 +2596,7 @@ ${lines.join("\n")}
2321
2596
  }
2322
2597
  }
2323
2598
 
2599
+ // prettier-ignore
2324
2600
  declare module 'virtual:verbaly/locale/*' {
2325
2601
  const messages: Record<string, string>;
2326
2602
  export default messages;
@@ -2484,6 +2760,11 @@ function formatDoctorEntry(entry) {
2484
2760
  return entry.fix ? `${head}
2485
2761
  fix: ${entry.fix}` : head;
2486
2762
  }
2763
+ function formatDoctorHealth(result) {
2764
+ if (!result.ok) return "problems found";
2765
+ const warnings = result.entries.filter((entry) => entry.level === "warn").length;
2766
+ return warnings > 0 ? `setup works, with ${counted(warnings, "warning")} to read` : "setup looks healthy";
2767
+ }
2487
2768
  async function doctor(cfg) {
2488
2769
  const entries = [];
2489
2770
  const ok = (name, message) => entries.push({
@@ -3467,169 +3748,6 @@ function csvRows(content) {
3467
3748
  return rows;
3468
3749
  }
3469
3750
  //#endregion
3470
- //#region src/migrate.ts
3471
- const KNOWN = [
3472
- "i18next",
3473
- "react-i18next",
3474
- "vue-i18n",
3475
- "react-intl",
3476
- "next-intl",
3477
- "svelte-i18n"
3478
- ];
3479
- function detectLibraries(root) {
3480
- const path = join(root, "package.json");
3481
- if (!existsSync(path)) return [];
3482
- let manifest;
3483
- try {
3484
- manifest = JSON.parse(readFileSync(path, "utf8"));
3485
- } catch {
3486
- return [];
3487
- }
3488
- const deps = {
3489
- ...manifest.dependencies,
3490
- ...manifest.devDependencies
3491
- };
3492
- return KNOWN.filter((name) => deps[name] !== void 0);
3493
- }
3494
- const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
3495
- const FORMATTED = /\{\{\s*-?\s*[A-Za-z_$][\w$]*\s*,[^}]*\}\}/;
3496
- const UNESCAPED = /\{\{\s*-\s*[A-Za-z_$][\w$]*\s*\}\}/;
3497
- const NESTED = /\$t\(/;
3498
- const CATEGORIES = [
3499
- "zero",
3500
- "one",
3501
- "two",
3502
- "few",
3503
- "many",
3504
- "other"
3505
- ];
3506
- const SUFFIX = new RegExp(`^(.*)_(${[...CATEGORIES, "plural"].join("|")})$`);
3507
- function convertBraces(text) {
3508
- return text.replace(PLAIN, "{$1}");
3509
- }
3510
- function toHash(text) {
3511
- return text.replaceAll("{count}", "#");
3512
- }
3513
- function order(a, b) {
3514
- return CATEGORIES.indexOf(a) - CATEGORIES.indexOf(b);
3515
- }
3516
- function mergePlurals(locale, catalog, out, plurals, skipped) {
3517
- const groups = /* @__PURE__ */ new Map();
3518
- const legacy = /* @__PURE__ */ new Set();
3519
- for (const [key, value] of Object.entries(catalog)) {
3520
- const match = SUFFIX.exec(key);
3521
- if (!match || typeof value !== "string") continue;
3522
- const [, base, suffix] = match;
3523
- if (suffix === "plural") legacy.add(base);
3524
- const category = suffix === "plural" ? "other" : suffix;
3525
- if (!groups.has(base)) groups.set(base, /* @__PURE__ */ new Map());
3526
- groups.get(base).set(category, {
3527
- key,
3528
- value
3529
- });
3530
- }
3531
- for (const [base, forms] of groups) {
3532
- const bare = catalog[base];
3533
- if (legacy.has(base) && typeof bare === "string" && !forms.has("one")) forms.set("one", {
3534
- key: base,
3535
- value: bare
3536
- });
3537
- else if (bare !== void 0) {
3538
- skipped.push({
3539
- locale,
3540
- key: base,
3541
- reason: `"${base}" already exists, so merging would overwrite it`
3542
- });
3543
- continue;
3544
- }
3545
- if (!forms.has("other")) {
3546
- skipped.push({
3547
- locale,
3548
- key: base,
3549
- reason: "no _other form, so the block would have no catch-all"
3550
- });
3551
- continue;
3552
- }
3553
- if (forms.size === 1) {
3554
- skipped.push({
3555
- locale,
3556
- key: base,
3557
- reason: "only a plural form, so add the singular before merging"
3558
- });
3559
- continue;
3560
- }
3561
- const sorted = [...forms.entries()].sort((a, b) => order(a[0], b[0]));
3562
- const merged = `{count | ${sorted.map(([category, form]) => `${category}: ${toHash(convertBraces(form.value))}`).join(" | ")}}`;
3563
- for (const [, form] of sorted) delete out[form.key];
3564
- out[base] = merged;
3565
- plurals.push({
3566
- locale,
3567
- key: base,
3568
- from: sorted.map(([, form]) => form.key),
3569
- after: merged
3570
- });
3571
- }
3572
- }
3573
- function migrateCatalogs(cfg, options = {}) {
3574
- const braces = [];
3575
- const plurals = [];
3576
- const skipped = [];
3577
- const written = [];
3578
- for (const locale of cfg.locales) {
3579
- const catalog = readCatalog(cfg, locale);
3580
- const out = Object.assign(emptyCatalog(), catalog);
3581
- for (const [key, value] of Object.entries(catalog)) {
3582
- if (typeof value !== "string") continue;
3583
- if (NESTED.test(value)) {
3584
- skipped.push({
3585
- locale,
3586
- key,
3587
- reason: "uses $t() nesting, which has no direct equivalent"
3588
- });
3589
- continue;
3590
- }
3591
- if (UNESCAPED.test(value)) {
3592
- skipped.push({
3593
- locale,
3594
- key,
3595
- reason: "uses {{- name}}, so decide whether the message is rich"
3596
- });
3597
- continue;
3598
- }
3599
- if (FORMATTED.test(value)) {
3600
- skipped.push({
3601
- locale,
3602
- key,
3603
- reason: "uses an i18next format, which needs the matching Verbaly one"
3604
- });
3605
- continue;
3606
- }
3607
- const after = convertBraces(value);
3608
- if (after !== value) {
3609
- braces.push({
3610
- locale,
3611
- key,
3612
- before: value,
3613
- after
3614
- });
3615
- out[key] = after;
3616
- }
3617
- }
3618
- if (options.plurals) mergePlurals(locale, catalog, out, plurals, skipped);
3619
- if ((braces.some((b) => b.locale === locale) || plurals.some((p) => p.locale === locale)) && options.write) {
3620
- writeCatalog(cfg, locale, out);
3621
- written.push(locale);
3622
- }
3623
- }
3624
- return {
3625
- detected: detectLibraries(cfg.root),
3626
- braces,
3627
- plurals,
3628
- skipped,
3629
- written
3630
- };
3631
- }
3632
- //#endregion
3633
3751
  //#region src/project.ts
3634
3752
  async function syncProject(cfg, options = {}) {
3635
3753
  const registry = options.registry ?? await extractProject(cfg);
@@ -4651,6 +4769,7 @@ async function runCli(args = process.argv.slice(2)) {
4651
4769
  if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(", ")}`);
4652
4770
  for (const { from, to } of result.renamed) console.log(` wrote ${to} for ${from}, since a locale tag takes a hyphen`);
4653
4771
  for (const locale of result.refused) console.warn(` left out "${locale}": it is not a locale tag, use one like es or pt-BR`);
4772
+ if (result.found) console.log(` catalogs: ${result.found}, kept where they already are`);
4654
4773
  if (result.host) console.log(` detected: ${result.host}`);
4655
4774
  console.log([" next steps:", ...result.next.map((step, i) => ` ${i + 1}. ${step}`)].join("\n"));
4656
4775
  return;
@@ -4669,7 +4788,7 @@ async function runCli(args = process.argv.slice(2)) {
4669
4788
  else if (entry.level === "warn") console.warn(line);
4670
4789
  else console.log(line);
4671
4790
  }
4672
- if (result.ok) console.log("[verbaly] setup looks healthy ✓");
4791
+ if (result.ok) console.log(`[verbaly] ${formatDoctorHealth(result)} ✓`);
4673
4792
  else {
4674
4793
  console.error("[verbaly] doctor found problems");
4675
4794
  process.exitCode = 1;
@@ -4733,13 +4852,14 @@ async function runCli(args = process.argv.slice(2)) {
4733
4852
  });
4734
4853
  const from = result.detected.length ? result.detected.join(", ") : "no known i18n library";
4735
4854
  const changes = result.braces.length + result.plurals.length;
4855
+ const before = result.remembered.length ? `, ${counted(result.remembered.length, "language")} converted before` : "";
4736
4856
  if (changes === 0 && result.skipped.length === 0) {
4737
- console.log(`[verbaly] catalogs need nothing (${from}) ✓`);
4857
+ console.log(`[verbaly] catalogs need nothing (${from}${before}) ✓`);
4738
4858
  return;
4739
4859
  }
4740
4860
  const verb = values.write ? "ported" : "would port";
4741
4861
  const note = values.write ? "" : " (report only, use --write to apply)";
4742
- console.log(`[verbaly] ${verb} ${counted(changes, "message")} from ${from}${note}`);
4862
+ console.log(`[verbaly] ${verb} ${counted(changes, "message")} from ${from}${before}${note}`);
4743
4863
  for (const entry of result.braces) console.log(` ${entry.locale} ${entry.key} ${entry.before} → ${entry.after}`);
4744
4864
  for (const entry of result.plurals) console.log(` ${entry.locale} ${entry.key} ${entry.from.join(" + ")} → ${entry.after}`);
4745
4865
  if (!values.plurals && changes > 0) console.log(" --plurals also merges _one/_other into one message with variants");
@@ -4747,6 +4867,7 @@ async function runCli(args = process.argv.slice(2)) {
4747
4867
  console.log(" needs a human:");
4748
4868
  for (const entry of result.skipped) console.log(` ${entry.locale} ${entry.key} ${entry.reason}`);
4749
4869
  }
4870
+ 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`);
4750
4871
  if (values.write) console.log(" next: run verbaly check");
4751
4872
  return;
4752
4873
  }