@verbaly/compiler 0.66.0 → 0.68.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,4 +1,4 @@
1
- import { a as loadConfigFile, i as loadConfig, n as findConfigFile, o as resolveConfig, s as targetLocales, t as counted } from "./text-M4XbWU6N.js";
1
+ import { a as loadConfig, c as targetLocales, n as truncate, o as loadConfigFile, r as findConfigFile, s as resolveConfig, t as counted } from "./text-SqXoYAIB.js";
2
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";
@@ -195,17 +195,6 @@ function formatBundleIssue(issue) {
195
195
  return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
196
196
  }
197
197
  //#endregion
198
- //#region src/warn.ts
199
- const warned = /* @__PURE__ */ new Set();
200
- function warnOnce(message, dedupeKey = message) {
201
- if (warned.has(dedupeKey)) return;
202
- warned.add(dedupeKey);
203
- console.warn(`[verbaly] ${message}`);
204
- }
205
- function warnParseError(file, message) {
206
- warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
207
- }
208
- //#endregion
209
198
  //#region src/registry.ts
210
199
  var MessageRegistry = class {
211
200
  files = /* @__PURE__ */ new Map();
@@ -217,19 +206,28 @@ var MessageRegistry = class {
217
206
  }
218
207
  messages() {
219
208
  const out = /* @__PURE__ */ new Map();
220
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
221
- const existing = out.get(msg.key);
222
- if (existing) {
223
- if (existing.message !== msg.message) warnOnce(`key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped`, `collision:${msg.key}`);
224
- continue;
225
- }
226
- out.set(msg.key, msg);
209
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
210
+ const held = out.get(msg.key);
211
+ if (!held || earlier(msg, held)) out.set(msg.key, msg);
227
212
  }
228
213
  return out;
229
214
  }
215
+ collisions() {
216
+ const winners = this.messages();
217
+ const dropped = /* @__PURE__ */ new Map();
218
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
219
+ if (msg.message === winners.get(msg.key).message) continue;
220
+ dropped.set(msg.key, [...dropped.get(msg.key) ?? [], msg]);
221
+ }
222
+ return [...dropped].map(([key, others]) => ({
223
+ key,
224
+ kept: winners.get(key),
225
+ dropped: others.sort((a, b) => earlier(a, b) ? -1 : 1)
226
+ }));
227
+ }
230
228
  usedKeys(strict = false) {
231
229
  const out = /* @__PURE__ */ new Map();
232
- for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
230
+ for (const analysis of this.inOrder()) for (const used of analysis.usedKeys) {
233
231
  if (strict && used.loose) continue;
234
232
  const files = out.get(used.key) ?? [];
235
233
  if (!files.includes(used.file)) files.push(used.file);
@@ -238,26 +236,38 @@ var MessageRegistry = class {
238
236
  return out;
239
237
  }
240
238
  strayImports() {
241
- return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
239
+ return this.inOrder().flatMap((analysis) => analysis.strayImports);
240
+ }
241
+ missed() {
242
+ return this.inOrder().flatMap((analysis) => analysis.missed);
242
243
  }
243
244
  parseErrors() {
244
245
  const out = [];
245
- for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
246
- file,
247
- message: analysis.parseError
248
- });
246
+ for (const file of [...this.files.keys()].sort()) {
247
+ const { parseError } = this.files.get(file);
248
+ if (parseError) out.push({
249
+ file,
250
+ message: parseError
251
+ });
252
+ }
249
253
  return out;
250
254
  }
251
255
  origins() {
252
256
  const out = this.usedKeys();
253
- for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
257
+ for (const analysis of this.inOrder()) for (const msg of analysis.tagged) {
254
258
  const files = out.get(msg.key) ?? [];
255
259
  if (!files.includes(msg.file)) files.push(msg.file);
256
260
  out.set(msg.key, files);
257
261
  }
258
262
  return out;
259
263
  }
264
+ inOrder() {
265
+ return [...this.files.keys()].sort().map((file) => this.files.get(file));
266
+ }
260
267
  };
268
+ function earlier(a, b) {
269
+ return a.file === b.file ? a.start < b.start : a.file < b.file;
270
+ }
261
271
  //#endregion
262
272
  //#region src/key.ts
