@verbaly/compiler 0.83.0 → 0.85.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/README.md CHANGED
@@ -7,7 +7,6 @@
7
7
  <p align="center">
8
8
  <a href="https://www.npmjs.com/package/@verbaly/compiler"><img src="https://img.shields.io/npm/v/@verbaly/compiler?logo=npm&color=cb3837" alt="npm version" /></a>
9
9
  <img src="https://img.shields.io/node/v/@verbaly/compiler?logo=nodedotjs&logoColor=white&color=5fa04e" alt="supported Node.js versions" />
10
- <a href="https://github.com/AronSoto/verbaly/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/AronSoto/verbaly/ci.yml?logo=github&label=CI" alt="CI" /></a>
11
10
  <a href="https://scorecard.dev/viewer/?uri=github.com/AronSoto/verbaly"><img src="https://api.scorecard.dev/projects/github.com/AronSoto/verbaly/badge" alt="OpenSSF Scorecard" /></a>
12
11
  <a href="https://www.npmjs.com/package/@verbaly/compiler#provenance"><img src="https://img.shields.io/badge/provenance-SLSA%20v1-3fb950?logo=npm" alt="published with npm provenance" /></a>
13
12
  <a href="https://github.com/AronSoto/verbaly/blob/develop/LICENSE"><img src="https://img.shields.io/npm/l/@verbaly/compiler?color=blue" alt="MIT" /></a>
@@ -80,7 +79,7 @@ Two more warnings name things that used to happen in silence, each with the file
80
79
 
