@verbaly/compiler 0.33.0 → 0.35.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/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { basename, dirname, join, relative, resolve } from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
5
- import { RICH_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
5
+ import { RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { glob } from "tinyglobby";
8
8
  import { parse as parse$1 } from "@babel/parser";
@@ -698,6 +698,14 @@ var MessageRegistry = class {
698
698
  strayImports() {
699
699
  return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
700
700
  }
701
+ parseErrors() {
702
+ const out = [];
703
+ for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
704
+ file,
705
+ message: analysis.parseError
706
+ });
707
+ return out;
708
+ }
701
709
  origins() {
702
710
  const out = this.usedKeys();
703
711
  for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
@@ -715,6 +723,9 @@ function stableKey(message) {
715
723
  }
716
724
  //#endregion
717
725
  //#region src/analyze.ts
726
+ function parseErrorMessage(error) {
727
+ return error instanceof Error ? error.message : String(error);
728
+ }
718
729
  const SKIP_KEYS = /* @__PURE__ */ new Set([
719
730
  "loc",
720
731
  "leadingComments",
@@ -723,12 +734,13 @@ const SKIP_KEYS = /* @__PURE__ */ new Set([
723
734
  "extra"
724
735
  ]);
725
736
  const DEFAULT_T_NAMES = ["t"];
737
+ const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
726
738
  function analyze(code, file, options = {}) {
727
739
  const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
728
740
  const ast = parse$1(code, {
729
741
  sourceType: "module",
730
742
  errorRecovery: true,
731
- plugins: /\.[jt]sx$/.test(file) ? ["typescript", "jsx"] : ["typescript"]
743
+ plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
732
744
  });
733
745
  const tagged = [];
734
746
  const usedKeys = [];
@@ -995,7 +1007,17 @@ function isNode(value) {
995
1007
  //#region src/sfc.ts
996
1008
  const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
997
1009
  function analyzeFile(code, file) {
998
- return SFC_FILE_RE.test(file) ? analyzeSfc(code, file) : analyze(code, file);
1010
+ if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
1011
+ try {
1012
+ return analyze(code, file);
1013
+ } catch (error) {
1014
+ return {
1015
+ tagged: [],
1016
+ usedKeys: [],
1017
+ strayImports: [],
1018
+ parseError: parseErrorMessage(error)
1019
+ };
1020
+ }
999
1021
  }
1000
1022
  const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
1001
1023
  const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
@@ -1011,12 +1033,17 @@ function analyzeSfc(code, file) {
1011
1033
  const tagged = [];
1012
1034
  const usedKeys = [];
1013
1035
  const strayImports = [];
1036
+ let parseError;
1037
+ const block = (segment, offset) => {
1038
+ parseError ??= segment.error;
1039
+ merge(segment.analysis, offset, false);
1040
+ };
1014
1041
  const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
1015
- if (frontmatter?.[2]) merge(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length, false);
1042
+ if (frontmatter?.[2]) block(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length);
1016
1043
  for (const match of code.matchAll(SCRIPT_RE)) {
1017
1044
  const content = match[2];
1018
1045
  if (!content) continue;
1019
- merge(analyzeSegment(content, file, options), match.index + match[1].length, false);
1046
+ block(analyzeSegment(content, file, options), match.index + match[1].length);
1020
1047
  }
1021
1048
  const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
1022
1049
  const candidates = svelte ? CANDIDATE_SVELTE : CANDIDATE_VUE;
@@ -1030,13 +1057,14 @@ function analyzeSfc(code, file) {
1030
1057
  if (range >= ranges.length || start < ranges[range][0]) continue;
1031
1058
  const end = expressionExtent(markup, start);
1032
1059
  if (end === void 0) continue;
1033
- merge(analyzeSegment(code.slice(start, end), file, options), start, true);
1060
+ merge(analyzeSegment(code.slice(start, end), file, options).analysis, start, true);
1034
1061
  consumedTo = end;
1035
1062
  }
1036
1063
  return {
1037
1064
  tagged,
1038
1065
  usedKeys,
1039
- strayImports
1066
+ strayImports,
1067
+ ...parseError && { parseError }
1040
1068
  };
1041
1069
  function merge(analysis, offset, markupSegment) {
1042
1070
  if (!analysis) return;
@@ -1059,9 +1087,9 @@ function analyzeSfc(code, file) {
1059
1087
  }
1060
1088
  function analyzeSegment(code, file, options) {
1061
1089
  try {
1062
- return analyze(code, file, options);
1063
- } catch {
1064
- return;
1090
+ return { analysis: analyze(code, file, options) };
1091
+ } catch (error) {
1092
+ return { error: parseErrorMessage(error) };
1065
1093
  }
1066
1094
  }
1067
1095
  function blank(source, re) {
@@ -1370,6 +1398,12 @@ async function doctor(cfg) {
1370
1398
  }
1371
1399
  const registry = await extractProject(cfg);
1372
1400
  if (scanning) {
1401
+ const unreadable = registry.parseErrors();
1402
+ if (unreadable.length > 0) {
1403
+ const first = unreadable[0];
1404
+ const one = unreadable.length === 1;
1405
+ warn("sources", `${unreadable.length} ${one ? "file" : "files"} could not be parsed, so ${one ? "its" : "their"} messages are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
1406
+ }
1373
1407
  const stray = registry.strayImports();
1374
1408
  if (stray.length > 0) {
1375
1409
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
@@ -2098,22 +2132,7 @@ function csvRows(content) {
2098
2132
  //#region src/render.ts
2099
2133
  const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
2100
2134
  const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
2101
- const VOID_TAGS = /* @__PURE__ */ new Set([
2102
- "area",
2103
- "base",
2104
- "br",
2105
- "col",
2106
- "embed",
2107
- "hr",
2108
- "img",
2109
- "input",
2110
- "link",
2111
- "meta",
2112
- "param",
2113
- "source",
2114
- "track",
2115
- "wbr"
2116
- ]);
2135
+ const VOID = new Set(VOID_TAGS);
2117
2136
  const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
2118
2137
  const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
2119
2138
  function renderHtml(html, options) {
@@ -2135,13 +2154,15 @@ function renderHtml(html, options) {
2135
2154
  const missing = /* @__PURE__ */ new Set();
2136
2155
  const skip = protectedRanges(html);
2137
2156
  const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
2157
+ const filled = [];
2158
+ const inFilled = (index) => filled.some(([from, to]) => index >= from && index < to);
2138
2159
  const selfUrl = options.alternates?.find((a) => a.hreflang === options.locale)?.href;
2139
2160
  const sourceUrl = options.alternates?.find((a) => a.hreflang === "x-default")?.href;
2140
2161
  const rewriteUrl = selfUrl !== void 0 && selfUrl !== sourceUrl;
2141
2162
  START_TAG.lastIndex = 0;
2142
2163
  let m;
2143
2164
  while ((m = START_TAG.exec(html)) !== null) {
2144
- if (inSkip(m.index)) continue;
2165
+ if (inSkip(m.index) || inFilled(m.index)) continue;
2145
2166
  const [full, rawName, attrChunk] = m;
2146
2167
  const tagName = rawName.toLowerCase();
2147
2168
  const openEnd = m.index + full.length;
@@ -2154,13 +2175,25 @@ function renderHtml(html, options) {
2154
2175
  const attrs = parseAttrs(attrChunk);
2155
2176
  if (rewriteUrl && tagName === "link" && attrs.get("rel")?.toLowerCase() === "canonical" && decodeEntities(attrs.get("href") ?? "") === sourceUrl) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", selfUrl);
2156
2177
  if (rewriteUrl && tagName === "meta" && attrs.get("property") === "og:url" && decodeEntities(attrs.get("content") ?? "") === sourceUrl) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", selfUrl);
2178
+ const mirror = options.mirror;
2179
+ if (mirror) {
2180
+ if (tagName === "a" || tagName === "area") {
2181
+ const inside = mirroredHref(attrs.get("href"), mirror);
2182
+ if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", inside);
2183
+ } else if (tagName === "meta" && attrs.get("http-equiv")?.toLowerCase() === "refresh") {
2184
+ const content = attrs.get("content") ?? "";
2185
+ const url = /^([^;]*;\s*url\s*=\s*)(.*)$/i.exec(decodeEntities(content));
2186
+ const inside = url && mirroredHref(url[2], mirror);
2187
+ if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", `${url[1]}${inside}`);
2188
+ }
2189
+ }
2157
2190
  const key = attrs.get(attr);
2158
2191
  const attrMapRaw = attrs.get(attrsAttr);
2159
2192
  if (key === void 0 && attrMapRaw === void 0) continue;
2160
2193
  const args = parseArgs$1(attrs.get(argsAttr));
2161
2194
  if (key) {
2162
2195
  if (!v.has(key)) missing.add(key);
2163
- else if (!VOID_TAGS.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
2196
+ else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
2164
2197
  const close = findClose(html, tagName, openEnd, inSkip);
2165
2198
  if (close) {
2166
2199
  const text = t(key, args);
@@ -2172,6 +2205,7 @@ function renderHtml(html, options) {
2172
2205
  const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
2173
2206
  if (html.slice(openEnd, close.contentEnd) !== content) if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
2174
2207
  else ms.overwrite(openEnd, close.contentEnd, content);
2208
+ filled.push([openEnd, close.contentEnd]);
2175
2209
  }
2176
2210
  }
2177
2211
  }
@@ -2194,6 +2228,19 @@ function renderHtml(html, options) {
2194
2228
  missing: [...missing]
2195
2229
  };
2196
2230
  }
2231
+ function publicPath(rel) {
2232
+ const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
2233
+ return path.length > 1 ? path.replace(/\/+$/, "") : path;
2234
+ }
2235
+ function mirroredHref(raw, mirror) {
2236
+ if (raw === void 0) return void 0;
2237
+ const href = decodeEntities(raw);
2238
+ if (!href.startsWith("/") || href.startsWith("//")) return void 0;
2239
+ const cut = href.search(/[?#]/);
2240
+ const path = cut < 0 ? href : href.slice(0, cut);
2241
+ if (!mirror.pages.has(publicPath(path.replace(/^\//, "")))) return void 0;
2242
+ return `${mirror.prefix}${href}`;
2243
+ }
2197
2244
  function injectAlternates(ms, html, alternates) {
2198
2245
  const links = alternates.map((a) => `<link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}">`).join("");
2199
2246
  const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;
@@ -2230,6 +2277,7 @@ async function renderSite(cfg, options = {}) {
2230
2277
  absolute: true,
2231
2278
  ignore: locales.map((locale) => `${locale}/**`)
2232
2279
  });
2280
+ const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
2233
2281
  const missing = {};
2234
2282
  const urls = [];
2235
2283
  for (const file of files) {
@@ -2248,7 +2296,11 @@ async function renderSite(cfg, options = {}) {
2248
2296
  attribute,
2249
2297
  richTags: options.richTags,
2250
2298
  richLinks: options.richLinks ?? cfg.render.links,
2251
- alternates
2299
+ alternates,
2300
+ mirror: locale === cfg.sourceLocale ? void 0 : {
2301
+ prefix: `/${locale}`,
2302
+ pages
2303
+ }
2252
2304
  });
2253
2305
  for (const key of result.missing) {
2254
2306
  const list = missing[locale] ??= [];
@@ -2352,7 +2404,7 @@ function richToHtml(nodes, allowed, links) {
2352
2404
  if (target) attrs += ` target="${escapeAttr(target)}"`;
2353
2405
  if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
2354
2406
  out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
2355
- } else if (allowed.has(node.name)) out += `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
2407
+ } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
2356
2408
  else out += richToHtml(node.children, allowed, links);
2357
2409
  return out;
2358
2410
  }
@@ -2705,7 +2757,7 @@ Options:
2705
2757
  --out <path> export directory (export, default: verbaly-export)
2706
2758
  --missing export only untranslated entries (export)
2707
2759
  --overwrite replace existing translations on import (import)
2708
- --locale <id> pseudo-locale id (pseudo) / target-locale override (import)
2760
+ --locale <id> pseudo-locale id (pseudo) / one locale only (review, import)
2709
2761
  --site <path> built site directory (render, default: dist)
2710
2762
  --attribute <name> base data attribute (render, default: data-verbaly)
2711
2763
  --base-url <url> site origin, enables hreflang alternates (render)
@@ -2781,7 +2833,7 @@ async function runCli(args = process.argv.slice(2)) {
2781
2833
  warn: "⚠",
2782
2834
  error: "✗"
2783
2835
  };
2784
- console.log(`[verbaly] doctor: ${result.entries.length} checks`);
2836
+ console.log(`[verbaly] doctor: ${plural(result.entries.length, "check")}`);
2785
2837
  for (const entry of result.entries) {
2786
2838
  const line = ` ${icon[entry.level]} ${entry.check}: ${entry.message}`;
2787
2839
  if (entry.level === "error") console.error(line);
@@ -2816,8 +2868,9 @@ async function runCli(args = process.argv.slice(2)) {
2816
2868
  if (cfg.dts !== false) writeDts(cfg, catalogs[cfg.sourceLocale] ?? {}, cfg.dts);
2817
2869
  }
2818
2870
  const total = registry.messages().size;
2819
- console.log(`[verbaly] ${total} messages · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
2871
+ console.log(`[verbaly] ${plural(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
2820
2872
  for (const [locale, keys] of Object.entries(added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
2873
+ reportParseErrors(cfg, registry);
2821
2874
  reportEscapedSyntax(cfg, registry);
2822
2875
  }
2823
2876
  await runExtract();
@@ -2830,12 +2883,12 @@ async function runCli(args = process.argv.slice(2)) {
2830
2883
  if (command === "wrap") {
2831
2884
  const result = await wrapProject(cfg, { write: values.write });
2832
2885
  if (result.wrapped.length === 0 && result.skipped.length === 0) {
2833
- console.log(`[verbaly] nothing to wrap (${result.files} files scanned) ✓`);
2886
+ console.log(`[verbaly] nothing to wrap (${plural(result.files, "file")} scanned) ✓`);
2834
2887
  return;
2835
2888
  }
2836
2889
  const verb = values.write ? "wrapped" : "would wrap";
2837
2890
  const note = values.write ? "" : " (report only, use --write to apply)";
2838
- console.log(`[verbaly] ${verb} ${result.wrapped.length} texts in ${result.changed.length} files${note}`);
2891
+ console.log(`[verbaly] ${verb} ${plural(result.wrapped.length, "text")} in ${plural(result.changed.length, "file")}${note}`);
2839
2892
  for (const entry of result.wrapped) {
2840
2893
  const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
2841
2894
  console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
@@ -3014,8 +3067,8 @@ async function runCli(args = process.argv.slice(2)) {
3014
3067
  sitemap: values.sitemap,
3015
3068
  clean: values.clean
3016
3069
  });
3017
- console.log(`[verbaly] ${result.files} pages × ${result.locales.length} locales (${result.locales.join(", ")})`);
3018
- for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${keys.length} keys not pre-filled: ${keys.join(", ")}`);
3070
+ console.log(`[verbaly] ${plural(result.files, "page")} × ${plural(result.locales.length, "locale")} (${result.locales.join(", ")})`);
3071
+ for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${plural(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
3019
3072
  return;
3020
3073
  }
3021
3074
  if (command === "pseudo") {
@@ -3023,7 +3076,7 @@ async function runCli(args = process.argv.slice(2)) {
3023
3076
  const locale = values.locale ?? "en-XA";
3024
3077
  const keys = pseudoCatalogs(cfg, catalogs, locale);
3025
3078
  writeCatalog(cfg, locale, catalogs[locale] ?? {});
3026
- console.log(`[verbaly] ${keys.length} messages pseudo-localized → ${locale}`);
3079
+ console.log(`[verbaly] ${plural(keys.length, "message")} pseudo-localized → ${locale}`);
3027
3080
  return;
3028
3081
  }
3029
3082
  console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
@@ -3033,6 +3086,15 @@ function formatCliError(error) {
3033
3086
  const message = error instanceof Error ? error.message : String(error);
3034
3087
  return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
3035
3088
  }
3089
+ function plural(count, noun) {
3090
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
3091
+ }
3092
+ function reportParseErrors(cfg, registry) {
3093
+ for (const { file, message } of registry.parseErrors()) {
3094
+ const rel = relative(cfg.root, file).replaceAll("\\", "/");
3095
+ console.warn(` ${rel}: could not be parsed (${message}), its messages were not extracted`);
3096
+ }
3097
+ }
3036
3098
  function reportEscapedSyntax(cfg, registry) {
3037
3099
  for (const msg of registry.messages().values()) {
3038
3100
  const slice = escapedSyntax(msg.message);