@verbaly/compiler 0.65.0 → 0.67.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.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
  }
@@ -189,17 +195,6 @@ function formatBundleIssue(issue) {
189
195
  return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
190
196
  }
191
197
  //#endregion
192
- //#region src/warn.ts
193
- const warned = /* @__PURE__ */ new Set();
194
- function warnOnce(message, dedupeKey = message) {
195
- if (warned.has(dedupeKey)) return;
196
- warned.add(dedupeKey);
197
- console.warn(`[verbaly] ${message}`);
198
- }
199
- function warnParseError(file, message) {
200
- warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
201
- }
202
- //#endregion
203
198
  //#region src/registry.ts
204
199
  var MessageRegistry = class {
205
200
  files = /* @__PURE__ */ new Map();
@@ -211,15 +206,21 @@ var MessageRegistry = class {
211
206
  }
212
207
  messages() {
213
208
  const out = /* @__PURE__ */ new Map();
209
+ for (const analysis of this.files.values()) for (const msg of analysis.tagged) if (!out.has(msg.key)) out.set(msg.key, msg);
210
+ return out;
211
+ }
212
+ collisions() {
213
+ const seen = /* @__PURE__ */ new Map();
214
214
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
215
- const existing = out.get(msg.key);
216
- if (existing) {
217
- if (existing.message !== msg.message) warnOnce(`key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped`, `collision:${msg.key}`);
218
- continue;
219
- }
220
- out.set(msg.key, msg);
215
+ const found = seen.get(msg.key);
216
+ if (!found) seen.set(msg.key, {
217
+ key: msg.key,
218
+ kept: msg,
219
+ dropped: []
220
+ });
221
+ else if (msg.message !== found.kept.message && !found.dropped.some((other) => other.message === msg.message)) found.dropped.push(msg);
221
222
  }
222
- return out;
223
+ return [...seen.values()].filter((entry) => entry.dropped.length > 0);
223
224
  }
