@verbaly/compiler 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -29,9 +29,15 @@ interface UsedKey {
29
29
  key: string;
30
30
  file: string;
31
31
  }
32
+ interface StrayImport {
33
+ name: string;
34
+ source: string;
35
+ file: string;
36
+ }
32
37
  interface Analysis {
33
38
  tagged: TaggedMessage[];
34
39
  usedKeys: UsedKey[];
40
+ strayImports: StrayImport[];
35
41
  }
36
42
  interface AnalyzeOptions {
37
43
  tNames?: readonly string[];
@@ -125,6 +131,7 @@ declare class MessageRegistry {
125
131
  remove(file: string): void;
126
132
  messages(): Map<string, TaggedMessage>;
127
133
  usedKeys(): Map<string, string[]>;
134
+ strayImports(): StrayImport[];
128
135
  origins(): Map<string, string[]>;
129
136
  }
130
137
  //#endregion
@@ -160,8 +167,10 @@ interface CheckResult {
160
167
  unknown: UnknownEntry[];
161
168
  broken: BrokenEntry[];
162
169
  }
170
+ declare function gatePasses(result: Omit<CheckResult, 'ok'>): boolean;
163
171
  declare function check(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): CheckResult;
164
172
  declare function formatCheckResult(result: CheckResult): string;
173
+ declare function checkNextSteps(result: CheckResult): string;
165
174
  declare function formatCheckWarnings(result: CheckResult): string;
166
175
  declare function githubCheckAnnotations(result: CheckResult, registry: MessageRegistry, root: string): string[];
167
176
  //#endregion
@@ -283,11 +292,19 @@ interface InitOptions {
283
292
  interface InitResult {
284
293
  created: string[];
285
294
  skipped: string[];
286
- bundler: 'astro' | 'vite' | 'webpack' | 'rollup' | 'rspack' | 'esbuild' | undefined;
295
+ host: Host | undefined;
287
296
  configFile: string;
288
297
  next: string[];
289
298
  }
290
- declare function detectBundler(root: string): InitResult['bundler'];
299
+ type Host = 'nuxt' | 'next' | 'sveltekit' | 'astro' | 'vite' | 'webpack' | 'rspack' | 'rollup' | 'esbuild';
300
+ interface HostSetup {
301
+ name: Host;
302
+ pkg: string;
303
+ wire: string;
304
+ }
305
+ declare const WIRING_PACKAGES: string[];
306
+ declare function readDependencies(root: string): Record<string, string>;
307
+ declare function detectHost(root: string): HostSetup | undefined;
291
308
  declare function init(options?: InitOptions): InitResult;
292
309
  //#endregion
293
310
  //#region src/key.d.ts
@@ -402,5 +419,5 @@ interface WrapCodeResult {
402
419
  }
403
420
  declare function wrapCode(code: string, file: string): WrapCodeResult;
404
421
  //#endregion
405
- export { type Alternate, type Analysis, type AnalyzeOptions, type BrokenEntry, type Catalog, type Catalogs, type CheckResult, type ClaudeProviderOptions, DRAFTS_FILE, type DoctorEntry, type DoctorResult, type Drafts, type ExchangeFormat, type ExportFormat, type ExportOptions, type ExportResult, type ExportedFile, type ImportOptions, type ImportResult, type InitOptions, type InitResult, type IssueSeverity, LOCALE_MODULE_PREFIX, type LocaleStatus, MessageRegistry, type MissingEntry, type MobileFormat, PLURAL_CATEGORIES, PSEUDO_LOCALE, type ParamType, type PluginOptions, RESOLVED_VIRTUAL_ID, type RenderConfig, type RenderHtmlOptions, type RenderHtmlResult, type RenderSiteOptions, type RenderSiteResult, type ResolvedConfig, type RuntimeModuleOptions, SFC_FILE_RE, SOURCE_FILE_RE, type StatusResult, type StructureIssue, type SyncResult, type TaggedMessage, type TaggedParam, type TransComponent, type TransformResult, type TranslateConfig, type TranslateOptions, type TranslateProvider, type TranslateRequest, type TranslateResult, type UnknownEntry, type UsedKey, VIRTUAL_ID, type VerbalyConfig, type WatchProjectOptions, type WrapCodeResult, type WrapEntry, type WrapOptions, type WrapResult, type WrapSkip, analyze, analyzeFile, analyzeSfc, catalogPath, check, claudeProvider, clearDrafts, collectOrigins, collectParams, createSourceFilter, detectBundler, doctor, effectiveDrafts, exportCatalogs, extractProject, findConfigFile, formatCheckResult, formatCheckWarnings, formatStatusResult, generateDts, generateLocaleModule, generateRuntimeModule, githubCheckAnnotations, importCatalogs, init, isMobileFormat, isTransformTarget, loadCatalogs, loadConfig, loadConfigFile, loadDrafts, loadVirtualModule, markDrafts, parseExchangeFile, pruneCatalogs, pseudoCatalogs, pseudoLocalize, readCatalog, renderHtml, renderParamType, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, serializeCatalog, stableKey, status, structureMatches, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, validateMessage, validatePair, watchProject, wrapCode, wrapProject, writeCatalog, writeDts };
422
+ export { type Alternate, type Analysis, type AnalyzeOptions, type BrokenEntry, type Catalog, type Catalogs, type CheckResult, type ClaudeProviderOptions, DRAFTS_FILE, type DoctorEntry, type DoctorResult, type Drafts, type ExchangeFormat, type ExportFormat, type ExportOptions, type ExportResult, type ExportedFile, type Host, type HostSetup, type ImportOptions, type ImportResult, type InitOptions, type InitResult, type IssueSeverity, LOCALE_MODULE_PREFIX, type LocaleStatus, MessageRegistry, type MissingEntry, type MobileFormat, PLURAL_CATEGORIES, PSEUDO_LOCALE, type ParamType, type PluginOptions, RESOLVED_VIRTUAL_ID, type RenderConfig, type RenderHtmlOptions, type RenderHtmlResult, type RenderSiteOptions, type RenderSiteResult, type ResolvedConfig, type RuntimeModuleOptions, SFC_FILE_RE, SOURCE_FILE_RE, type StatusResult, type StrayImport, type StructureIssue, type SyncResult, type TaggedMessage, type TaggedParam, type TransComponent, type TransformResult, type TranslateConfig, type TranslateOptions, type TranslateProvider, type TranslateRequest, type TranslateResult, type UnknownEntry, type UsedKey, VIRTUAL_ID, type VerbalyConfig, WIRING_PACKAGES, type WatchProjectOptions, type WrapCodeResult, type WrapEntry, type WrapOptions, type WrapResult, type WrapSkip, analyze, analyzeFile, analyzeSfc, catalogPath, check, checkNextSteps, claudeProvider, clearDrafts, collectOrigins, collectParams, createSourceFilter, detectHost, doctor, effectiveDrafts, exportCatalogs, extractProject, findConfigFile, formatCheckResult, formatCheckWarnings, formatStatusResult, gatePasses, generateDts, generateLocaleModule, generateRuntimeModule, githubCheckAnnotations, importCatalogs, init, isMobileFormat, isTransformTarget, loadCatalogs, loadConfig, loadConfigFile, loadDrafts, loadVirtualModule, markDrafts, parseExchangeFile, pruneCatalogs, pseudoCatalogs, pseudoLocalize, readCatalog, readDependencies, renderHtml, renderParamType, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, serializeCatalog, stableKey, status, structureMatches, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, validateMessage, validatePair, watchProject, wrapCode, wrapProject, writeCatalog, writeDts };
406
423
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -42,8 +42,10 @@ function analyze(code, file, options = {}) {
42
42
  });
43
43
  const tagged = [];
44
44
  const usedKeys = [];
45
+ const strayImports = [];
45
46
  walk$1(ast.program, (node) => {
46
- if (node.type === "TaggedTemplateExpression") {
47
+ if (node.type === "ImportDeclaration") collectStrayImports(node, file, strayImports);
48
+ else if (node.type === "TaggedTemplateExpression") {
47
49
  const tag = node.tag;
48
50
  const explicit = explicitId(tag, names);
49
51
  if (!explicit && !isTReference(tag, names)) return;
@@ -72,9 +74,24 @@ function analyze(code, file, options = {}) {
72
74
  });
73
75
  return {
74
76
  tagged,
75
- usedKeys
77
+ usedKeys,
78
+ strayImports
76
79
  };
77
80
  }
81
+ const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
82
+ function collectStrayImports(node, file, out) {
83
+ const source = node.source;
84
+ if (typeof source.value !== "string" || !VERBALY_PACKAGE.test(source.value)) return;
85
+ for (const spec of node.specifiers) {
86
+ if (spec.type !== "ImportSpecifier") continue;
87
+ const imported = spec.imported;
88
+ if (imported.type === "Identifier" && imported.name === "t") out.push({
89
+ name: "t",
90
+ source: source.value,
91
+ file
92
+ });
93
+ }
94
+ }
78
95
  function handleTrans(code, node, file, tagged, usedKeys, names) {
79
96
  const opening = node.openingElement;
80
97
  const nameNode = opening.name;
@@ -303,6 +320,7 @@ function analyzeSfc(code, file) {
303
320
  const options = svelte ? { tNames: ["t", "$t"] } : void 0;
304
321
  const tagged = [];
305
322
  const usedKeys = [];
323
+ const strayImports = [];
306
324
  const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
307
325
  if (frontmatter?.[2]) merge(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length, false);
308
326
  for (const match of code.matchAll(SCRIPT_RE)) {
@@ -327,7 +345,8 @@ function analyzeSfc(code, file) {
327
345
  }
328
346
  return {
329
347
  tagged,
330
- usedKeys
348
+ usedKeys,
349
+ strayImports
331
350
  };
332
351
  function merge(analysis, offset, markupSegment) {
333
352
  if (!analysis) return;
@@ -345,6 +364,7 @@ function analyzeSfc(code, file) {
345
364
  ...markupSegment && { singleQuote: true }
346
365
  });
347
366
  usedKeys.push(...analysis.usedKeys);
367
+ strayImports.push(...analysis.strayImports);
348
368
  }
349
369
  }
350
370
  function analyzeSegment(code, file, options) {
@@ -505,9 +525,14 @@ function collect(nodes, out) {
505
525
  }
506
526
  }
507
527
  const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
508
- function tagTokens(message) {
528
+ function markupNames(message) {
529
+ const out = /* @__PURE__ */ new Set();
530
+ for (const match of message.matchAll(TAG)) if (match[1] || match[3]) out.add(match[2]);
531
+ return out;
532
+ }
533
+ function tagTokens(message, markup) {
509
534
  const out = [];
510
- for (const match of message.matchAll(TAG)) out.push(`${match[1]}${match[2]}${match[3]}`);
535
+ for (const match of message.matchAll(TAG)) if (markup.has(match[2])) out.push(`${match[1]}${match[2]}${match[3]}`);
511
536
  return out.sort();
512
537
  }
513
538
  function surplus(a, b) {
@@ -523,6 +548,10 @@ function surplus(a, b) {
523
548
  function list(items) {
524
549
  return items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}` : items[0];
525
550
  }
551
+ const ESCAPED_SYNTAX = /(?<!\{)\{\{\s*[\w.]+\s*[|:][^{}]*\}\}/;
552
+ function escapedSyntax(message) {
553
+ return ESCAPED_SYNTAX.exec(message)?.[0];
554
+ }
526
555
  function validateMessage(message, locale) {
527
556
  const issues = [];
528
557
  for (const [name, shape] of shapes(message)) {
@@ -555,8 +584,9 @@ function validatePair(source, translated) {
555
584
  severity: "error",
556
585
  message: `${list(newParams.map((name) => `{${name}}`))} ${newParams.length > 1 ? "are" : "is"} not in the source message, so ${newParams.length > 1 ? "they render" : "it renders"} as literal text`
557
586
  });
558
- const lostTags = tagReport(surplus(tagTokens(source), tagTokens(translated)));
559
- const newTags = tagReport(surplus(tagTokens(translated), tagTokens(source)));
587
+ const markup = /* @__PURE__ */ new Set([...markupNames(source), ...markupNames(translated)]);
588
+ const lostTags = tagReport(surplus(tagTokens(source, markup), tagTokens(translated, markup)));
589
+ const newTags = tagReport(surplus(tagTokens(translated, markup), tagTokens(source, markup)));
560
590
  if (lostTags.length > 0) issues.push({
561
591
  severity: "error",
562
592
  message: `${list(lostTags)} ${lostTags.length > 1 ? "are" : "is"} missing from the translation`
@@ -602,7 +632,7 @@ const COUNT_PROBE = 200;
602
632
  const reachable = /* @__PURE__ */ new Map();
603
633
  function reachableCategories(locale, ordinal) {
604
634
  const type = ordinal ? "ordinal" : "cardinal";
605
- const cacheKey = `${locale}${type}`;
635
+ const cacheKey = `${locale}\u0000${type}`;
606
636
  const hit = reachable.get(cacheKey);
607
637
  if (hit) return hit;
608
638
  let out;
@@ -619,11 +649,16 @@ function reachableCategories(locale, ordinal) {
619
649
  }
620
650
  //#endregion
621
651
  //#region src/check.ts
652
+ function gatePasses(result) {
653
+ return result.missing.length === 0 && result.unknown.length === 0 && !result.broken.some((entry) => entry.severity === "error");
654
+ }
622
655
  function check(cfg, catalogs, registry) {
623
- const source = catalogs[cfg.sourceLocale] ?? {};
624
656
  const extracted = registry.messages();
657
+ const flat = {};
658
+ for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
659
+ const source = flat[cfg.sourceLocale] ?? {};
625
660
  const unknown = [];
626
- for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => catalogs[locale]?.[key] !== void 0))) unknown.push({
661
+ for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
627
662
  key,
628
663
  files
629
664
  });
@@ -636,7 +671,7 @@ function check(cfg, catalogs, registry) {
636
671
  });
637
672
  for (const locale of cfg.locales) {
638
673
  if (locale === cfg.sourceLocale) continue;
639
- for (const key of needed) if (!catalogs[locale]?.[key]) missing.push({
674
+ for (const key of needed) if (!flat[locale]?.[key]) missing.push({
640
675
  locale,
641
676
  key,
642
677
  source: source[key] ?? extracted.get(key)?.message
@@ -651,23 +686,24 @@ function check(cfg, catalogs, registry) {
651
686
  issue: issue.message
652
687
  });
653
688
  };
654
- const sourceFlat = flatten(source);
655
- for (const key of needed) {
656
- const text = sourceFlat[key] ?? extracted.get(key)?.message;
657
- if (text) sourceFlat[key] = text;
658
- }
659
- for (const [key, text] of Object.entries(sourceFlat)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
689
+ const sourceText = { ...source };
690
+ for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
691
+ for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
660
692
  for (const locale of cfg.locales) {
661
693
  if (locale === cfg.sourceLocale) continue;
662
- for (const [key, translated] of Object.entries(flatten(catalogs[locale] ?? {}))) {
694
+ for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
663
695
  if (!translated) continue;
664
696
  add(locale, key, validateMessage(translated, locale));
665
- const text = sourceFlat[key];
697
+ const text = sourceText[key];
666
698
  if (text) add(locale, key, validatePair(text, translated));
667
699
  }
668
700
  }
669
701
  return {
670
- ok: missing.length === 0 && unknown.length === 0 && !broken.some((entry) => entry.severity === "error"),
702
+ ok: gatePasses({
703
+ missing,
704
+ unknown,
705
+ broken
706
+ }),
671
707
  missing,
672
708
  unknown,
673
709
  broken
@@ -693,6 +729,13 @@ function formatCheckResult(result) {
693
729
  }
694
730
  return lines.join("\n");
695
731
  }
732
+ function checkNextSteps(result) {
733
+ const steps = [];
734
+ if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
735
+ if (result.unknown.length > 0) steps.push("unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`");
736
+ if (result.broken.some((entry) => entry.severity === "error")) steps.push("broken: a translation has to keep the params, tags and plural cases of its source message");
737
+ return steps.join("\n");
738
+ }
696
739
  function formatCheckWarnings(result) {
697
740
  return result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`).join("\n");
698
741
  }
@@ -1182,9 +1225,13 @@ function transformSource(code, id, registry) {
1182
1225
  };
1183
1226
  }
1184
1227
  function runBuildGate(cfg, registry, failOnMissing) {
1185
- if (failOnMissing === false) return;
1186
- const result = check(cfg, loadCatalogs(cfg), registry);
1187
- if (!result.ok) throw new Error(`[verbaly] build blocked\n${formatCheckResult(result)}\nRun \`npx verbaly extract\` and fill the missing translations.`);
1228
+ const found = check(cfg, loadCatalogs(cfg), registry);
1229
+ const result = failOnMissing === false ? {
1230
+ ...found,
1231
+ missing: []
1232
+ } : found;
1233
+ if (gatePasses(result)) return;
1234
+ throw new Error(`[verbaly] build blocked\n${formatCheckResult(result)}\n${checkNextSteps(result)}`);
1188
1235
  }
1189
1236
  //#endregion
1190
1237
  //#region src/registry.ts
@@ -1217,6 +1264,9 @@ var MessageRegistry = class {
1217
1264
  }
1218
1265
  return out;
1219
1266
  }
1267
+ strayImports() {
1268
+ return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
1269
+ }
1220
1270
  origins() {
1221
1271
  const out = this.usedKeys();
1222
1272
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
@@ -1278,28 +1328,80 @@ function pruneCatalogs(cfg, catalogs, registry) {
1278
1328
  }
1279
1329
  //#endregion
1280
1330
  //#region src/init.ts
1281
- const BUNDLERS = [
1282
- "astro",
1283
- "vite",
1284
- "webpack",
1285
- "rollup",
1286
- "rspack",
1287
- "esbuild"
1331
+ const HOSTS = [
1332
+ {
1333
+ name: "nuxt",
1334
+ dep: "nuxt",
1335
+ pkg: "@verbaly/nuxt",
1336
+ wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
1337
+ },
1338
+ {
1339
+ name: "next",
1340
+ dep: "next",
1341
+ pkg: "@verbaly/next",
1342
+ wire: "wrap the export of next.config with withVerbaly"
1343
+ },
1344
+ {
1345
+ name: "sveltekit",
1346
+ dep: "@sveltejs/kit",
1347
+ pkg: "@verbaly/vite",
1348
+ wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
1349
+ },
1350
+ {
1351
+ name: "astro",
1352
+ dep: "astro",
1353
+ pkg: "@verbaly/astro",
1354
+ wire: "add verbaly() to the integrations in astro.config"
1355
+ },
1356
+ {
1357
+ name: "vite",
1358
+ dep: "vite",
1359
+ pkg: "@verbaly/vite",
1360
+ wire: "add verbaly() to the plugins in vite.config"
1361
+ },
1362
+ {
1363
+ name: "webpack",
1364
+ dep: "webpack",
1365
+ pkg: "@verbaly/unplugin",
1366
+ wire: "add the verbaly webpack plugin to your build config"
1367
+ },
1368
+ {
1369
+ name: "rspack",
1370
+ dep: "@rspack/core",
1371
+ pkg: "@verbaly/unplugin",
1372
+ wire: "add the verbaly rspack plugin to your build config"
1373
+ },
1374
+ {
1375
+ name: "rollup",
1376
+ dep: "rollup",
1377
+ pkg: "@verbaly/unplugin",
1378
+ wire: "add the verbaly rollup plugin to your build config"
1379
+ },
1380
+ {
1381
+ name: "esbuild",
1382
+ dep: "esbuild",
1383
+ pkg: "@verbaly/unplugin",
1384
+ wire: "add the verbaly esbuild plugin to your build config"
1385
+ }
1288
1386
  ];
1289
- function detectBundler(root) {
1387
+ const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
1388
+ function readDependencies(root) {
1290
1389
  const path = join(root, "package.json");
1291
- if (!existsSync(path)) return void 0;
1390
+ if (!existsSync(path)) return {};
1292
1391
  try {
1293
1392
  const pkg = JSON.parse(readFileSync(path, "utf8"));
1294
- const deps = {
1393
+ return {
1295
1394
  ...pkg.dependencies,
1296
1395
  ...pkg.devDependencies
1297
1396
  };
1298
- return BUNDLERS.find((name) => deps[name]);
1299
1397
  } catch {
1300
- return;
1398
+ return {};
1301
1399
  }
1302
1400
  }
1401
+ function detectHost(root) {
1402
+ const deps = readDependencies(root);
1403
+ return HOSTS.find((host) => deps[host.dep]);
1404
+ }
1303
1405
  function configSource(options, typescript) {
1304
1406
  const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
1305
1407
  if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
@@ -1331,16 +1433,12 @@ function init(options = {}) {
1331
1433
  created.push(label);
1332
1434
  }
1333
1435
  }
1334
- const bundler = detectBundler(root);
1335
- const next = [];
1336
- if (bundler === "astro") next.push("install the integration: pnpm add -D @verbaly/astro", "add verbaly() to the integrations in astro.config");
1337
- else if (bundler === "vite") next.push("install the plugin: pnpm add -D @verbaly/vite", "add verbaly() to the plugins in vite.config");
1338
- else if (bundler) next.push("install the plugin: pnpm add -D @verbaly/unplugin", `add the verbaly ${bundler} plugin to your build config`);
1339
- else next.push("run \"verbaly extract\" after writing your first t`…` message");
1436
+ const host = detectHost(root);
1437
+ const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1340
1438
  return {
1341
1439
  created,
1342
1440
  skipped,
1343
- bundler,
1441
+ host: host?.name,
1344
1442
  configFile,
1345
1443
  next
1346
1444
  };
@@ -1386,11 +1484,11 @@ async function doctor(cfg) {
1386
1484
  }
1387
1485
  try {
1388
1486
  const parsed = JSON.parse(readFileSync(file, "utf8"));
1389
- const bad = Object.entries(parsed).find(([, value]) => typeof value !== "string");
1487
+ const bad = badLeaf(parsed);
1390
1488
  if (bad) {
1391
1489
  catalogsHealthy = false;
1392
- error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad[0]}"`, "catalogs are flat key → string JSON; fix the value");
1393
- } else catalogs[locale] = parsed;
1490
+ error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
1491
+ } else catalogs[locale] = flatten(parsed);
1394
1492
  } catch {
1395
1493
  catalogsHealthy = false;
1396
1494
  error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
@@ -1400,21 +1498,34 @@ async function doctor(cfg) {
1400
1498
  }
1401
1499
  const source = catalogs[cfg.sourceLocale];
1402
1500
  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`");
1403
- const deps = readDeps(cfg.root);
1404
- const bundler = detectBundler(cfg.root);
1405
- const wired = deps["@verbaly/vite"] || deps["@verbaly/unplugin"];
1406
- if (!bundler) ok("plugin", "no bundler detected, the CLI flow (extract/check) applies");
1407
- else if (wired) ok("plugin", `${deps["@verbaly/vite"] ? "@verbaly/vite" : "@verbaly/unplugin"} installed for ${bundler}`);
1408
- else if (bundler === "vite") warn("plugin", "vite detected but @verbaly/vite is not installed", "pnpm add -D @verbaly/vite and add verbaly() to the plugins in vite.config");
1409
- else warn("plugin", `${bundler} detected but @verbaly/unplugin is not installed`, `pnpm add -D @verbaly/unplugin and add the verbaly ${bundler} plugin to your build config`);
1410
- if (source && cfg.dts !== false) {
1501
+ const deps = readDependencies(cfg.root);
1502
+ const host = detectHost(cfg.root);
1503
+ const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
1504
+ if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
1505
+ else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
1506
+ else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `pnpm add -D ${host.pkg} and ${host.wire}`);
1507
+ const scanning = cfg.include.length > 0;
1508
+ if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
1509
+ if (source && scanning && cfg.dts !== false) {
1411
1510
  const dtsPath = cfg.dts ?? join(cfg.root, "verbaly.d.ts");
1412
1511
  if (!existsSync(dtsPath)) warn("types", "verbaly.d.ts has not been generated", "run `npx verbaly extract`");
1413
1512
  else if (readFileSync(dtsPath, "utf8") !== generateDts(source)) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
1414
1513
  else ok("types", "verbaly.d.ts is up to date");
1415
1514
  }
1416
1515
  const registry = await extractProject(cfg);
1417
- if (source) {
1516
+ if (scanning) {
1517
+ const stray = registry.strayImports();
1518
+ if (stray.length > 0) {
1519
+ const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1520
+ error("imports", `${files.length} ${files.length === 1 ? "file imports" : "files import"} t from a verbaly package, which never exports it (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
1521
+ }
1522
+ const escaped = [...registry.messages().values()].map((msg) => ({
1523
+ file: rel(msg.file),
1524
+ slice: escapedSyntax(msg.message)
1525
+ })).filter((entry) => entry.slice !== void 0);
1526
+ if (escaped.length > 0) warn("messages", `${escaped.length} extracted ${escaped.length === 1 ? "message keeps" : "messages keep"} a block as literal text (${escaped[0].file}: ${escaped[0].slice})`, "a tagged template takes its values from ${…}: use t(key, params) for a plural or format block");
1527
+ }
1528
+ if (source && scanning) {
1418
1529
  const extracted = registry.messages();
1419
1530
  const used = registry.usedKeys();
1420
1531
  const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
@@ -1428,6 +1539,13 @@ async function doctor(cfg) {
1428
1539
  const locales = [...new Set(result.missing.map((m) => m.locale))];
1429
1540
  warn("translations", `${result.missing.length} missing ${result.missing.length === 1 ? "translation" : "translations"} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
1430
1541
  }
1542
+ const broken = result.broken.filter((entry) => entry.severity === "error");
1543
+ if (broken.length > 0) {
1544
+ const locales = [...new Set(broken.map((b) => b.locale))];
1545
+ error("translations", `${broken.length} broken ${broken.length === 1 ? "translation" : "translations"} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
1546
+ }
1547
+ const warnings = result.broken.filter((entry) => entry.severity === "warning");
1548
+ if (warnings.length > 0) warn("translations", `${warnings.length} structural ${warnings.length === 1 ? "warning" : "warnings"} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
1431
1549
  if (result.ok) ok("translations", "all translations complete");
1432
1550
  }
1433
1551
  return {
@@ -1439,15 +1557,13 @@ function preview(keys) {
1439
1557
  const head = keys.slice(0, PREVIEW).join(", ");
1440
1558
  return keys.length > PREVIEW ? `${head}, …` : head;
1441
1559
  }
1442
- function readDeps(root) {
1443
- try {
1444
- const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1445
- return {
1446
- ...pkg.dependencies,
1447
- ...pkg.devDependencies
1448
- };
1449
- } catch {
1450
- return {};
1560
+ function badLeaf(tree, prefix = "") {
1561
+ for (const [key, value] of Object.entries(tree)) {
1562
+ const path = prefix ? `${prefix}.${key}` : key;
1563
+ if (typeof value === "string") continue;
1564
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return path;
1565
+ const bad = badLeaf(value, path);
1566
+ if (bad) return bad;
1451
1567
  }
1452
1568
  }
1453
1569
  //#endregion
@@ -2451,20 +2567,22 @@ function decodeEntities(text) {
2451
2567
  //#endregion
2452
2568
  //#region src/status.ts
2453
2569
  function status(cfg, catalogs, registry, drafts = {}) {
2454
- const source = catalogs[cfg.sourceLocale] ?? {};
2455
- const needed = /* @__PURE__ */ new Set([...registry.messages().keys(), ...Object.keys(source)]);
2456
- const live = effectiveDrafts(drafts, catalogs);
2457
2570
  const extracted = registry.messages();
2571
+ const flat = {};
2572
+ for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
2573
+ const source = flat[cfg.sourceLocale] ?? {};
2574
+ const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
2575
+ const live = effectiveDrafts(drafts, flat);
2458
2576
  const locales = [];
2459
2577
  for (const locale of cfg.locales) {
2460
2578
  if (locale === cfg.sourceLocale) continue;
2579
+ const catalog = flat[locale] ?? {};
2461
2580
  let translated = 0;
2462
- for (const key of needed) if (catalogs[locale]?.[key]) translated += 1;
2581
+ for (const key of needed) if (catalog[key]) translated += 1;
2463
2582
  let broken = 0;
2464
- const flatSource = flatten(source ?? {});
2465
- for (const [key, text] of Object.entries(flatten(catalogs[locale] ?? {}))) {
2583
+ for (const [key, text] of Object.entries(catalog)) {
2466
2584
  if (!text) continue;
2467
- const from = flatSource[key] ?? extracted.get(key)?.message;
2585
+ const from = source[key] ?? extracted.get(key)?.message;
2468
2586
  if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
2469
2587
  }
2470
2588
  locales.push({
@@ -2750,6 +2868,6 @@ function line(node) {
2750
2868
  return node.loc?.start?.line ?? 1;
2751
2869
  }
2752
2870
  //#endregion
2753
- export { DRAFTS_FILE, LOCALE_MODULE_PREFIX, MessageRegistry, PLURAL_CATEGORIES, PSEUDO_LOCALE, RESOLVED_VIRTUAL_ID, SFC_FILE_RE, SOURCE_FILE_RE, VIRTUAL_ID, analyze, analyzeFile, analyzeSfc, catalogPath, check, claudeProvider, clearDrafts, collectOrigins, collectParams, createSourceFilter, detectBundler, doctor, effectiveDrafts, exportCatalogs, extractProject, findConfigFile, formatCheckResult, formatCheckWarnings, formatStatusResult, generateDts, generateLocaleModule, generateRuntimeModule, githubCheckAnnotations, importCatalogs, init, isMobileFormat, isTransformTarget, loadCatalogs, loadConfig, loadConfigFile, loadDrafts, loadVirtualModule, markDrafts, parseExchangeFile, pruneCatalogs, pseudoCatalogs, pseudoLocalize, readCatalog, renderHtml, renderParamType, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, serializeCatalog, stableKey, status, structureMatches, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, validateMessage, validatePair, watchProject, wrapCode, wrapProject, writeCatalog, writeDts };
2871
+ export { DRAFTS_FILE, LOCALE_MODULE_PREFIX, MessageRegistry, PLURAL_CATEGORIES, PSEUDO_LOCALE, RESOLVED_VIRTUAL_ID, SFC_FILE_RE, SOURCE_FILE_RE, VIRTUAL_ID, WIRING_PACKAGES, analyze, analyzeFile, analyzeSfc, catalogPath, check, checkNextSteps, claudeProvider, clearDrafts, collectOrigins, collectParams, createSourceFilter, detectHost, doctor, effectiveDrafts, exportCatalogs, extractProject, findConfigFile, formatCheckResult, formatCheckWarnings, formatStatusResult, gatePasses, generateDts, generateLocaleModule, generateRuntimeModule, githubCheckAnnotations, importCatalogs, init, isMobileFormat, isTransformTarget, loadCatalogs, loadConfig, loadConfigFile, loadDrafts, loadVirtualModule, markDrafts, parseExchangeFile, pruneCatalogs, pseudoCatalogs, pseudoLocalize, readCatalog, readDependencies, renderHtml, renderParamType, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, serializeCatalog, stableKey, status, structureMatches, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, validateMessage, validatePair, watchProject, wrapCode, wrapProject, writeCatalog, writeDts };
2754
2872
 
2755
2873
  //# sourceMappingURL=index.js.map