81
80
  ```text
82
81
  [verbaly] ✗ the build goes on with 1 broken translation, each rendering differently from its source:
83
- [es] cart.total: {amount} is missing, so its value never reaches the text
82
+ [es] cart.total: the translation lost {amount}, so the value never reaches the text
84
83
  [verbaly] ⚠ the build goes on without 1 translation, shown in en instead:
85
84
  [es] home.lead: "Pick a language"
86
85
  [verbaly] ⚠ the build goes on with 1 key no catalog has, so the key itself shows:
@@ -1,4 +1,4 @@
1
- import { At as counted, St as isModuleNotFound } from "./run-BBxX6CcL.js";
1
+ import { kt as counted, xt as isModuleNotFound } from "./run-1p0TD3d7.js";
2
2
  // src/exchange/providers/claude.ts
3
3
  const DEFAULT_MODEL = "claude-sonnet-5-5";
4
4
  const FALLBACK_MODELS = /* @__PURE__ */ new Set([
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as runCli, t as formatCliError } from "./run-BBxX6CcL.js";
2
+ import { n as runCli, t as formatCliError } from "./run-1p0TD3d7.js";
3
3
  // src/cli.ts
4
4
  runCli().catch((error) => {
5
5
  console.error(formatCliError(error));
package/dist/index.d.ts CHANGED
@@ -127,6 +127,7 @@ interface TranslateOptions {
127
127
  dryRun?: boolean;
128
128
  origins?: Record<string, string[]>;
129
129
  onProgress?: (progress: TranslateProgress) => void;
130
+ onLocale?: (locale: string, keys: string[]) => void;
130
131
  }
131
132
  interface TranslateFailure {
132
133
  locale: string;
@@ -213,6 +214,7 @@ interface ResolvedConfig {
213
214
  locales: string[];
214
215
  localesDeclared: boolean;
215
216
  routing: Routing;
217
+ routingDeclared: boolean;
216
218
  icu: boolean | undefined;
217
219
  relative: boolean | undefined;
218
220
  include: string[];
@@ -581,6 +583,10 @@ interface RenderSiteResult {
581
583
  locales: string[];
582
584
  missing: Record<string, string[]>;
583
585
  untranslatedHead: string[];
586
+ sourceFolder?: {
587
+ folder: string;
588
+ pages: number;
589
+ };
584
590
  }
585
591
  export declare function renderSite(cfg: ResolvedConfig, options?: RenderSiteOptions): Promise<RenderSiteResult>;
586
592
  export declare function formatRenderWarnings(result: RenderSiteResult, sourceLocale: string): string[];
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as collectOrigins, A as collisionEntries, At as counted, B as loadState, C as translateProject, Ct as loadConfig, D as translateCatalogs, Dt as warnOnce, E as resolveProvider, Et as targetLocales, F as outdatedTranslations, G as generateLocaleModule, H as readState, I as recordTranslations, J as validateMessage, K as generateRuntimeModule, L as updateState, M as formatCollision, N as formatFinding, O as writeDrafts, Ot as warnParseError, P as effectiveDrafts, Q as syncCatalogs, R as STATE_FILE, S as warningCount, T as mergeTranslations, Tt as resolveConfig, U as saveState, V as markDrafts, W as generateDts, X as pruneCatalogs, Y as validatePair, Z as shippedCatalogs, _ as formatCheckResult, _t as own, a as formatRenderWarnings, at as APP_ID, b as gatePasses, bt as writeCatalog, c as watchTree, ct as isAppModule, d as formatDoctorHealth, dt as clientCatalogs, et as extractProject, f as formatStatusResult, ft as formatBundleIssue, g as formatBuildReport, gt as needsRelative, h as checkNextSteps, ht as needsIcu, i as wrapProject, it as stableKey, j as createDevReporter, jt as singleQuoted, k as syncProject, kt as cliReachable, l as doctor, lt as MessageRegistry, m as reportOutsideInclude, mt as loadCatalogs, nt as relativePath, o as renderSite, ot as LOCALE_IMPORT, p as status, pt as emptyCatalog, q as writeDts, r as formatWrapResult, rt as analyzeFile, s as init, st as VIRTUAL_ID, t as formatCliError, tt as scannedAnalysis, u as formatDoctorEntry, ut as auditBundle, v as formatCheckWarnings, vt as parseCatalog, w as formatTranslateFailures, wt as pluginOnlyOptions, x as relativeCheck, xt as SOURCE_FILE_RE, y as check, yt as readCatalog, z as clearDrafts } from "./run-BBxX6CcL.js";
1
+ import { $ as collectOrigins, A as collisionEntries, At as singleQuoted, B as loadState, C as translateProject, Ct as pluginOnlyOptions, D as translateCatalogs, Dt as warnParseError, E as resolveProvider, Et as warnOnce, F as outdatedTranslations, G as generateLocaleModule, H as readState, I as recordTranslations, J as validateMessage, K as generateRuntimeModule, L as updateState, M as formatCollision, N as formatFinding, O as writeDrafts, Ot as cliReachable, P as effectiveDrafts, Q as syncCatalogs, R as STATE_FILE, S as warningCount, St as loadConfig, T as mergeTranslations, Tt as targetLocales, U as saveState, V as markDrafts, W as generateDts, X as pruneCatalogs, Y as validatePair, Z as shippedCatalogs, _ as formatCheckResult, _t as parseCatalog, a as formatRenderWarnings, at as LOCALE_IMPORT, b as gatePasses, bt as SOURCE_FILE_RE, c as watchTree, ct as MessageRegistry, d as formatDoctorHealth, dt as formatBundleIssue, et as extractProject, f as formatStatusResult, ft as emptyCatalog, g as formatBuildReport, gt as own, h as checkNextSteps, ht as needsRelative, i as wrapProject, it as APP_ID, j as createDevReporter, jt as relativePath, k as syncProject, kt as counted, l as doctor, lt as auditBundle, m as reportOutsideInclude, mt as needsIcu, nt as analyzeFile, o as renderSite, ot as VIRTUAL_ID, p as status, pt as loadCatalogs, q as writeDts, r as formatWrapResult, rt as stableKey, s as init, st as isAppModule, t as formatCliError, tt as scannedAnalysis, u as formatDoctorEntry, ut as clientCatalogs, v as formatCheckWarnings, vt as readCatalog, w as formatTranslateFailures, wt as resolveConfig, x as relativeCheck, y as check, yt as writeCatalog, z as clearDrafts } from "./run-1p0TD3d7.js";
2
2
  import picomatch from "picomatch";
3
3
  import MagicString from "magic-string";
4
4
  // src/scan/transform.ts
@@ -11,6 +11,13 @@ import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
11
11
  import picomatch from "picomatch";
12
12
  import MagicString from "magic-string";
13
13
  import { parseArgs as parseArgs$1 } from "node:util";
14
+ // src/util/path.ts
15
+ function slashed(path) {
16
+ return path.replaceAll("\\", "/");
17
+ }
18
+ function relativePath(root, file) {
19
+ return slashed(relative(root, file));
20
+ }
14
21
  // src/util/text.ts
15
22
  function counted(count, noun, many = `${noun}s`) {
16
23
  return `${count} ${count === 1 ? noun : many}`;
@@ -221,7 +228,7 @@ function warnParseError(file, message) {
221
228
  warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
222
229
  }
223
230
  // src/config/config.ts
224
- const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}";
231
+ const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,cjs,cts,svelte,vue,astro}";
225
232
  const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
226
233
  const PSEUDO_LOCALE = "en-XA";
227
234
  function resolveConfig(config = {}) {
@@ -242,10 +249,11 @@ function resolveConfig(config = {}) {
242
249
  sourceLocale,
243
250
  localesDeclared,
244
251
  routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
252
+ routingDeclared: config.routing !== void 0,
245
253
  icu: config.icu,
246
254
  relative: config.relative,
247
255
  locales: [...locales],
248
- include: config.include ?? [`{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}`],
256
+ include: config.include ?? [`{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,cjs,cts,svelte,vue,astro}`],
249
257
  exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
250
258
  dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts === false ? false : defaultTypesPath(root, host),
251
259
  translate: config.translate ?? {},
@@ -297,8 +305,17 @@ async function loadTsConfig(path) {
297
305
  function isModuleNotFound(error, name) {
298
306
  return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
299
307
  }
308
+ function strangerLocales(cfg, said, named) {
309
+ const unknown = named.filter((locale) => !cfg.locales.includes(locale));
310
+ if (unknown.length === 0) return void 0;
311
+ const dir = relativePath(cfg.root, cfg.dir);
312
+ const start = cfg.localesDeclared ? `add ${unknown.join(", ")} to locales in your verbaly config` : `create ${unknown.map((locale) => `${dir}/${locale}.json`).join(", ")} holding {}`;
313
+ return `[verbaly] ${said} names ${unknown.map((locale) => `"${locale}"`).join(", ")}, and this project has ${cfg.locales.join(", ")}\n fix: check the spelling, or ${start} to start a new language`;
314
+ }
300
315
  function targetLocales(cfg, override) {
301
- return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
316
+ const typo = override && strangerLocales(cfg, "locales", override);
317
+ if (typo) throw new Error(typo);
318
+ return (override ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale);
302
319
  }
303
320
  async function loadConfig(root, overrides = {}, from = {}) {
304
321
  const fileConfig = await loadConfigFile(root);
@@ -396,6 +413,7 @@ function parseCatalog(content) {
396
413
  }
397
414
  function parseTree(content) {
398
415
  const body = stripBom(content);
416
+ if (body.trim() === "") return {};
399
417
  try {
400
418
  return JSON.parse(body);
401
419
  } catch {
@@ -495,7 +513,8 @@ function writeCatalog(cfg, locale, catalog) {
495
513
  return serialized;
496
514
  }
497
515
  function shapeFor(cfg, locale, existing, previous) {
498
- if (existing !== void 0) return previous;
516
+ const blank = previous !== void 0 && Object.keys(previous).length === 0;
517
+ if (existing !== void 0 && !blank) return previous;
499
518
  return locale === cfg.sourceLocale ? void 0 : readTree(cfg, cfg.sourceLocale);
500
519
  }
501
520
  const ICU_ARG = /(^|[^{])\{\s*[a-zA-Z0-9_]+\s*,\s*(?:plural|selectordinal|select|number|date|time)\b/;
@@ -1486,13 +1505,6 @@ function stringEnd(code, start) {
1486
1505
  else i += 1;
1487
1506
  return code.length;
1488
1507
  }
1489
- // src/util/path.ts
1490
- function slashed(path) {
1491
- return path.replaceAll("\\", "/");
1492
- }
1493
- function relativePath(root, file) {
1494
- return slashed(relative(root, file));
1495
- }
1496
1508
  // src/scan/extract.ts
1497
1509
  const kept = /* @__PURE__ */ new WeakMap();
1498
1510
  async function readSources(files, each, platform = process.platform) {
@@ -1719,7 +1731,7 @@ function validateMessage(message, locale) {
1719
1731
  const missing = reachableCategories(locale, shape.ordinal).filter((category) => category !== "other" && !shape.selectors.includes(category));
1720
1732
  if (missing.length > 0) issues.push({
1721
1733
  severity: "warning",
1722
- message: `${locale} also needs the ${list(missing)} plural ${missing.length > 1 ? "forms" : "form"} for {${name}}`
1734
+ message: `${locale} needs ${counted(missing.length, "more plural form")} for {${name}}: ${list(missing)}`
1723
1735
  });
1724
1736
  }
1725
1737
  return issues;
@@ -1730,22 +1742,22 @@ function validatePair(source, translated) {
1730
1742
  const newParams = surplus(paramNames(translated), paramNames(source));
1731
1743
  if (lostParams.length > 0) issues.push({
1732
1744
  severity: "error",
1733
- message: `${list(lostParams.map((name) => `{${name}}`))} ${lostParams.length > 1 ? "are" : "is"} missing, so ${lostParams.length > 1 ? "their values never reach" : "its value never reaches"} the text`
1745
+ message: `the translation lost ${list(lostParams.map((name) => `{${name}}`))}, so the value never reaches the text`
1734
1746
  });
1735
1747
  if (newParams.length > 0) issues.push({
1736
1748
  severity: "error",
1737
- message: `${list(newParams.map((name) => `{${name}}`))} ${newParams.length > 1 ? "are" : "is"} not in the source message, so ${newParams.length > 1 ? "they render" : "it renders"} as literal text`
1749
+ message: `the translation adds ${list(newParams.map((name) => `{${name}}`))}, not in the source message, so the braces render as literal text`
1738
1750
  });
1739
1751
  const markup = /* @__PURE__ */ new Set([...markupNames(source), ...markupNames(translated)]);
1740
1752
  const lostTags = tagReport(surplus(tagTokens(source, markup), tagTokens(translated, markup)));
1741
1753
  const newTags = tagReport(surplus(tagTokens(translated, markup), tagTokens(source, markup)));
1742
1754
  if (lostTags.length > 0) issues.push({
1743
1755
  severity: "error",
1744
- message: `${list(lostTags)} ${lostTags.length > 1 ? "are" : "is"} missing from the translation`
1756
+ message: `the translation lost ${list(lostTags)}`
1745
1757
  });
1746
1758
  if (newTags.length > 0) issues.push({
1747
1759
  severity: "error",
1748
- message: `${list(newTags)} ${newTags.length > 1 ? "are" : "is"} not in the source message`
1760
+ message: `the translation adds ${list(newTags)}, not in the source message`
1749
1761
  });
1750
1762
  const target = shapes(translated);
1751
1763
  for (const [name, shape] of shapes(source)) {
@@ -1764,7 +1776,7 @@ function validatePair(source, translated) {
1764
1776
  const lostExact = shape.selectors.filter((key) => EXACT.test(key)).filter((key) => !other.selectors.includes(key));
1765
1777
  if (lostExact.length > 0) issues.push({
1766
1778
  severity: "warning",
1767
- message: `the ${list(lostExact)} ${lostExact.length > 1 ? "cases" : "case"} for {${name}} ${lostExact.length > 1 ? "are" : "is"} missing, so ${lostExact.length > 1 ? "those counts" : "that count"} falls back to "other"`
1779
+ message: `the translation lost ${counted(lostExact.length, "exact case")} for {${name}} (${list(lostExact)}), so "other" renders instead`
1768
1780
  });
1769
1781
  }
1770
1782
  return issues;
@@ -2780,6 +2792,22 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2780
2792
  failed: []
2781
2793
  };
2782
2794
  const jobs = [];
2795
+ const open = /* @__PURE__ */ new Map();
2796
+ const settle = (locale) => {
2797
+ const left = open.get(locale) - 1;
2798
+ open.set(locale, left);
2799
+ const keys = [...result.translated[locale] ?? []].sort();
2800
+ if (left > 0 || keys.length === 0 || !options.onLocale) return;
2801
+ try {
2802
+ options.onLocale(locale, keys);
2803
+ } catch (error) {
2804
+ result.failed.push({
2805
+ locale,
2806
+ keys,
2807
+ error: reason(error)
2808
+ });
2809
+ }
2810
+ };
2783
2811
  for (const locale of targets) {
2784
2812
  const catalog = catalogs[locale] ??= emptyCatalog();
2785
2813
  const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
@@ -2789,6 +2817,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2789
2817
  continue;
2790
2818
  }
2791
2819
  const batches = Math.ceil(missing.length / batchSize);
2820
+ open.set(locale, batches);
2792
2821
  for (let i = 0; i < missing.length; i += batchSize) {
2793
2822
  const index = Math.floor(i / batchSize) + 1;
2794
2823
  jobs.push({
@@ -2821,6 +2850,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2821
2850
  keys,
2822
2851
  error: message
2823
2852
  });
2853
+ settle(locale);
2824
2854
  options.onProgress?.({
2825
2855
  ...progressOf(job),
2826
2856
  error: message
@@ -2834,6 +2864,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2834
2864
  (result.translated[locale] ??= []).push(key);
2835
2865
  } else (result.invalid[locale] ??= []).push(key);
2836
2866
  }
2867
+ settle(locale);
2837
2868
  options.onProgress?.(progressOf(job));
2838
2869
  });
2839
2870
  for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
@@ -2844,22 +2875,30 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2844
2875
  function compare(a, b) {
2845
2876
  return byCodeUnit(a[0] ?? "", b[0] ?? "");
2846
2877
  }
2847
- function mergeTranslations(cfg, locale, translated, keys) {
2878
+ function mergePlan(cfg, locale, translated, keys) {
2848
2879
  const source = readCatalog(cfg, cfg.sourceLocale);
2849
2880
  const current = readCatalog(cfg, locale);
2850
- const written = [];
2881
+ const landed = [];
2851
2882
  for (const key of keys) {
2852
2883
  const text = own(translated, key);
2853
2884
  if (!source[key] || current[key] || !text) continue;
2854
2885
  current[key] = text;
2855
- written.push(key);
2886
+ landed.push(key);
2856
2887
  }
2857
- if (written.length > 0) writeCatalog(cfg, locale, current);
2858
- return written;
2888
+ return {
2889
+ current,
2890
+ landed
2891
+ };
2892
+ }
2893
+ function mergeTranslations(cfg, locale, translated, keys) {
2894
+ const { current, landed } = mergePlan(cfg, locale, translated, keys);
2895
+ if (landed.length > 0) writeCatalog(cfg, locale, current);
2896
+ return landed;
2859
2897
  }
2860
2898
  function writeDrafts(cfg, locale, entries, options = {}) {
2861
- const targets = targetLocales(cfg);
2862
- if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
2899
+ const typo = strangerLocales(cfg, "locale", [locale]);
2900
+ if (typo) throw new Error(typo);
2901
+ if (locale === cfg.sourceLocale) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targetLocales(cfg).join(", ") || "none yet"})`);
2863
2902
  loadState(cfg);