224
225
  usedKeys(strict = false) {
225
226
  const out = /* @__PURE__ */ new Map();
@@ -234,6 +235,9 @@ var MessageRegistry = class {
234
235
  strayImports() {
235
236
  return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
236
237
  }
238
+ missed() {
239
+ return [...this.files.values()].flatMap((analysis) => analysis.missed ?? []);
240
+ }
237
241
  parseErrors() {
238
242
  const out = [];
239
243
  for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
@@ -282,12 +286,22 @@ function analyze(code, file, options = {}) {
282
286
  const tagged = [];
283
287
  const usedKeys = [];
284
288
  const strayImports = [];
289
+ const missed = [];
290
+ const renamed = renamedBindings(ast.program, names);
285
291
  walk$1(ast.program, (node) => {
286
292
  if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
287
293
  else if (node.type === "TaggedTemplateExpression") {
288
294
  const tag = node.tag;
289
295
  const explicit = explicitId(tag, names);
290
- if (!explicit && !isTReference(tag, names)) return;
296
+ if (!explicit && !isTReference(tag, names)) {
297
+ const name = renamedTag(tag, renamed);
298
+ if (name) missed.push({
299
+ name,
300
+ file,
301
+ start: node.start
302
+ });
303
+ return;
304
+ }
291
305
  const quasi = node.quasi;
292
306
  const message = buildMessage(code, quasi, names);
293
307
  if (!message) return;
@@ -308,7 +322,15 @@ function analyze(code, file, options = {}) {
308
322
  collectDeclaredKeys(args[0], file, usedKeys);
309
323
  return;
310
324
  }
311
- if (!isTReference(callee, names)) return;
325
+ if (!isTReference(callee, names)) {
326
+ const key = renamed.has(identifierName(callee)) ? staticString(args[0]) : void 0;
327
+ if (key !== void 0) usedKeys.push({
328
+ key,
329
+ file,
330
+ loose: true
331
+ });
332
+ return;
333
+ }
312
334
  const key = staticString(args[0]);
313
335
  if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
314
336
  } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
@@ -316,9 +338,53 @@ function analyze(code, file, options = {}) {
316
338
  return {
317
339
  tagged,
318
340
  usedKeys,
319
- strayImports
341
+ strayImports,
342
+ ...missed.length > 0 && { missed }
320
343
  };
321
344
  }
345
+ function renamedBindings(program, names) {
346
+ const out = /* @__PURE__ */ new Set();
347
+ const add = (node) => {
348
+ const name = identifierName(node);
349
+ if (name && !names.has(name)) out.add(name);
350
+ };
351
+ walk$1(program, (node) => {
352
+ if (node.type === "ImportDeclaration") {
353
+ if (node.source.value !== "virtual:verbaly") return;
354
+ for (const spec of node.specifiers) if (spec.type === "ImportSpecifier" && identifierName(spec.imported) === "t") add(spec.local);
355
+ } else if (node.type === "VariableDeclarator") {
356
+ const id = node.id;
357
+ const init = node.init;
358
+ if (id.type === "Identifier" && init && handsOutT(init)) add(id);
359
+ if (id.type !== "ObjectPattern") return;
360
+ for (const property of id.properties) {
361
+ if (property.type !== "ObjectProperty" || property.computed) continue;
362
+ if (identifierName(property.key) === "t") add(property.value);
363
+ }
364
+ }
365
+ });
366
+ return out;
367
+ }
368
+ function handsOutT(init) {
369
+ const call = init.type === "AwaitExpression" ? init.argument : init;
370
+ if (call.type !== "CallExpression") return false;
371
+ const callee = identifierName(call.callee);
372
+ return init.type === "AwaitExpression" ? callee === "getT" : callee === "useT";
373
+ }
374
+ function identifierName(node) {
375
+ return node?.type === "Identifier" ? node.name : "";
376
+ }
377
+ function renamedTag(tag, renamed) {
378
+ if (renamed.size === 0) return void 0;
379
+ const name = identifierName(tag);
380
+ if (renamed.has(name)) return name;
381
+ if (tag.type !== "CallExpression") return void 0;
382
+ const callee = tag.callee;
383
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
384
+ if (identifierName(callee.property) !== "id") return void 0;
385
+ const object = identifierName(callee.object);
386
+ return renamed.has(object) ? object : void 0;
387
+ }
322
388
  function collectDeclaredKeys(node, file, out) {
323
389
  if (node?.type !== "ObjectExpression") return;
324
390
  for (const property of node.properties) {
@@ -740,31 +806,40 @@ async function extractProject(cfg) {
740
806
  }
741
807
  async function collectOrigins(cfg, reuse) {
742
808
  const registry = reuse ?? await extractProject(cfg);
743
- const origins = {};
809
+ const origins = Object.create(null);
744
810
  for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
745
811
  return origins;
746
812
  }
747
813
  function syncCatalogs(cfg, catalogs, registry) {
748
814
  const added = {};
749
- const source = catalogs[cfg.sourceLocale] ??= {};
750
- for (const [key, msg] of registry.messages()) if (source[key] !== msg.message) {
751
- source[key] = msg.message;
752
- (added[cfg.sourceLocale] ??= []).push(key);
815
+ const replaced = [];
816
+ const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
817
+ for (const [key, msg] of registry.messages()) {
818
+ const before = own(source, key);
819
+ if (before !== msg.message) {
820
+ if (before) replaced.push(key);
821
+ source[key] = msg.message;
822
+ (added[cfg.sourceLocale] ??= []).push(key);
823
+ }
753
824
  }
754
825
  const needed = Object.keys(source);
755
826
  for (const locale of cfg.locales) {
756
827
  if (locale === cfg.sourceLocale) continue;
757
- const catalog = catalogs[locale] ??= {};
758
- for (const key of needed) if (catalog[key] === void 0) {
828
+ const catalog = catalogs[locale] ??= emptyCatalog();
829
+ for (const key of needed) if (own(catalog, key) === void 0) {
759
830
  catalog[key] = "";
760
831
  (added[locale] ??= []).push(key);
761
832
  }
762
833
  }
763
- return { added };
834
+ return {
835
+ added,
836
+ replaced
837
+ };
764
838
  }
765
839
  function pruneCatalogs(cfg, catalogs, registry) {
766
- const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
767
840
  const removed = {};
841
+ if (registry.parseErrors().length > 0) return removed;
842
+ const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
768
843
  for (const locale of cfg.locales) {
769
844
  const catalog = catalogs[locale];
770
845
  if (!catalog) continue;
@@ -928,7 +1003,7 @@ function reachableCategories(locale, ordinal) {
928
1003
  if (hit) return hit;
929
1004
  let out;
930
1005
  try {
931
- const rules = new Intl.PluralRules(locale, { type });
1006
+ const rules = new Intl.PluralRules(locale.replace(/_/g, "-"), { type });
932
1007
  const seen = /* @__PURE__ */ new Set();
933
1008
  for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));
934
1009
  out = [...seen];
@@ -1087,7 +1162,7 @@ export async function setLocale(locale) {
1087
1162
  ${options.extraExports ?? ""}`;
1088
1163
  }
1089
1164
  function generateLocaleModule(catalog) {
1090
- return `export default ${JSON.stringify(catalog)};\n`;
1165
+ return `export default ${JSON.stringify(catalog).replace(/([{,])"__proto__":/, "$1[\"__proto__\"]:")};\n`;
1091
1166
  }
1092
1167
  function generateDts(catalog, options = {}) {
1093
1168
  const lines = [];
@@ -1160,7 +1235,9 @@ declare module 'virtual:verbaly/locale/*' {
1160
1235
  `;
1161
1236
  }
1162
1237
  function writeDts(cfg, catalog, file) {
1163
- file ??= join(cfg.root, "verbaly.d.ts");
1238
+ const target = file === void 0 ? cfg.dts : file;
1239
+ if (target === false) return;
1240
+ file = target ?? join(cfg.root, "verbaly.d.ts");
1164
1241
  const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
1165
1242
  try {
1166
1243
  if (readFileSync(file, "utf8") === content) return;
@@ -1341,12 +1418,209 @@ async function init(input = {}) {
1341
1418
  };
1342
1419
  }
1343
1420
  //#endregion
1421
+ //#region src/location.ts
1422
+ function lineAt(content, offset) {
1423
+ let line = 1;
1424
+ const end = Math.min(offset, content.length);
1425
+ for (let i = 0; i < end; i++) if (content[i] === "\n") line += 1;
1426
+ return line;
1427
+ }
1428
+ function createLocator() {
1429
+ const contents = /* @__PURE__ */ new Map();
1430
+ return (file, offset) => {
1431
+ if (!contents.has(file)) try {
1432
+ contents.set(file, readFileSync(file, "utf8"));
1433
+ } catch {
1434
+ contents.set(file, void 0);
1435
+ }
1436
+ const content = contents.get(file);
1437
+ return content === void 0 ? void 0 : lineAt(content, offset);
1438
+ };
1439
+ }
1440
+ //#endregion
1441
+ //#region src/state.ts
1442
+ const STATE_FILE = ".verbaly-state.json";
1443
+ const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1444
+ function statePath(cfg, file = STATE_FILE) {
1445
+ return join(cfg.dir, file);
1446
+ }
1447
+ function loadState(cfg) {
1448
+ const current = readJson(statePath(cfg));
1449
+ if (current !== void 0) {
1450
+ if (!isObject(current)) throw corrupt(statePath(cfg));
1451
+ return {
1452
+ drafts: readDrafts(current.drafts),
1453
+ fingerprints: readFingerprints(current.fingerprints)
1454
+ };
1455
+ }
1456
+ const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1457
+ if (legacy === void 0) return {
1458
+ drafts: {},
1459
+ fingerprints: {}
1460
+ };
1461
+ if (!isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1462
+ return {
1463
+ drafts: readDrafts(legacy),
1464
+ fingerprints: {}
1465
+ };
1466
+ }
1467
+ function saveState(cfg, state) {
1468
+ const serialized = serializeState(state);
1469
+ const path = statePath(cfg);
1470
+ const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1471
+ if (serialized === void 0) {
1472
+ rmSync(path, { force: true });
1473
+ rmSync(legacy, { force: true });
1474
+ return;
1475
+ }
1476
+ let existing;
1477
+ try {
1478
+ existing = readFileSync(path, "utf8");
1479
+ } catch {
1480
+ mkdirSync(cfg.dir, { recursive: true });
1481
+ }
1482
+ if (existing !== serialized) writeFileSync(path, serialized);
1483
+ if (existsSync(legacy)) rmSync(legacy);
1484
+ }
1485
+ function updateState(cfg, catalogs) {
1486
+ const state = loadState(cfg);
1487
+ const next = {
1488
+ drafts: effectiveDrafts(state.drafts, catalogs),
1489
+ fingerprints: refreshFingerprints(cfg, catalogs, state.fingerprints)
1490
+ };
1491
+ saveState(cfg, next);
1492
+ return next;
1493
+ }
1494
+ function effectiveDrafts(drafts, catalogs) {
1495
+ const out = {};
1496
+ for (const [locale, keys] of Object.entries(drafts)) {
1497
+ const catalog = catalogs[locale] ?? {};
1498
+ const live = keys.filter((key) => own(catalog, key));
1499
+ if (live.length) out[locale] = live;
1500
+ }
1501
+ return out;
1502
+ }
1503
+ function fingerprint(text) {
1504
+ return stableKey(text);
1505
+ }
1506
+ function tracked(key, text) {
1507
+ return stableKey(text) !== key;
1508
+ }
1509
+ function stamp(source, translated) {
1510
+ return `${fingerprint(source)}.${fingerprint(translated)}`;
1511
+ }
1512
+ function refreshFingerprints(cfg, catalogs, previous) {
1513
+ const source = catalogs[cfg.sourceLocale] ?? {};
1514
+ const out = {};
1515
+ for (const locale of targetLocales(cfg)) {
1516
+ const catalog = catalogs[locale] ?? {};
1517
+ const before = previous[locale] ?? {};
1518
+ const after = emptyCatalog();
1519
+ for (const [key, text] of Object.entries(source)) {
1520
+ const translated = own(catalog, key);
1521
+ if (!text || !translated || !tracked(key, text)) continue;
1522
+ const was = own(before, key);
1523
+ after[key] = was !== void 0 && translationOf(was) === fingerprint(translated) ? was : stamp(text, translated);
1524
+ }
1525
+ if (Object.keys(after).length) out[locale] = after;
1526
+ }
1527
+ return out;
1528
+ }
1529
+ function outdatedTranslations(cfg, catalogs, fingerprints) {
1530
+ const source = catalogs[cfg.sourceLocale] ?? {};
1531
+ const out = [];
1532
+ for (const locale of targetLocales(cfg)) {
1533
+ const catalog = catalogs[locale] ?? {};
1534
+ for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
1535
+ const text = own(source, key);
1536
+ const translated = own(catalog, key);
1537
+ if (!text || !translated) continue;
1538
+ if (translationOf(was) !== fingerprint(translated)) continue;
1539
+ if (sourceOf(was) !== fingerprint(text)) out.push({
1540
+ locale,
1541
+ key
1542
+ });
1543
+ }
1544
+ }
1545
+ return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
1546
+ }
1547
+ function sourceOf(stamped) {
1548
+ return stamped.slice(0, stamped.indexOf("."));
1549
+ }
1550
+ function translationOf(stamped) {
1551
+ return stamped.slice(stamped.indexOf(".") + 1);
1552
+ }
1553
+ function serializeState(state) {
1554
+ const drafts = {};
1555
+ for (const locale of Object.keys(state.drafts).sort()) {
1556
+ const keys = [...new Set(state.drafts[locale])].sort();
1557
+ if (keys.length) drafts[locale] = keys;
1558
+ }
1559
+ const fingerprints = {};
1560
+ for (const locale of Object.keys(state.fingerprints).sort()) {
1561
+ const entries = state.fingerprints[locale] ?? {};
1562
+ const keys = Object.keys(entries).sort();
1563
+ if (!keys.length) continue;
1564
+ fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1565
+ }
1566
+ const out = {};
1567
+ if (Object.keys(drafts).length) out.drafts = drafts;
1568
+ if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1569
+ if (!out.drafts && !out.fingerprints) return void 0;
1570
+ return JSON.stringify(out, null, 2) + "\n";
1571
+ }
1572
+ function readJson(path) {
1573
+ let content;
1574
+ try {
1575
+ content = readFileSync(path, "utf8");
1576
+ } catch {
1577
+ return;
1578
+ }
1579
+ try {
1580
+ return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1581
+ } catch (error) {
1582
+ throw corrupt(path, error);
1583
+ }
1584
+ }
1585
+ function corrupt(path, cause) {
1586
+ return new Error(`[verbaly] ${path} is not valid JSON, fix or delete the file`, { cause });
1587
+ }
1588
+ function isObject(value) {
1589
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1590
+ }
1591
+ function readDrafts(value) {
1592
+ const out = {};
1593
+ if (!isObject(value)) return out;
1594
+ for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1595
+ return out;
1596
+ }
1597
+ function readFingerprints(value) {
1598
+ const out = {};
1599
+ if (!isObject(value)) return out;
1600
+ for (const [locale, entries] of Object.entries(value)) {
1601
+ if (!isObject(entries)) continue;
1602
+ const kept = emptyCatalog();
1603
+ for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
1604
+ out[locale] = kept;
1605
+ }
1606
+ return out;
1607
+ }
1608
+ //#endregion
1344
1609
  //#region src/check.ts
1345
1610
  function gatePasses(result) {
1346
1611
  return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
1347
1612
  }
1348
- function check(cfg, catalogs, registry) {
1613
+ function warningCount(result) {
1614
+ return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.collisions.length + result.divergent.length + result.outdated.length;
1615
+ }
1616
+ function check(cfg, catalogs, registry, fingerprints = {}) {
1349
1617
  const extracted = registry.messages();
1618
+ const locate = createLocator();
1619
+ const site = (msg) => ({
1620
+ file: msg.file,
1621
+ line: locate(msg.file, msg.start),
1622
+ message: msg.message
1623
+ });
1350
1624
  const flat = {};
1351
1625
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1352
1626
  const source = flat[cfg.sourceLocale] ?? {};
@@ -1380,8 +1654,17 @@ function check(cfg, catalogs, registry) {
1380
1654
  issue: issue.message
1381
1655
  });
1382
1656
  };
1383
- const sourceText = { ...source };
1384
- for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
1657
+ const sourceText = Object.assign(emptyCatalog(), source);
1658
+ const divergent = [];
1659
+ for (const [key, entry] of extracted) {
1660
+ const written = sourceText[key];
1661
+ if (written && written !== entry.message) divergent.push({
1662
+ key,
1663
+ catalog: written,
1664
+ code: site(entry)
1665
+ });
1666
+ sourceText[key] = entry.message;
1667
+ }
1385
1668
  for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
1386
1669
  for (const locale of cfg.locales) {
1387
1670
  if (locale === cfg.sourceLocale) continue;
@@ -1404,6 +1687,8 @@ function check(cfg, catalogs, registry) {
1404
1687
  });
1405
1688
  }
1406
1689
  }
1690
+ const collisions = collisionEntries(registry, locate);
1691
+ const outdated = outdatedTranslations(cfg, flat, fingerprints);
1407
1692
  return {
1408
1693
  ok: gatePasses({
1409
1694
  missing,
@@ -1413,7 +1698,10 @@ function check(cfg, catalogs, registry) {
1413
1698
  missing,
1414
1699
  unknown,
1415
1700
  broken,
1416
- extra
1701
+ extra,
1702
+ collisions,
1703
+ divergent,
1704
+ outdated
1417
1705
  };
1418
1706
  }
1419
1707
  function formatCheckResult(result, root) {
@@ -1445,15 +1733,50 @@ function checkNextSteps(result, cliReachable = true) {
1445
1733
  if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
1446
1734
  return steps.join("\n");
1447
1735
  }
1448
- function formatCheckWarnings(result) {
1736
+ function collisionEntries(registry, locate = createLocator()) {
1737
+ return registry.collisions().map(({ key, kept, dropped }) => ({
1738
+ key,
1739
+ sites: [kept, ...dropped].map((msg) => ({
1740
+ file: msg.file,
1741
+ line: locate(msg.file, msg.start),
1742
+ message: msg.message
1743
+ }))
1744
+ }));
1745
+ }
1746
+ function sourcePlace(at, root) {
1747
+ const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1748
+ return at.line ? `${file}:${at.line}` : file;
1749
+ }
1750
+ function quoted(at, root) {
1751
+ return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1752
+ }
1753
+ function formatCollision({ key, sites }, root) {
1754
+ const [kept, ...others] = sites;
1755
+ return ` ${key}: one key with ${counted(sites.length, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
1756
+ }
1757
+ function formatCheckWarnings(result, root) {
1449
1758
  const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1450
1759
  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`);
1760
+ for (const entry of result.collisions) lines.push(formatCollision(entry, root));
1761
+ for (const { key, catalog, code } of result.divergent) lines.push(` ${key}: the source catalog says "${truncate(catalog, 40)}" and the code says ${quoted(code, root)}: the code wins, so edit the text there (extract writes it into the catalog)`);
1762
+ for (const { locale, key } of result.outdated) lines.push(` [${locale}] ${key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``);
1451
1763
  return lines.join("\n");
1452
1764
  }
1453
1765
  function truncate(text, max) {
1454
1766
  return text.length > max ? text.slice(0, max - 1) + "…" : text;
1455
1767
  }
1456
1768
  //#endregion
1769
+ //#region src/warn.ts
1770
+ const warned = /* @__PURE__ */ new Set();
1771
+ function warnOnce(message, dedupeKey = message) {
1772
+ if (warned.has(dedupeKey)) return;
1773
+ warned.add(dedupeKey);
1774
+ console.warn(`[verbaly] ${message}`);
1775
+ }
1776
+ function warnParseError(file, message) {
1777
+ warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
1778
+ }
1779
+ //#endregion
1457
1780
  //#region src/transform.ts
1458
1781
  function quote(text, single) {
1459
1782
  if (!single) return JSON.stringify(text);
@@ -1516,7 +1839,7 @@ function transformSource(code, id, registry) {
1516
1839
  const analysis = analyzeFile(code, id);
1517
1840
  registry.update(id, analysis);
1518
1841
  if (analysis.parseError) warnParseError(id, analysis.parseError);
1519
- const messages = {};
1842
+ const messages = emptyCatalog();
1520
1843
  for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
1521
1844
  return {
1522
1845
  messages,
@@ -1526,7 +1849,9 @@ function transformSource(code, id, registry) {
1526
1849
  function runBuildGate(cfg, registry, failOnMissing) {
1527
1850
  const catalogs = loadCatalogs(cfg);
1528
1851
  for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
1529
- const found = check(cfg, catalogs, registry);
1852
+ const found = check(cfg, catalogs, registry, buildFingerprints(cfg));
1853
+ const warnings = warningCount(found);
1854
+ if (warnings > 0) warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: run \`npx verbaly check\` to read them`, "gate:warnings");
1530
1855
  const result = failOnMissing === false ? {
1531
1856
  ...found,
1532
1857
  missing: []
@@ -1534,42 +1859,24 @@ function runBuildGate(cfg, registry, failOnMissing) {
1534
1859
  if (gatePasses(result)) return;
1535
1860
  throw new Error(`[verbaly] build blocked\n${formatCheckResult(result, cfg.root)}\n${checkNextSteps(result, cliReachable(cfg.root))}`);
1536
1861
  }
1537
- //#endregion
1538
- //#region src/drafts.ts
1539
- const DRAFTS_FILE = ".verbaly-drafts.json";
1540
- function draftsPath(cfg) {
1541
- return join(cfg.dir, DRAFTS_FILE);
1542
- }
1543
- function loadDrafts(cfg) {
1544
- let content;
1545
- try {
1546
- content = readFileSync(draftsPath(cfg), "utf8");
1547
- } catch {
1548
- return {};
1549
- }
1862
+ function buildFingerprints(cfg) {
1550
1863
  try {
1551
- return JSON.parse(content.replace(/^\uFEFF/, ""));
1864
+ return loadState(cfg).fingerprints;
1552
1865
  } catch (error) {
1553
- throw new Error(`[verbaly] ${draftsPath(cfg)} is not valid JSON, fix or delete the file`, { cause: error });
1866
+ warnOnce(`${error.message.replace(/^\[verbaly\] /, "")}, so outdated translations are not reported`, "gate:state");
1867
+ return {};
1554
1868
  }
1555
1869
  }
1556
- function serializeDrafts(drafts) {
1557
- const sorted = {};
1558
- for (const locale of Object.keys(drafts).sort()) {
1559
- const keys = [...new Set(drafts[locale])].sort();
1560
- if (keys.length) sorted[locale] = keys;
1561
- }
1562
- return JSON.stringify(sorted, null, 2) + "\n";
1870
+ //#endregion
1871
+ //#region src/drafts.ts
1872
+ function loadDrafts(cfg) {
1873
+ return loadState(cfg).drafts;
1563
1874
  }
1564
1875
  function saveDrafts(cfg, drafts) {
1565
- const serialized = serializeDrafts(drafts);
1566
- const path = draftsPath(cfg);
1567
- try {
1568
- if (readFileSync(path, "utf8") === serialized) return;
1569
- } catch {
1570
- mkdirSync(cfg.dir, { recursive: true });
1571
- }
1572
- writeFileSync(path, serialized);
1876
+ saveState(cfg, {
1877
+ ...loadState(cfg),
1878
+ drafts
1879
+ });
1573
1880
  }
1574
1881
  function markDrafts(drafts, locale, keys) {
1575
1882
  if (!keys.length) return;
@@ -1585,24 +1892,16 @@ function clearDrafts(drafts, locale, keys) {
1585
1892
  drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1586
1893
  if (!drafts[locale].length) delete drafts[locale];
1587
1894
  }
1588
- function effectiveDrafts(drafts, catalogs) {
1589
- const out = {};
1590
- for (const [locale, keys] of Object.entries(drafts)) {
1591
- const catalog = catalogs[locale] ?? {};
1592
- const live = keys.filter((key) => catalog[key]);
1593
- if (live.length) out[locale] = live;
1594
- }
1595
- return out;
1596
- }
1597
1895
  //#endregion
1598
1896
  //#region src/status.ts
1599
- function status(cfg, catalogs, registry, drafts = {}) {
1897
+ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
1600
1898
  const extracted = registry.messages();
1601
1899
  const flat = {};
1602
1900
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1603
1901
  const source = flat[cfg.sourceLocale] ?? {};
1604
1902
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
1605
1903
  const live = effectiveDrafts(drafts, flat);
1904
+ const outdated = outdatedTranslations(cfg, flat, fingerprints);
1606
1905
  const locales = [];
1607
1906
  for (const locale of cfg.locales) {
1608
1907
  if (locale === cfg.sourceLocale) continue;
@@ -1620,7 +1919,8 @@ function status(cfg, catalogs, registry, drafts = {}) {
1620
1919
  translated,
1621
1920
  total: needed.size,
1622
1921
  drafts: live[locale]?.length ?? 0,
1623
- broken
1922
+ broken,
1923
+ outdated: outdated.filter((entry) => entry.locale === locale).length
1624
1924
  });
1625
1925
  }
1626
1926
  return {
@@ -1635,10 +1935,14 @@ function formatStatusResult(result) {
1635
1935
  lines.push(" no target locales (add locales to your config)");
1636
1936
  return lines.join("\n");
1637
1937
  }
1638
- for (const { locale, translated, total, drafts, broken } of result.locales) {
1938
+ for (const { locale, translated, total, drafts, broken, outdated } of result.locales) {
1639
1939
  const pct = total === 0 ? 100 : Math.floor(translated / total * 100);
1640
- const mark = translated === total && broken === 0 ? " ✓" : "";
1641
- const notes = [drafts > 0 ? `${drafts} unreviewed` : "", broken > 0 ? `${broken} broken` : ""].filter(Boolean);
1940
+ const mark = translated === total && broken === 0 && outdated === 0 ? " ✓" : "";
1941
+ const notes = [
1942
+ drafts > 0 ? `${drafts} unreviewed` : "",
1943
+ broken > 0 ? `${broken} broken` : "",
1944
+ outdated > 0 ? `${outdated} outdated` : ""
1945
+ ].filter(Boolean);
1642
1946
  const note = notes.length > 0 ? `, ${notes.join(", ")}` : "";
1643
1947
  lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);
1644
1948
  }
@@ -1707,17 +2011,22 @@ async function doctor(cfg) {
1707
2011
  error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
1708
2012
  continue;
1709
2013
  }
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 {
2014
+ const parsed = parseTree(readFileSync(file, "utf8"));
2015
+ if (parsed === void 0) {
1718
2016
  catalogsHealthy = false;
1719
2017
  error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
2018
+ continue;
2019
+ }
2020
+ if (!isTree(parsed)) {
2021
+ catalogsHealthy = false;
2022
+ 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");
2023
+ continue;
1720
2024
  }
2025
+ const bad = badLeaf(parsed);
2026
+ if (bad) {
2027
+ catalogsHealthy = false;
2028
+ error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
2029
+ } else catalogs[locale] = flatten(parsed);
1721
2030
  }
1722
2031
  if (catalogsHealthy) {
1723
2032
  const how = cfg.localesDeclared ? "" : ", no locales set, so the catalog files decide";
@@ -1734,6 +2043,7 @@ async function doctor(cfg) {
1734
2043
  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
2044
  const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
1736
2045
  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");
2046
+ 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
2047
  else {
1738
2048
  const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
1739
2049
  ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
@@ -1764,6 +2074,18 @@ async function doctor(cfg) {
1764
2074
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1765
2075
  error("imports", `t is imported from a verbaly package, which never exports it, in ${counted(files.length, "file")} (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
1766
2076
  }
2077
+ const missed = registry.missed();
2078
+ if (missed.length > 0) {
2079
+ const locate = createLocator();
2080
+ const first = missed[0];
2081
+ const line = locate(first.file, first.start);
2082
+ warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${rel(first.file)}${line ? `:${line}` : ""}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
2083
+ }
2084
+ const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
2085
+ if (positional.length > 0) {
2086
+ const first = positional[0];
2087
+ warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${rel(first.file)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
2088
+ }
1767
2089
  const escaped = [...registry.messages().values()].map((msg) => ({
1768
2090
  file: rel(msg.file),
1769
2091
  slice: escapedSyntax(msg.message)
@@ -1774,7 +2096,8 @@ async function doctor(cfg) {
1774
2096
  const extracted = registry.messages();
1775
2097
  const used = registry.usedKeys();
1776
2098
  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");
2099
+ const unread = registry.parseErrors().length > 0;
2100
+ 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
2101
  else ok("orphans", "no orphan keys");
1779
2102
  }
1780
2103
  const excluded = cfg.bundle.exclude ?? [];
@@ -1783,8 +2106,24 @@ async function doctor(cfg) {
1783
2106
  for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
1784
2107
  if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
1785
2108
  }
2109
+ let state = {
2110
+ drafts: {},
2111
+ fingerprints: {}
2112
+ };
2113
+ try {
2114
+ state = loadState(cfg);
2115
+ } catch (error) {
2116
+ warn("state", error.message.replace(/^\[verbaly\] /, ""), `delete ${STATE_FILE}: drafts and outdated tracking start again from the catalogs`);
2117
+ }
1786
2118
  if (catalogsHealthy) {
1787
- const result = check(cfg, catalogs, registry);
2119
+ const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2120
+ const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
2121
+ return keys.filter((key) => !live.has(key)).map((key) => `${locale}: ${key}`);
2122
+ });
2123
+ if (stale.length > 0) warn("drafts", `${STATE_FILE} lists ${counted(stale.length, "draft")} whose translation is gone (${preview(stale)})`, "run `npx verbaly extract`, which drops them");
2124
+ }
2125
+ if (catalogsHealthy) {
2126
+ const result = check(cfg, catalogs, registry, state.fingerprints);
1788
2127
  if (result.unknown.length > 0) error("keys", `${counted(result.unknown.length, "unknown key")} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
1789
2128
  if (result.missing.length > 0) {
1790
2129
  const locales = [...new Set(result.missing.map((m) => m.locale))];
@@ -1801,6 +2140,18 @@ async function doctor(cfg) {
1801
2140
  }
1802
2141
  const warnings = result.broken.filter((entry) => entry.severity === "warning");
1803
2142
  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");
2143
+ if (result.collisions.length > 0) {
2144
+ const first = result.collisions[0];
2145
+ warn("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
2146
+ }
2147
+ if (result.divergent.length > 0) {
2148
+ const first = result.divergent[0];
2149
+ warn("source texts", `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, "text")}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`, "edit those texts in the code; `npx verbaly extract` writes them into the catalog");
2150
+ }
2151
+ if (result.outdated.length > 0) {
2152
+ const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
2153
+ warn("outdated", `${counted(result.outdated.length, "translation")} written for an older source text (${preview(shown)})`, "update them, or keep them with `npx verbaly review --approve`");
2154
+ }
1804
2155
  if (result.ok) ok("translations", "all translations complete");
1805
2156
  }
1806
2157
  return {
@@ -1865,8 +2216,8 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1865
2216
  };
1866
2217
  const jobs = [];
1867
2218
  for (const locale of targets) {
1868
- const catalog = catalogs[locale] ??= {};
1869
- const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
2219
+ const catalog = catalogs[locale] ??= emptyCatalog();
2220
+ const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
1870
2221
  if (missing.length === 0) continue;
1871
2222
  if (options.dryRun) {
1872
2223
  result.pending[locale] = missing;
@@ -1887,7 +2238,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1887
2238
  const { locale, keys } = job;
1888
2239
  const catalog = catalogs[locale];
1889
2240
  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;
2241
+ const origins = options.origins ? Object.fromEntries(keys.filter((key) => Object.hasOwn(options.origins, key)).map((key) => [key, options.origins[key]])) : void 0;
1891
2242
  let out;
1892
2243
  try {
1893
2244
  out = await attempt(() => provider({
@@ -1941,6 +2292,35 @@ function mergeTranslations(cfg, locale, translated, keys) {
1941
2292
  if (written.length > 0) writeCatalog(cfg, locale, current);
1942
2293
  return written;
1943
2294
  }
2295
+ function writeDrafts(cfg, locale, entries, options = {}) {
2296
+ const targets = targetLocales(cfg);
2297
+ if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
2298
+ const source = readCatalog(cfg, cfg.sourceLocale);
2299
+ const current = readCatalog(cfg, locale);
2300
+ const result = {
2301
+ written: [],
2302
+ kept: [],
2303
+ invalid: [],
2304
+ unknown: []
2305
+ };
2306
+ for (const { key, text } of entries) {
2307
+ const from = own(source, key);
2308
+ if (!from) result.unknown.push(key);
2309
+ else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);
2310
+ else if (own(current, key) && !options.overwrite) result.kept.push(key);
2311
+ else {
2312
+ current[key] = text;
2313
+ result.written.push(key);
2314
+ }
2315
+ }
2316
+ if (result.written.length > 0) {
2317
+ writeCatalog(cfg, locale, current);
2318
+ const drafts = loadDrafts(cfg);
2319
+ markDrafts(drafts, locale, result.written);
2320
+ saveDrafts(cfg, drafts);
2321
+ }
2322
+ return result;
2323
+ }
1944
2324
  function formatTranslateFailures(failed) {
1945
2325
  const grouped = [];
1946
2326
  for (const entry of failed) {
@@ -1956,7 +2336,7 @@ function formatTranslateFailures(failed) {
1956
2336
  async function resolveProvider(cfg, model) {
1957
2337
  const configured = cfg.translate.provider;
1958
2338
  if (typeof configured === "function") return configured;
1959
- const { claudeProvider } = await import("./claude--aMMLA-N.js");
2339
+ const { claudeProvider } = await import("./claude-D-j-ZiYH.js");
1960
2340
  return claudeProvider({ model: model ?? cfg.translate.model });
1961
2341
  }
1962
2342
  function structureMatches(source, translated) {
@@ -2115,7 +2495,7 @@ function renderHtml(html, options) {
2115
2495
  };
2116
2496
  }
2117
2497
  function pageSlice(v, locale, used) {
2118
- const slice = {};
2498
+ const slice = Object.create(null);
2119
2499
  for (const key of used) {
2120
2500
  const found = v.inspect(key);
2121
2501
  slice[key] = found?.from === locale ? found.source : "";
@@ -2456,17 +2836,17 @@ function watchTree(root, options, onFile) {
2456
2836
  close(name);
2457
2837
  if (name !== options.keep && (name === "node_modules" || name.startsWith("."))) return;
2458
2838
  try {
2459
- if (!statSync(join(root, name)).isDirectory()) return;
2460
- } catch {
2461
- return;
2839
+ if (!lstatSync(join(root, name)).isDirectory()) return;
2840
+ open(name, true, (_event, file) => {
2841
+ if (file) onFile(`${name}/${file}`);
2842
+ });
2843
+ } catch (error) {
2844
+ if (error.code !== "ENOENT") console.warn(`[verbaly] could not watch ${name}:`, error);
2462
2845
  }
2463
- open(name, true, (_event, file) => {
2464
- if (file) onFile(`${name}/${file}`);
2465
- });
2466
2846
  };
2467
- open("", false, (_event, file) => {
2847
+ open("", false, (event, file) => {
2468
2848
  if (!file) return;
2469
- sync(file);
2849
+ if (event === "rename") sync(file);
2470
2850
  onFile(file);
2471
2851
  });
2472
2852
  for (const entry of readdirSync(root, { withFileTypes: true })) if (entry.isDirectory()) sync(entry.name);
@@ -2758,6 +3138,6 @@ function formatCliError(error) {
2758
3138
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
2759
3139
  }
2760
3140
  //#endregion
2761
- export { DRAFTS_FILE, LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, clearDrafts, clientCatalogs, collectOrigins, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatCliError, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, mergeTranslations, needsIcu, needsRelative, parseCatalog, pruneCatalogs, readCatalog, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDts };
3141
+ export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, STATE_FILE, check, clearDrafts, clientCatalogs, collectOrigins, collisionEntries, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatCliError, formatCollision, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadState, loadVirtualModule, markDrafts, mergeTranslations, needsIcu, needsRelative, outdatedTranslations, parseCatalog, pruneCatalogs, readCatalog, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, updateState, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDrafts, writeDts };
2762
3142
 
2763
3143
  //# sourceMappingURL=index.js.map