@verbaly/compiler 0.63.0 → 0.65.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,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { basename, dirname, join, relative, resolve } from "node:path";
3
3
  import { parseArgs } from "node:util";
4
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { glob } from "tinyglobby";
@@ -55,14 +55,17 @@ function loadCatalogs(cfg) {
55
55
  function isNested(tree) {
56
56
  return Object.values(tree).some((value) => typeof value === "object" && value !== null);
57
57
  }
58
+ function group() {
59
+ return Object.create(null);
60
+ }
58
61
  function nest(catalog) {
59
- const tree = {};
62
+ const tree = group();
60
63
  for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
61
64
  const parts = key.split(".");
62
65
  const leaf = parts[parts.length - 1];
63
66
  let node = parts.length > 1 ? tree : void 0;
64
67
  for (let i = 0; node && i < parts.length - 1; i++) {
65
- const next = node[parts[i]] ??= {};
68
+ const next = node[parts[i]] ??= group();
66
69
  node = typeof next === "object" && next !== null ? next : void 0;
67
70
  }
68
71
  if (node && typeof node[leaf] !== "object") node[leaf] = message;
@@ -71,7 +74,7 @@ function nest(catalog) {
71
74
  return tree;
72
75
  }
73
76
  function sortTree(tree) {
74
- const sorted = {};
77
+ const sorted = group();
75
78
  for (const key of Object.keys(tree).sort()) {
76
79
  const value = tree[key];
77
80
  if (typeof value === "string") sorted[key] = value;
@@ -86,7 +89,7 @@ function isSorted(keys) {
86
89
  function orderLike(tree, previous) {
87
90
  const had = Object.keys(previous);
88
91
  if (isSorted(had)) return sortTree(tree);
89
- const out = {};
92
+ const out = group();
90
93
  const take = (key) => {
91
94
  const value = tree[key];
92
95
  if (typeof value === "string") {
@@ -97,8 +100,8 @@ function orderLike(tree, previous) {
97
100
  const before = previous[key];
98
101
  out[key] = typeof before === "object" && before !== null ? orderLike(value, before) : sortTree(value);
99
102
  };
100
- for (const key of had) if (key in tree) take(key);
101
- for (const key of Object.keys(tree).sort()) if (!(key in previous)) take(key);
103
+ for (const key of had) if (Object.hasOwn(tree, key)) take(key);
104
+ for (const key of Object.keys(tree).sort()) if (!Object.hasOwn(previous, key)) take(key);
102
105
  return out;
103
106
  }
104
107
  function serializeCatalog(catalog, nested = false, previous) {
@@ -321,6 +324,25 @@ function definedOnly(config) {
321
324
  return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
322
325
  }
323
326
  //#endregion
327
+ //#region src/tag.ts
328
+ function isLocaleTag(tag) {
329
+ try {
330
+ Intl.getCanonicalLocales(tag);
331
+ return true;
332
+ } catch {
333
+ return false;
334
+ }
335
+ }
336
+ function suggestTag(tag) {
337
+ const near = tag.replace(/_/g, "-");
338
+ return near !== tag && isLocaleTag(near) ? near : void 0;
339
+ }
340
+ function projectLocale(tag, locales) {
341
+ if (locales.includes(tag)) return tag;
342
+ const plain = (value) => value.replace(/_/g, "-").toLowerCase();
343
+ return locales.find((locale) => plain(locale) === plain(tag));
344
+ }
345
+ //#endregion
324
346
  //#region src/init.ts
325
347
  const HOSTS = [
326
348
  {
@@ -409,10 +431,38 @@ function configSource(options, typescript) {
409
431
  if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
410
432
  return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
411
433
  }
412
- async function init(options = {}) {
413
- const root = options.root ?? process.cwd();
434
+ async function init(input = {}) {
435
+ const root = input.root ?? process.cwd();
414
436
  const created = [];
415
437
  const skipped = [];
438
+ const renamed = [];
439
+ const refused = [];
440
+ const typed = input.locales?.flatMap((locale) => {
441
+ if (isLocaleTag(locale)) return [locale];
442
+ const near = suggestTag(locale);
443
+ if (near) renamed.push({
444
+ from: locale,
445
+ to: near
446
+ });
447
+ else refused.push(locale);
448
+ return near ? [near] : [];
449
+ });
450
+ const locales = typed && [...new Set(typed)];
451
+ let sourceLocale = input.sourceLocale;
452
+ if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
453
+ const near = suggestTag(sourceLocale);
454
+ if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
455
+ renamed.push({
456
+ from: sourceLocale,
457
+ to: near
458
+ });
459
+ sourceLocale = near;
460
+ }
461
+ const options = {
462
+ ...input,
463
+ locales,
464
+ sourceLocale
465
+ };
416
466
  const existing = findConfigFile(root);
417
467
  const typescript = existsSync(join(root, "tsconfig.json"));
418
468
  const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
@@ -445,7 +495,9 @@ async function init(options = {}) {
445
495
  skipped,
446
496
  host: host?.name,
447
497
  configFile,
448
- next
498
+ next,
499
+ renamed,
500
+ refused
449
501
  };
450
502
  }
451
503
  //#endregion
@@ -621,8 +673,9 @@ function check(cfg, catalogs, registry) {
621
673
  const flat = {};
622
674
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
623
675
  const source = flat[cfg.sourceLocale] ?? {};
676
+ const used = registry.usedKeys();
624
677
  const unknown = [];
625
- for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
678
+ for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
626
679
  key,
627
680
  files
628
681
  });
@@ -662,6 +715,18 @@ function check(cfg, catalogs, registry) {
662
715
  if (text) add(locale, key, validatePair(text, translated));
663
716
  }
664
717
  }
718
+ const extra = [];
719
+ for (const locale of cfg.locales) {
720
+ if (locale === cfg.sourceLocale) continue;
721
+ for (const key of Object.keys(flat[locale] ?? {})) {
722
+ if (source[key] !== void 0 || extracted.has(key)) continue;
723
+ extra.push({
724
+ locale,
725
+ key,
726
+ files: used.get(key) ?? []
727
+ });
728
+ }
729
+ }
665
730
  return {
666
731
  ok: gatePasses({
667
732
  missing,
@@ -670,7 +735,8 @@ function check(cfg, catalogs, registry) {
670
735
  }),
671
736
  missing,
672
737
  unknown,
673
- broken
738
+ broken,
739
+ extra
674
740
  };
675
741
  }
676
742
  function formatCheckResult(result, root) {
@@ -703,7 +769,9 @@ function checkNextSteps(result, cliReachable = true) {
703
769
  return steps.join("\n");
704
770
  }
705
771
  function formatCheckWarnings(result) {
706
- return result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`).join("\n");
772
+ const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
773
+ 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`);
774
+ return lines.join("\n");
707
775
  }
708
776
  function truncate(text, max) {
709
777
  return text.length > max ? text.slice(0, max - 1) + "…" : text;
@@ -758,6 +826,11 @@ function githubCheckAnnotations(result, registry, root) {
758
826
  const line = content === void 0 ? void 0 : lineAt(content, origin.start);
759
827
  lines.push(`::${command} file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
760
828
  }
829
+ for (const entry of result.extra) {
830
+ const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);
831
+ const file = entry.files[0];
832
+ lines.push(file ? `::warning file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::warning::${text}`);
833
+ }
761
834
  return lines;
762
835
  }
763
836
  function lineAt(content, offset) {
@@ -783,7 +856,7 @@ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
783
856
  const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
784
857
  function collectParams(message) {
785
858
  const out = /* @__PURE__ */ new Map();
786
- visit(parse(message), out);
859
+ visit(parse(message, parseIcu), out);
787
860
  return out;
788
861
  }
789
862
  function visit(nodes, out) {
@@ -962,9 +1035,10 @@ var MessageRegistry = class {
962
1035
  }
963
1036
  return out;
964
1037
  }
965
- usedKeys() {
1038
+ usedKeys(strict = false) {
966
1039
  const out = /* @__PURE__ */ new Map();
967
1040
  for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
1041
+ if (strict && used.loose) continue;
968
1042
  const files = out.get(used.key) ?? [];
969
1043
  if (!files.includes(used.file)) files.push(used.file);
970
1044
  out.set(used.key, files);
@@ -1049,11 +1123,8 @@ function analyze(code, file, options = {}) {
1049
1123
  return;
1050
1124
  }
1051
1125
  if (!isTReference(callee, names)) return;
1052
- const first = args[0];
1053
- if (first?.type === "StringLiteral") usedKeys.push({
1054
- key: first.value,
1055
- file
1056
- });
1126
+ const key = staticString(args[0]);
1127
+ if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
1057
1128
  } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
1058
1129
  });
1059
1130
  return {
@@ -1067,14 +1138,28 @@ function collectDeclaredKeys(node, file, out) {
1067
1138
  for (const property of node.properties) {
1068
1139
  if (property.type !== "ObjectProperty") continue;
1069
1140
  const value = property.value;
1070
- if (value.type === "StringLiteral") {
1071
- if (value.value !== "") out.push({
1072
- key: value.value,
1073
- file
1074
- });
1141
+ const key = staticString(value);
1142
+ if (key !== void 0) {
1143
+ if (key !== "") out.push(usedKey(key, file, value));
1075
1144
  } else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
1076
1145
  }
1077
1146
  }
1147
+ function usedKey(key, file, node) {
1148
+ return node?.type === "StringLiteral" ? {
1149
+ key,
1150
+ file
1151
+ } : {
1152
+ key,
1153
+ file,
1154
+ loose: true
1155
+ };
1156
+ }
1157
+ function staticString(node) {
1158
+ if (!node) return void 0;
1159
+ if (node.type === "StringLiteral") return node.value;
1160
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
1161
+ if (node.type === "JSXExpressionContainer") return staticString(node.expression);
1162
+ }
1078
1163
  const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
1079
1164
  function collectStrayImports(node, file, out) {
1080
1165
  const source = node.source;
@@ -1114,19 +1199,16 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
1114
1199
  });
1115
1200
  if (idAttr) {
1116
1201
  const value = idAttr.value;
1117
- if (value?.type !== "StringLiteral") return;
1118
- const id = value.value;
1119
- if (attrs.length === 1 && children?.length) {
1202
+ const id = staticString(value);
1203
+ if (id === void 0) return;
1204
+ if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
1120
1205
  const built = buildTransMessage(code, children, names);
1121
1206
  if (built?.text.trim()) {
1122
1207
  push(id, built);
1123
1208
  return;
1124
1209
  }
1125
1210
  }
1126
- usedKeys.push({
1127
- key: id,
1128
- file
1129
- });
1211
+ usedKeys.push(usedKey(id, file, value));
1130
1212
  return;
1131
1213
  }
1132
1214
  if (attrs.length > 0) return;
@@ -1587,6 +1669,12 @@ async function doctor(cfg) {
1587
1669
  ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/${how}`);
1588
1670
  }
1589
1671
  }
1672
+ for (const locale of cfg.locales) {
1673
+ if (isLocaleTag(locale)) continue;
1674
+ const near = suggestTag(locale);
1675
+ const file = rel(join(cfg.dir, `${locale}.json`));
1676
+ warn("locales", `"${locale}" is not a locale tag, so numbers, dates and plurals in it format in a fallback`, near ? `rename it to ${near}: the file ${file} and your config` : `name it with a language tag like es or pt-BR, in ${file} and in your config`);
1677
+ }
1590
1678
  const source = catalogs[cfg.sourceLocale];
1591
1679
  if (source && Object.keys(source).length === 0) warn("source", `source catalog ${cfg.sourceLocale}.json is empty`, "write your first t`…` message and run `npx verbaly extract`");
1592
1680
  const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
@@ -1652,6 +1740,10 @@ async function doctor(cfg) {
1652
1740
  const locales = [...new Set(broken.map((b) => b.locale))];
1653
1741
  error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
1654
1742
  }
1743
+ if (result.extra.length > 0) {
1744
+ const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);
1745
+ warn("extras", `a translation has ${counted(result.extra.length, "key")} the source catalog does not (${preview(shown)})`, scanning ? "add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest" : "add them to the source catalog if your code uses them, or delete them from the translations");
1746
+ }
1655
1747
  const warnings = result.broken.filter((entry) => entry.severity === "warning");
1656
1748
  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");
1657
1749
  if (result.ok) ok("translations", "all translations complete");
@@ -2004,7 +2096,7 @@ function toPo(sourceLocale, locale, entries) {
2004
2096
  ].join("\n\n");
2005
2097
  }
2006
2098
  function parsePo(content) {
2007
- const entries = {};
2099
+ const entries = Object.create(null);
2008
2100
  let locale;
2009
2101
  let msgctxt;
2010
2102
  let msgid;
@@ -2187,6 +2279,19 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2187
2279
  function compare(a, b) {
2188
2280
  return (a[0] ?? "").localeCompare(b[0] ?? "");
2189
2281
  }
2282
+ function mergeTranslations(cfg, locale, translated, keys) {
2283
+ const source = readCatalog(cfg, cfg.sourceLocale);
2284
+ const current = readCatalog(cfg, locale);
2285
+ const written = [];
2286
+ for (const key of keys) {
2287
+ const text = translated[key];
2288
+ if (!source[key] || current[key] || !text) continue;
2289
+ current[key] = text;
2290
+ written.push(key);
2291
+ }
2292
+ if (written.length > 0) writeCatalog(cfg, locale, current);
2293
+ return written;
2294
+ }
2190
2295
  function formatTranslateFailures(failed) {
2191
2296
  const grouped = [];
2192
2297
  for (const entry of failed) {
@@ -2202,7 +2307,7 @@ function formatTranslateFailures(failed) {
2202
2307
  async function resolveProvider(cfg, model) {
2203
2308
  const configured = cfg.translate.provider;
2204
2309
  if (typeof configured === "function") return configured;
2205
- const { claudeProvider } = await import("./claude-ByRATJ03.js");
2310
+ const { claudeProvider } = await import("./claude-arq_js_3.js");
2206
2311
  return claudeProvider({ model: model ?? cfg.translate.model });
2207
2312
  }
2208
2313
  function structureMatches(source, translated) {
@@ -2303,14 +2408,35 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
2303
2408
  imported: {},
2304
2409
  rejected: {},
2305
2410
  skipped: {},
2306
- unknown: {}
2411
+ unknown: {},
2412
+ unmatched: [],
2413
+ mapped: []
2307
2414
  };
2308
2415
  for (const file of files) {
2309
2416
  const parsed = parseExchangeFile(file, options.locale);
2310
- const locale = parsed.locale;
2311
- if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(locale)) throw new Error(`[verbaly] ${file}: "${locale}" doesn't look like a locale, pass --locale <id>.`);
2417
+ const detected = parsed.locale;
2418
+ if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(detected)) throw new Error(`[verbaly] ${file}: "${detected}" doesn't look like a locale, pass --locale <id>.`);
2419
+ const locale = projectLocale(detected, cfg.locales) ?? newLocale(cfg, detected);
2312
2420
  if (locale === cfg.sourceLocale) throw new Error(`[verbaly] ${file} targets the source locale "${locale}": import fills translations, not the source. Pass --locale if the detection is wrong.`);
2313
- const catalog = catalogs[locale] ??= {};
2421
+ if (locale === void 0) {
2422
+ const near = isLocaleTag(detected) ? detected : suggestTag(detected);
2423
+ result.unmatched.push(near ? {
2424
+ file,
2425
+ locale: near,
2426
+ reason: "undeclared"
2427
+ } : {
2428
+ file,
2429
+ locale: detected,
2430
+ reason: "invalid"
2431
+ });
2432
+ continue;
2433
+ }
2434
+ if (locale !== detected) result.mapped.push({
2435
+ file,
2436
+ from: detected,
2437
+ to: locale
2438
+ });
2439
+ const catalog = catalogs[locale] ??= Object.create(null);
2314
2440
  for (const [key, text] of Object.entries(parsed.entries)) {
2315
2441
  if (!text.trim()) continue;
2316
2442
  if (!source[key]) {
@@ -2379,9 +2505,13 @@ function toXliff(sourceLocale, locale, entries) {
2379
2505
  ""
2380
2506
  ].join("\n");
2381
2507
  }
2508
+ function newLocale(cfg, detected) {
2509
+ if (cfg.localesDeclared) return void 0;
2510
+ return isLocaleTag(detected) ? detected : suggestTag(detected);
2511
+ }
2382
2512
  function parseXliff(content) {
2383
2513
  const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
2384
- const entries = {};
2514
+ const entries = Object.create(null);
2385
2515
  for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
2386
2516
  const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
2387
2517
  if (!id) continue;
@@ -2412,7 +2542,7 @@ function parseCsv(content) {
2412
2542
  const keyCol = header.indexOf("key");
2413
2543
  const targetCol = header.indexOf("target");
2414
2544
  if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
2415
- const entries = {};
2545
+ const entries = Object.create(null);
2416
2546
  for (const row of rows.slice(1)) {
2417
2547
  const key = row[keyCol];
2418
2548
  if (key) entries[key] = row[targetCol] ?? "";
@@ -2752,12 +2882,16 @@ function publicPath(rel) {
2752
2882
  const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
2753
2883
  return path.length > 1 ? path.replace(/\/+$/, "") : path;
2754
2884
  }
2885
+ function linkFor(links, name) {
2886
+ return links && Object.hasOwn(links, name) ? links[name] : void 0;
2887
+ }
2755
2888
  function usedLinks(nodes, links) {
2756
2889
  const out = {};
2757
2890
  const walk = (list) => {
2758
2891
  for (const node of list) {
2759
2892
  if (typeof node === "string") continue;
2760
- if (links[node.name] !== void 0) out[node.name] = links[node.name];
2893
+ const link = linkFor(links, node.name);
2894
+ if (link !== void 0) out[node.name] = link;
2761
2895
  walk(node.children);
2762
2896
  }
2763
2897
  };
@@ -2841,7 +2975,7 @@ function injectAlternates(ms, html, alternates) {
2841
2975
  if (head) ms.appendLeft(head.index, block);
2842
2976
  }
2843
2977
  function injectCatalog(ms, html, messages) {
2844
- const json = JSON.stringify(messages).replace(/<\//g, "<\\/");
2978
+ const json = JSON.stringify(messages).replace(/<\//g, "<\\/").replace(/<!--/g, "\\u003c!--");
2845
2979
  const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
2846
2980
  const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
2847
2981
  const from = html.indexOf(CATALOG_OPEN);
@@ -3027,15 +3161,18 @@ function setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value) {
3027
3161
  }
3028
3162
  function richToHtml(nodes, allowed, links) {
3029
3163
  let out = "";
3030
- for (const node of nodes) if (typeof node === "string") out += escapeHtml(node);
3031
- else if (links?.[node.name] !== void 0) {
3032
- const { href, target, rel } = normalizeLink(links[node.name]);
3033
- let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
3034
- if (target) attrs += ` target="${escapeAttr(target)}"`;
3035
- if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
3036
- out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
3037
- } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
3038
- else out += richToHtml(node.children, allowed, links);
3164
+ for (const node of nodes) {
3165
+ const link = typeof node === "string" ? void 0 : linkFor(links, node.name);
3166
+ if (typeof node === "string") out += escapeHtml(node);
3167
+ else if (link !== void 0) {
3168
+ const { href, target, rel } = normalizeLink(link);
3169
+ let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
3170
+ if (target) attrs += ` target="${escapeAttr(target)}"`;
3171
+ if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
3172
+ out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
3173
+ } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
3174
+ else out += richToHtml(node.children, allowed, links);
3175
+ }
3039
3176
  return out;
3040
3177
  }
3041
3178
  function escapeHtml(text) {
@@ -3100,6 +3237,51 @@ function formatStatusResult(result) {
3100
3237
  const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
3101
3238
  //#endregion
3102
3239
  //#region src/watch.ts
3240
+ const NATIVE_TREE = process.platform === "darwin" || process.platform === "win32";
3241
+ function watchTree(root, options, onFile) {
3242
+ const watchers = /* @__PURE__ */ new Map();
3243
+ const close = (name) => {
3244
+ watchers.get(name)?.close();
3245
+ watchers.delete(name);
3246
+ };
3247
+ const open = (name, recursive, listener) => {
3248
+ const watcher = watch(join(root, name), {
3249
+ recursive,
3250
+ persistent: options.persistent ?? true
3251
+ }, listener);
3252
+ watcher.on("error", (error) => {
3253
+ close(name);
3254
+ console.warn(`[verbaly] stopped watching ${name || "the project"}:`, error);
3255
+ });
3256
+ watchers.set(name, watcher);
3257
+ };
3258
+ if (options.native ?? NATIVE_TREE) open("", true, (_event, file) => {
3259
+ if (file) onFile(file);
3260
+ });
3261
+ else {
3262
+ const sync = (name) => {
3263
+ close(name);
3264
+ if (name !== options.keep && (name === "node_modules" || name.startsWith("."))) return;
3265
+ try {
3266
+ if (!statSync(join(root, name)).isDirectory()) return;
3267
+ } catch {
3268
+ return;
3269
+ }
3270
+ open(name, true, (_event, file) => {
3271
+ if (file) onFile(`${name}/${file}`);
3272
+ });
3273
+ };
3274
+ open("", false, (_event, file) => {
3275
+ if (!file) return;
3276
+ sync(file);
3277
+ onFile(file);
3278
+ });
3279
+ for (const entry of readdirSync(root, { withFileTypes: true })) if (entry.isDirectory()) sync(entry.name);
3280
+ }
3281
+ return () => {
3282
+ for (const name of [...watchers.keys()]) close(name);
3283
+ };
3284
+ }
3103
3285
  function watchProject(cfg, run, options = {}) {
3104
3286
  const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
3105
3287
  let timer;
@@ -3127,7 +3309,7 @@ function watchProject(cfg, run, options = {}) {
3127
3309
  clearTimeout(timer);
3128
3310
  timer = setTimeout(() => void refresh(), options.debounce ?? 150);
3129
3311
  }
3130
- const watcher = watch(cfg.root, { recursive: true }, (_event, filename) => {
3312
+ const close = watchTree(cfg.root, {}, (filename) => {
3131
3313
  if (!filename) return;
3132
3314
  const file = filename.replaceAll("\\", "/");
3133
3315
  if (file.includes("node_modules/") || file.endsWith(".d.ts")) return;
@@ -3136,7 +3318,7 @@ function watchProject(cfg, run, options = {}) {
3136
3318
  });
3137
3319
  return () => {
3138
3320
  clearTimeout(timer);
3139
- watcher.close();
3321
+ close();
3140
3322
  };
3141
3323
  }
3142
3324
  //#endregion
@@ -3438,7 +3620,7 @@ Options:
3438
3620
  --root <path> project root (default: cwd)
3439
3621
  --dir <path> catalogs directory (default: locales)
3440
3622
  --source <locale> source locale (default: en)
3441
- --locales <csv> extra locales; for translate: target locales to fill
3623
+ --locales <csv> run on these locales only, the source always included (init: the ones to create)
3442
3624
  --prune drop keys no longer referenced (extract)
3443
3625
  --watch keep extracting as source files change (extract)
3444
3626
  --write apply the rewrites instead of only reporting (wrap, migrate)
@@ -3518,6 +3700,8 @@ async function runCli(args = process.argv.slice(2)) {
3518
3700
  });
3519
3701
  if (result.created.length) console.log(`[verbaly] created: ${result.created.join(", ")}`);
3520
3702
  if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(", ")}`);
3703
+ for (const { from, to } of result.renamed) console.log(` wrote ${to} for ${from}, since a locale tag takes a hyphen`);
3704
+ for (const locale of result.refused) console.warn(` left out "${locale}": it is not a locale tag, use one like es or pt-BR`);
3521
3705
  if (result.host) console.log(` detected: ${result.host}`);
3522
3706
  console.log([" next steps:", ...result.next.map((step, i) => ` ${i + 1}. ${step}`)].join("\n"));
3523
3707
  return;
@@ -3690,10 +3874,12 @@ async function runCli(args = process.argv.slice(2)) {
3690
3874
  return;
3691
3875
  }
3692
3876
  const drafts = loadDrafts(cfg);
3693
- for (const locale of Object.keys(result.translated)) {
3694
- writeCatalog(cfg, locale, catalogs[locale] ?? {});
3695
- markDrafts(drafts, locale, result.translated[locale]);
3696
- console.log(` ${locale}: +${result.translated[locale].length} translated (draft)`);
3877
+ for (const [locale, keys] of Object.entries(result.translated)) {
3878
+ const written = mergeTranslations(cfg, locale, catalogs[locale] ?? {}, keys);
3879
+ markDrafts(drafts, locale, written);
3880
+ console.log(` ${locale}: +${written.length} translated (draft)`);
3881
+ const kept = keys.length - written.length;
3882
+ if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
3697
3883
  }
3698
3884
  if (Object.keys(result.translated).length > 0) saveDrafts(cfg, drafts);
3699
3885
  for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
@@ -3775,6 +3961,17 @@ async function runCli(args = process.argv.slice(2)) {
3775
3961
  overwrite: values.overwrite,
3776
3962
  dryRun: values["dry-run"]
3777
3963
  });
3964
+ for (const { file, from, to } of result.mapped) console.log(` ${file}: "${from}" read as ${to}`);
3965
+ for (const { file, locale, reason } of result.unmatched) {
3966
+ if (reason === "undeclared") {
3967
+ console.warn(` ${file}: "${locale}" is not one of this project's locales (${cfg.locales.join(", ")}), so nothing was imported from it`);
3968
+ console.warn(` fix: add ${locale} to locales in your verbaly config, or pass --locale with one of them`);
3969
+ } else {
3970
+ console.warn(` ${file}: "${locale}" is not a locale tag, so nothing was imported from it`);
3971
+ console.warn(" fix: pass --locale with the tag it stands for, like pt-BR");
3972
+ }
3973
+ process.exitCode = 1;
3974
+ }
3778
3975
  const drafts = loadDrafts(cfg);
3779
3976
  let draftsChanged = false;
3780
3977
  for (const [locale, keys] of Object.entries(result.imported)) {
@@ -3790,7 +3987,7 @@ async function runCli(args = process.argv.slice(2)) {
3790
3987
  for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
3791
3988
  for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
3792
3989
  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(", ")}`);
3793
- if (Object.keys(result.imported).length === 0) console.log("[verbaly] nothing to import ✓");
3990
+ if (Object.keys(result.imported).length === 0 && result.unmatched.length === 0) console.log("[verbaly] nothing to import ✓");
3794
3991
  return;
3795
3992
  }
3796
3993
  if (command === "render") {