@verbaly/compiler 0.65.0 → 0.66.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/index.d.ts CHANGED
@@ -205,7 +205,7 @@ interface DtsOptions {
205
205
  inlineCatalog?: boolean;
206
206
  }
207
207
  export declare function generateDts(catalog: Catalog, options?: DtsOptions): string;
208
- export declare function writeDts(cfg: ResolvedConfig, catalog: Catalog, file?: string): void;
208
+ export declare function writeDts(cfg: ResolvedConfig, catalog: Catalog, file?: string | false): void;
209
209
  //#endregion
210
210
  //#region src/transform.d.ts
211
211
  interface TransformResult {
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { a as resolveConfig, i as loadConfigFile, o as targetLocales, r as loadConfig, t as findConfigFile } from "./config-DYlbHrPc.js";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
1
+ import { a as loadConfigFile, i as loadConfig, n as findConfigFile, o as resolveConfig, s as targetLocales, t as counted } from "./text-M4XbWU6N.js";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
3
3
  import { dirname, join, relative } from "node:path";
4
4
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
5
5
  import { glob } from "tinyglobby";
@@ -8,6 +8,12 @@ import { createHash } from "node:crypto";
8
8
  import picomatch from "picomatch";
9
9
  import MagicString from "magic-string";
10
10
  //#region src/catalog.ts
11
+ function emptyCatalog() {
12
+ return Object.create(null);
13
+ }
14
+ function own(catalog, key) {
15
+ return Object.hasOwn(catalog, key) ? catalog[key] : void 0;
16
+ }
11
17
  function catalogPath(cfg, locale) {
12
18
  return join(cfg.dir, `${locale}.json`);
13
19
  }
@@ -34,8 +40,9 @@ function readTree(cfg, locale) {
34
40
  return {};
35
41
  }
36
42
  const parsed = parseTree(content);
37
- if (parsed) return parsed;
38
- throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`);
43
+ if (parsed === void 0) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`);
44
+ if (!isTree(parsed)) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not a JSON object of messages, fix or delete the file`);
45
+ return parsed;
39
46
  }
40
47
  function parseCatalog(content) {
41
48
  const tree = parseTree(content);
@@ -49,6 +56,9 @@ function parseTree(content) {
49
56
  return;
50
57
  }
51
58
  }
59
+ function isTree(value) {
60
+ return typeof value === "object" && value !== null && !Array.isArray(value);
61
+ }
52
62
  function loadCatalogs(cfg) {
53
63
  const catalogs = {};
54
64
  for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
@@ -118,7 +128,8 @@ function writeCatalog(cfg, locale, catalog) {
118
128
  } catch {
119
129
  mkdirSync(cfg.dir, { recursive: true });
120
130
  }
121
- const previous = existing === void 0 ? void 0 : parseTree(existing);
131
+ const parsed = existing === void 0 ? void 0 : parseTree(existing);
132
+ const previous = isTree(parsed) ? parsed : void 0;
122
133
  const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous);
123
134
  if (existing === serialized) return serialized;
124
135
  writeFileSync(path, serialized);
@@ -140,11 +151,6 @@ function needsRelative(catalogs) {
140
151
  return false;
141
152
  }
142
153
  //#endregion
143
- //#region src/text.ts
144
- function counted(count, noun, many = `${noun}s`) {
145
- return `${count} ${count === 1 ? noun : many}`;
146
- }
147
- //#endregion
148
154
  //#region src/bundle.ts
149
155
  function isExcluded(key, prefixes) {
150
156
  return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
@@ -154,7 +160,7 @@ function clientCatalogs(cfg, catalogs) {
154
160
  if (prefixes.length === 0) return catalogs;
155
161
  const out = {};
156
162
  for (const [locale, catalog] of Object.entries(catalogs)) {
157
- const kept = {};
163
+ const kept = emptyCatalog();
158
164
  for (const [key, message] of Object.entries(catalog)) if (!isExcluded(key, prefixes)) kept[key] = message;
159
165
  out[locale] = kept;
160
166
  }
@@ -740,22 +746,22 @@ async function extractProject(cfg) {
740
746
  }
741
747
  async function collectOrigins(cfg, reuse) {
742
748
  const registry = reuse ?? await extractProject(cfg);
743
- const origins = {};
749
+ const origins = Object.create(null);
744
750
  for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
745
751
  return origins;
746
752
  }
747
753
  function syncCatalogs(cfg, catalogs, registry) {
748
754
  const added = {};
749
- const source = catalogs[cfg.sourceLocale] ??= {};
750
- for (const [key, msg] of registry.messages()) if (source[key] !== msg.message) {
755
+ const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
756
+ for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) {
751
757
  source[key] = msg.message;
752
758
  (added[cfg.sourceLocale] ??= []).push(key);
753
759
  }
754
760
  const needed = Object.keys(source);
755
761
  for (const locale of cfg.locales) {
756
762
  if (locale === cfg.sourceLocale) continue;
757
- const catalog = catalogs[locale] ??= {};
758
- for (const key of needed) if (catalog[key] === void 0) {
763
+ const catalog = catalogs[locale] ??= emptyCatalog();
764
+ for (const key of needed) if (own(catalog, key) === void 0) {
759
765
  catalog[key] = "";
760
766
  (added[locale] ??= []).push(key);
761
767
  }
@@ -763,8 +769,9 @@ function syncCatalogs(cfg, catalogs, registry) {
763
769
  return { added };
764
770
  }
765
771
  function pruneCatalogs(cfg, catalogs, registry) {
766
- const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
767
772
  const removed = {};
773
+ if (registry.parseErrors().length > 0) return removed;
774
+ const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
768
775
  for (const locale of cfg.locales) {
769
776
  const catalog = catalogs[locale];
770
777
  if (!catalog) continue;
@@ -928,7 +935,7 @@ function reachableCategories(locale, ordinal) {
928
935
  if (hit) return hit;
929
936
  let out;
930
937
  try {
931
- const rules = new Intl.PluralRules(locale, { type });
938
+ const rules = new Intl.PluralRules(locale.replace(/_/g, "-"), { type });
932
939
  const seen = /* @__PURE__ */ new Set();
933
940
  for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));
934
941
  out = [...seen];
@@ -1087,7 +1094,7 @@ export async function setLocale(locale) {
1087
1094
  ${options.extraExports ?? ""}`;
