@verbaly/compiler 0.79.0 → 0.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -231,7 +231,7 @@ import { switchLocale } from 'verbaly/app';
231
231
  await switchLocale('es');
232
232
  ```
233
233
 
234
- Under a prefix mode that goes to `/es/…`, which is already rendered in Spanish, so there is no catalog to fetch and no flash. Under `no-prefix` it swaps the text where it stands and the address never changes. Either way it remembers the choice, in the cookie a server reads **and** in the storage the pre-paint redirect reads, and it sets `<html lang>` and `<html dir>`. Pass your framework's router so the app survives the switch:
234
+ Under a prefix mode that goes to `/es/…`, which is already rendered in Spanish, so there is no catalog to fetch and no flash. Under `no-prefix` it swaps the text where it stands and the address never changes. Either way it remembers the choice, in the cookie a server reads **and** in the storage the pre-paint redirect reads, and it sets `<html lang>` and `<html dir>`. A single-page app has neither a server nor a redirect, and starts in its source language: read the choice back before the first render with `setLocale(resolveLocale({ supported: locales, path: false })).then(render)`. Pass your framework's router so the app survives the switch:
235
235
 
236
236
  ```ts
237
237
  await switchLocale('es', { navigate: (path) => router.push(path) });
@@ -391,6 +391,8 @@ runBuildGate(cfg, registry);
391
391
 
392
392
  Your plugin's options go second and `{ plugin: true }` third: when one the command line also reads (`sourceLocale`, `locales`, `dir`, `include`, `exclude`) differs from `verbaly.config`, the build says once to move it there, since `verbaly check` never reads a bundler config.
393
393
 
394
+ `transformSource` also loads `verbaly/app` in a file that imports `@verbaly/react`, `@verbaly/vue` or `@verbaly/svelte`, on that import's own line, since their hooks read its instance when no provider is above them. `transformCode` alone, which Next's loader calls, does not.
395
+
394
396
  A build that scans first, as the Vite plugin does to sync the catalogs, keeps that scan with `extractProject(cfg, { keepSource: true })` and passes it as the fourth argument of `transformSource`: a file it read unchanged is not parsed a second time. Call `reportOutsideInclude(cfg)` once when your build starts: it names every file outside `include` that writes a `` t`…` ``, which no build translates. It reads the project itself, so a cached transform never hides one. `writeDts(cfg, catalog)` writes the types where the config resolves them and returns the file and whether it changed. A build calls `writeBuildTypes(cfg, catalogs)` once it has synced the catalogs: it writes the same file, and a checkout it cannot write gets a warning instead of a failed build.
395
397
 
396
398
  A dev server that writes the catalogs goes through `syncProject`, the same path `extract`, the MCP server and Studio take: it scans (or takes the registry you hold), syncs, writes the catalogs and the types, and keeps `verbaly.lock` in step, in that order; its `findings` say once when that file first appears. Pass `confirm: true` when your registry is built file by file, so a file that changed on disk unseen is read again before its text is written back. `createDevReporter` then says each of its findings once, says it again if it goes away and comes back, and keeps a long list to a few lines.
@@ -1,4 +1,4 @@
1
- import { _t as isModuleNotFound, ut as counted } from "./run-DobJrwby.js";
1
+ import { _t as isModuleNotFound, ut as counted } from "./run-DTmm0EUF.js";
2
2
  // src/exchange/providers/claude.ts
3
3
  const DEFAULT_MODEL = "claude-sonnet-5-5";
