@verbaly/compiler 0.52.0 → 0.53.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 +9 -7
- package/dist/cli.js +3 -3
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +15 -2
- package/dist/index.js +700 -684
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -701,8 +701,8 @@ async function extractProject(cfg) {
|
|
|
701
701
|
for (const file of files) registry.update(file, analyzeFile(readFileSync(file, "utf8"), file));
|
|
702
702
|
return registry;
|
|
703
703
|
}
|
|
704
|
-
async function collectOrigins(cfg) {
|
|
705
|
-
const registry = await extractProject(cfg);
|
|
704
|
+
async function collectOrigins(cfg, reuse) {
|
|
705
|
+
const registry = reuse ?? await extractProject(cfg);
|
|
706
706
|
const origins = {};
|
|
707
707
|
for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
|
|
708
708
|
return origins;
|
|
@@ -831,7 +831,7 @@ function validatePair(source, translated) {
|
|
|
831
831
|
const newParams = surplus(paramNames(translated), paramNames(source));
|
|
832
832
|
if (lostParams.length > 0) issues.push({
|
|
833
833
|
severity: "error",
|
|
834
|
-
message: `${list(lostParams.map((name) => `{${name}}`))} ${lostParams.length > 1 ? "are" : "is"} missing, so ${lostParams.length > 1 ? "their values" : "its value
|
|
834
|
+
message: `${list(lostParams.map((name) => `{${name}}`))} ${lostParams.length > 1 ? "are" : "is"} missing, so ${lostParams.length > 1 ? "their values never reach" : "its value never reaches"} the text`
|
|
835
835
|
});
|
|
836
836
|
if (newParams.length > 0) issues.push({
|
|
837
837
|
severity: "error",
|
|
@@ -1474,6 +1474,16 @@ function markDrafts(drafts, locale, keys) {
|
|
|
1474
1474
|
if (!keys.length) return;
|
|
1475
1475
|
drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
|
|
1476
1476
|
}
|
|
1477
|
+
function clearDrafts(drafts, locale, keys) {
|
|
1478
|
+
if (!drafts[locale]) return;
|
|
1479
|
+
if (!keys) {
|
|
1480
|
+
delete drafts[locale];
|
|
1481
|
+
return;
|
|
1482
|
+
}
|
|
1483
|
+
const drop = new Set(keys);
|
|
1484
|
+
drafts[locale] = drafts[locale].filter((key) => !drop.has(key));
|
|
1485
|
+
if (!drafts[locale].length) delete drafts[locale];
|
|
1486
|
+
}
|
|
1477
1487
|
function effectiveDrafts(drafts, catalogs) {
|
|
1478
1488
|
const out = {};
|
|
1479
1489
|
for (const [locale, keys] of Object.entries(drafts)) {
|
|
@@ -1534,6 +1544,164 @@ function formatStatusResult(result) {
|
|
|
1534
1544
|
return lines.join("\n");
|
|
1535
1545
|
}
|
|
1536
1546
|
//#endregion
|
|
1547
|
+
//#region src/doctor.ts
|
|
1548
|
+
const PREVIEW = 5;
|
|
1549
|
+
function readRoutingChoice(root, configFile) {
|
|
1550
|
+
try {
|
|
1551
|
+
return /\brouting["']?\s*[:=]/.test(readFileSync(join(root, configFile), "utf8"));
|
|
1552
|
+
} catch {
|
|
1553
|
+
return false;
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
const ROUTING_SAYS = {
|
|
1557
|
+
"prefix-except-source": "the source locale has no prefix, every other locale does",
|
|
1558
|
+
"prefix-all": "every locale has a prefix, the source included",
|
|
1559
|
+
"no-prefix": "the language is not in the url, one address serves every locale"
|
|
1560
|
+
};
|
|
1561
|
+
const ICON = {
|
|
1562
|
+
ok: "✓",
|
|
1563
|
+
warn: "⚠",
|
|
1564
|
+
error: "✗"
|
|
1565
|
+
};
|
|
1566
|
+
function formatDoctorEntry(entry) {
|
|
1567
|
+
const head = ` ${ICON[entry.level]} ${entry.check}: ${entry.message}`;
|
|
1568
|
+
return entry.fix ? `${head}
|
|
1569
|
+
fix: ${entry.fix}` : head;
|
|
1570
|
+
}
|
|
1571
|
+
async function doctor(cfg) {
|
|
1572
|
+
const entries = [];
|
|
1573
|
+
const ok = (name, message) => entries.push({
|
|
1574
|
+
level: "ok",
|
|
1575
|
+
check: name,
|
|
1576
|
+
message
|
|
1577
|
+
});
|
|
1578
|
+
const warn = (name, message, fix) => entries.push({
|
|
1579
|
+
level: "warn",
|
|
1580
|
+
check: name,
|
|
1581
|
+
message,
|
|
1582
|
+
fix
|
|
1583
|
+
});
|
|
1584
|
+
const error = (name, message, fix) => entries.push({
|
|
1585
|
+
level: "error",
|
|
1586
|
+
check: name,
|
|
1587
|
+
message,
|
|
1588
|
+
fix
|
|
1589
|
+
});
|
|
1590
|
+
const rel = (path) => relative(cfg.root, path).replaceAll("\\", "/");
|
|
1591
|
+
const configFile = findConfigFile(cfg.root);
|
|
1592
|
+
if (configFile) ok("config", `${configFile} found`);
|
|
1593
|
+
else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
|
|
1594
|
+
if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
|
|
1595
|
+
else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
|
|
1596
|
+
const catalogs = {};
|
|
1597
|
+
let catalogsHealthy = true;
|
|
1598
|
+
if (!existsSync(cfg.dir)) {
|
|
1599
|
+
catalogsHealthy = false;
|
|
1600
|
+
error("catalogs", `catalogs directory ${rel(cfg.dir)}/ does not exist`, "run `npx verbaly init` to scaffold it");
|
|
1601
|
+
} else {
|
|
1602
|
+
for (const locale of cfg.locales) {
|
|
1603
|
+
const file = join(cfg.dir, `${locale}.json`);
|
|
1604
|
+
if (!existsSync(file)) {
|
|
1605
|
+
catalogsHealthy = false;
|
|
1606
|
+
error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
|
|
1607
|
+
continue;
|
|
1608
|
+
}
|
|
1609
|
+
try {
|
|
1610
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
1611
|
+
const bad = badLeaf(parsed);
|
|
1612
|
+
if (bad) {
|
|
1613
|
+
catalogsHealthy = false;
|
|
1614
|
+
error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
|
|
1615
|
+
} else catalogs[locale] = flatten(parsed);
|
|
1616
|
+
} catch {
|
|
1617
|
+
catalogsHealthy = false;
|
|
1618
|
+
error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
if (catalogsHealthy) {
|
|
1622
|
+
const how = cfg.localesDeclared ? "" : ", no locales set, so the catalog files decide";
|
|
1623
|
+
ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/${how}`);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
const source = catalogs[cfg.sourceLocale];
|
|
1627
|
+
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`");
|
|
1628
|
+
const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
|
|
1629
|
+
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");
|
|
1630
|
+
else {
|
|
1631
|
+
const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
|
|
1632
|
+
ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
|
|
1633
|
+
}
|
|
1634
|
+
const deps = readDependencies(cfg.root);
|
|
1635
|
+
const host = detectHost(cfg.root);
|
|
1636
|
+
const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
|
|
1637
|
+
if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
|
|
1638
|
+
else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
|
|
1639
|
+
else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `pnpm add -D ${host.pkg} and ${host.wire}`);
|
|
1640
|
+
const scanning = cfg.include.length > 0;
|
|
1641
|
+
if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
|
|
1642
|
+
if (source && scanning && cfg.dts !== false) {
|
|
1643
|
+
const dtsPath = cfg.dts ?? join(cfg.root, "verbaly.d.ts");
|
|
1644
|
+
if (!existsSync(dtsPath)) warn("types", "verbaly.d.ts has not been generated", "run `npx verbaly extract`");
|
|
1645
|
+
else if (readFileSync(dtsPath, "utf8") !== generateDts(source, { inlineCatalog: cfg.render.inlineCatalog === true })) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
|
|
1646
|
+
else ok("types", "verbaly.d.ts is up to date");
|
|
1647
|
+
}
|
|
1648
|
+
const registry = await extractProject(cfg);
|
|
1649
|
+
if (scanning) {
|
|
1650
|
+
const unreadable = registry.parseErrors();
|
|
1651
|
+
if (unreadable.length > 0) {
|
|
1652
|
+
const first = unreadable[0];
|
|
1653
|
+
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");
|
|
1654
|
+
}
|
|
1655
|
+
const stray = registry.strayImports();
|
|
1656
|
+
if (stray.length > 0) {
|
|
1657
|
+
const files = [...new Set(stray.map((entry) => rel(entry.file)))];
|
|
1658
|
+
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");
|
|
1659
|
+
}
|
|
1660
|
+
const escaped = [...registry.messages().values()].map((msg) => ({
|
|
1661
|
+
file: rel(msg.file),
|
|
1662
|
+
slice: escapedSyntax(msg.message)
|
|
1663
|
+
})).filter((entry) => entry.slice !== void 0);
|
|
1664
|
+
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");
|
|
1665
|
+
}
|
|
1666
|
+
if (source && scanning) {
|
|
1667
|
+
const extracted = registry.messages();
|
|
1668
|
+
const used = registry.usedKeys();
|
|
1669
|
+
const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
|
|
1670
|
+
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");
|
|
1671
|
+
else ok("orphans", "no orphan keys");
|
|
1672
|
+
}
|
|
1673
|
+
const excluded = cfg.bundle.exclude ?? [];
|
|
1674
|
+
if (excluded.length > 0 && catalogsHealthy) {
|
|
1675
|
+
const issues = auditBundle(cfg, catalogs, registry);
|
|
1676
|
+
for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
|
|
1677
|
+
if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
|
|
1678
|
+
}
|
|
1679
|
+
if (catalogsHealthy) {
|
|
1680
|
+
const result = check(cfg, catalogs, registry);
|
|
1681
|
+
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)");
|
|
1682
|
+
if (result.missing.length > 0) {
|
|
1683
|
+
const locales = [...new Set(result.missing.map((m) => m.locale))];
|
|
1684
|
+
warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
|
|
1685
|
+
}
|
|
1686
|
+
const broken = result.broken.filter((entry) => entry.severity === "error");
|
|
1687
|
+
if (broken.length > 0) {
|
|
1688
|
+
const locales = [...new Set(broken.map((b) => b.locale))];
|
|
1689
|
+
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");
|
|
1690
|
+
}
|
|
1691
|
+
const warnings = result.broken.filter((entry) => entry.severity === "warning");
|
|
1692
|
+
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");
|
|
1693
|
+
if (result.ok) ok("translations", "all translations complete");
|
|
1694
|
+
}
|
|
1695
|
+
return {
|
|
1696
|
+
ok: entries.every((entry) => entry.level !== "error"),
|
|
1697
|
+
entries
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1700
|
+
function preview(keys) {
|
|
1701
|
+
const head = keys.slice(0, PREVIEW).join(", ");
|
|
1702
|
+
return keys.length > PREVIEW ? `${head}, …` : head;
|
|
1703
|
+
}
|
|
1704
|
+
//#endregion
|
|
1537
1705
|
//#region src/translate.ts
|
|
1538
1706
|
const RETRY_STATUS = /* @__PURE__ */ new Set([
|
|
1539
1707
|
408,
|
|
@@ -1695,446 +1863,12 @@ function glossaryFor(cfg, locale, messages) {
|
|
|
1695
1863
|
return Object.keys(out).length > 0 ? out : void 0;
|
|
1696
1864
|
}
|
|
1697
1865
|
//#endregion
|
|
1698
|
-
//#region src/
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
return false;
|
|
1705
|
-
}
|
|
1706
|
-
}
|
|
1707
|
-
const ROUTING_SAYS = {
|
|
1708
|
-
"prefix-except-source": "the source locale has no prefix, every other locale does",
|
|
1709
|
-
"prefix-all": "every locale has a prefix, the source included",
|
|
1710
|
-
"no-prefix": "the language is not in the url, one address serves every locale"
|
|
1711
|
-
};
|
|
1712
|
-
const ICON = {
|
|
1713
|
-
ok: "✓",
|
|
1714
|
-
warn: "⚠",
|
|
1715
|
-
error: "✗"
|
|
1716
|
-
};
|
|
1717
|
-
function formatDoctorEntry(entry) {
|
|
1718
|
-
const head = ` ${ICON[entry.level]} ${entry.check}: ${entry.message}`;
|
|
1719
|
-
return entry.fix ? `${head}
|
|
1720
|
-
fix: ${entry.fix}` : head;
|
|
1721
|
-
}
|
|
1722
|
-
async function doctor(cfg) {
|
|
1723
|
-
const entries = [];
|
|
1724
|
-
const ok = (name, message) => entries.push({
|
|
1725
|
-
level: "ok",
|
|
1726
|
-
check: name,
|
|
1727
|
-
message
|
|
1728
|
-
});
|
|
1729
|
-
const warn = (name, message, fix) => entries.push({
|
|
1730
|
-
level: "warn",
|
|
1731
|
-
check: name,
|
|
1732
|
-
message,
|
|
1733
|
-
fix
|
|
1734
|
-
});
|
|
1735
|
-
const error = (name, message, fix) => entries.push({
|
|
1736
|
-
level: "error",
|
|
1737
|
-
check: name,
|
|
1738
|
-
message,
|
|
1739
|
-
fix
|
|
1740
|
-
});
|
|
1741
|
-
const rel = (path) => relative(cfg.root, path).replaceAll("\\", "/");
|
|
1742
|
-
const configFile = findConfigFile(cfg.root);
|
|
1743
|
-
if (configFile) ok("config", `${configFile} found`);
|
|
1744
|
-
else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
|
|
1745
|
-
if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
|
|
1746
|
-
else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
|
|
1747
|
-
const catalogs = {};
|
|
1748
|
-
let catalogsHealthy = true;
|
|
1749
|
-
if (!existsSync(cfg.dir)) {
|
|
1750
|
-
catalogsHealthy = false;
|
|
1751
|
-
error("catalogs", `catalogs directory ${rel(cfg.dir)}/ does not exist`, "run `npx verbaly init` to scaffold it");
|
|
1752
|
-
} else {
|
|
1753
|
-
for (const locale of cfg.locales) {
|
|
1754
|
-
const file = join(cfg.dir, `${locale}.json`);
|
|
1755
|
-
if (!existsSync(file)) {
|
|
1756
|
-
catalogsHealthy = false;
|
|
1757
|
-
error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
|
|
1758
|
-
continue;
|
|
1759
|
-
}
|
|
1760
|
-
try {
|
|
1761
|
-
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
1762
|
-
const bad = badLeaf(parsed);
|
|
1763
|
-
if (bad) {
|
|
1764
|
-
catalogsHealthy = false;
|
|
1765
|
-
error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
|
|
1766
|
-
} else catalogs[locale] = flatten(parsed);
|
|
1767
|
-
} catch {
|
|
1768
|
-
catalogsHealthy = false;
|
|
1769
|
-
error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
|
|
1770
|
-
}
|
|
1771
|
-
}
|
|
1772
|
-
if (catalogsHealthy) {
|
|
1773
|
-
const how = cfg.localesDeclared ? "" : ", no locales set, so the catalog files decide";
|
|
1774
|
-
ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/${how}`);
|
|
1775
|
-
}
|
|
1776
|
-
}
|
|
1777
|
-
const source = catalogs[cfg.sourceLocale];
|
|
1778
|
-
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`");
|
|
1779
|
-
const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
|
|
1780
|
-
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");
|
|
1781
|
-
else {
|
|
1782
|
-
const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
|
|
1783
|
-
ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
|
|
1784
|
-
}
|
|
1785
|
-
const deps = readDependencies(cfg.root);
|
|
1786
|
-
const host = detectHost(cfg.root);
|
|
1787
|
-
const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
|
|
1788
|
-
if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
|
|
1789
|
-
else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
|
|
1790
|
-
else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `pnpm add -D ${host.pkg} and ${host.wire}`);
|
|
1791
|
-
const scanning = cfg.include.length > 0;
|
|
1792
|
-
if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
|
|
1793
|
-
if (source && scanning && cfg.dts !== false) {
|
|
1794
|
-
const dtsPath = cfg.dts ?? join(cfg.root, "verbaly.d.ts");
|
|
1795
|
-
if (!existsSync(dtsPath)) warn("types", "verbaly.d.ts has not been generated", "run `npx verbaly extract`");
|
|
1796
|
-
else if (readFileSync(dtsPath, "utf8") !== generateDts(source, { inlineCatalog: cfg.render.inlineCatalog === true })) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
|
|
1797
|
-
else ok("types", "verbaly.d.ts is up to date");
|
|
1798
|
-
}
|
|
1799
|
-
const registry = await extractProject(cfg);
|
|
1800
|
-
if (scanning) {
|
|
1801
|
-
const unreadable = registry.parseErrors();
|
|
1802
|
-
if (unreadable.length > 0) {
|
|
1803
|
-
const first = unreadable[0];
|
|
1804
|
-
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");
|
|
1805
|
-
}
|
|
1806
|
-
const stray = registry.strayImports();
|
|
1807
|
-
if (stray.length > 0) {
|
|
1808
|
-
const files = [...new Set(stray.map((entry) => rel(entry.file)))];
|
|
1809
|
-
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");
|
|
1810
|
-
}
|
|
1811
|
-
const escaped = [...registry.messages().values()].map((msg) => ({
|
|
1812
|
-
file: rel(msg.file),
|
|
1813
|
-
slice: escapedSyntax(msg.message)
|
|
1814
|
-
})).filter((entry) => entry.slice !== void 0);
|
|
1815
|
-
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");
|
|
1816
|
-
}
|
|
1817
|
-
if (source && scanning) {
|
|
1818
|
-
const extracted = registry.messages();
|
|
1819
|
-
const used = registry.usedKeys();
|
|
1820
|
-
const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
|
|
1821
|
-
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");
|
|
1822
|
-
else ok("orphans", "no orphan keys");
|
|
1823
|
-
}
|
|
1824
|
-
const excluded = cfg.bundle.exclude ?? [];
|
|
1825
|
-
if (excluded.length > 0 && catalogsHealthy) {
|
|
1826
|
-
const issues = auditBundle(cfg, catalogs, registry);
|
|
1827
|
-
for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
|
|
1828
|
-
if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
|
|
1829
|
-
}
|
|
1830
|
-
if (catalogsHealthy) {
|
|
1831
|
-
const result = check(cfg, catalogs, registry);
|
|
1832
|
-
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)");
|
|
1833
|
-
if (result.missing.length > 0) {
|
|
1834
|
-
const locales = [...new Set(result.missing.map((m) => m.locale))];
|
|
1835
|
-
warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
|
|
1836
|
-
}
|
|
1837
|
-
const broken = result.broken.filter((entry) => entry.severity === "error");
|
|
1838
|
-
if (broken.length > 0) {
|
|
1839
|
-
const locales = [...new Set(broken.map((b) => b.locale))];
|
|
1840
|
-
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");
|
|
1841
|
-
}
|
|
1842
|
-
const warnings = result.broken.filter((entry) => entry.severity === "warning");
|
|
1843
|
-
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");
|
|
1844
|
-
if (result.ok) ok("translations", "all translations complete");
|
|
1845
|
-
}
|
|
1846
|
-
return {
|
|
1847
|
-
ok: entries.every((entry) => entry.level !== "error"),
|
|
1848
|
-
entries
|
|
1849
|
-
};
|
|
1850
|
-
}
|
|
1851
|
-
function preview(keys) {
|
|
1852
|
-
const head = keys.slice(0, PREVIEW).join(", ");
|
|
1853
|
-
return keys.length > PREVIEW ? `${head}, …` : head;
|
|
1854
|
-
}
|
|
1855
|
-
//#endregion
|
|
1856
|
-
//#region src/wrap.ts
|
|
1857
|
-
const WRAP_ATTRS = /* @__PURE__ */ new Set([
|
|
1858
|
-
"title",
|
|
1859
|
-
"alt",
|
|
1860
|
-
"placeholder",
|
|
1861
|
-
"aria-label"
|
|
1862
|
-
]);
|
|
1863
|
-
const CODE_TAGS = /* @__PURE__ */ new Set([
|
|
1864
|
-
"code",
|
|
1865
|
-
"pre",
|
|
1866
|
-
"kbd",
|
|
1867
|
-
"samp",
|
|
1868
|
-
"var"
|
|
1869
|
-
]);
|
|
1870
|
-
const T_NAMES = /* @__PURE__ */ new Set(["t"]);
|
|
1871
|
-
const LETTER = /\p{L}/u;
|
|
1872
|
-
const WHITESPACE = /\s/;
|
|
1873
|
-
async function wrapProject(cfg, options = {}) {
|
|
1874
|
-
const files = (await glob(cfg.include, {
|
|
1875
|
-
cwd: cfg.root,
|
|
1876
|
-
ignore: cfg.exclude,
|
|
1877
|
-
absolute: true
|
|
1878
|
-
})).filter((file) => /\.[jt]sx$/.test(file));
|
|
1879
|
-
const result = {
|
|
1880
|
-
files: files.length,
|
|
1881
|
-
changed: [],
|
|
1882
|
-
wrapped: [],
|
|
1883
|
-
skipped: [],
|
|
1884
|
-
blocked: []
|
|
1885
|
-
};
|
|
1886
|
-
for (const file of files) {
|
|
1887
|
-
const code = readFileSync(file, "utf8");
|
|
1888
|
-
const label = relative(cfg.root, file).replaceAll("\\", "/");
|
|
1889
|
-
const out = wrapCode(code, label);
|
|
1890
|
-
result.wrapped.push(...out.wrapped);
|
|
1891
|
-
result.skipped.push(...out.skipped);
|
|
1892
|
-
if (out.code === void 0) continue;
|
|
1893
|
-
result.changed.push(label);
|
|
1894
|
-
if (!out.hasT) {
|
|
1895
|
-
result.blocked.push({
|
|
1896
|
-
file: label,
|
|
1897
|
-
texts: out.wrapped.length,
|
|
1898
|
-
client: out.client
|
|
1899
|
-
});
|
|
1900
|
-
continue;
|
|
1901
|
-
}
|
|
1902
|
-
if (options.write) writeFileSync(file, out.code);
|
|
1903
|
-
}
|
|
1904
|
-
return result;
|
|
1905
|
-
}
|
|
1906
|
-
function wrapCode(code, file) {
|
|
1907
|
-
const wrapped = [];
|
|
1908
|
-
const skipped = [];
|
|
1909
|
-
let ast;
|
|
1910
|
-
try {
|
|
1911
|
-
ast = parse$1(code, {
|
|
1912
|
-
sourceType: "module",
|
|
1913
|
-
errorRecovery: true,
|
|
1914
|
-
plugins: ["typescript", "jsx"]
|
|
1915
|
-
}).program;
|
|
1916
|
-
} catch {
|
|
1917
|
-
return {
|
|
1918
|
-
wrapped,
|
|
1919
|
-
skipped,
|
|
1920
|
-
hasT: false,
|
|
1921
|
-
client: false
|
|
1922
|
-
};
|
|
1923
|
-
}
|
|
1924
|
-
const hasT = declaresT(ast);
|
|
1925
|
-
const client = hasDirective(ast, "use client");
|
|
1926
|
-
const s = new MagicString(code);
|
|
1927
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1928
|
-
let changed = false;
|
|
1929
|
-
walk$1(ast, (node) => {
|
|
1930
|
-
if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
|
|
1931
|
-
if (visited.has(node)) return;
|
|
1932
|
-
processElement(node);
|
|
1933
|
-
});
|
|
1934
|
-
return changed ? {
|
|
1935
|
-
code: s.toString(),
|
|
1936
|
-
wrapped,
|
|
1937
|
-
skipped,
|
|
1938
|
-
hasT,
|
|
1939
|
-
client
|
|
1940
|
-
} : {
|
|
1941
|
-
wrapped,
|
|
1942
|
-
skipped,
|
|
1943
|
-
hasT,
|
|
1944
|
-
client
|
|
1945
|
-
};
|
|
1946
|
-
function processElement(node) {
|
|
1947
|
-
visited.add(node);
|
|
1948
|
-
if (node.type === "JSXElement") {
|
|
1949
|
-
const opening = node.openingElement;
|
|
1950
|
-
const name = opening.name;
|
|
1951
|
-
if (name.type === "JSXIdentifier" && name.name === "Trans") return markSubtree(node);
|
|
1952
|
-
if (hasVerbalyAttr(opening)) return markSubtree(node);
|
|
1953
|
-
if (name.type === "JSXIdentifier" && CODE_TAGS.has(name.name)) return markSubtree(node);
|
|
1954
|
-
wrapAttributes(opening);
|
|
1955
|
-
}
|
|
1956
|
-
const children = node.children ?? [];
|
|
1957
|
-
const hasElementChild = children.some((c) => c.type === "JSXElement" || c.type === "JSXFragment");
|
|
1958
|
-
const hasText = children.some((c) => c.type === "JSXText" && LETTER.test(c.value) || c.type === "JSXExpressionContainer" && c.expression.type === "StringLiteral" && LETTER.test(c.expression.value));
|
|
1959
|
-
if (hasElementChild && hasText) {
|
|
1960
|
-
skip(node, snippet(children), "mixed text and markup: wrap by hand or use <Trans>");
|
|
1961
|
-
return markSubtree(node);
|
|
1962
|
-
}
|
|
1963
|
-
if (hasText) {
|
|
1964
|
-
wrapSegment(node, children);
|
|
1965
|
-
return markSubtree(node);
|
|
1966
|
-
}
|
|
1967
|
-
for (const child of children) if (child.type === "JSXElement" || child.type === "JSXFragment") processElement(child);
|
|
1968
|
-
}
|
|
1969
|
-
function wrapSegment(parent, children) {
|
|
1970
|
-
const meaningful = children.filter((c) => c.type === "JSXText" && c.value.trim() !== "" || c.type === "JSXExpressionContainer" && c.expression.type !== "JSXEmptyExpression");
|
|
1971
|
-
if (meaningful.length === 0) return;
|
|
1972
|
-
const first = meaningful[0];
|
|
1973
|
-
const last = meaningful[meaningful.length - 1];
|
|
1974
|
-
if (first.type === "JSXExpressionContainer" && meaningful.length > 1) {
|
|
1975
|
-
skip(parent, snippet(children), "starts with an interpolation: wrap the sentence by hand");
|
|
1976
|
-
return;
|
|
1977
|
-
}
|
|
1978
|
-
let template = "";
|
|
1979
|
-
let report = "";
|
|
1980
|
-
for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {
|
|
1981
|
-
const child = children[i];
|
|
1982
|
-
if (child.type === "JSXText") {
|
|
1983
|
-
let value = cleanJsxText(child.value);
|
|
1984
|
-
if (child === first) value = value.trimStart();
|
|
1985
|
-
if (child === last) value = value.trimEnd();
|
|
1986
|
-
template += escapeTemplate(value);
|
|
1987
|
-
report += value;
|
|
1988
|
-
} else if (child.type === "JSXExpressionContainer") {
|
|
1989
|
-
const expr = child.expression;
|
|
1990
|
-
if (expr.type === "JSXEmptyExpression") continue;
|
|
1991
|
-
if (usesT(expr)) {
|
|
1992
|
-
skip(parent, snippet(children), "already uses t: finish it by hand");
|
|
1993
|
-
return;
|
|
1994
|
-
}
|
|
1995
|
-
if (containsJsx(expr)) {
|
|
1996
|
-
skip(parent, snippet(children), "an expression renders markup: wrap by hand or use <Trans>");
|
|
1997
|
-
markSubtree(child);
|
|
1998
|
-
return;
|
|
1999
|
-
}
|
|
2000
|
-
if (expr.type === "StringLiteral") {
|
|
2001
|
-
template += escapeTemplate(expr.value);
|
|
2002
|
-
report += expr.value;
|
|
2003
|
-
} else {
|
|
2004
|
-
const source = code.slice(expr.start, expr.end);
|
|
2005
|
-
template += "${" + source + "}";
|
|
2006
|
-
report += "${" + source + "}";
|
|
2007
|
-
}
|
|
2008
|
-
} else return;
|
|
2009
|
-
}
|
|
2010
|
-
if (!LETTER.test(report)) return;
|
|
2011
|
-
if (isIdentifierLike(report)) return;
|
|
2012
|
-
const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
|
|
2013
|
-
const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
|
|
2014
|
-
s.overwrite(start, end, "{t`" + template + "`}");
|
|
2015
|
-
changed = true;
|
|
2016
|
-
wrapped.push({
|
|
2017
|
-
file,
|
|
2018
|
-
line: line(first),
|
|
2019
|
-
text: report,
|
|
2020
|
-
kind: "text"
|
|
2021
|
-
});
|
|
2022
|
-
}
|
|
2023
|
-
function wrapAttributes(opening) {
|
|
2024
|
-
for (const attr of opening.attributes) {
|
|
2025
|
-
if (attr.type !== "JSXAttribute") continue;
|
|
2026
|
-
const name = attr.name;
|
|
2027
|
-
if (name.type !== "JSXIdentifier" || !WRAP_ATTRS.has(name.name)) continue;
|
|
2028
|
-
const value = attr.value;
|
|
2029
|
-
if (value?.type !== "StringLiteral") continue;
|
|
2030
|
-
const raw = value.value;
|
|
2031
|
-
if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;
|
|
2032
|
-
s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
|
|
2033
|
-
changed = true;
|
|
2034
|
-
wrapped.push({
|
|
2035
|
-
file,
|
|
2036
|
-
line: line(value),
|
|
2037
|
-
text: raw,
|
|
2038
|
-
kind: "attribute",
|
|
2039
|
-
attribute: name.name
|
|
2040
|
-
});
|
|
2041
|
-
}
|
|
2042
|
-
}
|
|
2043
|
-
function skip(node, text, reason) {
|
|
2044
|
-
skipped.push({
|
|
2045
|
-
file,
|
|
2046
|
-
line: line(node),
|
|
2047
|
-
text,
|
|
2048
|
-
reason
|
|
2049
|
-
});
|
|
2050
|
-
}
|
|
2051
|
-
function snippet(children) {
|
|
2052
|
-
const start = children[0]?.start ?? 0;
|
|
2053
|
-
const end = children[children.length - 1]?.end ?? start;
|
|
2054
|
-
const text = code.slice(start, end).replace(/\s+/g, " ").trim();
|
|
2055
|
-
return text.length > 60 ? text.slice(0, 59) + "…" : text;
|
|
2056
|
-
}
|
|
2057
|
-
function markSubtree(node) {
|
|
2058
|
-
walk$1(node, (n) => {
|
|
2059
|
-
if (n.type === "JSXElement" || n.type === "JSXFragment") visited.add(n);
|
|
2060
|
-
});
|
|
2061
|
-
}
|
|
2062
|
-
}
|
|
2063
|
-
function isIdentifierLike(text) {
|
|
2064
|
-
const trimmed = text.trim();
|
|
2065
|
-
if (WHITESPACE.test(trimmed)) return false;
|
|
2066
|
-
const first = [...trimmed].find((char) => LETTER.test(char));
|
|
2067
|
-
return first !== void 0 && first !== first.toUpperCase();
|
|
2068
|
-
}
|
|
2069
|
-
function hasDirective(program, value) {
|
|
2070
|
-
return (program.directives ?? []).some((d) => d.value?.value === value);
|
|
2071
|
-
}
|
|
2072
|
-
function declaresT(program) {
|
|
2073
|
-
let found = false;
|
|
2074
|
-
walk$1(program, (node) => {
|
|
2075
|
-
if (found) return;
|
|
2076
|
-
if (node.type === "ImportDeclaration") {
|
|
2077
|
-
for (const spec of node.specifiers) if (isTName(spec.local?.name)) found = true;
|
|
2078
|
-
return;
|
|
2079
|
-
}
|
|
2080
|
-
if (node.type === "VariableDeclarator" && bindsT(node.id)) found = true;
|
|
2081
|
-
if (node.type === "FunctionDeclaration" && isTName(node.id?.name)) found = true;
|
|
2082
|
-
if (node.params?.some((param) => bindsT(param))) found = true;
|
|
2083
|
-
});
|
|
2084
|
-
return found;
|
|
2085
|
-
}
|
|
2086
|
-
function bindsT(pattern) {
|
|
2087
|
-
if (!pattern) return false;
|
|
2088
|
-
if (pattern.type === "Identifier") return isTName(pattern.name);
|
|
2089
|
-
if (pattern.type === "AssignmentPattern") return bindsT(pattern.left);
|
|
2090
|
-
if (pattern.type === "ObjectPattern") return pattern.properties.some((prop) => prop.type === "RestElement" ? bindsT(prop.argument) : bindsT(prop.value));
|
|
2091
|
-
if (pattern.type === "ArrayPattern") return pattern.elements.some((el) => bindsT(el ?? void 0));
|
|
2092
|
-
return false;
|
|
2093
|
-
}
|
|
2094
|
-
function isTName(name) {
|
|
2095
|
-
return typeof name === "string" && T_NAMES.has(name);
|
|
2096
|
-
}
|
|
2097
|
-
function hasVerbalyAttr(opening) {
|
|
2098
|
-
return opening.attributes.some((attr) => {
|
|
2099
|
-
if (attr.type !== "JSXAttribute") return false;
|
|
2100
|
-
const name = attr.name;
|
|
2101
|
-
return name.type === "JSXIdentifier" && name.name.startsWith("data-verbaly");
|
|
2102
|
-
});
|
|
2103
|
-
}
|
|
2104
|
-
function usesT(node) {
|
|
2105
|
-
let found = false;
|
|
2106
|
-
walk$1(node, (n) => {
|
|
2107
|
-
if (n.type === "TaggedTemplateExpression" && isTReference(n.tag, T_NAMES)) found = true;
|
|
2108
|
-
if (n.type === "CallExpression" && isTReference(n.callee, T_NAMES)) found = true;
|
|
2109
|
-
});
|
|
2110
|
-
return found;
|
|
2111
|
-
}
|
|
2112
|
-
function containsJsx(node) {
|
|
2113
|
-
let found = false;
|
|
2114
|
-
walk$1(node, (n) => {
|
|
2115
|
-
if (n.type === "JSXElement" || n.type === "JSXFragment") found = true;
|
|
2116
|
-
});
|
|
2117
|
-
return found;
|
|
2118
|
-
}
|
|
2119
|
-
function escapeTemplate(text) {
|
|
2120
|
-
return text.replace(/[\\`]/g, "\\$&").replace(/\$\{/g, "\\${");
|
|
2121
|
-
}
|
|
2122
|
-
function leadingWs(text) {
|
|
2123
|
-
return text.length - text.trimStart().length;
|
|
2124
|
-
}
|
|
2125
|
-
function trailingWs(text) {
|
|
2126
|
-
return text.length - text.trimEnd().length;
|
|
2127
|
-
}
|
|
2128
|
-
function line(node) {
|
|
2129
|
-
return node.loc?.start?.line ?? 1;
|
|
2130
|
-
}
|
|
2131
|
-
//#endregion
|
|
2132
|
-
//#region src/render.ts
|
|
2133
|
-
function localeInstance(catalogs, locale, sourceLocale) {
|
|
2134
|
-
return createVerbaly({
|
|
2135
|
-
locale,
|
|
2136
|
-
fallback: sourceLocale,
|
|
2137
|
-
messages: catalogs
|
|
1866
|
+
//#region src/render.ts
|
|
1867
|
+
function localeInstance(catalogs, locale, sourceLocale) {
|
|
1868
|
+
return createVerbaly({
|
|
1869
|
+
locale,
|
|
1870
|
+
fallback: sourceLocale,
|
|
1871
|
+
messages: catalogs
|
|
2138
1872
|
});
|
|
2139
1873
|
}
|
|
2140
1874
|
const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
|
|
@@ -2291,279 +2025,561 @@ function mirroredLinks(links, mirror) {
|
|
|
2291
2025
|
href: inside
|
|
2292
2026
|
};
|
|
2293
2027
|
}
|
|
2294
|
-
return out;
|
|
2295
|
-
}
|
|
2296
|
-
function mirroredHref(raw, mirror) {
|
|
2297
|
-
if (raw === void 0) return void 0;
|
|
2298
|
-
const href = decodeEntities(raw);
|
|
2299
|
-
if (!href.startsWith("/") || href.startsWith("//")) return void 0;
|
|
2300
|
-
const base = mirror.base ?? "";
|
|
2301
|
-
const inside = base ? stripBase(href, base) : href;
|
|
2302
|
-
if (base && inside === href) return void 0;
|
|
2303
|
-
const cut = inside.search(/[?#]/);
|
|
2304
|
-
const path = cut < 0 ? inside : inside.slice(0, cut);
|
|
2305
|
-
if (!mirror.pages.has(publicPath(path.replace(/^\//, "")))) return void 0;
|
|
2306
|
-
return `${base}${mirror.prefix}${inside}`;
|
|
2028
|
+
return out;
|
|
2029
|
+
}
|
|
2030
|
+
function mirroredHref(raw, mirror) {
|
|
2031
|
+
if (raw === void 0) return void 0;
|
|
2032
|
+
const href = decodeEntities(raw);
|
|
2033
|
+
if (!href.startsWith("/") || href.startsWith("//")) return void 0;
|
|
2034
|
+
const base = mirror.base ?? "";
|
|
2035
|
+
const inside = base ? stripBase(href, base) : href;
|
|
2036
|
+
if (base && inside === href) return void 0;
|
|
2037
|
+
const cut = inside.search(/[?#]/);
|
|
2038
|
+
const path = cut < 0 ? inside : inside.slice(0, cut);
|
|
2039
|
+
if (!mirror.pages.has(publicPath(path.replace(/^\//, "")))) return void 0;
|
|
2040
|
+
return `${base}${mirror.prefix}${inside}`;
|
|
2041
|
+
}
|
|
2042
|
+
function stripBase(path, base) {
|
|
2043
|
+
if (!path.startsWith(base)) return path;
|
|
2044
|
+
const rest = path.slice(base.length);
|
|
2045
|
+
if (rest === "") return "/";
|
|
2046
|
+
return rest.startsWith("/") ? rest : path;
|
|
2047
|
+
}
|
|
2048
|
+
function normalizeBase(base) {
|
|
2049
|
+
const trimmed = base?.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
2050
|
+
return trimmed ? `/${trimmed}` : "";
|
|
2051
|
+
}
|
|
2052
|
+
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+p+location.search+location.hash)})()";
|
|
2053
|
+
function jsLiteral(value) {
|
|
2054
|
+
return JSON.stringify(value ?? null).replace(/</g, "\\u003c");
|
|
2055
|
+
}
|
|
2056
|
+
function redirectScript(options) {
|
|
2057
|
+
return `<script>var ${[
|
|
2058
|
+
`S=${jsLiteral(options.locales)}`,
|
|
2059
|
+
`D=${jsLiteral(options.sourceLocale)}`,
|
|
2060
|
+
`B=${jsLiteral(normalizeBase(options.base))}`,
|
|
2061
|
+
`K=${options.storageKey === false ? "null" : jsLiteral(options.storageKey ?? LOCALE_STORAGE_KEY)}`
|
|
2062
|
+
].join(",")};${REDIRECT_BODY};<\/script>`;
|
|
2063
|
+
}
|
|
2064
|
+
function injectRedirect(ms, html, options) {
|
|
2065
|
+
const block = `${REDIRECT_OPEN}${redirectScript(options)}${REDIRECT_CLOSE}`;
|
|
2066
|
+
const from = html.indexOf(REDIRECT_OPEN);
|
|
2067
|
+
if (from !== -1) {
|
|
2068
|
+
const to = html.indexOf(REDIRECT_CLOSE, from);
|
|
2069
|
+
if (to !== -1) {
|
|
2070
|
+
const end = to + 24;
|
|
2071
|
+
if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
|
|
2072
|
+
return;
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
const head = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i.exec(html);
|
|
2076
|
+
if (head) ms.appendRight(head.index + head[0].length, block);
|
|
2077
|
+
}
|
|
2078
|
+
function injectAlternates(ms, html, alternates) {
|
|
2079
|
+
const links = alternates.map((a) => `<link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}">`).join("");
|
|
2080
|
+
const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;
|
|
2081
|
+
const from = html.indexOf(HREFLANG_OPEN);
|
|
2082
|
+
if (from !== -1) {
|
|
2083
|
+
const to = html.indexOf(HREFLANG_CLOSE, from);
|
|
2084
|
+
if (to !== -1) {
|
|
2085
|
+
const end = to + 24;
|
|
2086
|
+
if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
|
|
2087
|
+
return;
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
const head = /<\/head\s*>/i.exec(html);
|
|
2091
|
+
if (head) ms.appendLeft(head.index, block);
|
|
2092
|
+
}
|
|
2093
|
+
function injectCatalog(ms, html, messages) {
|
|
2094
|
+
const json = JSON.stringify(messages).replace(/<\//g, "<\\/");
|
|
2095
|
+
const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
|
|
2096
|
+
const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
|
|
2097
|
+
const from = html.indexOf(CATALOG_OPEN);
|
|
2098
|
+
if (from !== -1) {
|
|
2099
|
+
const to = html.indexOf(CATALOG_CLOSE, from);
|
|
2100
|
+
if (to !== -1) {
|
|
2101
|
+
const end = to + 23;
|
|
2102
|
+
if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
|
|
2103
|
+
return;
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
const head = /<\/head\s*>/i.exec(html);
|
|
2107
|
+
if (head) ms.appendLeft(head.index, block);
|
|
2108
|
+
}
|
|
2109
|
+
const TITLE_TAG = /<title\b([^>]*)>/i;
|
|
2110
|
+
const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
|
|
2111
|
+
const NOINDEX_META = /<meta\b[^>]*name\s*=\s*["']?robots["']?[^>]*content\s*=\s*["'][^"']*noindex/i;
|
|
2112
|
+
function isIndexable(html) {
|
|
2113
|
+
return !REFRESH_META.test(html) && !NOINDEX_META.test(html);
|
|
2114
|
+
}
|
|
2115
|
+
function headIsBound(html, attr) {
|
|
2116
|
+
if (REFRESH_META.test(html)) return true;
|
|
2117
|
+
const title = TITLE_TAG.exec(html);
|
|
2118
|
+
return title ? title[1].includes(attr) : true;
|
|
2119
|
+
}
|
|
2120
|
+
async function renderSite(cfg, options = {}) {
|
|
2121
|
+
const site = join(cfg.root, options.site ?? cfg.render.site ?? "dist");
|
|
2122
|
+
const locales = options.locales ?? cfg.locales;
|
|
2123
|
+
const attribute = options.attribute ?? cfg.render.attribute;
|
|
2124
|
+
const base = normalizeBase(options.base ?? cfg.render.base);
|
|
2125
|
+
const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\/+$/, "");
|
|
2126
|
+
const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== void 0;
|
|
2127
|
+
const patterns = options.exclude ?? cfg.render.exclude ?? [];
|
|
2128
|
+
const excluded = patterns.length > 0 ? picomatch(patterns) : () => false;
|
|
2129
|
+
const sitemap = options.sitemap ?? cfg.render.sitemap ?? false;
|
|
2130
|
+
const wantSitemap = sitemap !== false && baseUrl !== void 0;
|
|
2131
|
+
const clean = options.clean ?? cfg.render.clean ?? false;
|
|
2132
|
+
const wanted = options.redirect ?? cfg.render.redirect ?? false;
|
|
2133
|
+
const redirect = wanted === false ? void 0 : wanted === true ? {} : wanted;
|
|
2134
|
+
const script = redirect && {
|
|
2135
|
+
locales,
|
|
2136
|
+
sourceLocale: cfg.sourceLocale,
|
|
2137
|
+
base,
|
|
2138
|
+
storageKey: redirect.storageKey
|
|
2139
|
+
};
|
|
2140
|
+
const catalogs = loadCatalogs(cfg);
|
|
2141
|
+
const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
|
|
2142
|
+
if (clean) {
|
|
2143
|
+
for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
|
|
2144
|
+
recursive: true,
|
|
2145
|
+
force: true
|
|
2146
|
+
});
|
|
2147
|
+
}
|
|
2148
|
+
const files = await glob("**/*.html", {
|
|
2149
|
+
cwd: site,
|
|
2150
|
+
absolute: true,
|
|
2151
|
+
ignore: locales.map((locale) => `${locale}/**`)
|
|
2152
|
+
});
|
|
2153
|
+
const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
|
|
2154
|
+
const missing = {};
|
|
2155
|
+
const untranslatedHead = [];
|
|
2156
|
+
const urls = [];
|
|
2157
|
+
for (const file of files) {
|
|
2158
|
+
const html = readFileSync(file, "utf8");
|
|
2159
|
+
const rel = relative(site, file).replace(/\\/g, "/");
|
|
2160
|
+
if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
|
|
2161
|
+
const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale) : [];
|
|
2162
|
+
if (wantHreflang && isIndexable(html) && !excluded(rel)) urls.push({
|
|
2163
|
+
rel,
|
|
2164
|
+
alternates
|
|
2165
|
+
});
|
|
2166
|
+
const routed = script && (redirect.on === "all" || rel === "index.html");
|
|
2167
|
+
for (const locale of locales) {
|
|
2168
|
+
const result = renderHtml(html, {
|
|
2169
|
+
locale,
|
|
2170
|
+
instance: instances.get(locale),
|
|
2171
|
+
sourceLocale: cfg.sourceLocale,
|
|
2172
|
+
attribute,
|
|
2173
|
+
richTags: options.richTags,
|
|
2174
|
+
richLinks: options.richLinks ?? cfg.render.links,
|
|
2175
|
+
alternates,
|
|
2176
|
+
mirror: locale === cfg.sourceLocale ? void 0 : {
|
|
2177
|
+
prefix: `/${locale}`,
|
|
2178
|
+
base,
|
|
2179
|
+
pages
|
|
2180
|
+
},
|
|
2181
|
+
redirect: routed && locale === cfg.sourceLocale ? script : void 0,
|
|
2182
|
+
inlineCatalog: cfg.render.inlineCatalog === true
|
|
2183
|
+
});
|
|
2184
|
+
for (const key of result.missing) {
|
|
2185
|
+
const list = missing[locale] ??= [];
|
|
2186
|
+
if (!list.includes(key)) list.push(key);
|
|
2187
|
+
}
|
|
2188
|
+
const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);
|
|
2189
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
2190
|
+
writeFileSync(out, result.html);
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
if (wantSitemap && urls.length) writeFileSync(join(site, typeof sitemap === "string" ? sitemap : "sitemap-i18n.xml"), buildSitemap(urls));
|
|
2194
|
+
return {
|
|
2195
|
+
files: files.length,
|
|
2196
|
+
locales: [...locales],
|
|
2197
|
+
missing,
|
|
2198
|
+
untranslatedHead
|
|
2199
|
+
};
|
|
2200
|
+
}
|
|
2201
|
+
function formatRenderWarnings(result, sourceLocale) {
|
|
2202
|
+
const lines = [];
|
|
2203
|
+
for (const [locale, keys] of Object.entries(result.missing)) lines.push(` ${locale}: ${counted(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
|
|
2204
|
+
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`);
|
|
2205
|
+
return lines;
|
|
2206
|
+
}
|
|
2207
|
+
function pagePath(rel) {
|
|
2208
|
+
const path = rel.replace(/(^|\/)index\.html$/, "$1");
|
|
2209
|
+
return path ? `/${path}` : "/";
|
|
2210
|
+
}
|
|
2211
|
+
function pageAlternates(baseUrl, rel, locales, sourceLocale) {
|
|
2212
|
+
return alternateLinks({
|
|
2213
|
+
supported: locales,
|
|
2214
|
+
sourceLocale,
|
|
2215
|
+
path: pagePath(rel),
|
|
2216
|
+
routing: "prefix-except-source",
|
|
2217
|
+
baseUrl
|
|
2218
|
+
});
|
|
2219
|
+
}
|
|
2220
|
+
function buildSitemap(urls) {
|
|
2221
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls.flatMap(({ alternates }) => {
|
|
2222
|
+
const alts = alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${a.hreflang}" href="${escapeAttr(a.href)}"/>`).join("");
|
|
2223
|
+
return alternates.filter((a) => a.hreflang !== "x-default").map((self) => `<url><loc>${escapeAttr(self.href)}</loc>${alts}</url>`);
|
|
2224
|
+
}).join("")}</urlset>\n`;
|
|
2225
|
+
}
|
|
2226
|
+
function parseAttrs(chunk) {
|
|
2227
|
+
const attrs = /* @__PURE__ */ new Map();
|
|
2228
|
+
ATTR.lastIndex = 0;
|
|
2229
|
+
let m;
|
|
2230
|
+
while ((m = ATTR.exec(chunk)) !== null) attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
|
|
2231
|
+
return attrs;
|
|
2232
|
+
}
|
|
2233
|
+
function parseArgs(raw) {
|
|
2234
|
+
if (!raw) return void 0;
|
|
2235
|
+
try {
|
|
2236
|
+
return JSON.parse(decodeEntities(raw));
|
|
2237
|
+
} catch {
|
|
2238
|
+
console.warn(`[verbaly] invalid args JSON: ${raw}`);
|
|
2239
|
+
return;
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
function protectedRanges(html) {
|
|
2243
|
+
const ranges = [];
|
|
2244
|
+
const re = /<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
|
|
2245
|
+
let m;
|
|
2246
|
+
while ((m = re.exec(html)) !== null) {
|
|
2247
|
+
const openEnd = m[0].startsWith("<!--") ? m.index : html.indexOf(">", m.index) + 1;
|
|
2248
|
+
ranges.push([openEnd, m.index + m[0].length]);
|
|
2249
|
+
}
|
|
2250
|
+
return ranges;
|
|
2251
|
+
}
|
|
2252
|
+
function findClose(html, tagName, from, inSkip) {
|
|
2253
|
+
const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
|
|
2254
|
+
re.lastIndex = from;
|
|
2255
|
+
let depth = 1;
|
|
2256
|
+
let m;
|
|
2257
|
+
while ((m = re.exec(html)) !== null) {
|
|
2258
|
+
if (inSkip(m.index)) continue;
|
|
2259
|
+
if (m[0][1] === "/") {
|
|
2260
|
+
depth -= 1;
|
|
2261
|
+
if (depth === 0) return { contentEnd: m.index };
|
|
2262
|
+
} else if (!m[0].endsWith("/>")) depth += 1;
|
|
2263
|
+
}
|
|
2264
|
+
return null;
|
|
2265
|
+
}
|
|
2266
|
+
function setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value) {
|
|
2267
|
+
const escaped = escapeAttr(value);
|
|
2268
|
+
const existing = new RegExp(`(\\s${name}\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s>]+)`, "i").exec(attrChunk);
|
|
2269
|
+
if (existing) {
|
|
2270
|
+
const valueStart = chunkStart + existing.index + existing[1].length;
|
|
2271
|
+
const valueEnd = valueStart + existing[2].length;
|
|
2272
|
+
if (html.slice(valueStart, valueEnd) !== `"${escaped}"`) ms.overwrite(valueStart, valueEnd, `"${escaped}"`);
|
|
2273
|
+
return;
|
|
2274
|
+
}
|
|
2275
|
+
const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
|
|
2276
|
+
ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
|
|
2307
2277
|
}
|
|
2308
|
-
function
|
|
2309
|
-
|
|
2310
|
-
const
|
|
2311
|
-
if (
|
|
2312
|
-
|
|
2278
|
+
function richToHtml(nodes, allowed, links) {
|
|
2279
|
+
let out = "";
|
|
2280
|
+
for (const node of nodes) if (typeof node === "string") out += escapeHtml(node);
|
|
2281
|
+
else if (links?.[node.name] !== void 0) {
|
|
2282
|
+
const { href, target, rel } = normalizeLink(links[node.name]);
|
|
2283
|
+
let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
|
|
2284
|
+
if (target) attrs += ` target="${escapeAttr(target)}"`;
|
|
2285
|
+
if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
|
|
2286
|
+
out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
|
|
2287
|
+
} else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
|
|
2288
|
+
else out += richToHtml(node.children, allowed, links);
|
|
2289
|
+
return out;
|
|
2313
2290
|
}
|
|
2314
|
-
function
|
|
2315
|
-
|
|
2316
|
-
return trimmed ? `/${trimmed}` : "";
|
|
2291
|
+
function escapeHtml(text) {
|
|
2292
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
2317
2293
|
}
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
return JSON.stringify(value ?? null).replace(/</g, "\\u003c");
|
|
2294
|
+
function escapeAttr(text) {
|
|
2295
|
+
return escapeHtml(text).replace(/"/g, """);
|
|
2321
2296
|
}
|
|
2322
|
-
function
|
|
2323
|
-
return
|
|
2324
|
-
`S=${jsLiteral(options.locales)}`,
|
|
2325
|
-
`D=${jsLiteral(options.sourceLocale)}`,
|
|
2326
|
-
`B=${jsLiteral(normalizeBase(options.base))}`,
|
|
2327
|
-
`K=${options.storageKey === false ? "null" : jsLiteral(options.storageKey ?? LOCALE_STORAGE_KEY)}`
|
|
2328
|
-
].join(",")};${REDIRECT_BODY};<\/script>`;
|
|
2297
|
+
function decodeEntities(text) {
|
|
2298
|
+
return text.replace(/"/g, "\"").replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
2329
2299
|
}
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2300
|
+
//#endregion
|
|
2301
|
+
//#region src/wrap.ts
|
|
2302
|
+
const WRAP_ATTRS = /* @__PURE__ */ new Set([
|
|
2303
|
+
"title",
|
|
2304
|
+
"alt",
|
|
2305
|
+
"placeholder",
|
|
2306
|
+
"aria-label"
|
|
2307
|
+
]);
|
|
2308
|
+
const CODE_TAGS = /* @__PURE__ */ new Set([
|
|
2309
|
+
"code",
|
|
2310
|
+
"pre",
|
|
2311
|
+
"kbd",
|
|
2312
|
+
"samp",
|
|
2313
|
+
"var"
|
|
2314
|
+
]);
|
|
2315
|
+
const T_NAMES = /* @__PURE__ */ new Set(["t"]);
|
|
2316
|
+
const LETTER = /\p{L}/u;
|
|
2317
|
+
const WHITESPACE = /\s/;
|
|
2318
|
+
async function wrapProject(cfg, options = {}) {
|
|
2319
|
+
const files = (await glob(cfg.include, {
|
|
2320
|
+
cwd: cfg.root,
|
|
2321
|
+
ignore: cfg.exclude,
|
|
2322
|
+
absolute: true
|
|
2323
|
+
})).filter((file) => /\.[jt]sx$/.test(file));
|
|
2324
|
+
const result = {
|
|
2325
|
+
files: files.length,
|
|
2326
|
+
changed: [],
|
|
2327
|
+
wrapped: [],
|
|
2328
|
+
skipped: [],
|
|
2329
|
+
blocked: []
|
|
2330
|
+
};
|
|
2331
|
+
for (const file of files) {
|
|
2332
|
+
const code = readFileSync(file, "utf8");
|
|
2333
|
+
const label = relative(cfg.root, file).replaceAll("\\", "/");
|
|
2334
|
+
const out = wrapCode(code, label);
|
|
2335
|
+
result.wrapped.push(...out.wrapped);
|
|
2336
|
+
result.skipped.push(...out.skipped);
|
|
2337
|
+
if (out.code === void 0) continue;
|
|
2338
|
+
result.changed.push(label);
|
|
2339
|
+
if (!out.hasT) {
|
|
2340
|
+
result.blocked.push({
|
|
2341
|
+
file: label,
|
|
2342
|
+
texts: out.wrapped.length,
|
|
2343
|
+
client: out.client
|
|
2344
|
+
});
|
|
2345
|
+
continue;
|
|
2339
2346
|
}
|
|
2347
|
+
if (options.write) writeFileSync(file, out.code);
|
|
2340
2348
|
}
|
|
2341
|
-
|
|
2342
|
-
if (head) ms.appendRight(head.index + head[0].length, block);
|
|
2349
|
+
return result;
|
|
2343
2350
|
}
|
|
2344
|
-
function
|
|
2345
|
-
const
|
|
2346
|
-
const
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2351
|
+
function wrapCode(code, file) {
|
|
2352
|
+
const wrapped = [];
|
|
2353
|
+
const skipped = [];
|
|
2354
|
+
let ast;
|
|
2355
|
+
try {
|
|
2356
|
+
ast = parse$1(code, {
|
|
2357
|
+
sourceType: "module",
|
|
2358
|
+
errorRecovery: true,
|
|
2359
|
+
plugins: ["typescript", "jsx"]
|
|
2360
|
+
}).program;
|
|
2361
|
+
} catch {
|
|
2362
|
+
return {
|
|
2363
|
+
wrapped,
|
|
2364
|
+
skipped,
|
|
2365
|
+
hasT: false,
|
|
2366
|
+
client: false
|
|
2367
|
+
};
|
|
2368
|
+
}
|
|
2369
|
+
const hasT = declaresT(ast);
|
|
2370
|
+
const client = hasDirective(ast, "use client");
|
|
2371
|
+
const s = new MagicString(code);
|
|
2372
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2373
|
+
let changed = false;
|
|
2374
|
+
walk$1(ast, (node) => {
|
|
2375
|
+
if (node.type !== "JSXElement" && node.type !== "JSXFragment") return;
|
|
2376
|
+
if (visited.has(node)) return;
|
|
2377
|
+
processElement(node);
|
|
2378
|
+
});
|
|
2379
|
+
return changed ? {
|
|
2380
|
+
code: s.toString(),
|
|
2381
|
+
wrapped,
|
|
2382
|
+
skipped,
|
|
2383
|
+
hasT,
|
|
2384
|
+
client
|
|
2385
|
+
} : {
|
|
2386
|
+
wrapped,
|
|
2387
|
+
skipped,
|
|
2388
|
+
hasT,
|
|
2389
|
+
client
|
|
2390
|
+
};
|
|
2391
|
+
function processElement(node) {
|
|
2392
|
+
visited.add(node);
|
|
2393
|
+
if (node.type === "JSXElement") {
|
|
2394
|
+
const opening = node.openingElement;
|
|
2395
|
+
const name = opening.name;
|
|
2396
|
+
if (name.type === "JSXIdentifier" && name.name === "Trans") return markSubtree(node);
|
|
2397
|
+
if (hasVerbalyAttr(opening)) return markSubtree(node);
|
|
2398
|
+
if (name.type === "JSXIdentifier" && CODE_TAGS.has(name.name)) return markSubtree(node);
|
|
2399
|
+
wrapAttributes(opening);
|
|
2400
|
+
}
|
|
2401
|
+
const children = node.children ?? [];
|
|
2402
|
+
const hasElementChild = children.some((c) => c.type === "JSXElement" || c.type === "JSXFragment");
|
|
2403
|
+
const hasText = children.some((c) => c.type === "JSXText" && LETTER.test(c.value) || c.type === "JSXExpressionContainer" && c.expression.type === "StringLiteral" && LETTER.test(c.expression.value));
|
|
2404
|
+
if (hasElementChild && hasText) {
|
|
2405
|
+
skip(node, snippet(children), "mixed text and markup: wrap by hand or use <Trans>");
|
|
2406
|
+
return markSubtree(node);
|
|
2407
|
+
}
|
|
2408
|
+
if (hasText) {
|
|
2409
|
+
wrapSegment(node, children);
|
|
2410
|
+
return markSubtree(node);
|
|
2354
2411
|
}
|
|
2412
|
+
for (const child of children) if (child.type === "JSXElement" || child.type === "JSXFragment") processElement(child);
|
|
2355
2413
|
}
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
const from = html.indexOf(CATALOG_OPEN);
|
|
2364
|
-
if (from !== -1) {
|
|
2365
|
-
const to = html.indexOf(CATALOG_CLOSE, from);
|
|
2366
|
-
if (to !== -1) {
|
|
2367
|
-
const end = to + 23;
|
|
2368
|
-
if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
|
|
2414
|
+
function wrapSegment(parent, children) {
|
|
2415
|
+
const meaningful = children.filter((c) => c.type === "JSXText" && c.value.trim() !== "" || c.type === "JSXExpressionContainer" && c.expression.type !== "JSXEmptyExpression");
|
|
2416
|
+
if (meaningful.length === 0) return;
|
|
2417
|
+
const first = meaningful[0];
|
|
2418
|
+
const last = meaningful[meaningful.length - 1];
|
|
2419
|
+
if (first.type === "JSXExpressionContainer" && meaningful.length > 1) {
|
|
2420
|
+
skip(parent, snippet(children), "starts with an interpolation: wrap the sentence by hand");
|
|
2369
2421
|
return;
|
|
2370
2422
|
}
|
|
2423
|
+
let template = "";
|
|
2424
|
+
let report = "";
|
|
2425
|
+
for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {
|
|
2426
|
+
const child = children[i];
|
|
2427
|
+
if (child.type === "JSXText") {
|
|
2428
|
+
let value = cleanJsxText(child.value);
|
|
2429
|
+
if (child === first) value = value.trimStart();
|
|
2430
|
+
if (child === last) value = value.trimEnd();
|
|
2431
|
+
template += escapeTemplate(value);
|
|
2432
|
+
report += value;
|
|
2433
|
+
} else if (child.type === "JSXExpressionContainer") {
|
|
2434
|
+
const expr = child.expression;
|
|
2435
|
+
if (expr.type === "JSXEmptyExpression") continue;
|
|
2436
|
+
if (usesT(expr)) {
|
|
2437
|
+
skip(parent, snippet(children), "already uses t: finish it by hand");
|
|
2438
|
+
return;
|
|
2439
|
+
}
|
|
2440
|
+
if (containsJsx(expr)) {
|
|
2441
|
+
skip(parent, snippet(children), "an expression renders markup: wrap by hand or use <Trans>");
|
|
2442
|
+
markSubtree(child);
|
|
2443
|
+
return;
|
|
2444
|
+
}
|
|
2445
|
+
if (expr.type === "StringLiteral") {
|
|
2446
|
+
template += escapeTemplate(expr.value);
|
|
2447
|
+
report += expr.value;
|
|
2448
|
+
} else {
|
|
2449
|
+
const source = code.slice(expr.start, expr.end);
|
|
2450
|
+
template += "${" + source + "}";
|
|
2451
|
+
report += "${" + source + "}";
|
|
2452
|
+
}
|
|
2453
|
+
} else return;
|
|
2454
|
+
}
|
|
2455
|
+
if (!LETTER.test(report)) return;
|
|
2456
|
+
if (isIdentifierLike(report)) return;
|
|
2457
|
+
const start = first.type === "JSXText" ? first.start + leadingWs(first.value) : first.start;
|
|
2458
|
+
const end = last.type === "JSXText" ? last.end - trailingWs(last.value) : last.end;
|
|
2459
|
+
s.overwrite(start, end, "{t`" + template + "`}");
|
|
2460
|
+
changed = true;
|
|
2461
|
+
wrapped.push({
|
|
2462
|
+
file,
|
|
2463
|
+
line: line(first),
|
|
2464
|
+
text: report,
|
|
2465
|
+
kind: "text"
|
|
2466
|
+
});
|
|
2467
|
+
}
|
|
2468
|
+
function wrapAttributes(opening) {
|
|
2469
|
+
for (const attr of opening.attributes) {
|
|
2470
|
+
if (attr.type !== "JSXAttribute") continue;
|
|
2471
|
+
const name = attr.name;
|
|
2472
|
+
if (name.type !== "JSXIdentifier" || !WRAP_ATTRS.has(name.name)) continue;
|
|
2473
|
+
const value = attr.value;
|
|
2474
|
+
if (value?.type !== "StringLiteral") continue;
|
|
2475
|
+
const raw = value.value;
|
|
2476
|
+
if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;
|
|
2477
|
+
s.overwrite(value.start, value.end, "{t`" + escapeTemplate(raw) + "`}");
|
|
2478
|
+
changed = true;
|
|
2479
|
+
wrapped.push({
|
|
2480
|
+
file,
|
|
2481
|
+
line: line(value),
|
|
2482
|
+
text: raw,
|
|
2483
|
+
kind: "attribute",
|
|
2484
|
+
attribute: name.name
|
|
2485
|
+
});
|
|
2486
|
+
}
|
|
2371
2487
|
}
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
function isIndexable(html) {
|
|
2379
|
-
return !REFRESH_META.test(html) && !NOINDEX_META.test(html);
|
|
2380
|
-
}
|
|
2381
|
-
function headIsBound(html, attr) {
|
|
2382
|
-
if (REFRESH_META.test(html)) return true;
|
|
2383
|
-
const title = TITLE_TAG.exec(html);
|
|
2384
|
-
return title ? title[1].includes(attr) : true;
|
|
2385
|
-
}
|
|
2386
|
-
async function renderSite(cfg, options = {}) {
|
|
2387
|
-
const site = join(cfg.root, options.site ?? cfg.render.site ?? "dist");
|
|
2388
|
-
const locales = options.locales ?? cfg.locales;
|
|
2389
|
-
const attribute = options.attribute ?? cfg.render.attribute;
|
|
2390
|
-
const base = normalizeBase(options.base ?? cfg.render.base);
|
|
2391
|
-
const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\/+$/, "");
|
|
2392
|
-
const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== void 0;
|
|
2393
|
-
const patterns = options.exclude ?? cfg.render.exclude ?? [];
|
|
2394
|
-
const excluded = patterns.length > 0 ? picomatch(patterns) : () => false;
|
|
2395
|
-
const sitemap = options.sitemap ?? cfg.render.sitemap ?? false;
|
|
2396
|
-
const wantSitemap = sitemap !== false && baseUrl !== void 0;
|
|
2397
|
-
const clean = options.clean ?? cfg.render.clean ?? false;
|
|
2398
|
-
const wanted = options.redirect ?? cfg.render.redirect ?? false;
|
|
2399
|
-
const redirect = wanted === false ? void 0 : wanted === true ? {} : wanted;
|
|
2400
|
-
const script = redirect && {
|
|
2401
|
-
locales,
|
|
2402
|
-
sourceLocale: cfg.sourceLocale,
|
|
2403
|
-
base,
|
|
2404
|
-
storageKey: redirect.storageKey
|
|
2405
|
-
};
|
|
2406
|
-
const catalogs = loadCatalogs(cfg);
|
|
2407
|
-
const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
|
|
2408
|
-
if (clean) {
|
|
2409
|
-
for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
|
|
2410
|
-
recursive: true,
|
|
2411
|
-
force: true
|
|
2488
|
+
function skip(node, text, reason) {
|
|
2489
|
+
skipped.push({
|
|
2490
|
+
file,
|
|
2491
|
+
line: line(node),
|
|
2492
|
+
text,
|
|
2493
|
+
reason
|
|
2412
2494
|
});
|
|
2413
2495
|
}
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
for (const file of files) {
|
|
2424
|
-
const html = readFileSync(file, "utf8");
|
|
2425
|
-
const rel = relative(site, file).replace(/\\/g, "/");
|
|
2426
|
-
if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
|
|
2427
|
-
const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale) : [];
|
|
2428
|
-
if (wantHreflang && isIndexable(html) && !excluded(rel)) urls.push({
|
|
2429
|
-
rel,
|
|
2430
|
-
alternates
|
|
2496
|
+
function snippet(children) {
|
|
2497
|
+
const start = children[0]?.start ?? 0;
|
|
2498
|
+
const end = children[children.length - 1]?.end ?? start;
|
|
2499
|
+
const text = code.slice(start, end).replace(/\s+/g, " ").trim();
|
|
2500
|
+
return text.length > 60 ? text.slice(0, 59) + "…" : text;
|
|
2501
|
+
}
|
|
2502
|
+
function markSubtree(node) {
|
|
2503
|
+
walk$1(node, (n) => {
|
|
2504
|
+
if (n.type === "JSXElement" || n.type === "JSXFragment") visited.add(n);
|
|
2431
2505
|
});
|
|
2432
|
-
const routed = script && (redirect.on === "all" || rel === "index.html");
|
|
2433
|
-
for (const locale of locales) {
|
|
2434
|
-
const result = renderHtml(html, {
|
|
2435
|
-
locale,
|
|
2436
|
-
instance: instances.get(locale),
|
|
2437
|
-
sourceLocale: cfg.sourceLocale,
|
|
2438
|
-
attribute,
|
|
2439
|
-
richTags: options.richTags,
|
|
2440
|
-
richLinks: options.richLinks ?? cfg.render.links,
|
|
2441
|
-
alternates,
|
|
2442
|
-
mirror: locale === cfg.sourceLocale ? void 0 : {
|
|
2443
|
-
prefix: `/${locale}`,
|
|
2444
|
-
base,
|
|
2445
|
-
pages
|
|
2446
|
-
},
|
|
2447
|
-
redirect: routed && locale === cfg.sourceLocale ? script : void 0,
|
|
2448
|
-
inlineCatalog: cfg.render.inlineCatalog === true
|
|
2449
|
-
});
|
|
2450
|
-
for (const key of result.missing) {
|
|
2451
|
-
const list = missing[locale] ??= [];
|
|
2452
|
-
if (!list.includes(key)) list.push(key);
|
|
2453
|
-
}
|
|
2454
|
-
const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);
|
|
2455
|
-
mkdirSync(dirname(out), { recursive: true });
|
|
2456
|
-
writeFileSync(out, result.html);
|
|
2457
|
-
}
|
|
2458
2506
|
}
|
|
2459
|
-
if (wantSitemap && urls.length) writeFileSync(join(site, typeof sitemap === "string" ? sitemap : "sitemap-i18n.xml"), buildSitemap(urls));
|
|
2460
|
-
return {
|
|
2461
|
-
files: files.length,
|
|
2462
|
-
locales: [...locales],
|
|
2463
|
-
missing,
|
|
2464
|
-
untranslatedHead
|
|
2465
|
-
};
|
|
2466
2507
|
}
|
|
2467
|
-
function
|
|
2468
|
-
const
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
return
|
|
2508
|
+
function isIdentifierLike(text) {
|
|
2509
|
+
const trimmed = text.trim();
|
|
2510
|
+
if (WHITESPACE.test(trimmed)) return false;
|
|
2511
|
+
const first = [...trimmed].find((char) => LETTER.test(char));
|
|
2512
|
+
return first !== void 0 && first !== first.toUpperCase();
|
|
2472
2513
|
}
|
|
2473
|
-
function
|
|
2474
|
-
|
|
2475
|
-
return path ? `/${path}` : "/";
|
|
2514
|
+
function hasDirective(program, value) {
|
|
2515
|
+
return (program.directives ?? []).some((d) => d.value?.value === value);
|
|
2476
2516
|
}
|
|
2477
|
-
function
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2517
|
+
function declaresT(program) {
|
|
2518
|
+
let found = false;
|
|
2519
|
+
walk$1(program, (node) => {
|
|
2520
|
+
if (found) return;
|
|
2521
|
+
if (node.type === "ImportDeclaration") {
|
|
2522
|
+
for (const spec of node.specifiers) if (isTName(spec.local?.name)) found = true;
|
|
2523
|
+
return;
|
|
2524
|
+
}
|
|
2525
|
+
if (node.type === "VariableDeclarator" && bindsT(node.id)) found = true;
|
|
2526
|
+
if (node.type === "FunctionDeclaration" && isTName(node.id?.name)) found = true;
|
|
2527
|
+
if (node.params?.some((param) => bindsT(param))) found = true;
|
|
2484
2528
|
});
|
|
2529
|
+
return found;
|
|
2485
2530
|
}
|
|
2486
|
-
function
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2531
|
+
function bindsT(pattern) {
|
|
2532
|
+
if (!pattern) return false;
|
|
2533
|
+
if (pattern.type === "Identifier") return isTName(pattern.name);
|
|
2534
|
+
if (pattern.type === "AssignmentPattern") return bindsT(pattern.left);
|
|
2535
|
+
if (pattern.type === "ObjectPattern") return pattern.properties.some((prop) => prop.type === "RestElement" ? bindsT(prop.argument) : bindsT(prop.value));
|
|
2536
|
+
if (pattern.type === "ArrayPattern") return pattern.elements.some((el) => bindsT(el ?? void 0));
|
|
2537
|
+
return false;
|
|
2491
2538
|
}
|
|
2492
|
-
function
|
|
2493
|
-
|
|
2494
|
-
ATTR.lastIndex = 0;
|
|
2495
|
-
let m;
|
|
2496
|
-
while ((m = ATTR.exec(chunk)) !== null) attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
|
|
2497
|
-
return attrs;
|
|
2539
|
+
function isTName(name) {
|
|
2540
|
+
return typeof name === "string" && T_NAMES.has(name);
|
|
2498
2541
|
}
|
|
2499
|
-
function
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
return;
|
|
2506
|
-
}
|
|
2542
|
+
function hasVerbalyAttr(opening) {
|
|
2543
|
+
return opening.attributes.some((attr) => {
|
|
2544
|
+
if (attr.type !== "JSXAttribute") return false;
|
|
2545
|
+
const name = attr.name;
|
|
2546
|
+
return name.type === "JSXIdentifier" && name.name.startsWith("data-verbaly");
|
|
2547
|
+
});
|
|
2507
2548
|
}
|
|
2508
|
-
function
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
}
|
|
2516
|
-
return ranges;
|
|
2549
|
+
function usesT(node) {
|
|
2550
|
+
let found = false;
|
|
2551
|
+
walk$1(node, (n) => {
|
|
2552
|
+
if (n.type === "TaggedTemplateExpression" && isTReference(n.tag, T_NAMES)) found = true;
|
|
2553
|
+
if (n.type === "CallExpression" && isTReference(n.callee, T_NAMES)) found = true;
|
|
2554
|
+
});
|
|
2555
|
+
return found;
|
|
2517
2556
|
}
|
|
2518
|
-
function
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
if (inSkip(m.index)) continue;
|
|
2525
|
-
if (m[0][1] === "/") {
|
|
2526
|
-
depth -= 1;
|
|
2527
|
-
if (depth === 0) return { contentEnd: m.index };
|
|
2528
|
-
} else if (!m[0].endsWith("/>")) depth += 1;
|
|
2529
|
-
}
|
|
2530
|
-
return null;
|
|
2557
|
+
function containsJsx(node) {
|
|
2558
|
+
let found = false;
|
|
2559
|
+
walk$1(node, (n) => {
|
|
2560
|
+
if (n.type === "JSXElement" || n.type === "JSXFragment") found = true;
|
|
2561
|
+
});
|
|
2562
|
+
return found;
|
|
2531
2563
|
}
|
|
2532
|
-
function
|
|
2533
|
-
|
|
2534
|
-
const existing = new RegExp(`(\\s${name}\\s*=\\s*)("[^"]*"|'[^']*'|[^\\s>]+)`, "i").exec(attrChunk);
|
|
2535
|
-
if (existing) {
|
|
2536
|
-
const valueStart = chunkStart + existing.index + existing[1].length;
|
|
2537
|
-
const valueEnd = valueStart + existing[2].length;
|
|
2538
|
-
if (html.slice(valueStart, valueEnd) !== `"${escaped}"`) ms.overwrite(valueStart, valueEnd, `"${escaped}"`);
|
|
2539
|
-
return;
|
|
2540
|
-
}
|
|
2541
|
-
const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
|
|
2542
|
-
ms.appendLeft(insertAt, ` ${name}="${escaped}"`);
|
|
2564
|
+
function escapeTemplate(text) {
|
|
2565
|
+
return text.replace(/[\\`]/g, "\\$&").replace(/\$\{/g, "\\${");
|
|
2543
2566
|
}
|
|
2544
|
-
function
|
|
2545
|
-
|
|
2546
|
-
for (const node of nodes) if (typeof node === "string") out += escapeHtml(node);
|
|
2547
|
-
else if (links?.[node.name] !== void 0) {
|
|
2548
|
-
const { href, target, rel } = normalizeLink(links[node.name]);
|
|
2549
|
-
let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
|
|
2550
|
-
if (target) attrs += ` target="${escapeAttr(target)}"`;
|
|
2551
|
-
if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
|
|
2552
|
-
out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
|
|
2553
|
-
} else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
|
|
2554
|
-
else out += richToHtml(node.children, allowed, links);
|
|
2555
|
-
return out;
|
|
2567
|
+
function leadingWs(text) {
|
|
2568
|
+
return text.length - text.trimStart().length;
|
|
2556
2569
|
}
|
|
2557
|
-
function
|
|
2558
|
-
return text.
|
|
2570
|
+
function trailingWs(text) {
|
|
2571
|
+
return text.length - text.trimEnd().length;
|
|
2559
2572
|
}
|
|
2560
|
-
function
|
|
2561
|
-
return
|
|
2573
|
+
function line(node) {
|
|
2574
|
+
return node.loc?.start?.line ?? 1;
|
|
2562
2575
|
}
|
|
2563
|
-
|
|
2564
|
-
|
|
2576
|
+
//#endregion
|
|
2577
|
+
//#region src/run.ts
|
|
2578
|
+
function formatCliError(error) {
|
|
2579
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2580
|
+
return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
|
|
2565
2581
|
}
|
|
2566
2582
|
//#endregion
|
|
2567
|
-
export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, clientCatalogs, collectOrigins, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, needsIcu, needsRelative, pruneCatalogs, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, transformCode, transformSource, translateCatalogs, wrapProject, writeCatalog, writeDts };
|
|
2583
|
+
export { DRAFTS_FILE, LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, clearDrafts, clientCatalogs, collectOrigins, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatCliError, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, needsIcu, needsRelative, pruneCatalogs, readCatalog, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, targetLocales, transformCode, transformSource, translateCatalogs, validateMessage, validatePair, wrapProject, writeCatalog, writeDts };
|
|
2568
2584
|
|
|
2569
2585
|
//# sourceMappingURL=index.js.map
|