263
273
  function stableKey(message) {
@@ -279,6 +289,9 @@ const DEFAULT_T_NAMES = ["t"];
279
289
  const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
280
290
  const DEFINE_KEYS = "defineKeys";
281
291
  function analyze(code, file, options = {}) {
292
+ return analyzeScript(code, file, options).analysis;
293
+ }
294
+ function analyzeScript(code, file, options = {}) {
282
295
  const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
283
296
  const ast = parse$1(code, {
284
297
  sourceType: "module",
@@ -288,12 +301,23 @@ function analyze(code, file, options = {}) {
288
301
  const tagged = [];
289
302
  const usedKeys = [];
290
303
  const strayImports = [];
304
+ const bindings = new Bindings(names);
305
+ const candidates = [];
291
306
  walk$1(ast.program, (node) => {
292
- if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
307
+ if (node.type === "ImportDeclaration") {
308
+ collectStrayImports(node, file, strayImports);
309
+ bindings.addImport(node);
310
+ } else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
293
311
  else if (node.type === "TaggedTemplateExpression") {
294
312
  const tag = node.tag;
295
313
  const explicit = explicitId(tag, names);
296
- if (!explicit && !isTReference(tag, names)) return;
314
+ if (!explicit && !isTReference(tag, names)) {
315
+ candidates.push({
316
+ kind: "tag",
317
+ node
318
+ });
319
+ return;
320
+ }
297
321
  const quasi = node.quasi;
298
322
  const message = buildMessage(code, quasi, names);
299
323
  if (!message) return;
@@ -303,6 +327,7 @@ function analyze(code, file, options = {}) {
303
327
  params: message.params,
304
328
  start: node.start,
305
329
  end: node.end,
330
+ line: lineOf(node),
306
331
  tagStart: explicit ? explicit.refStart : tag.start,
307
332
  tagEnd: explicit ? explicit.refEnd : tag.end,
308
333
  file
@@ -314,17 +339,174 @@ function analyze(code, file, options = {}) {
314
339
  collectDeclaredKeys(args[0], file, usedKeys);
315
340
  return;
316
341
  }
317
- if (!isTReference(callee, names)) return;
342
+ if (!isTReference(callee, names)) {
343
+ const key = callee.type === "Identifier" ? staticString(args[0]) : void 0;
344
+ if (key !== void 0) candidates.push({
345
+ kind: "call",
346
+ name: callee.name,
347
+ key
348
+ });
349
+ return;
350
+ }
318
351
  const key = staticString(args[0]);
319
352
  if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
320
353
  } else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
321
354
  });
355
+ const renamed = bindings.renamed(options.renamed);
356
+ const missed = [];
357
+ for (const candidate of candidates) {
358
+ if (candidate.kind === "call") {
359
+ if (renamed.has(candidate.name)) usedKeys.push({
360
+ key: candidate.key,
361
+ file,
362
+ loose: true
363
+ });
364
+ continue;
365
+ }
366
+ const { node } = candidate;
367
+ const name = renamedTag(node.tag, renamed);
368
+ if (!name) continue;
369
+ missed.push({
370
+ name,
371
+ file,
372
+ start: node.start,
373
+ line: lineOf(node)
374
+ });
375
+ const key = missedKey(code, node, names);
376
+ if (key !== void 0) usedKeys.push({
377
+ key,
378
+ file,
379
+ loose: true
380
+ });
381
+ }
322
382
  return {
323
- tagged,
324
- usedKeys,
325
- strayImports
383
+ analysis: {
384
+ tagged,
385
+ usedKeys,
386
+ strayImports,
387
+ missed
388
+ },
389
+ renamed: [...renamed]
326
390
  };
327
391
  }
392
+ function lineOf(node) {
393
+ return node.loc?.start.line ?? 1;
394
+ }
395
+ const VERBALY_SOURCE = /^(?:verbaly|virtual:verbaly|@verbaly\/[\w-]+(?:\/[\w-]+)*)$/;
396
+ const T_FACTORIES = /* @__PURE__ */ new Map([["useT", "call"], ["getT", "await"]]);
397
+ const INSTANCE_FACTORIES = /* @__PURE__ */ new Set(["useVerbaly", "getVerbaly"]);
398
+ var Bindings = class {
399
+ names;
400
+ imports = /* @__PURE__ */ new Map();
401
+ direct = /* @__PURE__ */ new Set();
402
+ declared = [];
403
+ destructured = [];
404
+ constructor(names) {
405
+ this.names = names;
406
+ }
407
+ addImport(node) {
408
+ const source = node.source.value;
409
+ if (typeof source !== "string") return;
410
+ for (const spec of node.specifiers) {
411
+ const local = identifierName(spec.local);
412
+ if (!local) continue;
413
+ const imported = spec.type === "ImportSpecifier" ? importedName(spec.imported) : spec.type;
414
+ this.imports.set(local, {
415
+ source,
416
+ imported
417
+ });
418
+ if (source === "virtual:verbaly" && imported === "t") this.direct.add(local);
419
+ }
420
+ }
421
+ addDeclarator(node) {
422
+ const id = node.id;
423
+ const init = node.init;
424
+ if (!init) return;
425
+ if (id.type === "Identifier") {
426
+ this.declared.push({
427
+ name: id.name,
428
+ init
429
+ });
430
+ return;
431
+ }
432
+ if (id.type !== "ObjectPattern") return;
433
+ for (const property of id.properties) {
434
+ if (property.type !== "ObjectProperty" || property.computed) continue;
435
+ if (identifierName(property.key) !== "t") continue;
436
+ const value = property.value;
437
+ const name = identifierName(value.type === "AssignmentPattern" ? value.left : value);
438
+ if (name) this.destructured.push({
439
+ name,
440
+ init
441
+ });
442
+ }
443
+ }
444
+ renamed(seed = []) {
445
+ const out = new Set(seed);
446
+ const add = (name) => {
447
+ if (this.names.has(name)) return;
448
+ out.add(name);
449
+ if (this.names.has("$t")) out.add(`$${name}`);
450
+ };
451
+ for (const name of this.direct) add(name);
452
+ for (const { name, init } of this.declared) if (this.handsOutT(init)) add(name);
453
+ for (const { name, init } of this.destructured) if (this.carriesT(init)) add(name);
454
+ return out;
455
+ }
456
+ handsOutT(init) {
457
+ const awaited = init.type === "AwaitExpression";
458
+ const call = awaited ? init.argument : init;
459
+ if (call.type !== "CallExpression") return false;
460
+ const origin = this.origin(identifierName(call.callee));
461
+ if (origin.verbaly === false) return false;
462
+ const how = T_FACTORIES.get(origin.imported);
463
+ return how !== void 0 && how === "await" === awaited;
464
+ }
465
+ carriesT(init) {
466
+ const inner = init.type === "AwaitExpression" ? init.argument : init;
467
+ const name = identifierName(inner.type === "CallExpression" ? inner.callee : inner);
468
+ if (!name) return false;
469
+ return this.origin(name).verbaly ?? INSTANCE_FACTORIES.has(name);
470
+ }
471
+ origin(local) {
472
+ const found = this.imports.get(local);
473
+ if (!found) return {
474
+ verbaly: void 0,
475
+ imported: local
476
+ };
477
+ return {
478
+ verbaly: VERBALY_SOURCE.test(found.source),
479
+ imported: found.imported
480
+ };
481
+ }
482
+ };
483
+ function importedName(node) {
484
+ return node.type === "StringLiteral" ? node.value : identifierName(node);
485
+ }
486
+ function identifierName(node) {
487
+ return node?.type === "Identifier" ? node.name : "";
488
+ }
489
+ function renamedTag(tag, renamed) {
490
+ if (renamed.size === 0) return void 0;
491
+ const name = identifierName(tag);
492
+ if (renamed.has(name)) return name;
493
+ if (tag.type !== "CallExpression") return void 0;
494
+ const callee = tag.callee;
495
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
496
+ if (identifierName(callee.property) !== "id") return void 0;
497
+ const object = identifierName(callee.object);
498
+ return renamed.has(object) ? object : void 0;
499
+ }
500
+ function missedKey(code, node, names) {
501
+ const tag = node.tag;
502
+ if (tag.type === "CallExpression") {
503
+ const args = tag.arguments;
504
+ const first = args[0];
505
+ return args.length === 1 && first?.type === "StringLiteral" ? first.value : void 0;
506
+ }
507
+ const message = buildMessage(code, node.quasi, names);
508
+ return message ? stableKey(message.text) : void 0;
509
+ }
328
510
  function collectDeclaredKeys(node, file, out) {
329
511
  if (node?.type !== "ObjectExpression") return;
330
512
  for (const property of node.properties) {
@@ -381,6 +563,7 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
381
563
  params: built.params,
382
564
  start: node.start,
383
565
  end: node.end,
566
+ line: lineOf(node),
384
567
  tagStart: nameNode.start,
385
568
  tagEnd: nameNode.end,
386
569
  file,
@@ -586,6 +769,7 @@ function analyzeFile(code, file) {
586
769
  tagged: [],
587
770
  usedKeys: [],
588
771
  strayImports: [],
772
+ missed: [],
589
773
  parseError: parseErrorMessage(error)
590
774
  };
591
775
  }
@@ -594,55 +778,63 @@ const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
594
778
  const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
595
779
  const COMMENT_RE = /<!--[\s\S]*?-->/g;
596
780
  const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
597
- const CANDIDATE_SVELTE = /(?<![\w$])\$?t(?=[`(]|\.id\()/g;
598
- const CANDIDATE_VUE = /(?<![\w$])t(?=[`(]|\.id\()/g;
599
781
  const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
600
782
  const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
601
783
  function analyzeSfc(code, file) {
602
784
  const svelte = file.endsWith(".svelte");
603
- const options = svelte ? { tNames: ["t", "$t"] } : void 0;
785
+ const tNames = svelte ? ["t", "$t"] : ["t"];
604
786
  const tagged = [];
605
787
  const usedKeys = [];
606
788
  const strayImports = [];
789
+ const missed = [];
790
+ const renamed = /* @__PURE__ */ new Set();
791
+ const lineAt = lineCounter(code);
607
792
  let parseError;
608
- const block = (segment, offset) => {
793
+ const block = (content, offset) => {
794
+ const segment = analyzeSegment(content, file, { tNames });
609
795
  parseError ??= segment.error;
796
+ for (const name of segment.renamed) renamed.add(name);
610
797
  merge(segment.analysis, offset, false);
611
798
  };
612
799
  const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
613
- if (frontmatter?.[2]) block(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length);
800
+ if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1].length);
614
801
  for (const match of code.matchAll(SCRIPT_RE)) {
615
802
  const content = match[2];
616
- if (!content) continue;
617
- block(analyzeSegment(content, file, options), match.index + match[1].length);
803
+ if (content) block(content, match.index + match[1].length);
618
804
  }
619
805
  const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
620
- const candidates = svelte ? CANDIDATE_SVELTE : CANDIDATE_VUE;
806
+ const markupOptions = {
807
+ tNames,
808
+ renamed: [...renamed]
809
+ };
621
810
  const ranges = file.endsWith(".vue") ? vueExpressionRanges(markup) : braceRanges(markup);
622
811
  let range = 0;
623
812
  let consumedTo = 0;
624
- for (const match of markup.matchAll(candidates)) {
813
+ for (const match of markup.matchAll(candidatePattern(svelte, renamed))) {
625
814
  const start = match.index;
626
815
  if (start < consumedTo) continue;
627
816
  while (range < ranges.length && ranges[range][1] <= start) range += 1;
628
817
  if (range >= ranges.length || start < ranges[range][0]) continue;
629
- const end = expressionExtent(markup, start);
818
+ const end = expressionExtent(markup, start, match[0].length);
630
819
  if (end === void 0) continue;
631
- merge(analyzeSegment(code.slice(start, end), file, options).analysis, start, true);
820
+ merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);
632
821
  consumedTo = end;
633
822
  }
634
823
  return {
635
824
  tagged,
636
825
  usedKeys,
637
826
  strayImports,
827
+ missed,
638
828
  ...parseError && { parseError }
639
829
  };
640
830
  function merge(analysis, offset, markupSegment) {
641
831
  if (!analysis) return;
832
+ const lines = lineAt(offset) - 1;
642
833
  for (const msg of analysis.tagged) tagged.push({
643
834
  ...msg,
644
835
  start: msg.start + offset,
645
836
  end: msg.end + offset,
837
+ line: msg.line + lines,
646
838
  tagStart: msg.tagStart + offset,
647
839
  tagEnd: msg.tagEnd + offset,
648
840
  params: msg.params.map((p) => ({
@@ -652,15 +844,41 @@ function analyzeSfc(code, file) {
652
844
  })),
653
845
  ...markupSegment && { singleQuote: true }
654
846
  });
847
+ for (const call of analysis.missed) missed.push({
848
+ ...call,
849
+ start: call.start + offset,
850
+ line: call.line + lines
851
+ });
655
852
  usedKeys.push(...analysis.usedKeys);
656
853
  strayImports.push(...analysis.strayImports);
657
854
  }
658
855
  }
856
+ function candidatePattern(svelte, renamed) {
857
+ const names = [.../* @__PURE__ */ new Set(["t", ...[...renamed].map((name) => name.replace(/^\$/, ""))])].map((name) => name.replace(/[$]/g, "\\$")).join("|");
858
+ return new RegExp(`(?<![\\w$])${svelte ? "\\$?" : ""}(?:${names})(?=[\`(]|\\.id\\()`, "g");
859
+ }
860
+ function lineCounter(code) {
861
+ const breaks = [];
862
+ for (let i = code.indexOf("\n"); i !== -1; i = code.indexOf("\n", i + 1)) breaks.push(i);
863
+ return (offset) => {
864
+ let low = 0;
865
+ let high = breaks.length;
866
+ while (low < high) {
867
+ const mid = low + high >> 1;
868
+ if (breaks[mid] < offset) low = mid + 1;
869
+ else high = mid;
870
+ }
871
+ return low + 1;
872
+ };
873
+ }
659
874
  function analyzeSegment(code, file, options) {
660
875
  try {
661
- return { analysis: analyze(code, file, options) };
876
+ return analyzeScript(code, file, options);
662
877
  } catch (error) {
663
- return { error: parseErrorMessage(error) };
878
+ return {
879
+ renamed: [],
880
+ error: parseErrorMessage(error)
881
+ };
664
882
  }
665
883
  }
666
884
  function blank(source, re) {
@@ -691,10 +909,8 @@ function vueExpressionRanges(markup) {
691
909
  }
692
910
  return ranges.sort((a, b) => a[0] - b[0]);
693
911
  }
694
- function expressionExtent(code, start) {
695
- let i = start;
696
- if (code[i] === "$") i += 1;
697
- i += 1;
912
+ function expressionExtent(code, start, nameLength) {
913
+ const i = start + nameLength;
698
914
  if (code.startsWith(".id(", i)) {
699
915
  const close = balancedEnd(code, i + 3);
700
916
  if (close === void 0 || code[close] !== "`") return void 0;
@@ -741,7 +957,7 @@ async function extractProject(cfg) {
741
957
  absolute: true
742
958
  });
743
959
  const registry = new MessageRegistry();
744
- for (const file of files) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
960
+ for (const file of files.sort()) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
745
961
  return registry;
746
962
  }
747
963
  async function collectOrigins(cfg, reuse) {
@@ -752,10 +968,17 @@ async function collectOrigins(cfg, reuse) {
752
968
  }
753
969
  function syncCatalogs(cfg, catalogs, registry) {
754
970
  const added = {};
971
+ const replaced = [];
755
972
  const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
756
- for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) {
973
+ for (const [key, msg] of registry.messages()) {
974
+ const before = own(source, key);
975
+ if (before === msg.message) continue;
757
976
  source[key] = msg.message;
758
- (added[cfg.sourceLocale] ??= []).push(key);
977
+ if (before) replaced.push({
978
+ key,
979
+ before
980
+ });
981
+ else (added[cfg.sourceLocale] ??= []).push(key);
759
982
  }
760
983
  const needed = Object.keys(source);
761
984
  for (const locale of cfg.locales) {
@@ -766,7 +989,18 @@ function syncCatalogs(cfg, catalogs, registry) {
766
989
  (added[locale] ??= []).push(key);
767
990
  }
768
991
  }
769
- return { added };
992
+ return {
993
+ added,
994
+ replaced
995
+ };
996
+ }
997
+ function shippedCatalogs(cfg, catalogs, registry, options = {}) {
998
+ const source = Object.assign(emptyCatalog(), flatten(catalogs[cfg.sourceLocale] ?? {}));
999
+ for (const [key, msg] of registry.messages()) if (options.newKeys !== false || own(source, key) !== void 0) source[key] = msg.message;
1000
+ return {
1001
+ ...catalogs,
1002
+ [cfg.sourceLocale]: source
1003
+ };
770
1004
  }
771
1005
  function pruneCatalogs(cfg, catalogs, registry) {
772
1006
  const removed = {};
@@ -1178,6 +1412,401 @@ function writeDts(cfg, catalog, file) {
1178
1412
  writeFileSync(file, content);
1179
1413
  }
1180
1414
  //#endregion
1415
+ //#region src/findings.ts
1416
+ function siteOf(msg) {
1417
+ return {
1418
+ file: msg.file,
1419
+ line: msg.line,
1420
+ message: msg.message
1421
+ };
1422
+ }
1423
+ function collisionEntries(registry) {
1424
+ return registry.collisions().map(({ key, kept, dropped }) => ({
1425
+ key,
1426
+ sites: [kept, ...dropped].map(siteOf)
1427
+ }));
1428
+ }
1429
+ function scanFindings(cfg, registry, replaced = []) {
1430
+ const messages = registry.messages();
1431
+ const out = [];
1432
+ for (const { key, before } of replaced) {
1433
+ const msg = messages.get(key);
1434
+ if (msg) out.push({
1435
+ kind: "replaced",
1436
+ locale: cfg.sourceLocale,
1437
+ key,
1438
+ before,
1439
+ site: siteOf(msg)
1440
+ });
1441
+ }
1442
+ for (const entry of collisionEntries(registry)) out.push({
1443
+ kind: "collision",
1444
+ ...entry
1445
+ });
1446
+ for (const { name, file, line } of registry.missed()) out.push({
1447
+ kind: "renamed",
1448
+ name,
1449
+ file,
1450
+ line
1451
+ });
1452
+ for (const msg of messages.values()) {
1453
+ const params = msg.params.map((param) => param.name).filter((name) => /^_\d+$/.test(name));
1454
+ if (params.length > 0) out.push({
1455
+ kind: "positional",
1456
+ params,
1457
+ site: siteOf(msg)
1458
+ });
1459
+ const slice = escapedSyntax(msg.message);
1460
+ if (slice) out.push({
1461
+ kind: "escaped",
1462
+ slice,
1463
+ site: siteOf(msg)
1464
+ });
1465
+ }
1466
+ for (const { file, message } of registry.parseErrors()) out.push({
1467
+ kind: "unparsed",
1468
+ file,
1469
+ message
1470
+ });
1471
+ return out;
1472
+ }
1473
+ function sourcePlace(at, root) {
1474
+ const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
1475
+ return at.line ? `${file}:${at.line}` : file;
1476
+ }
1477
+ function quoted(at, root) {
1478
+ return `"${truncate(at.message, 40)}" (${sourcePlace(at, root)})`;
1479
+ }
1480
+ function formatCollision({ key, sites }, root) {
1481
+ const [kept, ...others] = sites;
1482
+ const texts = new Set(sites.map((at) => at.message)).size;
1483
+ return `${key}: one key with ${counted(texts, "text")}, and every place shows ${quoted(kept, root)}, never ${others.map((at) => quoted(at, root)).join(" or ")}: give each text its own key`;
1484
+ }
1485
+ function formatFinding(finding, root) {
1486
+ switch (finding.kind) {
1487
+ case "collision": return formatCollision(finding, root);
1488
+ case "replaced": {
1489
+ const place = sourcePlace(finding.site, root);
1490
+ return finding.edited ? `${finding.locale}.json: your edit of "${finding.key}" was replaced, its text lives in ${place}: change it there` : `${finding.locale}: ${finding.key} follows the code (${place}): "${truncate(finding.site.message, 40)}", was "${truncate(finding.before, 40)}"`;
1491
+ }
1492
+ case "renamed": return `${sourcePlace(finding, root)}: ${finding.name}\`…\` is never extracted, so it stays in the source language: name it t`;
1493
+ case "positional": {
1494
+ const names = finding.params.map((name) => `{${name}}`).join(", ");
1495
+ return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
1496
+ }
1497
+ case "escaped": return `${sourcePlace(finding.site, root)}: ${finding.slice} renders as literal text, a tagged template has no params (use t(key, params) for a plural or format block, or pass a \${…} value)`;
1498
+ case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
1499
+ case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
1500
+ }
1501
+ }
1502
+ function findingId(finding) {
1503
+ switch (finding.kind) {
1504
+ case "collision":
1505
+ case "replaced": return `${finding.kind}:${finding.key}`;
1506
+ case "outdated": return `outdated:${finding.locale}:${finding.key}`;
1507
+ case "renamed": return `renamed:${finding.file}:${finding.name}`;
1508
+ case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
1509
+ case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
1510
+ case "unparsed": return `unparsed:${finding.file}`;
1511
+ }
1512
+ }
1513
+ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
1514
+ const shown = /* @__PURE__ */ new Map();
1515
+ return { report(channel, findings) {
1516
+ const before = shown.get(channel) ?? /* @__PURE__ */ new Set();
1517
+ const now = /* @__PURE__ */ new Set();
1518
+ const fresh = [];
1519
+ for (const finding of findings) {
1520
+ const id = findingId(finding);
1521
+ if (now.has(id)) continue;
1522
+ now.add(id);
1523
+ if (!before.has(id)) fresh.push(finding);
1524
+ }
1525
+ shown.set(channel, now);
1526
+ for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));
1527
+ if (fresh.length > cap) print(`and ${fresh.length - cap} more: \`npx verbaly doctor\` names them`);
1528
+ } };
1529
+ }
1530
+ //#endregion
1531
+ //#region src/state.ts
1532
+ const STATE_FILE = ".verbaly-state.json";
1533
+ const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
1534
+ function statePath(cfg, file = STATE_FILE) {
1535
+ return join(cfg.dir, file);
1536
+ }
1537
+ function loadState(cfg) {
1538
+ const current = readJson(statePath(cfg));
1539
+ if (current !== void 0 && !isObject(current)) throw corrupt(statePath(cfg));
1540
+ const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));
1541
+ if (legacy !== void 0 && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));
1542
+ const state = isObject(current) ? {
1543
+ drafts: readDrafts(current.drafts),
1544
+ fingerprints: readFingerprints(current.fingerprints)
1545
+ } : {
1546
+ drafts: {},
1547
+ fingerprints: {}
1548
+ };
1549
+ if (legacy !== void 0) for (const [locale, keys] of Object.entries(readDrafts(legacy))) markDrafts(state.drafts, locale, keys);
1550
+ return state;
1551
+ }
1552
+ function readState(cfg) {
1553
+ try {
1554
+ return { state: loadState(cfg) };
1555
+ } catch (error) {
1556
+ return {
1557
+ state: {
1558
+ drafts: {},
1559
+ fingerprints: {}
1560
+ },
1561
+ problem: error.message.replace(/^\[verbaly\] /, "")
1562
+ };
1563
+ }
1564
+ }
1565
+ function saveState(cfg, state) {
1566
+ const serialized = serializeState(state);
1567
+ const path = statePath(cfg);
1568
+ const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1569
+ if (serialized === void 0) {
1570
+ rmSync(path, { force: true });
1571
+ rmSync(legacy, { force: true });
1572
+ return;
1573
+ }
1574
+ let existing;
1575
+ try {
1576
+ existing = readFileSync(path, "utf8");
1577
+ } catch {
1578
+ mkdirSync(cfg.dir, { recursive: true });
1579
+ }
1580
+ if (existing !== serialized) writeFileSync(path, serialized);
1581
+ if (existsSync(legacy)) rmSync(legacy);
1582
+ }
1583
+ function updateState(cfg, catalogs) {
1584
+ const next = refreshState(cfg, catalogs, loadState(cfg));
1585
+ saveState(cfg, next);
1586
+ return next;
1587
+ }
1588
+ function refreshState(cfg, catalogs, previous) {
1589
+ const flat = flatCatalogs(catalogs);
1590
+ const source = flat[cfg.sourceLocale] ?? {};
1591
+ const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
1592
+ const drafts = {};
1593
+ for (const [locale, keys] of Object.entries(previous.drafts)) {
1594
+ if (!shown.has(locale)) {
1595
+ drafts[locale] = keys;
1596
+ continue;
1597
+ }
1598
+ const live = keys.filter((key) => own(flat[locale], key));
1599
+ if (live.length) drafts[locale] = live;
1600
+ }
1601
+ const fingerprints = {};
1602
+ for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
1603
+ for (const locale of shown) {
1604
+ const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
1605
+ if (Object.keys(stamps).length) fingerprints[locale] = stamps;
1606
+ }
1607
+ return {
1608
+ drafts,
1609
+ fingerprints
1610
+ };
1611
+ }
1612
+ function refreshStamps(source, catalog, before) {
1613
+ const after = emptyCatalog();
1614
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
1615
+ const translated = own(catalog, key);
1616
+ if (!translated) continue;
1617
+ const was = own(before, key);
1618
+ if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
1619
+ after[key] = was;
1620
+ continue;
1621
+ }
1622
+ const text = own(source, key);
1623
+ if (text && tracked(key, text)) after[key] = stamp(text, translated);
1624
+ else if (was !== void 0) after[key] = was;
1625
+ }
1626
+ return after;
1627
+ }
1628
+ function recordTranslations(cfg, source, writes) {
1629
+ const state = loadState(cfg);
1630
+ for (const { locale, entries, draft } of writes) {
1631
+ if (entries.length === 0) continue;
1632
+ const stamps = state.fingerprints[locale] ??= emptyCatalog();
1633
+ for (const entry of entries) {
1634
+ const from = entry.source || own(source, entry.key);
1635
+ if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
1636
+ }
1637
+ const keys = entries.map((entry) => entry.key);
1638
+ if (draft === true) markDrafts(state.drafts, locale, keys);
1639
+ else if (draft === false) clearDrafts(state.drafts, locale, keys);
1640
+ }
1641
+ saveState(cfg, state);
1642
+ return state;
1643
+ }
1644
+ function effectiveDrafts(drafts, catalogs) {
1645
+ const out = {};
1646
+ for (const [locale, keys] of Object.entries(drafts)) {
1647
+ const catalog = catalogs[locale] ?? {};
1648
+ const live = keys.filter((key) => own(catalog, key));
1649
+ if (live.length) out[locale] = live;
1650
+ }
1651
+ return out;
1652
+ }
1653
+ function markDrafts(drafts, locale, keys) {
1654
+ if (!keys.length) return;
1655
+ drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1656
+ }
1657
+ function clearDrafts(drafts, locale, keys) {
1658
+ if (!drafts[locale]) return;
1659
+ if (!keys) {
1660
+ delete drafts[locale];
1661
+ return;
1662
+ }
1663
+ const drop = new Set(keys);
1664
+ drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1665
+ if (!drafts[locale].length) delete drafts[locale];
1666
+ }
1667
+ function fingerprint(text) {
1668
+ return stableKey(text);
1669
+ }
1670
+ function tracked(key, text) {
1671
+ return stableKey(text) !== key;
1672
+ }
1673
+ function stamp(source, translated) {
1674
+ return `${fingerprint(source)}.${fingerprint(translated)}`;
1675
+ }
1676
+ function outdatedTranslations(cfg, catalogs, fingerprints) {
1677
+ const source = catalogs[cfg.sourceLocale] ?? {};
1678
+ const out = [];
1679
+ for (const locale of targetLocales(cfg)) {
1680
+ const catalog = catalogs[locale] ?? {};
1681
+ for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
1682
+ const text = own(source, key);
1683
+ const translated = own(catalog, key);
1684
+ if (!text || !translated) continue;
1685
+ if (translationOf(was) !== fingerprint(translated)) continue;
1686
+ if (sourceOf(was) !== fingerprint(text)) out.push({
1687
+ locale,
1688
+ key
1689
+ });
1690
+ }
1691
+ }
1692
+ return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
1693
+ }
1694
+ function sourceOf(stamped) {
1695
+ return stamped.slice(0, stamped.indexOf("."));
1696
+ }
1697
+ function translationOf(stamped) {
1698
+ return stamped.slice(stamped.indexOf(".") + 1);
1699
+ }
1700
+ function flatCatalogs(catalogs) {
1701
+ const out = {};
1702
+ for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
1703
+ return out;
1704
+ }
1705
+ function serializeState(state) {
1706
+ const drafts = {};
1707
+ for (const locale of Object.keys(state.drafts).sort()) {
1708
+ const keys = [...new Set(state.drafts[locale])].sort();
1709
+ if (keys.length) drafts[locale] = keys;
1710
+ }
1711
+ const fingerprints = {};
1712
+ for (const locale of Object.keys(state.fingerprints).sort()) {
1713
+ const entries = state.fingerprints[locale] ?? {};
1714
+ const keys = Object.keys(entries).sort();
1715
+ if (!keys.length) continue;
1716
+ fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]]));
1717
+ }
1718
+ const out = {};
1719
+ if (Object.keys(drafts).length) out.drafts = drafts;
1720
+ if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;
1721
+ if (!out.drafts && !out.fingerprints) return void 0;
1722
+ return JSON.stringify(out, null, 2) + "\n";
1723
+ }
1724
+ function readJson(path) {
1725
+ let content;
1726
+ try {
1727
+ content = readFileSync(path, "utf8");
1728
+ } catch {
1729
+ return;
1730
+ }
1731
+ try {
1732
+ return JSON.parse(content.charCodeAt(0) === 65279 ? content.slice(1) : content);
1733
+ } catch (error) {
1734
+ throw corrupt(path, error);
1735
+ }
1736
+ }
1737
+ function corrupt(path, cause) {
1738
+ return new Error(`[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
1739
+ }
1740
+ function isObject(value) {
1741
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1742
+ }
1743
+ function readDrafts(value) {
1744
+ const out = {};
1745
+ if (!isObject(value)) return out;
1746
+ for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
1747
+ return out;
1748
+ }
1749
+ function readFingerprints(value) {
1750
+ const out = {};
1751
+ if (!isObject(value)) return out;
1752
+ for (const [locale, entries] of Object.entries(value)) {
1753
+ if (!isObject(entries)) continue;
1754
+ const kept = emptyCatalog();
1755
+ for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
1756
+ out[locale] = kept;
1757
+ }
1758
+ return out;
1759
+ }
1760
+ //#endregion
1761
+ //#region src/project.ts
1762
+ async function syncProject(cfg, options = {}) {
1763
+ const registry = options.registry ?? await extractProject(cfg);
1764
+ const catalogs = options.catalogs ?? loadCatalogs(cfg);
1765
+ if (options.confirm) confirmFromDisk(cfg, catalogs, registry);
1766
+ const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;
1767
+ const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};
1768
+ const { added, replaced } = syncCatalogs(cfg, catalogs, registry);
1769
+ const result = {
1770
+ registry,
1771
+ catalogs,
1772
+ added,
1773
+ replaced,
1774
+ pruned,
1775
+ pruneBlocked,
1776
+ findings: scanFindings(cfg, registry, replaced),
1777
+ written: {}
1778
+ };
1779
+ if (options.dryRun) return result;
1780
+ const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
1781
+ if (replaced.length > 0) changed.add(cfg.sourceLocale);
1782
+ for (const locale of cfg.locales) {
1783
+ if (options.write === "changed" && !changed.has(locale)) continue;
1784
+ result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
1785
+ }
1786
+ writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
1787
+ try {
1788
+ result.state = updateState(cfg, catalogs);
1789
+ } catch (error) {
1790
+ result.stateProblem = error.message.replace(/^\[verbaly\] /, "");
1791
+ }
1792
+ return result;
1793
+ }
1794
+ function confirmFromDisk(cfg, catalogs, registry) {
1795
+ const source = catalogs[cfg.sourceLocale] ?? {};
1796
+ const stale = /* @__PURE__ */ new Set();
1797
+ for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
1798
+ for (const file of stale) {
1799
+ let code;
1800
+ try {
1801
+ code = readFileSync(file, "utf8");
1802
+ } catch {
1803
+ registry.remove(file);
1804
+ continue;
1805
+ }
1806
+ registry.update(file, analyzeFile(code, file));
1807
+ }
1808
+ }
1809
+ //#endregion
1181
1810
  //#region src/tag.ts
1182
1811
  function isLocaleTag(tag) {
1183
1812
  try {
@@ -1354,11 +1983,16 @@ async function init(input = {}) {
1354
1983
  function gatePasses(result) {
1355
1984
  return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
1356
1985
  }
1357
- function check(cfg, catalogs, registry) {
1986
+ function warningCount(result) {
1987
+ return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.collisions.length + result.divergent.length + result.outdated.length;
1988
+ }
1989
+ function check(cfg, catalogs, registry, fingerprints = {}) {
1358
1990
  const extracted = registry.messages();
1359
1991
  const flat = {};
1360
1992
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1361
1993
  const source = flat[cfg.sourceLocale] ?? {};
1994
+ const shipped = shippedCatalogs(cfg, flat, registry);
1995
+ const sourceText = shipped[cfg.sourceLocale];
1362
1996
  const used = registry.usedKeys();
1363
1997
  const unknown = [];
1364
1998
  for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
@@ -1389,8 +2023,15 @@ function check(cfg, catalogs, registry) {
1389
2023
  issue: issue.message
1390
2024
  });
1391
2025
  };
1392
- const sourceText = Object.assign(emptyCatalog(), source);
1393
- for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
2026
+ const divergent = [];
2027
+ for (const [key, entry] of extracted) {
2028
+ const written = source[key];
2029
+ if (written && written !== entry.message) divergent.push({
2030
+ key,
2031
+ catalog: written,
2032
+ code: siteOf(entry)
2033
+ });
2034
+ }
1394
2035
  for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
1395
2036
  for (const locale of cfg.locales) {
1396
2037
  if (locale === cfg.sourceLocale) continue;
@@ -1422,7 +2063,10 @@ function check(cfg, catalogs, registry) {
1422
2063
  missing,
1423
2064
  unknown,
1424
2065
  broken,
1425
- extra
2066
+ extra,
2067
+ collisions: collisionEntries(registry),
2068
+ divergent,
2069
+ outdated: outdatedTranslations(cfg, shipped, fingerprints)
1426
2070
  };
1427
2071
  }
1428
2072
  function formatCheckResult(result, root) {
@@ -1454,13 +2098,30 @@ function checkNextSteps(result, cliReachable = true) {
1454
2098
  if (steps.length > 0 && !cliReachable) steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);
1455
2099
  return steps.join("\n");
1456
2100
  }
1457
- function formatCheckWarnings(result) {
2101
+ function formatCheckWarnings(result, root, options = {}) {
1458
2102
  const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
1459
2103
  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`);
2104
+ for (const entry of result.collisions) lines.push(` ${formatFinding({
2105
+ kind: "collision",
2106
+ ...entry
2107
+ }, root)}`);
2108
+ for (const { key, catalog, code } of result.divergent) lines.push(` ${key}: the source catalog says "${truncate(catalog, 40)}" and the code says "${truncate(code.message, 40)}" (${sourcePlace(code, root)}): the code wins, so edit the text there (extract writes it into the catalog)`);
2109
+ if (!options.outdatedFails) for (const entry of result.outdated) lines.push(` ${formatFinding({
2110
+ kind: "outdated",
2111
+ ...entry
2112
+ }, root)}`);
1460
2113
  return lines.join("\n");
1461
2114
  }