4
4
  const FALLBACK_MODELS = /* @__PURE__ */ new Set([
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as runCli, t as formatCliError } from "./run-DobJrwby.js";
2
+ import { n as runCli, t as formatCliError } from "./run-DTmm0EUF.js";
3
3
  // src/cli.ts
4
4
  runCli().catch((error) => {
5
5
  console.error(formatCliError(error));
package/dist/index.d.ts CHANGED
@@ -56,6 +56,8 @@ interface Analysis {
56
56
  strayImports: StrayImport[];
57
57
  missed: MissedCall[];
58
58
  parseError?: string;
59
+ adapterImport?: number;
60
+ appImported?: true;
59
61
  }
60
62
  interface Collision {
61
63
  key: string;
@@ -367,7 +369,9 @@ interface TransformResult {
367
369
  code: string;
368
370
  map: ReturnType<MagicString['generateMap']>;
369
371
  }
370
- export declare function transformCode(code: string, file: string, analysis?: Analysis): TransformResult | null;
372
+ export declare function transformCode(code: string, file: string, analysis?: Analysis, options?: {
373
+ appImport?: boolean;
374
+ }): TransformResult | null;
371
375
  interface PluginOptions extends VerbalyConfig {
372
376
  failOnMissing?: boolean;
373
377
  liveExtraction?: boolean;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as validatePair, A as check, B as readState, C as isTransformTarget, D as transformSource, E as runBuildGate, F as clearDrafts, G as createDevReporter, H as saveState, I as effectiveDrafts, J as generateDts, K as formatCollision, L as loadState, M as formatCheckWarnings, N as syncProject, O as writeBuildTypes, P as STATE_FILE, Q as validateMessage, R as markDrafts, S as createSourceFilter, T as resolveVirtualId, U as updateState, V as recordTranslations, W as collisionEntries, X as generateRuntimeModule, Y as generateLocaleModule, Z as writeDts, _ as status, a as renderSite, at as stableKey, b as RESOLVED_VIRTUAL_ID, bt as targetLocales, c as formatTranslateFailures, ct as MessageRegistry, d as translateCatalogs, dt as loadCatalogs, et as collectOrigins, f as writeDrafts, ft as needsIcu, g as formatStatusResult, gt as writeCatalog, h as formatDoctorHealth, ht as readCatalog, i as formatRenderWarnings, it as syncCatalogs, j as formatCheckResult, k as transformCode, l as mergeTranslations, lt as clientCatalogs, m as formatDoctorEntry, mt as parseCatalog, nt as pruneCatalogs, o as init, ot as APP_ID, p as doctor, pt as needsRelative, q as formatFinding, r as wrapProject, rt as shippedCatalogs, s as watchTree, st as LOCALE_IMPORT, t as formatCliError, tt as extractProject, u as resolveProvider, ut as counted, v as reportOutsideInclude, vt as loadConfig, w as loadVirtualModule, x as SOURCE_FILE_RE, y as LOCALE_MODULE_PREFIX, yt as resolveConfig, z as outdatedTranslations } from "./run-DobJrwby.js";
1
+ import { $ as validatePair, A as check, B as readState, C as isTransformTarget, D as transformSource, E as runBuildGate, F as clearDrafts, G as createDevReporter, H as saveState, I as effectiveDrafts, J as generateDts, K as formatCollision, L as loadState, M as formatCheckWarnings, N as syncProject, O as writeBuildTypes, P as STATE_FILE, Q as validateMessage, R as markDrafts, S as createSourceFilter, T as resolveVirtualId, U as updateState, V as recordTranslations, W as collisionEntries, X as generateRuntimeModule, Y as generateLocaleModule, Z as writeDts, _ as status, a as renderSite, at as stableKey, b as RESOLVED_VIRTUAL_ID, bt as targetLocales, c as formatTranslateFailures, ct as MessageRegistry, d as translateCatalogs, dt as loadCatalogs, et as collectOrigins, f as writeDrafts, ft as needsIcu, g as formatStatusResult, gt as writeCatalog, h as formatDoctorHealth, ht as readCatalog, i as formatRenderWarnings, it as syncCatalogs, j as formatCheckResult, k as transformCode, l as mergeTranslations, lt as clientCatalogs, m as formatDoctorEntry, mt as parseCatalog, nt as pruneCatalogs, o as init, ot as APP_ID, p as doctor, pt as needsRelative, q as formatFinding, r as wrapProject, rt as shippedCatalogs, s as watchTree, st as LOCALE_IMPORT, t as formatCliError, tt as extractProject, u as resolveProvider, ut as counted, v as reportOutsideInclude, vt as loadConfig, w as loadVirtualModule, x as SOURCE_FILE_RE, y as LOCALE_MODULE_PREFIX, yt as resolveConfig, z as outdatedTranslations } from "./run-DTmm0EUF.js";
2
2
  // src/catalog/drafts.ts
3
3
  function loadDrafts(cfg) {
4
4
  return loadState(cfg).drafts;
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
@@ -207,7 +207,9 @@ async function loadConfigFile(root) {
207
207
  const path = join(root, name);
208
208
  if (existsSync(path)) {
209
209
  const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
210
- delete createRequire(import.meta.url).cache[resolve(path)];
210
+ const cache = createRequire(import.meta.url).cache;
211
+ delete cache[realpathSync(path)];
212
+ delete cache[resolve(path)];
211
213
  return (await import(url)).default ?? {};
212
214
  }
213
215
  }
@@ -259,6 +261,10 @@ const READ_BY_CLI = [
259
261
  "include",
260
262
  "exclude"
261
263
  ];
264
+ const pluginOnly = /* @__PURE__ */ new Map();
265
+ function pluginOnlyOptions(root) {
266
+ return pluginOnly.get(root) ?? "";
267
+ }
262
268
  function warnPluginOnly(root, file, overrides) {
263
269
  const cli = resolveConfig({
264
270
  ...file,
@@ -270,8 +276,12 @@ function warnPluginOnly(root, file, overrides) {
270
276
  root
271
277
  });
272
278
  const keys = READ_BY_CLI.filter((key) => overrides[key] !== void 0 && JSON.stringify(cli[key]) !== JSON.stringify(build[key]));
273
- if (keys.length === 0) return;
279
+ if (keys.length === 0) {
280
+ pluginOnly.delete(cli.root);
281
+ return;
282
+ }
274
283
  const names = keys.length > 1 ? `${keys.slice(0, -1).join(", ")} and ${keys.at(-1)}` : keys[0];
284
+ pluginOnly.set(cli.root, names);
275
285
  const [verb, pronoun] = keys.length > 1 ? ["are", "them"] : ["is", "it"];
276
286
  warnOnce(`${names} ${verb} set in the plugin options, which \`verbaly check\` and \`verbaly extract\` never read: move ${pronoun} to verbaly.config so the command line checks what the build ships`, `plugin-only:${root}`);
277
287
  }
@@ -287,8 +297,8 @@ function withLineEndings(text, existing) {
287
297
  function emptyCatalog() {
288
298
  return Object.create(null);
289
299
  }
290
- function own(catalog, key) {
291
- return Object.hasOwn(catalog, key) ? catalog[key] : void 0;
300
+ function own(map, key) {
301
+ return Object.hasOwn(map, key) ? map[key] : void 0;
292
302
  }
293
303
  function flatView(tree) {
294
304
  if (typeof tree !== "object" || tree === null || Object.getPrototypeOf(tree) !== null) return flatten(tree);
@@ -341,7 +351,7 @@ function isTree(value) {
341
351
  return typeof value === "object" && value !== null && !Array.isArray(value);
342
352
  }
343
353
  function loadCatalogs(cfg) {
344
- const catalogs = {};
354
+ const catalogs = emptyCatalog();
345
355
  for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
346
356
  return catalogs;
347
357
  }
@@ -445,6 +455,11 @@ function counted(count, noun, many = `${noun}s`) {
445
455
  function truncate(text, max) {
446
456
  return text.length > max ? text.slice(0, max - 1) + "…" : text;
447
457
  }
458
+ function trimTrailingSlashes(text) {
459
+ let end = text.length;
460
+ while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
461
+ return text.slice(0, end);
462
+ }
448
463
  function byCodeUnit(a, b) {
449
464
  return a < b ? -1 : a > b ? 1 : 0;
450
465
  }
@@ -455,7 +470,7 @@ function isExcluded(key, prefixes) {
455
470
  function clientCatalogs(cfg, catalogs) {
456
471
  const prefixes = cfg.bundle.exclude ?? [];
457
472
  if (prefixes.length === 0) return catalogs;
458
- const out = {};
473
+ const out = emptyCatalog();
459
474
  for (const [locale, catalog] of Object.entries(catalogs)) {
460
475
  const kept = emptyCatalog();
461
476
  for (const [key, message] of Object.entries(catalog)) if (!isExcluded(key, prefixes)) kept[key] = message;
@@ -604,11 +619,21 @@ function analyzeScript(code, file, options = {}) {
604
619
  const strayImports = [];
605
620
  const bindings = new Bindings(names);
606
621
  const candidates = [];
622
+ let adapterImport;
623
+ let appImported = false;
624
+ const noteLoad = (node) => {
625
+ const source = node.source?.value;
626
+ if (typeof source !== "string" || !loadsAtRuntime(node)) return;
627
+ if (isAppModule(source)) appImported = true;
628
+ else if (ADAPTER_SOURCE.test(source)) adapterImport ??= node.start;
629
+ };
607
630
  walk$1(ast.program, (node) => {
608
631
  if (node.type === "ImportDeclaration") {
609
632
  collectStrayImports(node, file, strayImports);
610
633
  bindings.addImport(node);
611
- } else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
634
+ noteLoad(node);
635
+ } else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") noteLoad(node);
636
+ else if (node.type === "VariableDeclarator") bindings.addDeclarator(node);
612
637
  else if (node.type === "TaggedTemplateExpression") {
613
638
  const tag = node.tag;
614
639
  const explicit = explicitId(tag, names);
@@ -682,16 +707,26 @@ function analyzeScript(code, file, options = {}) {
682
707
  loose: true
683
708
  });
684
709
  }
710
+ const analysis = {
711
+ tagged,
712
+ usedKeys,
713
+ strayImports,
714
+ missed
715
+ };
716
+ if (adapterImport !== void 0) analysis.adapterImport = adapterImport;
717
+ if (appImported) analysis.appImported = true;
685
718
  return {
686
- analysis: {
687
- tagged,
688
- usedKeys,
689
- strayImports,
690
- missed
691
- },
719
+ analysis,
692
720
  renamed: [...renamed]
693
721
  };
694
722
  }
723
+ const ADAPTER_SOURCE = /^@verbaly\/(?:react|vue|svelte)(?:\/Trans\.svelte)?$/;
724
+ function loadsAtRuntime(node) {
725
+ if (node.importKind === "type" || node.exportKind === "type") return false;
726
+ const specifiers = node.specifiers ?? [];
727
+ if (specifiers.length === 0) return true;
728
+ return specifiers.some((spec) => spec.importKind !== "type" && spec.exportKind !== "type");
729
+ }
695
730
  function lineOf(node) {
696
731
  return node.loc?.start.line ?? 1;
697
732
  }
@@ -1101,6 +1136,49 @@ function walk$1(node, visit) {
1101
1136
  function isNode(value) {
1102
1137
  return typeof value === "object" && value !== null && typeof value.type === "string";
1103
1138
  }
1139
+ // src/util/blocks.ts
1140
+ function blocks(source, shapes) {
1141
+ const found = [];
1142
+ const opens = shapes.map(() => void 0);
1143
+ let from = 0;
1144
+ for (;;) {
1145
+ let pick = -1;
1146
+ for (let i = 0; i < shapes.length; i += 1) {
1147
+ if (opens[i] === null) continue;
1148
+ if (opens[i] === void 0 || opens[i][0] < from) opens[i] = search(source, shapes[i].open, from);
1149
+ if (opens[i] && (pick < 0 || opens[i][0] < opens[pick][0])) pick = i;
1150
+ }
1151
+ if (pick < 0) return found;
1152
+ const block = closed(source, shapes[pick], opens[pick]);
1153
+ if (block) {
1154
+ found.push(block);
1155
+ from = block.end;
1156
+ } else opens[pick] = null;
1157
+ }
1158
+ }
1159
+ function closed(source, shape, [start, openEnd]) {
1160
+ const body = shape.openTag ? source.indexOf(">", openEnd) + 1 : openEnd;
1161
+ if (body === 0) return null;
1162
+ const close = search(source, shape.close, body);
1163
+ if (!close) return null;
1164
+ const end = shape.closeTag ? source.indexOf(">", close[1]) + 1 : close[1];
1165
+ if (end === 0) return null;
1166
+ return {
1167
+ start,
1168
+ body,
1169
+ close: close[0],
1170
+ end
1171
+ };
1172
+ }
1173
+ function search(source, what, from) {
1174
+ if (typeof what === "string") {
1175
+ const at = source.indexOf(what, from);
1176
+ return at < 0 ? null : [at, at + what.length];
1177
+ }
1178
+ what.lastIndex = from;
1179
+ const found = what.exec(source);
1180
+ return found ? [found.index, what.lastIndex] : null;
1181
+ }
1104
1182
  // src/scan/sfc.ts
1105
1183
  const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
1106
1184
  function analyzeFile(code, file) {
@@ -1117,11 +1195,25 @@ function analyzeFile(code, file) {
1117
1195
  };
1118
1196
  }
1119
1197
  }
1120
- const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
1121
- const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
1122
- const COMMENT_RE = /<!--[\s\S]*?-->/g;
1198
+ const SCRIPT_BLOCK = {
1199
+ open: /<script\b/gi,
1200
+ openTag: true,
1201
+ close: /<\/script\s*>/gi
1202
+ };
1203
+ const STYLE_BLOCK = {
1204
+ open: /<style\b/gi,
1205
+ openTag: true,
1206
+ close: /<\/style\s*>/gi
1207
+ };
1208
+ const COMMENT_BLOCK = {
1209
+ open: "<!--",
1210
+ close: "-->"
1211
+ };
1123
1212
  const FRONTMATTER_RE = /^(\uFEFF?\s*---\r?\n)([\s\S]*?)\r?\n---(?=\r?\n|$)/;
1124
- const MUSTACHE_RE = /\{\{[\s\S]*?\}\}/g;
1213
+ const MUSTACHE_BLOCK = {
1214
+ open: "{{",
1215
+ close: "}}"
1216
+ };
1125
1217
  const DIRECTIVE_RE = /\s(?:v-[\w-]+(?::[^\s=>/]+)?|[:@][^\s=>/]+)\s*=\s*("[^"]*"|'[^']*')/g;
1126
1218
  function analyzeSfc(code, file) {
1127
1219
  const svelte = file.endsWith(".svelte");
@@ -1133,6 +1225,8 @@ function analyzeSfc(code, file) {
1133
1225
  const renamed = /* @__PURE__ */ new Set();
1134
1226
  const lineAt = lineCounter(code);
1135
1227
  let parseError;
1228
+ let adapterImport;
1229
+ let appImported = false;
1136
1230
  const block = (content, offset) => {
1137
1231
  const segment = analyzeSegment(content, file, { tNames });
1138
1232
  parseError ??= segment.error;
@@ -1141,11 +1235,8 @@ function analyzeSfc(code, file) {
1141
1235
  };
1142
1236
  const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
1143
1237
  if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1].length);
1144
- for (const match of code.matchAll(SCRIPT_RE)) {
1145
- const content = match[2];
1146
- if (content) block(content, match.index + match[1].length);
1147
- }
1148
- const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
1238
+ for (const script of blocks(code, [SCRIPT_BLOCK])) if (script.close > script.body) block(code.slice(script.body, script.close), script.body);
1239
+ const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_BLOCK), STYLE_BLOCK), COMMENT_BLOCK);
1149
1240
  const markupOptions = {
1150
1241
  tNames,
1151
1242
  renamed: [...renamed]
@@ -1163,15 +1254,20 @@ function analyzeSfc(code, file) {
1163
1254
  merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);
1164
1255
  consumedTo = end;
1165
1256
  }
1166
- return {
1257
+ const analysis = {
1167
1258
  tagged,
1168
1259
  usedKeys,
1169
1260
  strayImports,
1170
- missed,
1171
- ...parseError && { parseError }
1261
+ missed
1172
1262
  };
1263
+ if (parseError) analysis.parseError = parseError;
1264
+ if (adapterImport !== void 0) analysis.adapterImport = adapterImport;
1265
+ if (appImported) analysis.appImported = true;
1266
+ return analysis;
1173
1267
  function merge(analysis, offset, markupSegment) {
1174
1268
  if (!analysis) return;
1269
+ if (analysis.adapterImport !== void 0) adapterImport ??= analysis.adapterImport + offset;
1270
+ if (analysis.appImported) appImported = true;
1175
1271
  const lines = lineAt(offset) - 1;
1176
1272
  for (const msg of analysis.tagged) tagged.push({
1177
1273
  ...msg,
@@ -1224,8 +1320,14 @@ function analyzeSegment(code, file, options) {
1224
1320
  };
1225
1321
  }
1226
1322
  }
1227
- function blank(source, re) {
1228
- return source.replace(re, (m) => " ".repeat(m.length));
1323
+ function blank(source, shape) {
1324
+ let out = "";
1325
+ let at = 0;
1326
+ for (const { start, end } of blocks(source, [shape])) {
1327
+ out += source.slice(at, start) + " ".repeat(end - start);
1328
+ at = end;
1329
+ }
1330
+ return out + source.slice(at);
1229
1331
  }
1230
1332
  function braceRanges(markup) {
1231
1333
  const ranges = [];
@@ -1245,7 +1347,7 @@ function braceRanges(markup) {
1245
1347
  }
1246
1348
  function vueExpressionRanges(markup) {
1247
1349
  const ranges = [];
1248
- for (const match of markup.matchAll(MUSTACHE_RE)) ranges.push([match.index + 2, match.index + match[0].length - 2]);
1350
+ for (const { body, close } of blocks(markup, [MUSTACHE_BLOCK])) ranges.push([body, close]);
1249
1351
  for (const match of markup.matchAll(DIRECTIVE_RE)) {
1250
1352
  const valueStart = match.index + match[0].length - match[1].length + 1;
1251
1353
  ranges.push([valueStart, valueStart + match[1].length - 2]);
@@ -1327,9 +1429,9 @@ async function collectOrigins(cfg, reuse) {
1327
1429
  return origins;
1328
1430
  }
1329
1431
  function syncCatalogs(cfg, catalogs, registry) {
1330
- const added = {};
1432
+ const added = emptyCatalog();
1331
1433
  const replaced = [];
1332
- const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
1434
+ const source = own(catalogs, cfg.sourceLocale) ?? (catalogs[cfg.sourceLocale] = emptyCatalog());
1333
1435
  for (const [key, msg] of registry.messages()) {
1334
1436
  const before = own(source, key);
1335
1437
  if (before === msg.message) continue;
@@ -1343,7 +1445,7 @@ function syncCatalogs(cfg, catalogs, registry) {
1343
1445
  const needed = Object.keys(source);
1344
1446
  for (const locale of cfg.locales) {
1345
1447
  if (locale === cfg.sourceLocale) continue;
1346
- const catalog = catalogs[locale] ??= emptyCatalog();
1448
+ const catalog = own(catalogs, locale) ?? (catalogs[locale] = emptyCatalog());
1347
1449
  for (const key of needed) if (own(catalog, key) === void 0) {
1348
1450
  catalog[key] = "";
1349
1451
  (added[locale] ??= []).push(key);
@@ -1357,17 +1459,14 @@ function syncCatalogs(cfg, catalogs, registry) {
1357
1459
  function shippedCatalogs(cfg, catalogs, registry, options = {}) {
1358
1460
  const source = flatten(catalogs[cfg.sourceLocale] ?? {});
1359
1461
  for (const [key, msg] of registry.messages()) if (options.newKeys !== false || own(source, key) !== void 0) source[key] = msg.message;
1360
- return {
1361
- ...catalogs,
1362
- [cfg.sourceLocale]: source
1363
- };
1462
+ return Object.assign(emptyCatalog(), catalogs, { [cfg.sourceLocale]: source });
1364
1463
  }
1365
1464
  function pruneCatalogs(cfg, catalogs, registry) {
1366
- const removed = {};
1465
+ const removed = emptyCatalog();
1367
1466
  if (registry.parseErrors().length > 0) return removed;
1368
1467
  const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
1369
1468
  for (const locale of cfg.locales) {
1370
- const catalog = catalogs[locale];
1469
+ const catalog = own(catalogs, locale);
1371
1470
  if (!catalog) continue;
1372
1471
  for (const key of Object.keys(catalog)) if (!keep.has(key)) {
1373
1472
  delete catalog[key];
@@ -1651,7 +1750,7 @@ function covered(list, entry) {
1651
1750
  if (!Array.isArray(list)) return false;
1652
1751
  return list.some((item) => {
1653
1752
  if (typeof item !== "string") return false;
1654
- const pattern = item.replace(/^\.\//, "").replace(/\/+$/, "");
1753
+ const pattern = trimTrailingSlashes(item.replace(/^\.\//, ""));
1655
1754
  return picomatch(pattern)(entry) || picomatch(`${pattern}/**/*`)(entry);
1656
1755
  });
1657
1756
  }
@@ -1704,11 +1803,14 @@ export function adoptPage(options) {
1704
1803
  }
1705
1804
 
1706
1805
  `;
1806
+ function loaderKey(locale) {
1807
+ return locale === "__proto__" ? "[\"__proto__\"]" : JSON.stringify(locale);
1808
+ }
1707
1809
  function generateRuntimeModule(cfg, options = {}) {
1708
1810
  const importPath = options.localeImport ?? ((locale) => "@verbaly/app/locale/" + locale);
1709
1811
  const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
1710
1812
  const src = JSON.stringify(cfg.sourceLocale);
1711
- const loaders = others.map((locale) => ` ${JSON.stringify(locale)}: () => import('${importPath(locale)}'),`).join("\n");
1813
+ const loaders = others.map((locale) => ` ${loaderKey(locale)}: () => import('${importPath(locale)}'),`).join("\n");
1712
1814
  const icu = options.icu ? ",\n parseIcu" : "";
1713
1815
  const rel = options.relative ? ",\n relativeFormatter" : "";
1714
1816
  const slice = options.inlineCatalog ? ",\n inlineMessages" : "";
@@ -1717,6 +1819,7 @@ function generateRuntimeModule(cfg, options = {}) {
1717
1819
  createVerbaly,
1718
1820
  localeFromPath as readPath,
1719
1821
  localePath as writePath,
1822
+ persistLocale,
1720
1823
  switchLocale as runSwitch${icu}${rel}${slice},
1721
1824
  } from 'verbaly';
1722
1825
  import source from '${importPath(cfg.sourceLocale)}';
@@ -1795,9 +1898,11 @@ export function subscribe(listener) {
1795
1898
  return v.subscribe(listener);
1796
1899
  }
1797
1900
 
1901
+ // <html lang> and dir follow; no choice is saved, since a startup read would freeze the browser's
1798
1902
  export async function setLocale(locale) {
1799
1903
  await v.loadLocale(locale);
1800
1904
  v.setLocale(locale);
1905
+ persistLocale(locale, false);
1801
1906
  }
1802
1907
  ${options.extraExports ?? ""}`;
1803
1908
  }
@@ -2106,8 +2211,8 @@ function loadState(cfg) {
2106
2211
  for (const side of lock) checkVersion(statePath(cfg), side.version);
2107
2212
  const [legacyState = [], legacyDrafts = []] = legacyPaths(cfg).map((path) => readSides(path) ?? []);
2108
2213
  const state = {
2109
- drafts: {},
2110
- fingerprints: {}
2214
+ drafts: emptyCatalog(),
2215
+ fingerprints: emptyCatalog()
2111
2216
  };
2112
2217
  const kept = lock.length > 1 ? keptStamp(cfg) : void 0;
2113
2218
  [...lock, ...legacyState].forEach((source, index) => {
@@ -2164,12 +2269,13 @@ function readState(cfg) {
2164
2269
  ...marked
2165
2270
  };
2166
2271
  } catch (error) {
2272
+ const problem = error.message.replace(/^\[verbaly\] /, "");
2167
2273
  return {
2168
2274
  state: {
2169
- drafts: {},
2170
- fingerprints: {}
2275
+ drafts: emptyCatalog(),
2276
+ fingerprints: emptyCatalog()
2171
2277
  },
2172
- problem: error.message.replace(/^\[verbaly\] /, ""),
2278
+ problem,
2173
2279
  ...marked
2174
2280
  };
2175
2281
  }
@@ -2207,7 +2313,7 @@ function refreshState(cfg, catalogs, previous) {
2207
2313
  const flat = flatCatalogs(catalogs);
2208
2314
  const source = flat[cfg.sourceLocale] ?? {};
2209
2315
  const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
2210
- const drafts = {};
2316
+ const drafts = emptyCatalog();
2211
2317
  for (const [locale, keys] of Object.entries(previous.drafts)) {
2212
2318
  if (!shown.has(locale)) {
2213
2319
  drafts[locale] = keys;
@@ -2216,7 +2322,7 @@ function refreshState(cfg, catalogs, previous) {
2216
2322
  const live = keys.filter((key) => own(flat[locale], key));
2217
2323
  if (live.length) drafts[locale] = live;
2218
2324
  }
2219
- const fingerprints = {};
2325
+ const fingerprints = emptyCatalog();
2220
2326
  for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
2221
2327
  for (const locale of shown) {
2222
2328
  const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
@@ -2261,7 +2367,7 @@ function recordTranslations(cfg, source, writes) {
2261
2367
  return state;
2262
2368
  }
2263
2369
  function effectiveDrafts(drafts, catalogs) {
2264
- const out = {};
2370
+ const out = emptyCatalog();
2265
2371
  for (const [locale, keys] of Object.entries(drafts)) {
2266
2372
  const catalog = catalogs[locale] ?? {};
2267
2373
  const live = keys.filter((key) => own(catalog, key));
@@ -2326,17 +2432,17 @@ function translationOf(stamped) {
2326
2432
  return stamped.slice(stamped.indexOf(".") + 1);
2327
2433
  }
2328
2434
  function flatCatalogs(catalogs) {
2329
- const out = {};
2435
+ const out = emptyCatalog();
2330
2436
  for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
2331
2437
  return out;
2332
2438
  }
2333
2439
  function serializeState(state) {
2334
- const drafts = {};
2440
+ const drafts = emptyCatalog();
2335
2441
  for (const locale of Object.keys(state.drafts).sort()) {
2336
2442
  const keys = [...new Set(state.drafts[locale])].sort();
2337
2443
  if (keys.length) drafts[locale] = keys;
2338
2444
  }
2339
- const fingerprints = {};
2445
+ const fingerprints = emptyCatalog();
2340
2446
  for (const locale of Object.keys(state.fingerprints).sort()) {
2341
2447
  const entries = state.fingerprints[locale] ?? {};
2342
2448
  const keys = Object.keys(entries).sort();
@@ -2400,7 +2506,7 @@ function isObject(value) {
2400
2506
  return typeof value === "object" && value !== null && !Array.isArray(value);
2401
2507
  }
2402
2508
  function readDrafts(value) {
2403
- const out = {};
2509
+ const out = emptyCatalog();
2404
2510
  if (!isObject(value)) return out;
2405
2511
  for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
2406
2512
  return out;
@@ -2411,7 +2517,7 @@ function readMigrated(value) {
2411
2517
  return locales.length ? locales : void 0;
2412
2518
  }
2413
2519
  function readFingerprints(value) {
2414
- const out = {};
2520
+ const out = emptyCatalog();
2415
2521
  if (!isObject(value)) return out;
2416
2522
  for (const [locale, entries] of Object.entries(value)) {
2417
2523
  if (!isObject(entries)) continue;
@@ -2439,7 +2545,7 @@ async function syncProject(cfg, options = {}) {
2439
2545
  pruned,
2440
2546
  pruneBlocked,
2441
2547
  findings: scanFindings(cfg, registry, replaced),
2442
- written: {}
2548
+ written: emptyCatalog()
2443
2549
  };
2444
2550
  if (options.dryRun) return result;
2445
2551
  const changed = /* @__PURE__ */ new Set([...Object.keys(added), ...Object.keys(pruned)]);
@@ -2484,12 +2590,12 @@ function gatePasses(result) {
2484
2590
  function warningCount(result) {
2485
2591
  return result.broken.filter((entry) => entry.severity === "warning").length + result.extra.length + result.divergent.length + result.outdated.length;
2486
2592
  }
2487
- function check(cfg, catalogs, registry, fingerprints = {}) {
2593
+ function check(cfg, catalogs, registry, fingerprints = emptyCatalog()) {
2488
2594
  return gatePass(() => checkPass(cfg, catalogs, registry, fingerprints));
2489
2595
  }
2490
2596
  function checkPass(cfg, catalogs, registry, fingerprints) {
2491
2597
  const extracted = registry.messages();
2492
- const flat = {};
2598
+ const flat = emptyCatalog();
2493
2599
  for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
2494
2600
  const source = flat[cfg.sourceLocale] ?? {};
2495
2601
  const shipped = shippedCatalogs(cfg, flat, registry);
@@ -2629,7 +2735,7 @@ function formatBuildReport(result, sourceLocale, root, cap = 5) {
2629
2735
  }
2630
2736
  function checkNextSteps(result, cliReachable = true) {
2631
2737
  const steps = [];
2632
- if (result.missing.length > 0) steps.push("missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)");
2738
+ if (result.missing.length > 0) steps.push("missing: fill the empty translations in your catalogs, or run `npx verbaly translate` (`npx verbaly extract` adds a key a catalog does not have yet)");
2633
2739
  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`");
2634
2740
  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");
2635
2741
  if (result.collisions.length > 0) steps.push("collisions: give each text its own key in t.id(…), or write the same text in every place");
@@ -2714,12 +2820,14 @@ function quote(text, single) {
2714
2820
  if (!single) return JSON.stringify(text);
2715
2821
  return `'${text.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
2716
2822
  }
2717
- function transformCode(code, file, analysis) {
2823
+ function transformCode(code, file, analysis, options = {}) {
2718
2824
  const own = analysis ?? analyzeFile(code, file);
2719
2825
  if (!analysis && own.parseError) warnParseError(file, own.parseError);
2720
2826
  const { tagged } = own;
2721
- if (tagged.length === 0) return null;
2827
+ const appAt = options.appImport && !own.appImported ? own.adapterImport : void 0;
2828
+ if (tagged.length === 0 && appAt === void 0) return null;
2722
2829
  const s = new MagicString(code);
2830
+ if (appAt !== void 0) s.appendLeft(appAt, `import '${APP_ID}'; `);
2723
2831
  for (const msg of tagged) {
2724
2832
  const seen = /* @__PURE__ */ new Set();
2725
2833
  const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));
@@ -2776,7 +2884,7 @@ function transformSource(code, id, registry, scan) {
2776
2884
  for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
2777
2885
  return {
2778
2886
  messages,
2779
- result: transformCode(code, id, analysis) ?? null
2887
+ result: transformCode(code, id, analysis, { appImport: true }) ?? null
2780
2888
  };
2781
2889
  }
2782
2890
  function writeBuildTypes(cfg, catalogs) {
@@ -2795,7 +2903,16 @@ function runBuildGate(cfg, registry, failOnMissing) {
2795
2903
  if (failOnMissing === true && !gatePasses(found)) throw new Error(`[verbaly] build blocked\n${formatCheckResult(found, cfg.root)}\n${checkNextSteps(found, cliReachable(cfg.root))}`);
2796
2904
  reportGate(cfg, found);
2797
2905
  const warnings = warningCount(found);
2798
- if (warnings > 0) warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: run \`npx verbaly check\` to read them`, "gate:warnings");
2906
+ if (warnings > 0) {
2907
+ const once = onceMoved(cfg.root);
2908
+ const read = once ? `\`npx verbaly check\` reads them${once}` : "run `npx verbaly check` to read them";
2909
+ warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: ${read}`, "gate:warnings");
2910
+ }
2911
+ }
2912
+ function onceMoved(root) {
2913
+ const moved = pluginOnlyOptions(root);
2914
+ if (!moved) return "";
2915
+ return ` once ${moved} ${moved.includes(" and ") ? "move" : "moves"} to verbaly.config`;
2799
2916
  }
2800
2917
  const reported = /* @__PURE__ */ new Map();
2801
2918
  function reportGate(cfg, found) {
@@ -2823,7 +2940,7 @@ function reportGate(cfg, found) {
2823
2940
  ...lines.map((line) => line.startsWith(" ") ? line : `[verbaly] ${line}`),
2824
2941
  "[verbaly] to fix them:",
2825
2942
  ...steps.split("\n").map((step) => ` ${step}`),
2826
- "[verbaly] `npx verbaly check` lists every one, and in your CI it stops a release on them"
2943
+ `[verbaly] \`npx verbaly check\` lists every one${onceMoved(cfg.root)}, and in your CI it stops a release on them`
2827
2944
  ];
2828
2945
  console.warn(block.join("\n"));
2829
2946
  }
@@ -2899,9 +3016,9 @@ async function filesOutsideInclude(cfg) {
2899
3016
  return found;
2900
3017
  }
2901
3018
  // src/gate/status.ts
2902
- function status(cfg, catalogs, registry, drafts = {}, fingerprints = {}) {
3019
+ function status(cfg, catalogs, registry, drafts = emptyCatalog(), fingerprints = emptyCatalog()) {
2903
3020
  const extracted = registry.messages();
2904
- const flat = {};
3021
+ const flat = emptyCatalog();
2905
3022
  for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
2906
3023
  const source = flat[cfg.sourceLocale] ?? {};
2907
3024
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
@@ -3086,6 +3203,31 @@ function readRoutingChoice(root, configFile) {
3086
3203
  return false;
3087
3204
  }
3088
3205
  }
3206
+ function readAstroRouting(root, source) {
3207
+ for (const file of [
3208
+ "astro.config.mjs",
3209
+ "astro.config.js",
3210
+ "astro.config.ts",
3211
+ "astro.config.mts"
3212
+ ]) {
3213
+ let text;
3214
+ try {
3215
+ text = readFileSync(join(root, file), "utf8");
3216
+ } catch {
3217
+ continue;
3218
+ }
3219
+ if (!/\bi18n\s*:/.test(text) || /\brouting\s*:\s*['"]manual['"]/.test(text)) return void 0;
3220
+ if (/\bprefixDefaultLocale\s*:\s*true\b/.test(text)) return {
3221
+ mode: "prefix-all",
3222
+ file
3223
+ };
3224
+ const atRoot = /\bdefaultLocale\s*:\s*['"]([^'"]+)['"]/.exec(text)?.[1];
3225
+ return atRoot && atRoot !== source ? void 0 : {
3226
+ mode: "prefix-except-source",
3227
+ file
3228
+ };
3229
+ }
3230
+ }
3089
3231
  const ROUTING_SAYS = {
3090
3232
  "prefix-except-source": "the source locale has no prefix, every other locale does",
3091
3233
  "prefix-all": "every locale has a prefix, the source included",
@@ -3131,7 +3273,7 @@ async function doctor(cfg) {
3131
3273
  else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
3132
3274
  if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
3133
3275
  else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
3134
- const catalogs = {};
3276
+ const catalogs = emptyCatalog();
3135
3277
  let catalogsHealthy = true;
3136
3278
  if (!existsSync(cfg.dir)) {
3137
3279
  catalogsHealthy = false;
@@ -3178,8 +3320,16 @@ async function doctor(cfg) {
3178
3320
  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");
3179
3321
  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");
3180
3322
  else {
3181
- const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
3182
- ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
3323
+ const named = configFile ? readRoutingChoice(cfg.root, configFile) : false;
3324
+ const astro = cfg.host === "astro" && cfg.routing === "no-prefix" ? readAstroRouting(cfg.root, cfg.sourceLocale) : void 0;
3325
+ if (astro && named) warn("routing", `routing is "no-prefix" in ${configFile}, but @verbaly/astro uses ${astro.mode}: Astro's i18n in ${astro.file} puts the language in the url`, `remove routing from ${configFile}, or remove i18n from ${astro.file}`);
3326
+ else if (astro) {
3327
+ const how = ` (from Astro's i18n in ${astro.file}, which @verbaly/astro follows)`;
3328
+ ok("routing", `${astro.mode}${how}: ${ROUTING_SAYS[astro.mode]}`);
3329
+ } else {
3330
+ const how = named ? "" : " (from your setup, no routing set)";
3331
+ ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
3332
+ }
3183
3333
  }
3184
3334
  const deps = readDependencies(cfg.root);
3185
3335
  const host = detectHost(cfg.root);
@@ -3713,9 +3863,9 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
3713
3863
  const targets = targetLocales(cfg, options.locales);
3714
3864
  const source = catalogs[cfg.sourceLocale] ?? {};
3715
3865
  const result = {
3716
- translated: {},
3717
- invalid: {},
3718
- pending: {},
3866
+ translated: emptyCatalog(),
3867
+ invalid: emptyCatalog(),
3868
+ pending: emptyCatalog(),
3719
3869
  failed: []
3720
3870
  };
3721
3871
  const jobs = [];
@@ -3847,7 +3997,7 @@ function formatTranslateFailures(failed) {
3847
3997
  async function resolveProvider(cfg, model) {
3848
3998
  const configured = cfg.translate.provider;
3849
3999
  if (typeof configured === "function") return configured;
3850
- const { claudeProvider } = await import("./claude-BtdaNZEw.js");
4000
+ const { claudeProvider } = await import("./claude-DelQkcx5.js");
3851
4001
  return claudeProvider({ model: model ?? cfg.translate.model });
3852
4002
  }
3853
4003
  function structureMatches(source, translated) {
@@ -3945,13 +4095,13 @@ function exportMobile(cfg, catalogs, format, dir, source, targets) {
3945
4095
  function importCatalogs(cfg, catalogs, files, options = {}) {
3946
4096
  const source = catalogs[cfg.sourceLocale] ?? {};
3947
4097
  const result = {
3948
- imported: {},
3949
- rejected: {},
3950
- skipped: {},
3951
- unknown: {},
4098
+ imported: emptyCatalog(),
4099
+ rejected: emptyCatalog(),
4100
+ skipped: emptyCatalog(),
4101
+ unknown: emptyCatalog(),
3952
4102
  unmatched: [],
3953
4103
  mapped: [],
3954
- sources: {}
4104
+ sources: emptyCatalog()
3955
4105
  };
3956
4106
  for (const file of files) {
3957
4107
  const parsed = parseExchangeFile(file, options.locale);
@@ -3996,7 +4146,7 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
3996
4146
  if (!options.dryRun) catalog[key] = text;
3997
4147
  (result.imported[locale] ??= []).push(key);
3998
4148
  const seen = parsed.sources[key];
3999
- if (seen) (result.sources[locale] ??= {})[key] = seen;
4149
+ if (seen) (result.sources[locale] ??= emptyCatalog())[key] = seen;
4000
4150
  }
4001
4151
  }
4002
4152
  return result;
@@ -4665,6 +4815,12 @@ async function init(input = {}) {
4665
4815
  const next = host ? [...missing.length ? [installCommand(root, missing)] : [], host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
4666
4816
  const others = detectLibraries(root);
4667
4817
  if (found && others.length) next.push(`port the ${others.join(" and ")} catalogs: npx verbaly migrate reports, --write applies`);
4818
+ const source = scaffold.sourceLocale ?? "en";
4819
+ const catalogs = readdirSync(dir).filter((name) => name.endsWith(".json") && name[0] !== ".");
4820
+ if (!scaffold.locales?.some((locale) => locale !== source) && catalogs.length <= 1) {
4821
+ const other = source === "es" ? "en" : "es";
4822
+ next.push(`add a language: locales: ['${source}', '${other}'] in ${configFile}, then npx verbaly extract`);
4823
+ }
4668
4824
  return {
4669
4825
  created,
4670
4826
  skipped,
@@ -4981,11 +5137,11 @@ function pageSlice(v, locale, used) {
4981
5137
  return slice;
4982
5138
  }
4983
5139
  function sameUrl(written, url) {
4984
- return url !== void 0 && written.replace(/\/+$/, "") === url.replace(/\/+$/, "");
5140
+ return url !== void 0 && trimTrailingSlashes(written) === trimTrailingSlashes(url);
4985
5141
  }
4986
5142
  function publicPath(rel) {
4987
5143
  const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
4988
- return path.length > 1 ? path.replace(/\/+$/, "") : path;
5144
+ return path.length > 1 ? trimTrailingSlashes(path) : path;
4989
5145
  }
4990
5146
  function linkFor(links, name) {
4991
5147
  return links && Object.hasOwn(links, name) ? links[name] : void 0;
@@ -5036,7 +5192,7 @@ function stripBase(path, base) {
5036
5192
  return rest.startsWith("/") ? rest : path;
5037
5193
  }
5038
5194
  function normalizeBase(base) {
5039
- const trimmed = base?.replace(/^\/+/, "").replace(/\/+$/, "");
5195
+ const trimmed = trimTrailingSlashes(base?.replace(/^\/+/, "") ?? "");
5040
5196
  return trimmed ? `/${trimmed}` : "";
5041
5197
  }
5042
5198
  const REDIRECT_BODY = "(function(){var T=/^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|[0-9]{3}))?$/i;function M(t,g){t=String(t||\"\");if(S.indexOf(t)>=0)return t;if(g&&!T.test(t))return;while(t){var i=t.lastIndexOf(\"-\");if(i<0)return;t=t.slice(0,i);if(S.indexOf(t)>=0)return t}}var p=location.pathname;if(B){if(p.indexOf(B)!==0)return;p=p.slice(B.length)||\"/\";if(p.charAt(0)!==\"/\")return}if(M(p.split(\"/\")[1],1))return;var w;if(K)try{w=M(localStorage.getItem(K))}catch(e){}if(!w){var l=navigator.languages||[navigator.language];for(var i=0;i<l.length&&!w;i++)w=M(l[i])}if(!w||w===D)return;location.replace(B+\"/\"+w+(N&&p===\"/\"?\"\":p)+location.search+location.hash)})()";
@@ -5113,7 +5269,8 @@ async function renderSite(cfg, options = {}) {
5113
5269
  const locales = options.locales ?? cfg.locales;
5114
5270
  const attribute = options.attribute ?? cfg.render.attribute;
5115
5271
  const base = normalizeBase(options.base ?? cfg.render.base);
5116
- const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\/+$/, "");
5272
+ const wantedUrl = options.baseUrl ?? cfg.render.baseUrl;
5273
+ const baseUrl = typeof wantedUrl === "string" ? trimTrailingSlashes(wantedUrl) : void 0;
5117
5274
  const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== void 0;
5118
5275
  const patterns = options.exclude ?? cfg.render.exclude ?? [];
5119
5276
  const excluded = patterns.length > 0 ? picomatch(patterns) : () => false;
@@ -5143,7 +5300,7 @@ async function renderSite(cfg, options = {}) {
5143
5300
  ignore: locales.map((locale) => `${locale}/**`)
5144
5301
  });
5145
5302
  const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
5146
- const missing = {};
5303
+ const missing = emptyCatalog();
5147
5304
  const untranslatedHead = [];
5148
5305
  const urls = [];
5149
5306
  for (const file of files) {
@@ -5233,15 +5390,26 @@ function parseArgs$1(raw, attribute) {
5233
5390
  return;
5234
5391
  }
5235
5392
  }
5236
- function protectedRanges(html) {
5237
- const ranges = [];
5238
- const re = /<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
5239
- let m;
5240
- while ((m = re.exec(html)) !== null) {
5241
- const openEnd = m[0].startsWith("<!--") ? m.index : html.indexOf(">", m.index) + 1;
5242
- ranges.push([openEnd, m.index + m[0].length]);
5393
+ const OPAQUE_BLOCKS = [
5394
+ {
5395
+ open: "<!--",
5396
+ close: /(?<=<!--)-?>|--!?>/g
5397
+ },
5398
+ {
5399
+ open: /<script\b/gi,
5400
+ close: /<\/script(?=[\t\n\f\r />])/gi,
5401
+ closeTag: true
5402
+ },
5403
+ {
5404
+ open: /<style\b/gi,
5405
+ close: /<\/style(?=[\t\n\f\r />])/gi,
5406
+ closeTag: true
5243
5407
  }
5244
- return ranges;
5408
+ ];
5409
+ function protectedRanges(html) {
5410
+ return blocks(html, OPAQUE_BLOCKS).map(({ start, end }) => {
5411
+ return [html.startsWith("<!--", start) ? start : html.indexOf(">", start) + 1, end];
5412
+ });
5245
5413
  }
5246
5414
  function findClose(html, tagName, from, inSkip) {
5247
5415
  const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
@@ -5707,6 +5875,12 @@ function line(node) {
5707
5875
  return node.loc?.start?.line ?? 1;
5708
5876
  }
5709
5877
  // src/cli/commands/wrap.ts
5878
+ function binding(cfg, client) {
5879
+ if (cfg.host !== "next") return "in the component: `const t = useT()` from @verbaly/react";
5880
+ const onClient = "`const t = useT()` from @verbaly/next/client";
5881
+ if (client) return `"use client", so ${onClient}`;
5882
+ return `no "use client": a Server Component takes \`const t = await getT()\` from @verbaly/next/server, a client one ${onClient}`;
5883
+ }
5710
5884
  async function wrapCommand(cfg, values) {
5711
5885
  const result = await wrapProject(cfg, { write: values.write });
5712
5886
  if (result.wrapped.length === 0 && result.skipped.length === 0) {
@@ -5718,7 +5892,9 @@ async function wrapCommand(cfg, values) {
5718
5892
  const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));
5719
5893
  const verb = values.write ? "wrapped" : "would wrap";
5720
5894
  const note = values.write ? "" : " (report only, use --write to apply)";
5721
- const counts = values.write ? `${counted(texts.length, "text")} in ${counted(done.length, "file")}` : `${counted(result.wrapped.length, "text")} in ${counted(result.changed.length, "file")}`;
5895
+ let counts = `${counted(texts.length, "text")} in ${counted(done.length, "file")}`;
5896
+ const waiting = result.wrapped.length - texts.length;
5897
+ if (!values.write && waiting > 0) counts += `, and ${counted(waiting, "text")} in ${counted(blocked.size, "file")} once t is in scope`;
5722
5898
  console.log(`[verbaly] ${verb} ${counts}${note}`);
5723
5899
  for (const entry of values.write ? texts : result.wrapped) {
5724
5900
  const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
@@ -5730,10 +5906,7 @@ async function wrapCommand(cfg, values) {
5730
5906
  }
5731
5907
  if (result.blocked.length > 0) {
5732
5908
  console.log(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
5733
- for (const entry of result.blocked) {
5734
- const how = entry.client ? "\"use client\", so const t = useT()" : "no \"use client\": check which side renders it before you pick the binding";
5735
- console.log(` ${entry.file} ${counted(entry.texts, "text")}, ${how}`);
5736
- }
5909
+ for (const entry of result.blocked) console.log(` ${entry.file} ${counted(entry.texts, "text")}, ${binding(cfg, entry.client)}`);
5737
5910
  console.log(" next: add t there, run verbaly wrap --write again, then verbaly extract");
5738
5911
  } else if (values.write && done.length > 0) console.log(" next: run verbaly extract");
5739
5912
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verbaly/compiler",
3
- "version": "0.79.0",
3
+ "version": "0.80.0",
4
4
  "description": "Message extraction and type-safe codegen for Verbaly.",
5
5
  "keywords": [
6
6
  "i18n",
@@ -46,13 +46,13 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@babel/parser": "^8.0.10",
49
+ "@babel/parser": "^8.1.0",
50
50
  "jiti": "^2.7.0",
51
51
  "jsonc-parser": "^3.3.1",
52
52
  "magic-string": "^1.4.5",
53
53
  "picomatch": "^4.0.7",
54
54
  "tinyglobby": "^0.2.17",
55
- "verbaly": "0.79.0"
55
+ "verbaly": "0.80.0"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "@anthropic-ai/sdk": ">=0.110.0"
@@ -63,7 +63,7 @@
63
63
  }
64
64
  },
65
65
  "devDependencies": {
66
- "@anthropic-ai/sdk": "^1.3.0",
66
+ "@anthropic-ai/sdk": "^1.6.0",
67
67
  "@types/picomatch": "^4.0.3",
68
68
  "esbuild": "^0.28.2",
69
69
  "fast-check": "^4.10.2",