2864
2903
  const catalogs = emptyCatalog();
2865
2904
  catalogs[cfg.sourceLocale] = readCatalog(cfg, cfg.sourceLocale);
@@ -2882,7 +2921,6 @@ function writeDrafts(cfg, locale, entries, options = {}) {
2882
2921
  }
2883
2922
  }
2884
2923
  if (result.written.length > 0) {
2885
- writeCatalog(cfg, locale, current);
2886
2924
  const written = result.written.map((key) => ({
2887
2925
  key,
2888
2926
  text: current[key]
@@ -2893,6 +2931,7 @@ function writeDrafts(cfg, locale, entries, options = {}) {
2893
2931
  entries: written,
2894
2932
  draft: true
2895
2933
  }]);
2934
+ writeCatalog(cfg, locale, current);
2896
2935
  const lock = lockNews(cfg, before);
2897
2936
  if (lock) result.lock = lock;
2898
2937
  }
@@ -2913,7 +2952,7 @@ function formatTranslateFailures(failed) {
2913
2952
  async function resolveProvider(cfg, model) {
2914
2953
  const configured = cfg.translate.provider;
2915
2954
  if (typeof configured === "function") return configured;
2916
- const { claudeProvider } = await import("./claude-DvjHi7np.js");
2955
+ const { claudeProvider } = await import("./claude-Cf5p2nJo.js");
2917
2956
  return claudeProvider({ model: model ?? cfg.translate.model });
2918
2957
  }
2919
2958
  function progressOf(job) {
@@ -2938,18 +2977,50 @@ function glossaryFor(cfg, locale, messages) {
2938
2977
  }
2939
2978
  // src/project/translate.ts
2940
2979
  async function translateProject(cfg, options = {}) {
2980
+ if (options.locales) targetLocales(cfg, options.locales);
2941
2981
  const dryRun = options.dryRun === true;
2942
2982
  if (!dryRun) loadState(cfg);
2943
2983
  const registry = await extractProject(cfg);
2944
2984
  const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
2945
- const run = await translateCatalogs(cfg, catalogs, options.provider ?? await resolveProvider(cfg, options.model), {
2985
+ const provider = options.provider ?? await resolveProvider(cfg, options.model);
2986
+ const source = catalogs[cfg.sourceLocale] ?? {};
2987
+ const written = emptyCatalog();
2988
+ const kept = emptyCatalog();
2989
+ let before;
2990
+ const save = (locale, keys) => {
2991
+ const catalog = catalogs[locale] ?? {};
2992
+ try {
2993
+ const { current, landed } = mergePlan(cfg, locale, catalog, keys);
2994
+ if (landed.length > 0) {
2995
+ const entries = landed.map((key) => ({
2996
+ key,
2997
+ text: catalog[key]
2998
+ }));
2999
+ before ??= { file: stateFile(cfg) };
3000
+ recordTranslations(cfg, source, [{
3001
+ locale,
3002
+ draft: true,
3003
+ entries
3004
+ }]);
3005
+ writeCatalog(cfg, locale, current);
3006
+ written[locale] = landed;
3007
+ }
3008
+ const left = keys.filter((key) => !landed.includes(key));
3009
+ if (left.length > 0) kept[locale] = left;
3010
+ } catch (error) {
3011
+ const why = error instanceof Error ? error.message : String(error);
3012
+ throw new Error(`could not be saved: ${why}`, { cause: error });
3013
+ }
3014
+ };
3015
+ const run = await translateCatalogs(cfg, catalogs, provider, {
2946
3016
  locales: options.locales,
2947
3017
  batchSize: cfg.translate.batchSize,
2948
3018
  concurrency: cfg.translate.concurrency,
2949
3019
  retries: cfg.translate.retries,
2950
3020
  dryRun,
2951
3021
  origins: dryRun ? void 0 : await collectOrigins(cfg, registry),
2952
- onProgress: dryRun ? void 0 : options.onProgress
3022
+ onProgress: dryRun ? void 0 : options.onProgress,
3023
+ onLocale: dryRun ? void 0 : save
2953
3024
  });
2954
3025
  const result = {
2955
3026
  pending: run.pending,
@@ -2959,26 +3030,11 @@ async function translateProject(cfg, options = {}) {
2959
3030
  failed: run.failed
2960
3031
  };
2961
3032
  if (dryRun) return result;
2962
- const writes = [];
2963
- for (const [locale, keys] of Object.entries(run.translated)) {
2964
- const catalog = catalogs[locale] ?? {};
2965
- const landed = mergeTranslations(cfg, locale, catalog, keys);
2966
- const left = keys.filter((key) => !landed.includes(key));
2967
- if (left.length > 0) result.kept[locale] = left;
2968
- if (landed.length === 0) continue;
2969
- result.written[locale] = landed;
2970
- writes.push({
2971
- locale,
2972
- draft: true,
2973
- entries: landed.map((key) => ({
2974
- key,
2975
- text: catalog[key]
2976
- }))
2977
- });
3033
+ for (const locale of targetLocales(cfg, options.locales)) {
3034
+ if (written[locale]) result.written[locale] = written[locale];
3035
+ if (kept[locale]) result.kept[locale] = kept[locale];
2978
3036
  }
2979
- const before = stateFile(cfg);
2980
- if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
2981
- const lock = lockNews(cfg, before);
3037
+ const lock = before && lockNews(cfg, before.file);
2982
3038
  if (lock) result.lock = lock;
2983
3039
  return result;
2984
3040
  }
@@ -3495,13 +3551,6 @@ function projectLocale(tag, locales) {
3495
3551
  }
3496
3552
  // src/project/doctor.ts
3497
3553
  const PREVIEW = 5;
3498
- function readRoutingChoice(root, configFile) {
3499
- try {
3500
- return /\brouting["']?\s*[:=]/.test(readFileSync(join(root, configFile), "utf8"));
3501
- } catch {
3502
- return false;
3503
- }
3504
- }
3505
3554
  function readAstroRouting(root, source) {
3506
3555
  for (const file of [
3507
3556
  "astro.config.mjs",
@@ -3659,7 +3708,7 @@ function checkRouting(report, cfg, configFile) {
3659
3708
  if (cfg.routing === "no-prefix" && mirrors) warn("routing", "routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale", "drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls");
3660
3709
  else if (cfg.routing === "prefix-all" && mirrors) warn("routing", `routing is "prefix-all" but render keeps ${cfg.sourceLocale} at the root, so its links point at a /${cfg.sourceLocale}/ tree nobody wrote`, "set routing to \"prefix-except-source\", the url tree render writes");
3661
3710
  else {
3662
- const named = configFile ? readRoutingChoice(cfg.root, configFile) : false;
3711
+ const named = configFile !== void 0 && cfg.routingDeclared;
3663
3712
  const astro = cfg.host === "astro" && cfg.routing === "no-prefix" ? readAstroRouting(cfg.root, cfg.sourceLocale) : void 0;
3664
3713
  if (astro && named) warn("routing", `routing is "no-prefix" in ${configFile}, but @verbaly/astro uses ${astro.mode}: Astro's i18n in ${astro.file} puts the language in the url`, `remove routing from ${configFile}, or remove i18n from ${astro.file}`);
3665
3714
  else if (astro) {
@@ -4686,27 +4735,29 @@ async function importCommand(cfg, values, positionals) {
4686
4735
  process.exitCode = 1;
4687
4736
  }
4688
4737
  const writes = [];
4689
- for (const [locale, keys] of Object.entries(result.imported)) {
4690
- if (!values["dry-run"]) {
4691
- const catalog = catalogs[locale] ?? {};
4692
- writeCatalog(cfg, locale, catalog);
4693
- const seen = result.sources[locale] ?? {};
4694
- const entries = keys.map((key) => ({
4695
- key,
4696
- text: catalog[key],
4697
- source: seen[key]
4698
- }));
4699
- writes.push({
4700
- locale,
4701
- entries,
4702
- draft: values.draft === true
4703
- });
4704
- }
4705
- const verb = values["dry-run"] ? "would import" : "imported";
4706
- console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? " (draft)" : ""}`);
4738
+ if (!values["dry-run"]) for (const [locale, keys] of Object.entries(result.imported)) {
4739
+ const catalog = catalogs[locale] ?? {};
4740
+ const seen = result.sources[locale] ?? {};
4741
+ const entries = keys.map((key) => ({
4742
+ key,
4743
+ text: catalog[key],
4744
+ source: seen[key]
4745
+ }));
4746
+ writes.push({
4747
+ locale,
4748
+ entries,
4749
+ draft: values.draft === true
4750
+ });
4707
4751
  }
4708
4752
  const lockBefore = stateFile(cfg);
4709
- if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
4753
+ const record = () => {
4754
+ if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
4755
+ };
4756
+ if (values.draft) record();
4757
+ for (const { locale } of writes) writeCatalog(cfg, locale, catalogs[locale] ?? {});
4758
+ if (!values.draft) record();
4759
+ const verb = values["dry-run"] ? "would import" : "imported";
4760
+ for (const [locale, keys] of Object.entries(result.imported)) console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? " (draft)" : ""}`);
4710
4761
  sayLockNews(cfg, lockBefore);
4711
4762
  for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
4712
4763
  for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
@@ -5618,17 +5669,28 @@ async function renderSite(cfg, options = {}) {
5618
5669
  if (wantSitemap && urls.length) writeFileSync(join(site, typeof sitemap === "string" ? sitemap : "sitemap-i18n.xml"), buildSitemap(urls));
5619
5670
  const missing = emptyCatalog();
5620
5671
  for (const [locale, keys] of Object.entries(unfilled)) missing[locale] = [...keys];
5621
- return {
5672
+ const result = {
5622
5673
  files: files.length,
5623
5674
  locales: [...locales],
5624
5675
  missing,
5625
5676
  untranslatedHead
5626
5677
  };
5678
+ const own = join(site, cfg.sourceLocale);
5679
+ const left = (await glob("**/*.html", { cwd: own })).length;
5680
+ if (left > 0) result.sourceFolder = {
5681
+ folder: relativePath(cfg.root, own),
5682
+ pages: left
5683
+ };
5684
+ return result;
5627
5685
  }
5628
5686
  function formatRenderWarnings(result, sourceLocale) {
5629
5687
  const lines = [];
5630
5688
  for (const [locale, keys] of Object.entries(result.missing)) lines.push(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
5631
5689
  if (result.untranslatedHead.length > 0) lines.push(` ${counted(result.untranslatedHead.length, "page")} of ${result.files} ship the same <title> in every locale (${result.untranslatedHead[0]}), so search results read in ${sourceLocale}`, ` fix: bind the head too, <title data-verbaly="key"> and a meta through data-verbaly-attr`);
5690
+ if (result.sourceFolder) {
5691
+ const { folder, pages } = result.sourceFolder;
5692
+ lines.push(` ${folder}/ is named like your source locale, so render does not mirror it (${counted(pages, "page")})`, ` fix: rename the folder if those pages are content, or delete it if an older run left it`);
5693
+ }
5632
5694
  return lines;
5633
5695
  }
5634
5696
  function pagePath(rel) {
@@ -6236,7 +6298,7 @@ async function runCli(args = process.argv.slice(2)) {
6236
6298
  const narrowed = csv(values.locales);
6237
6299
  if (narrowed || command === "review" && values.locale) {
6238
6300
  const whole = await loadConfig(root, project);
6239
- const typo = narrowed ? strangers(whole, "locales", narrowed) : strangers(whole, "locale", [values.locale]);
6301
+ const typo = narrowed ? strangerLocales(whole, "--locales", narrowed) : strangerLocales(whole, "--locale", [values.locale]);
6240
6302
  if (typo) {
6241
6303
  console.error(typo);
6242
6304
  process.exitCode = 1;
@@ -6249,13 +6311,6 @@ async function runCli(args = process.argv.slice(2)) {
6249
6311
  });
6250
6312
  return COMMANDS[command](cfg, values, positionals);
6251
6313
  }
6252
- function strangers(cfg, flag, named) {
6253
- const unknown = named.filter((locale) => !cfg.locales.includes(locale));
6254
- if (unknown.length === 0) return void 0;
6255
- const dir = relativePath(cfg.root, cfg.dir);
6256
- const start = cfg.localesDeclared ? `add ${unknown.join(", ")} to locales in your verbaly config` : `create ${unknown.map((locale) => `${dir}/${locale}.json`).join(", ")} holding {}`;
6257
- return `[verbaly] --${flag} names ${unknown.map((locale) => `"${locale}"`).join(", ")}, and this project has ${cfg.locales.join(", ")}\n fix: check the spelling, or ${start} to start a new language`;
6258
- }
6259
6314
  function formatCliError(error) {
6260
6315
  const message = error instanceof Error ? error.message : String(error);
6261
6316
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
@@ -6317,4 +6372,4 @@ function rejectStrayFlags(command, values) {
6317
6372
  process.exitCode = 1;
6318
6373
  return true;
6319
6374
  }
6320
- export { collectOrigins as $, collisionEntries as A, counted as At, loadState as B, translateProject as C, loadConfig as Ct, translateCatalogs as D, warnOnce as Dt, resolveProvider as E, targetLocales as Et, outdatedTranslations as F, generateLocaleModule as G, readState as H, recordTranslations as I, validateMessage as J, generateRuntimeModule as K, updateState as L, formatCollision as M, formatFinding as N, writeDrafts as O, warnParseError as Ot, effectiveDrafts as P, syncCatalogs as Q, STATE_FILE as R, warningCount as S, isModuleNotFound as St, mergeTranslations as T, resolveConfig as Tt, saveState as U, markDrafts as V, generateDts as W, pruneCatalogs as X, validatePair as Y, shippedCatalogs as Z, formatCheckResult as _, own as _t, formatRenderWarnings as a, APP_ID as at, gatePasses as b, writeCatalog as bt, watchTree as c, isAppModule as ct, formatDoctorHealth as d, clientCatalogs as dt, extractProject as et, formatStatusResult as f, formatBundleIssue as ft, formatBuildReport as g, needsRelative as gt, checkNextSteps as h, needsIcu as ht, wrapProject as i, stableKey as it, createDevReporter as j, singleQuoted as jt, syncProject as k, cliReachable as kt, doctor as l, MessageRegistry as lt, reportOutsideInclude as m, loadCatalogs as mt, runCli as n, relativePath as nt, renderSite as o, LOCALE_IMPORT as ot, status as p, emptyCatalog as pt, writeDts as q, formatWrapResult as r, analyzeFile as rt, init as s, VIRTUAL_ID as st, formatCliError as t, scannedAnalysis as tt, formatDoctorEntry as u, auditBundle as ut, formatCheckWarnings as v, parseCatalog as vt, formatTranslateFailures as w, pluginOnlyOptions as wt, relativeCheck as x, SOURCE_FILE_RE as xt, check as y, readCatalog as yt, clearDrafts as z };
6375
+ export { collectOrigins as $, collisionEntries as A, singleQuoted as At, loadState as B, translateProject as C, pluginOnlyOptions as Ct, translateCatalogs as D, warnParseError as Dt, resolveProvider as E, warnOnce as Et, outdatedTranslations as F, generateLocaleModule as G, readState as H, recordTranslations as I, validateMessage as J, generateRuntimeModule as K, updateState as L, formatCollision as M, formatFinding as N, writeDrafts as O, cliReachable as Ot, effectiveDrafts as P, syncCatalogs as Q, STATE_FILE as R, warningCount as S, loadConfig as St, mergeTranslations as T, targetLocales as Tt, saveState as U, markDrafts as V, generateDts as W, pruneCatalogs as X, validatePair as Y, shippedCatalogs as Z, formatCheckResult as _, parseCatalog as _t, formatRenderWarnings as a, LOCALE_IMPORT as at, gatePasses as b, SOURCE_FILE_RE as bt, watchTree as c, MessageRegistry as ct, formatDoctorHealth as d, formatBundleIssue as dt, extractProject as et, formatStatusResult as f, emptyCatalog as ft, formatBuildReport as g, own as gt, checkNextSteps as h, needsRelative as ht, wrapProject as i, APP_ID as it, createDevReporter as j, relativePath as jt, syncProject as k, counted as kt, doctor as l, auditBundle as lt, reportOutsideInclude as m, needsIcu as mt, runCli as n, analyzeFile as nt, renderSite as o, VIRTUAL_ID as ot, status as p, loadCatalogs as pt, writeDts as q, formatWrapResult as r, stableKey as rt, init as s, isAppModule as st, formatCliError as t, scannedAnalysis as tt, formatDoctorEntry as u, clientCatalogs as ut, formatCheckWarnings as v, readCatalog as vt, formatTranslateFailures as w, resolveConfig as wt, relativeCheck as x, isModuleNotFound as xt, check as y, writeCatalog as yt, clearDrafts as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verbaly/compiler",
3
- "version": "0.83.0",
3
+ "version": "0.85.0",
4
4
  "description": "Message extraction and type-safe codegen for Verbaly.",
5
5
  "keywords": [
6
6
  "i18n",
@@ -52,7 +52,7 @@
52
52
  "magic-string": "^1.4.5",
53
53
  "picomatch": "^4.0.7",
54
54
  "tinyglobby": "^0.2.17",
55
- "verbaly": "0.83.0"
55
+ "verbaly": "0.85.0"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "@anthropic-ai/sdk": ">=0.110.0"