@verbaly/compiler 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { i as targetLocales, n as loadConfig, r as resolveConfig } from "./config-D8gkaunO.js";
2
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1
+ import { a as targetLocales, i as resolveConfig, r as loadConfig, t as findConfigFile } from "./config-B6MP3zwt.js";
2
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join, relative } from "node:path";
4
4
  import { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
5
5
  import { glob } from "tinyglobby";
@@ -721,6 +721,10 @@ function surplus(a, b) {
721
721
  function list(items) {
722
722
  return items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}` : items[0];
723
723
  }
724
+ const ESCAPED_SYNTAX = /(?<!\{)\{\{\s*[\w.]+\s*[|:][^{}]*\}\}/;
725
+ function escapedSyntax(message) {
726
+ return ESCAPED_SYNTAX.exec(message)?.[0];
727
+ }
724
728
  function validateMessage(message, locale) {
725
729
  const issues = [];
726
730
  for (const [name, shape] of shapes(message)) {
@@ -864,11 +868,21 @@ function generateRuntimeModule(cfg, options = {}) {
864
868
  const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
865
869
  const src = JSON.stringify(cfg.sourceLocale);
866
870
  const loaders = others.map((locale) => ` ${JSON.stringify(locale)}: () => import('${importPath(locale)}'),`).join("\n");
867
- return `import { createVerbaly } from 'verbaly';
871
+ return `import { createVerbaly, localeFromPath as readPath, localePath as writePath } from 'verbaly';
868
872
  import source from '${importPath(cfg.sourceLocale)}';
869
873
 
870
874
  export const sourceLocale = ${src};
871
875
  export const locales = ${JSON.stringify(cfg.locales)};
876
+ export const routing = ${JSON.stringify(cfg.routing)};
877
+
878
+ // bound to this project: the locale set, the source and the routing mode are never passed in
879
+ export function localePath(locale, options) {
880
+ return writePath(locale, { ...options, supported: locales, sourceLocale, routing });
881
+ }
882
+
883
+ export function localeFromPath(options) {
884
+ return readPath({ ...options, supported: locales });
885
+ }
872
886
 
873
887
  const localeLoaders = {
874
888
  ${loaders}
@@ -942,6 +956,15 @@ ${lines.join("\n")}
942
956
 
943
957
  export const sourceLocale: string;
944
958
  export const locales: string[];
959
+ export const routing: import('verbaly').Routing;
960
+ export function localePath(
961
+ locale: string,
962
+ options?: { path?: string; base?: string },
963
+ ): string;
964
+ export function localeFromPath(options?: {
965
+ path?: string;
966
+ base?: string;
967
+ }): string | undefined;
945
968
  export function loadMessages(locale: string): Promise<Record<string, string>>;
946
969
  export function createInstance(
947
970
  options?: import('verbaly').VerbalyOptions<VerbalyKey>,
@@ -1257,15 +1280,56 @@ function formatStatusResult(result) {
1257
1280
  }
1258
1281
  //#endregion
1259
1282
  //#region src/translate.ts
1283
+ const RETRY_STATUS = /* @__PURE__ */ new Set([
1284
+ 408,
1285
+ 409,
1286
+ 425,
1287
+ 429,
1288
+ 500,
1289
+ 502,
1290
+ 503,
1291
+ 504,
1292
+ 529
1293
+ ]);
1294
+ function retryable(error) {
1295
+ const status = error?.status;
1296
+ const code = error?.statusCode;
1297
+ const value = typeof status === "number" ? status : code;
1298
+ return typeof value === "number" ? RETRY_STATUS.has(value) : true;
1299
+ }
1300
+ function reason(error) {
1301
+ return error instanceof Error ? error.message : String(error);
1302
+ }
1303
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1304
+ async function attempt(run, retries, delay) {
1305
+ for (let round = 0;; round++) try {
1306
+ return await run();
1307
+ } catch (error) {
1308
+ if (round >= retries || !retryable(error)) throw error;
1309
+ await wait(delay * 2 ** round);
1310
+ }
1311
+ }
1312
+ async function pooled(jobs, limit, run) {
1313
+ let next = 0;
1314
+ const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
1315
+ while (next < jobs.length) await run(jobs[next++]);
1316
+ });
1317
+ await Promise.all(workers);
1318
+ }
1260
1319
  async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1261
1320
  const batchSize = options.batchSize ?? 20;
1321
+ const concurrency = Math.max(1, options.concurrency ?? 4);
1322
+ const retries = Math.max(0, options.retries ?? 2);
1323
+ const retryDelay = options.retryDelay ?? 500;
1262
1324
  const targets = targetLocales(cfg, options.locales);
1263
1325
  const source = catalogs[cfg.sourceLocale] ?? {};
1264
1326
  const result = {
1265
1327
  translated: {},
1266
1328
  invalid: {},
1267
- pending: {}
1329
+ pending: {},
1330
+ failed: []
1268
1331
  };
1332
+ const jobs = [];
1269
1333
  for (const locale of targets) {
1270
1334
  const catalog = catalogs[locale] ??= {};
1271
1335
  const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
@@ -1274,31 +1338,78 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1274
1338
  result.pending[locale] = missing;
1275
1339
  continue;
1276
1340
  }
1341
+ const batches = Math.ceil(missing.length / batchSize);
1277
1342
  for (let i = 0; i < missing.length; i += batchSize) {
1278
- const keys = missing.slice(i, i + batchSize);
1279
- const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
1280
- const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins[key]).map((key) => [key, options.origins[key]])) : void 0;
1281
- const out = await provider({
1343
+ const index = Math.floor(i / batchSize) + 1;
1344
+ jobs.push({
1345
+ locale,
1346
+ index,
1347
+ batches,
1348
+ keys: missing.slice(i, i + batchSize)
1349
+ });
1350
+ }
1351
+ }
1352
+ await pooled(jobs, concurrency, async (job) => {
1353
+ const { locale, keys } = job;
1354
+ const catalog = catalogs[locale];
1355
+ const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
1356
+ const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins[key]).map((key) => [key, options.origins[key]])) : void 0;
1357
+ let out;
1358
+ try {
1359
+ out = await attempt(() => provider({
1282
1360
  sourceLocale: cfg.sourceLocale,
1283
1361
  targetLocale: locale,
1284
1362
  messages,
1285
- origins
1363
+ origins,
1364
+ instructions: cfg.translate.instructions,
1365
+ glossary: glossaryFor(cfg, locale, messages)
1366
+ }), retries, retryDelay);
1367
+ } catch (error) {
1368
+ const message = reason(error);
1369
+ result.failed.push({
1370
+ locale,
1371
+ keys,
1372
+ error: message
1286
1373
  });
1287
- for (const key of keys) {
1288
- const text = out[key];
1289
- if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
1290
- catalog[key] = text;
1291
- (result.translated[locale] ??= []).push(key);
1292
- } else (result.invalid[locale] ??= []).push(key);
1293
- }
1374
+ options.onProgress?.({
1375
+ ...progressOf(job),
1376
+ error: message
1377
+ });
1378
+ return;
1294
1379
  }
1295
- }
1380
+ for (const key of keys) {
1381
+ const text = out[key];
1382
+ if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
1383
+ catalog[key] = text;
1384
+ (result.translated[locale] ??= []).push(key);
1385
+ } else (result.invalid[locale] ??= []).push(key);
1386
+ }
1387
+ options.onProgress?.(progressOf(job));
1388
+ });
1389
+ for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
1390
+ for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
1391
+ result.failed.sort((a, b) => a.locale.localeCompare(b.locale) || compare(a.keys, b.keys));
1296
1392
  return result;
1297
1393
  }
1394
+ function compare(a, b) {
1395
+ return (a[0] ?? "").localeCompare(b[0] ?? "");
1396
+ }
1397
+ function formatTranslateFailures(failed) {
1398
+ const grouped = [];
1399
+ for (const entry of failed) {
1400
+ const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
1401
+ if (same) same.keys = [...same.keys, ...entry.keys];
1402
+ else grouped.push({
1403
+ ...entry,
1404
+ keys: [...entry.keys]
1405
+ });
1406
+ }
1407
+ return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
1408
+ }
1298
1409
  async function resolveProvider(cfg, model) {
1299
1410
  const configured = cfg.translate.provider;
1300
1411
  if (typeof configured === "function") return configured;
1301
- const { claudeProvider } = await import("./claude-CrAkiSVP.js");
1412
+ const { claudeProvider } = await import("./claude-DGo229kG.js");
1302
1413
  return claudeProvider({ model: model ?? cfg.translate.model });
1303
1414
  }
1304
1415
  function structureMatches(source, translated) {
@@ -1308,6 +1419,451 @@ function structureMatches(source, translated) {
1308
1419
  return false;
1309
1420
  }
1310
1421
  }
1422
+ function progressOf(job) {
1423
+ return {
1424
+ locale: job.locale,
1425
+ batch: job.index,
1426
+ batches: job.batches,
1427
+ keys: job.keys.length
1428
+ };
1429
+ }
1430
+ function glossaryFor(cfg, locale, messages) {
1431
+ const entries = cfg.translate.glossary;
1432
+ if (!entries) return void 0;
1433
+ const text = Object.values(messages).join("\n").toLowerCase();
1434
+ const out = {};
1435
+ for (const [term, rendering] of Object.entries(entries)) {
1436
+ if (!text.includes(term.toLowerCase())) continue;
1437
+ const value = typeof rendering === "string" ? rendering : rendering[locale];
1438
+ if (value) out[term] = value;
1439
+ }
1440
+ return Object.keys(out).length > 0 ? out : void 0;
1441
+ }
1442
+ //#endregion
1443
+ //#region src/init.ts
1444
+ const HOSTS = [
1445
+ {
1446
+ name: "nuxt",
1447
+ dep: "nuxt",
1448
+ pkg: "@verbaly/nuxt",
1449
+ wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
1450
+ },
1451
+ {
1452
+ name: "next",
1453
+ dep: "next",
1454
+ pkg: "@verbaly/next",
1455
+ wire: "wrap the export of next.config with withVerbaly"
1456
+ },
1457
+ {
1458
+ name: "sveltekit",
1459
+ dep: "@sveltejs/kit",
1460
+ pkg: "@verbaly/vite",
1461
+ wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
1462
+ },
1463
+ {
1464
+ name: "astro",
1465
+ dep: "astro",
1466
+ pkg: "@verbaly/astro",
1467
+ wire: "add verbaly() to the integrations in astro.config"
1468
+ },
1469
+ {
1470
+ name: "vite",
1471
+ dep: "vite",
1472
+ pkg: "@verbaly/vite",
1473
+ wire: "add verbaly() to the plugins in vite.config"
1474
+ },
1475
+ {
1476
+ name: "webpack",
1477
+ dep: "webpack",
1478
+ pkg: "@verbaly/unplugin",
1479
+ wire: "add the verbaly webpack plugin to your build config"
1480
+ },
1481
+ {
1482
+ name: "rspack",
1483
+ dep: "@rspack/core",
1484
+ pkg: "@verbaly/unplugin",
1485
+ wire: "add the verbaly rspack plugin to your build config"
1486
+ },
1487
+ {
1488
+ name: "rollup",
1489
+ dep: "rollup",
1490
+ pkg: "@verbaly/unplugin",
1491
+ wire: "add the verbaly rollup plugin to your build config"
1492
+ },
1493
+ {
1494
+ name: "esbuild",
1495
+ dep: "esbuild",
1496
+ pkg: "@verbaly/unplugin",
1497
+ wire: "add the verbaly esbuild plugin to your build config"
1498
+ }
1499
+ ];
1500
+ const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
1501
+ function readDependencies(root) {
1502
+ const path = join(root, "package.json");
1503
+ if (!existsSync(path)) return {};
1504
+ try {
1505
+ const pkg = JSON.parse(readFileSync(path, "utf8"));
1506
+ return {
1507
+ ...pkg.dependencies,
1508
+ ...pkg.devDependencies
1509
+ };
1510
+ } catch {
1511
+ return {};
1512
+ }
1513
+ }
1514
+ function detectHost(root) {
1515
+ const deps = readDependencies(root);
1516
+ return HOSTS.find((host) => deps[host.dep]);
1517
+ }
1518
+ //#endregion
1519
+ //#region src/doctor.ts
1520
+ const PREVIEW = 5;
1521
+ const ROUTING_SAYS = {
1522
+ "prefix-except-source": "the source locale has no prefix, every other locale does",
1523
+ "prefix-all": "every locale has a prefix, the source included",
1524
+ "no-prefix": "the language is not in the url, one address serves every locale"
1525
+ };
1526
+ const ICON = {
1527
+ ok: "✓",
1528
+ warn: "⚠",
1529
+ error: "✗"
1530
+ };
1531
+ function formatDoctorEntry(entry) {
1532
+ const head = ` ${ICON[entry.level]} ${entry.check}: ${entry.message}`;
1533
+ return entry.fix ? `${head}
1534
+ fix: ${entry.fix}` : head;
1535
+ }
1536
+ async function doctor(cfg) {
1537
+ const entries = [];
1538
+ const ok = (name, message) => entries.push({
1539
+ level: "ok",
1540
+ check: name,
1541
+ message
1542
+ });
1543
+ const warn = (name, message, fix) => entries.push({
1544
+ level: "warn",
1545
+ check: name,
1546
+ message,
1547
+ fix
1548
+ });
1549
+ const error = (name, message, fix) => entries.push({
1550
+ level: "error",
1551
+ check: name,
1552
+ message,
1553
+ fix
1554
+ });
1555
+ const rel = (path) => relative(cfg.root, path).replaceAll("\\", "/");
1556
+ const configFile = findConfigFile(cfg.root);
1557
+ if (configFile) ok("config", `${configFile} found`);
1558
+ else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
1559
+ const catalogs = {};
1560
+ let catalogsHealthy = true;
1561
+ if (!existsSync(cfg.dir)) {
1562
+ catalogsHealthy = false;
1563
+ error("catalogs", `catalogs directory ${rel(cfg.dir)}/ does not exist`, "run `npx verbaly init` to scaffold it");
1564
+ } else {
1565
+ for (const locale of cfg.locales) {
1566
+ const file = join(cfg.dir, `${locale}.json`);
1567
+ if (!existsSync(file)) {
1568
+ catalogsHealthy = false;
1569
+ error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
1570
+ continue;
1571
+ }
1572
+ try {
1573
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
1574
+ const bad = badLeaf(parsed);
1575
+ if (bad) {
1576
+ catalogsHealthy = false;
1577
+ error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
1578
+ } else catalogs[locale] = flatten(parsed);
1579
+ } catch {
1580
+ catalogsHealthy = false;
1581
+ error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
1582
+ }
1583
+ }
1584
+ if (catalogsHealthy) ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/`);
1585
+ }
1586
+ const source = catalogs[cfg.sourceLocale];
1587
+ 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`");
1588
+ const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
1589
+ 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");
1590
+ else ok("routing", `${cfg.routing}: ${ROUTING_SAYS[cfg.routing]}`);
1591
+ const deps = readDependencies(cfg.root);
1592
+ const host = detectHost(cfg.root);
1593
+ const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
1594
+ if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
1595
+ else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
1596
+ else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `pnpm add -D ${host.pkg} and ${host.wire}`);
1597
+ const scanning = cfg.include.length > 0;
1598
+ if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
1599
+ if (source && scanning && cfg.dts !== false) {
1600
+ const dtsPath = cfg.dts ?? join(cfg.root, "verbaly.d.ts");
1601
+ if (!existsSync(dtsPath)) warn("types", "verbaly.d.ts has not been generated", "run `npx verbaly extract`");
1602
+ else if (readFileSync(dtsPath, "utf8") !== generateDts(source)) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
1603
+ else ok("types", "verbaly.d.ts is up to date");
1604
+ }
1605
+ const registry = await extractProject(cfg);
1606
+ if (scanning) {
1607
+ const unreadable = registry.parseErrors();
1608
+ if (unreadable.length > 0) {
1609
+ const first = unreadable[0];
1610
+ warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
1611
+ }
1612
+ const stray = registry.strayImports();
1613
+ if (stray.length > 0) {
1614
+ const files = [...new Set(stray.map((entry) => rel(entry.file)))];
1615
+ 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");
1616
+ }
1617
+ const escaped = [...registry.messages().values()].map((msg) => ({
1618
+ file: rel(msg.file),
1619
+ slice: escapedSyntax(msg.message)
1620
+ })).filter((entry) => entry.slice !== void 0);
1621
+ if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${escaped[0].slice})`, "a tagged template takes its values from ${…}: use t(key, params) for a plural or format block");
1622
+ }
1623
+ if (source && scanning) {
1624
+ const extracted = registry.messages();
1625
+ const used = registry.usedKeys();
1626
+ const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
1627
+ if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, "run `npx verbaly extract --prune` to drop them");
1628
+ else ok("orphans", "no orphan keys");
1629
+ }
1630
+ if (catalogsHealthy) {
1631
+ const result = check(cfg, catalogs, registry);
1632
+ 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)");
1633
+ if (result.missing.length > 0) {
1634
+ const locales = [...new Set(result.missing.map((m) => m.locale))];
1635
+ warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
1636
+ }
1637
+ const broken = result.broken.filter((entry) => entry.severity === "error");
1638
+ if (broken.length > 0) {
1639
+ const locales = [...new Set(broken.map((b) => b.locale))];
1640
+ error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
1641
+ }
1642
+ const warnings = result.broken.filter((entry) => entry.severity === "warning");
1643
+ 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");
1644
+ if (result.ok) ok("translations", "all translations complete");
1645
+ }
1646
+ return {
1647
+ ok: entries.every((entry) => entry.level !== "error"),
1648
+ entries
1649
+ };
1650
+ }
1651
+ function preview(keys) {
1652
+ const head = keys.slice(0, PREVIEW).join(", ");
1653
+ return keys.length > PREVIEW ? `${head}, …` : head;
1654
+ }
1655
+ //#endregion
1656
+ //#region src/wrap.ts
1657
+ const WRAP_ATTRS = /* @__PURE__ */ new Set([
1658
+ "title",
1659
+ "alt",
1660
+ "placeholder",
1661
+ "aria-label"
1662
+ ]);
1663
+ const T_NAMES = /* @__PURE__ */ new Set(["t"]);
1664
+ const LETTER = /\p{L}/u;
1665
+ async function wrapProject(cfg, options = {}) {
1666
+ const files = (await glob(cfg.include, {
1667
+ cwd: cfg.root,
1668
+ ignore: cfg.exclude,
1669
+ absolute: true
1670
+ })).filter((file) => /\.[jt]sx$/.test(file));
1671
+ const result = {
1672
+ files: files.length,
1673
+ changed: [],
1674
+ wrapped: [],
1675
+ skipped: []
1676
+ };
1677
+ for (const file of files) {
1678
+ const code = readFileSync(file, "utf8");
1679
+ const label = relative(cfg.root, file).replaceAll("\\", "/");
1680
+ const out = wrapCode(code, label);
1681
+ result.wrapped.push(...out.wrapped);
1682
+ result.skipped.push(...out.skipped);
1683
+ if (out.code !== void 0) {
1684
+ result.changed.push(label);
1685
+ if (options.write) writeFileSync(file, out.code);
1686
+ }
1687
+ }
1688
+ return result;
1689
+ }
1690
+ function wrapCode(code, file) {
1691
+ const wrapped = [];
1692
+ const skipped = [];
1693
+ let ast;
1694
+ try {
1695
+ ast = parse$1(code, {
1696
+ sourceType: "module",
1697
+ errorRecovery: true,
1698
+ plugins: ["typescript", "jsx"]
1699
+ }).program;
1700
+ } catch {
1701
+ return {
1702
+ wrapped,
1703
+ skipped
1704
+ };
1705
+ }
1706
+ const s = new MagicString(code);
1707
+ const visited = /* @__PURE__ */ new Set();
1708
+ let changed = false;
1709
+ walk$1(ast, (node) => {
1710
+ if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
1711
+ if (visited.has(node)) return;
1712
+ processElement(node);
1713
+ });
1714
+ return changed ? {
1715
+ code: s.toString(),
1716
+ wrapped,
1717
+ skipped
1718
+ } : {
1719
+ wrapped,
1720
+ skipped
1721
+ };
1722
+ function processElement(node) {
1723
+ visited.add(node);
1724
+ if (node.type === "JSXElement") {
1725
+ const opening = node.openingElement;
1726
+ const name = opening.name;
1727
+ if (name.type === "JSXIdentifier" && name.name === "Trans") return markSubtree(node);
1728
+ if (hasVerbalyAttr(opening)) return markSubtree(node);
1729
+ wrapAttributes(opening);
1730
+ }
1731
+ const children = node.children ?? [];
1732
+ const hasElementChild = children.some((c) => c.type === "JSXElement" || c.type === "JSXFragment");
1733
+ const hasText = children.some((c) => c.type === "JSXText" && LETTER.test(c.value) || c.type === "JSXExpressionContainer" && c.expression.type === "StringLiteral" && LETTER.test(c.expression.value));
1734
+ if (hasElementChild && hasText) {
1735
+ skip(node, snippet(children), "mixed text and markup: wrap by hand or use <Trans>");
1736
+ return markSubtree(node);
1737
+ }
1738
+ if (hasText) {
1739
+ wrapSegment(node, children);
1740
+ return markSubtree(node);
1741
+ }
1742
+ for (const child of children) if (child.type === "JSXElement" || child.type === "JSXFragment") processElement(child);
1743
+ }
1744
+ function wrapSegment(parent, children) {
1745
+ const meaningful = children.filter((c) => c.type === "JSXText" && c.value.trim() !== "" || c.type === "JSXExpressionContainer" && c.expression.type !== "JSXEmptyExpression");
1746
+ if (meaningful.length === 0) return;
1747
+ const first = meaningful[0];
1748
+ const last = meaningful[meaningful.length - 1];
1749
+ let template = "";
1750
+ let report = "";
1751
+ for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {
1752
+ const child = children[i];
1753
+ if (child.type === "JSXText") {
1754
+ let value = cleanJsxText(child.value);
1755
+ if (child === first) value = value.trimStart();
1756
+ if (child === last) value = value.trimEnd();
1757
+ template += escapeTemplate(value);
1758
+ report += value;
1759
+ } else if (child.type === "JSXExpressionContainer") {
1760
+ const expr = child.expression;
1761
+ if (expr.type === "JSXEmptyExpression") continue;
1762
+ if (usesT(expr)) {
1763
+ skip(parent, snippet(children), "already uses t: finish it by hand");
1764
+ return;
1765
+ }
1766
+ if (containsJsx(expr)) {
1767
+ skip(parent, snippet(children), "an expression renders markup: wrap by hand or use <Trans>");
1768
+ markSubtree(child);
1769
+ return;
1770
+ }
1771
+ if (expr.type === "StringLiteral") {
1772
+ template += escapeTemplate(expr.value);
1773
+ report += expr.value;
1774
+ } else {
1775
+ const source = code.slice(expr.start, expr.end);
1776
+ template += "${" + source + "}";
1777
+ report += "${" + source + "}";
1778
+ }
1779
+ } else return;
1780
+ }
1781
+ if (!LETTER.test(report)) return;
1782
+ const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
1783
+ const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
1784
+ s.overwrite(start, end, "{t`" + template + "`}");
1785
+ changed = true;
1786
+ wrapped.push({
1787
+ file,
1788
+ line: line(first),
1789
+ text: report,
1790
+ kind: "text"
1791
+ });
1792
+ }
1793
+ function wrapAttributes(opening) {
1794
+ for (const attr of opening.attributes) {
1795
+ if (attr.type !== "JSXAttribute") continue;
1796
+ const name = attr.name;
1797
+ if (name.type !== "JSXIdentifier" || !WRAP_ATTRS.has(name.name)) continue;
1798
+ const value = attr.value;
1799
+ if (value?.type !== "StringLiteral") continue;
1800
+ const raw = value.value;
1801
+ if (!LETTER.test(raw)) continue;
1802
+ s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
1803
+ changed = true;
1804
+ wrapped.push({
1805
+ file,
1806
+ line: line(value),
1807
+ text: raw,
1808
+ kind: "attribute",
1809
+ attribute: name.name
1810
+ });
1811
+ }
1812
+ }
1813
+ function skip(node, text, reason) {
1814
+ skipped.push({
1815
+ file,
1816
+ line: line(node),
1817
+ text,
1818
+ reason
1819
+ });
1820
+ }
1821
+ function snippet(children) {
1822
+ const start = children[0]?.start ?? 0;
1823
+ const end = children[children.length - 1]?.end ?? start;
1824
+ const text = code.slice(start, end).replace(/\s+/g, " ").trim();
1825
+ return text.length > 60 ? text.slice(0, 59) + "…" : text;
1826
+ }
1827
+ function markSubtree(node) {
1828
+ walk$1(node, (n) => {
1829
+ if (n.type === "JSXElement" || n.type === "JSXFragment") visited.add(n);
1830
+ });
1831
+ }
1832
+ }
1833
+ function hasVerbalyAttr(opening) {
1834
+ return opening.attributes.some((attr) => {
1835
+ if (attr.type !== "JSXAttribute") return false;
1836
+ const name = attr.name;
1837
+ return name.type === "JSXIdentifier" && name.name.startsWith("data-verbaly");
1838
+ });
1839
+ }
1840
+ function usesT(node) {
1841
+ let found = false;
1842
+ walk$1(node, (n) => {
1843
+ if (n.type === "TaggedTemplateExpression" && isTReference(n.tag, T_NAMES)) found = true;
1844
+ if (n.type === "CallExpression" && isTReference(n.callee, T_NAMES)) found = true;
1845
+ });
1846
+ return found;
1847
+ }
1848
+ function containsJsx(node) {
1849
+ let found = false;
1850
+ walk$1(node, (n) => {
1851
+ if (n.type === "JSXElement" || n.type === "JSXFragment") found = true;
1852
+ });
1853
+ return found;
1854
+ }
1855
+ function escapeTemplate(text) {
1856
+ return text.replace(/[\\`]/g, "\\$&").replace(/\$\{/g, "\\${");
1857
+ }
1858
+ function leadingWs(text) {
1859
+ return text.length - text.trimStart().length;
1860
+ }
1861
+ function trailingWs(text) {
1862
+ return text.length - text.trimEnd().length;
1863
+ }
1864
+ function line(node) {
1865
+ return node.loc?.start?.line ?? 1;
1866
+ }
1311
1867
  //#endregion
1312
1868
  //#region src/render.ts
1313
1869
  function localeInstance(catalogs, locale, sourceLocale) {
@@ -1483,6 +2039,13 @@ function injectAlternates(ms, html, alternates) {
1483
2039
  const head = /<\/head\s*>/i.exec(html);
1484
2040
  if (head) ms.appendLeft(head.index, block);
1485
2041
  }
2042
+ const TITLE_TAG = /<title\b([^>]*)>/i;
2043
+ const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
2044
+ function headIsBound(html, attr) {
2045
+ if (REFRESH_META.test(html)) return true;
2046
+ const title = TITLE_TAG.exec(html);
2047
+ return title ? title[1].includes(attr) : true;
2048
+ }
1486
2049
  async function renderSite(cfg, options = {}) {
1487
2050
  const site = join(cfg.root, options.site ?? cfg.render.site ?? "dist");
1488
2051
  const locales = options.locales ?? cfg.locales;
@@ -1516,10 +2079,12 @@ async function renderSite(cfg, options = {}) {
1516
2079
  });
1517
2080
  const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
1518
2081
  const missing = {};
2082
+ const untranslatedHead = [];
1519
2083
  const urls = [];
1520
2084
  for (const file of files) {
1521
2085
  const html = readFileSync(file, "utf8");
1522
2086
  const rel = relative(site, file).replace(/\\/g, "/");
2087
+ if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
1523
2088
  const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale) : [];
1524
2089
  if (wantHreflang) urls.push({
1525
2090
  rel,
@@ -1555,9 +2120,16 @@ async function renderSite(cfg, options = {}) {
1555
2120
  return {
1556
2121
  files: files.length,
1557
2122
  locales: [...locales],
1558
- missing
2123
+ missing,
2124
+ untranslatedHead
1559
2125
  };
1560
2126
  }
2127
+ function formatRenderWarnings(result, sourceLocale) {
2128
+ const lines = [];
2129
+ for (const [locale, keys] of Object.entries(result.missing)) lines.push(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
2130
+ if (result.untranslatedHead.length > 0) lines.push(` ${counted(result.untranslatedHead.length, "page")} of ${result.files} ship the same <title> in every locale (${result.untranslatedHead[0]}), so search results read in ${sourceLocale}`, ` fix: bind the head too, <title data-verbaly="key"> and a meta through data-verbaly-attr`);
2131
+ return lines;
2132
+ }
1561
2133
  function pageUrl(baseUrl, prefix, rel) {
1562
2134
  const path = rel.replace(/(^|\/)index\.html$/, "$1");
1563
2135
  return `${baseUrl}${prefix}${path ? `/${path}` : "/"}`;
@@ -1658,6 +2230,6 @@ function decodeEntities(text) {
1658
2230
  return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
1659
2231
  }
1660
2232
  //#endregion
1661
- export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, collectOrigins, counted, createSourceFilter, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatStatusResult, generateDts, generateLocaleModule, generateRuntimeModule, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, pruneCatalogs, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, transformCode, transformSource, translateCatalogs, writeCatalog, writeDts };
2233
+ export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, collectOrigins, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, pruneCatalogs, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, transformCode, transformSource, translateCatalogs, wrapProject, writeCatalog, writeDts };
1662
2234
 
1663
2235
  //# sourceMappingURL=index.js.map