1462
- function truncate(text, max) {
1463
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
2115
+ //#endregion
2116
+ //#region src/warn.ts
2117
+ const warned = /* @__PURE__ */ new Set();
2118
+ function warnOnce(message, dedupeKey = message) {
2119
+ if (warned.has(dedupeKey)) return;
2120
+ warned.add(dedupeKey);
2121
+ console.warn(`[verbaly] ${message}`);
2122
+ }
2123
+ function warnParseError(file, message) {
2124
+ warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
1464
2125
  }
1465
2126
  //#endregion
1466
2127
  //#region src/transform.ts
@@ -1535,8 +2196,8 @@ function transformSource(code, id, registry) {
1535
2196
  function runBuildGate(cfg, registry, failOnMissing) {
1536
2197
  const catalogs = loadCatalogs(cfg);
1537
2198
  for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
1538
- const found = check(cfg, catalogs, registry);
1539
- const warnings = found.broken.filter((entry) => entry.severity === "warning").length + found.extra.length;
2199
+ const found = check(cfg, catalogs, registry, buildFingerprints(cfg));
2200
+ const warnings = warningCount(found);
1540
2201
  if (warnings > 0) warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: run \`npx verbaly check\` to read them`, "gate:warnings");
1541
2202
  const result = failOnMissing === false ? {
1542
2203
  ...found,
@@ -1545,75 +2206,34 @@ function runBuildGate(cfg, registry, failOnMissing) {
1545
2206
  if (gatePasses(result)) return;
1546
2207
  throw new Error(`[verbaly] build blocked\n${formatCheckResult(result, cfg.root)}\n${checkNextSteps(result, cliReachable(cfg.root))}`);
1547
2208
  }
2209
+ function buildFingerprints(cfg) {
2210
+ const { state, problem } = readState(cfg);
2211
+ if (problem) warnOnce(`${problem}, so outdated translations are not reported`, "gate:state");
2212
+ return state.fingerprints;
2213
+ }
1548
2214
  //#endregion
1549
2215
  //#region src/drafts.ts
1550
- const DRAFTS_FILE = ".verbaly-drafts.json";
1551
- function draftsPath(cfg) {
1552
- return join(cfg.dir, DRAFTS_FILE);
1553
- }
1554
2216
  function loadDrafts(cfg) {
1555
- let content;
1556
- try {
1557
- content = readFileSync(draftsPath(cfg), "utf8");
1558
- } catch {
1559
- return {};
1560
- }
1561
- try {
1562
- return JSON.parse(content.replace(/^\uFEFF/, ""));
1563
- } catch (error) {
1564
- throw new Error(`[verbaly] ${draftsPath(cfg)} is not valid JSON, fix or delete the file`, { cause: error });
1565
- }
1566
- }
1567
- function serializeDrafts(drafts) {
1568
- const sorted = {};
1569
- for (const locale of Object.keys(drafts).sort()) {
1570
- const keys = [...new Set(drafts[locale])].sort();
1571
- if (keys.length) sorted[locale] = keys;
1572
- }
1573
- return JSON.stringify(sorted, null, 2) + "\n";
2217
+ return loadState(cfg).drafts;
1574
2218
  }
1575
2219
  function saveDrafts(cfg, drafts) {
1576
- const serialized = serializeDrafts(drafts);
1577
- const path = draftsPath(cfg);
1578
- try {
1579
- if (readFileSync(path, "utf8") === serialized) return;
1580
- } catch {
1581
- mkdirSync(cfg.dir, { recursive: true });
1582
- }
1583
- writeFileSync(path, serialized);
1584
- }
1585
- function markDrafts(drafts, locale, keys) {
1586
- if (!keys.length) return;
1587
- drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
1588
- }
1589
- function clearDrafts(drafts, locale, keys) {
1590
- if (!drafts[locale]) return;
1591
- if (!keys) {
1592
- delete drafts[locale];
1593
- return;
1594
- }
1595
- const drop = new Set(keys);
1596
- drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
1597
- if (!drafts[locale].length) delete drafts[locale];
1598
- }
1599
- function effectiveDrafts(drafts, catalogs) {
1600
- const out = {};
1601
- for (const [locale, keys] of Object.entries(drafts)) {
1602
- const catalog = catalogs[locale] ?? {};
1603
- const live = keys.filter((key) => own(catalog, key));
1604
- if (live.length) out[locale] = live;
1605
- }
1606
- return out;
2220
+ saveState(cfg, {
2221
+ ...loadState(cfg),
2222
+ drafts
2223
+ });
1607
2224
  }
1608
2225
  //#endregion
1609
2226
  //#region src/status.ts
1610
- function status(cfg, catalogs, registry, drafts = {}) {
2227
+ function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
1611
2228
  const extracted = registry.messages();
1612
2229
  const flat = {};
1613
2230
  for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
1614
2231
  const source = flat[cfg.sourceLocale] ?? {};
1615
2232
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
1616
2233
  const live = effectiveDrafts(drafts, flat);
2234
+ const shipped = shippedCatalogs(cfg, flat, registry);
2235
+ const sourceText = shipped[cfg.sourceLocale];
2236
+ const outdated = outdatedTranslations(cfg, shipped, fingerprints);
1617
2237
  const locales = [];
1618
2238
  for (const locale of cfg.locales) {
1619
2239
  if (locale === cfg.sourceLocale) continue;
@@ -1623,7 +2243,7 @@ function status(cfg, catalogs, registry, drafts = {}) {
1623
2243
  let broken = 0;
1624
2244
  for (const [key, text] of Object.entries(catalog)) {
1625
2245
  if (!text) continue;
1626
- const from = source[key] ?? extracted.get(key)?.message;
2246
+ const from = sourceText[key];
1627
2247
  if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
1628
2248
  }
1629
2249
  locales.push({
@@ -1631,7 +2251,8 @@ function status(cfg, catalogs, registry, drafts = {}) {
1631
2251
  translated,
1632
2252
  total: needed.size,
1633
2253
  drafts: live[locale]?.length ?? 0,
1634
- broken
2254
+ broken,
2255
+ outdated: outdated.filter((entry) => entry.locale === locale).length
1635
2256
  });
1636
2257
  }
1637
2258
  return {
@@ -1646,10 +2267,14 @@ function formatStatusResult(result) {
1646
2267
  lines.push(" no target locales (add locales to your config)");
1647
2268
  return lines.join("\n");
1648
2269
  }
1649
- for (const { locale, translated, total, drafts, broken } of result.locales) {
2270
+ for (const { locale, translated, total, drafts, broken, outdated } of result.locales) {
1650
2271
  const pct = total === 0 ? 100 : Math.floor(translated / total * 100);
1651
- const mark = translated === total && broken === 0 ? " ✓" : "";
1652
- const notes = [drafts > 0 ? `${drafts} unreviewed` : "", broken > 0 ? `${broken} broken` : ""].filter(Boolean);
2272
+ const mark = translated === total && broken === 0 && outdated === 0 ? " ✓" : "";
2273
+ const notes = [
2274
+ drafts > 0 ? `${drafts} unreviewed` : "",
2275
+ broken > 0 ? `${broken} broken` : "",
2276
+ outdated > 0 ? `${outdated} outdated` : ""
2277
+ ].filter(Boolean);
1653
2278
  const note = notes.length > 0 ? `, ${notes.join(", ")}` : "";
1654
2279
  lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);
1655
2280
  }
@@ -1781,6 +2406,16 @@ async function doctor(cfg) {
1781
2406
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1782
2407
  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");
1783
2408
  }
2409
+ const missed = registry.missed();
2410
+ if (missed.length > 0) {
2411
+ const first = missed[0];
2412
+ warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
2413
+ }
2414
+ const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
2415
+ if (positional.length > 0) {
2416
+ const first = positional[0];
2417
+ warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
2418
+ }
1784
2419
  const escaped = [...registry.messages().values()].map((msg) => ({
1785
2420
  file: rel(msg.file),
1786
2421
  slice: escapedSyntax(msg.message)
@@ -1801,8 +2436,17 @@ async function doctor(cfg) {
1801
2436
  for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
1802
2437
  if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
1803
2438
  }
2439
+ const { state, problem } = readState(cfg);
2440
+ if (problem) warn("state", problem, `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
1804
2441
  if (catalogsHealthy) {
1805
- const result = check(cfg, catalogs, registry);
2442
+ const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
2443
+ const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
2444
+ return keys.filter((key) => !live.has(key)).map((key) => `${locale}: ${key}`);
2445
+ });
2446
+ 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");
2447
+ }
2448
+ if (catalogsHealthy) {
2449
+ const result = check(cfg, catalogs, registry, state.fingerprints);
1806
2450
  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)");
1807
2451
  if (result.missing.length > 0) {
1808
2452
  const locales = [...new Set(result.missing.map((m) => m.locale))];
@@ -1819,6 +2463,18 @@ async function doctor(cfg) {
1819
2463
  }
1820
2464
  const warnings = result.broken.filter((entry) => entry.severity === "warning");
1821
2465
  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");
2466
+ if (result.collisions.length > 0) {
2467
+ const first = result.collisions[0];
2468
+ 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)");
2469
+ }
2470
+ if (result.divergent.length > 0) {
2471
+ const first = result.divergent[0];
2472
+ 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");
2473
+ }
2474
+ if (result.outdated.length > 0) {
2475
+ const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
2476
+ 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`");
2477
+ }
1822
2478
  if (result.ok) ok("translations", "all translations complete");
1823
2479
  }
1824
2480
  return {
@@ -1959,6 +2615,42 @@ function mergeTranslations(cfg, locale, translated, keys) {
1959
2615
  if (written.length > 0) writeCatalog(cfg, locale, current);
1960
2616
  return written;
1961
2617
  }
2618
+ function writeDrafts(cfg, locale, entries, options = {}) {
2619
+ const targets = targetLocales(cfg);
2620
+ if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
2621
+ loadState(cfg);
2622
+ const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
2623
+ const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
2624
+ const current = readCatalog(cfg, locale);
2625
+ const result = {
2626
+ written: [],
2627
+ kept: [],
2628
+ invalid: [],
2629
+ unknown: []
2630
+ };
2631
+ for (const { key, text } of entries) {
2632
+ const from = own(source, key);
2633
+ if (!from) result.unknown.push(key);
2634
+ else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);
2635
+ else if (own(current, key) && !options.overwrite) result.kept.push(key);
2636
+ else {
2637
+ current[key] = text;
2638
+ result.written.push(key);
2639
+ }
2640
+ }
2641
+ if (result.written.length > 0) {
2642
+ writeCatalog(cfg, locale, current);
2643
+ recordTranslations(cfg, source, [{
2644
+ locale,
2645
+ entries: result.written.map((key) => ({
2646
+ key,
2647
+ text: current[key]
2648
+ })),
2649
+ draft: true
2650
+ }]);
2651
+ }
2652
+ return result;
2653
+ }
1962
2654
  function formatTranslateFailures(failed) {
1963
2655
  const grouped = [];
1964
2656
  for (const entry of failed) {
@@ -1974,7 +2666,7 @@ function formatTranslateFailures(failed) {
1974
2666
  async function resolveProvider(cfg, model) {
1975
2667
  const configured = cfg.translate.provider;
1976
2668
  if (typeof configured === "function") return configured;
1977
- const { claudeProvider } = await import("./claude-D-j-ZiYH.js");
2669
+ const { claudeProvider } = await import("./claude-BFIWiu_4.js");
1978
2670
  return claudeProvider({ model: model ?? cfg.translate.model });
1979
2671
  }
1980
2672
  function structureMatches(source, translated) {
@@ -2776,6 +3468,6 @@ function formatCliError(error) {
2776
3468
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
2777
3469
  }
2778
3470
  //#endregion
2779
- 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 };
3471
+ export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, STATE_FILE, check, clearDrafts, clientCatalogs, collectOrigins, collisionEntries, counted, createDevReporter, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatCliError, formatCollision, formatDoctorEntry, formatFinding, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadState, loadVirtualModule, markDrafts, mergeTranslations, needsIcu, needsRelative, outdatedTranslations, parseCatalog, pruneCatalogs, readCatalog, readState, recordTranslations, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, shippedCatalogs, stableKey, status, syncCatalogs, syncProject, targetLocales, transformCode, transformSource, translateCatalogs, updateState, validateMessage, validatePair, watchTree, wrapProject, writeCatalog, writeDrafts, writeDts };
2780
3472
 
2781
3473
  //# sourceMappingURL=index.js.map