1088
1095
  }
1089
1096
  function generateLocaleModule(catalog) {
1090
- return `export default ${JSON.stringify(catalog)};\n`;
1097
+ return `export default ${JSON.stringify(catalog).replace(/([{,])"__proto__":/, "$1[\"__proto__\"]:")};\n`;
1091
1098
  }
1092
1099
  function generateDts(catalog, options = {}) {
1093
1100
  const lines = [];
@@ -1160,7 +1167,9 @@ declare module 'virtual:verbaly/locale/*' {
1160
1167
  `;
1161
1168
  }
1162
1169
  function writeDts(cfg, catalog, file) {
1163
- file ??= join(cfg.root, "verbaly.d.ts");
1170
+ const target = file === void 0 ? cfg.dts : file;
1171
+ if (target === false) return;
1172
+ file = target ?? join(cfg.root, "verbaly.d.ts");
1164
1173
  const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
1165
1174
  try {
1166
1175
  if (readFileSync(file, "utf8") === content) return;
@@ -1380,7 +1389,7 @@ function check(cfg, catalogs, registry) {
1380
1389
  issue: issue.message
1381
1390
  });
1382
1391
  };
1383
- const sourceText = { ...source };
1392
+ const sourceText = Object.assign(emptyCatalog(), source);
1384
1393
  for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
1385
1394
  for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
1386
1395
  for (const locale of cfg.locales) {
@@ -1516,7 +1525,7 @@ function transformSource(code, id, registry) {
1516
1525
  const analysis = analyzeFile(code, id);
1517
1526
  registry.update(id, analysis);
1518
1527
  if (analysis.parseError) warnParseError(id, analysis.parseError);
1519
- const messages = {};
1528
+ const messages = emptyCatalog();
1520
1529
  for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
1521
1530
  return {
1522
1531
  messages,
@@ -1527,6 +1536,8 @@ function runBuildGate(cfg, registry, failOnMissing) {
1527
1536
  const catalogs = loadCatalogs(cfg);
1528
1537
  for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
1529
1538
  const found = check(cfg, catalogs, registry);
1539
+ const warnings = found.broken.filter((entry) => entry.severity === "warning").length + found.extra.length;
1540
+ if (warnings > 0) warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: run \`npx verbaly check\` to read them`, "gate:warnings");
1530
1541
  const result = failOnMissing === false ? {
1531
1542
  ...found,
1532
1543
  missing: []
@@ -1589,7 +1600,7 @@ function effectiveDrafts(drafts, catalogs) {
1589
1600
  const out = {};
1590
1601
  for (const [locale, keys] of Object.entries(drafts)) {
1591
1602
  const catalog = catalogs[locale] ?? {};
1592
- const live = keys.filter((key) => catalog[key]);
1603
+ const live = keys.filter((key) => own(catalog, key));
1593
1604
  if (live.length) out[locale] = live;
1594
1605
  }
1595
1606
  return out;
@@ -1707,17 +1718,22 @@ async function doctor(cfg) {
1707
1718
  error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
1708
1719
  continue;
1709
1720
  }
1710
- try {
1711
- const parsed = JSON.parse(readFileSync(file, "utf8"));
1712
- const bad = badLeaf(parsed);
1713
- if (bad) {
1714
- catalogsHealthy = false;
1715
- error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
1716
- } else catalogs[locale] = flatten(parsed);
1717
- } catch {
1721
+ const parsed = parseTree(readFileSync(file, "utf8"));
1722
+ if (parsed === void 0) {
1718
1723
  catalogsHealthy = false;
1719
1724
  error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
1725
+ continue;
1726
+ }
1727
+ if (!isTree(parsed)) {
1728
+ catalogsHealthy = false;
1729
+ error(`locale ${locale}`, `${rel(file)} is not a JSON object of messages`, "a catalog is an object of texts (groups of text are fine): fix the file");
1730
+ continue;
1720
1731
  }
1732
+ const bad = badLeaf(parsed);
1733
+ if (bad) {
1734
+ catalogsHealthy = false;
1735
+ error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
1736
+ } else catalogs[locale] = flatten(parsed);
1721
1737
  }
1722
1738
  if (catalogsHealthy) {
1723
1739
  const how = cfg.localesDeclared ? "" : ", no locales set, so the catalog files decide";
@@ -1734,6 +1750,7 @@ async function doctor(cfg) {
1734
1750
  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`");
1735
1751
  const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
1736
1752
  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");
1753
+ 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");
1737
1754
  else {
1738
1755
  const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
1739
1756
  ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
@@ -1774,7 +1791,8 @@ async function doctor(cfg) {
1774
1791
  const extracted = registry.messages();
1775
1792
  const used = registry.usedKeys();
1776
1793
  const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
1777
- if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, "run `npx verbaly extract --prune` to drop them");
1794
+ const unread = registry.parseErrors().length > 0;
1795
+ if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
1778
1796
  else ok("orphans", "no orphan keys");
1779
1797
  }
1780
1798
  const excluded = cfg.bundle.exclude ?? [];
@@ -1865,8 +1883,8 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1865
1883
  };
1866
1884
  const jobs = [];
1867
1885
  for (const locale of targets) {
1868
- const catalog = catalogs[locale] ??= {};
1869
- const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
1886
+ const catalog = catalogs[locale] ??= emptyCatalog();
1887
+ const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
1870
1888
  if (missing.length === 0) continue;
1871
1889
  if (options.dryRun) {
1872
1890
  result.pending[locale] = missing;
@@ -1887,7 +1905,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1887
1905
  const { locale, keys } = job;
1888
1906
  const catalog = catalogs[locale];
1889
1907
  const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
1890
- const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins[key]).map((key) => [key, options.origins[key]])) : void 0;
1908
+ const origins = options.origins ? Object.fromEntries(keys.filter((key) => Object.hasOwn(options.origins, key)).map((key) => [key, options.origins[key]])) : void 0;
1891
1909
  let out;
1892
1910
  try {
1893
1911
  out = await attempt(() => provider({
@@ -1956,7 +1974,7 @@ function formatTranslateFailures(failed) {
1956
1974
  async function resolveProvider(cfg, model) {
1957
1975
  const configured = cfg.translate.provider;
1958
1976
  if (typeof configured === "function") return configured;
1959
- const { claudeProvider } = await import("./claude--aMMLA-N.js");
1977
+ const { claudeProvider } = await import("./claude-D-j-ZiYH.js");
1960
1978
  return claudeProvider({ model: model ?? cfg.translate.model });
1961
1979
  }
1962
1980
  function structureMatches(source, translated) {
@@ -2115,7 +2133,7 @@ function renderHtml(html, options) {
2115
2133
  };
2116
2134
  }
2117
2135
  function pageSlice(v, locale, used) {
2118
- const slice = {};
2136
+ const slice = Object.create(null);
2119
2137
  for (const key of used) {
2120
2138
  const found = v.inspect(key);
2121
2139
  slice[key] = found?.from === locale ? found.source : "";
@@ -2456,17 +2474,17 @@ function watchTree(root, options, onFile) {
2456
2474
  close(name);
2457
2475
  if (name !== options.keep && (name === "node_modules" || name.startsWith("."))) return;
2458
2476
  try {
2459
- if (!statSync(join(root, name)).isDirectory()) return;
2460
- } catch {
2461
- return;
2477
+ if (!lstatSync(join(root, name)).isDirectory()) return;
2478
+ open(name, true, (_event, file) => {
2479
+ if (file) onFile(`${name}/${file}`);
2480
+ });
2481
+ } catch (error) {
2482
+ if (error.code !== "ENOENT") console.warn(`[verbaly] could not watch ${name}:`, error);
2462
2483
  }
2463
- open(name, true, (_event, file) => {
2464
- if (file) onFile(`${name}/${file}`);
2465
- });
2466
2484
  };
2467
- open("", false, (_event, file) => {
2485
+ open("", false, (event, file) => {
2468
2486
  if (!file) return;
2469
- sync(file);
2487
+ if (event === "rename") sync(file);
2470
2488
  onFile(file);
2471
2489
  });
2472
2490
  for (const entry of readdirSync(root, { withFileTypes: true })) if (entry.isDirectory()) sync(entry.name);