@verbaly/compiler 0.82.0 → 0.83.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.
@@ -3,6 +3,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSy
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
6
+ import { readFile } from "node:fs/promises";
6
7
  import { glob } from "tinyglobby";
7
8
  import { parse as parse$1 } from "@babel/parser";
8
9
  import { createHash } from "node:crypto";
@@ -10,6 +11,27 @@ import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
10
11
  import picomatch from "picomatch";
11
12
  import MagicString from "magic-string";
12
13
  import { parseArgs as parseArgs$1 } from "node:util";
14
+ // src/util/text.ts
15
+ function counted(count, noun, many = `${noun}s`) {
16
+ return `${count} ${count === 1 ? noun : many}`;
17
+ }
18
+ function truncate(text, max) {
19
+ return text.length > max ? text.slice(0, max - 1) + "…" : text;
20
+ }
21
+ function trimTrailingSlashes(text) {
22
+ let end = text.length;
23
+ while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
24
+ return text.slice(0, end);
25
+ }
26
+ function singleQuoted(text) {
27
+ return `'${text.replace(/[\\']/g, "\\$&")}'`;
28
+ }
29
+ function byCodeUnit(a, b) {
30
+ return a < b ? -1 : a > b ? 1 : 0;
31
+ }
32
+ function stripBom(text) {
33
+ return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
34
+ }
13
35
  // src/config/host.ts
14
36
  const HOSTS = [
15
37
  {
@@ -95,19 +117,21 @@ const HOSTS = [
95
117
  }
96
118
  ];
97
119
  const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
98
- function readDependencies(root) {
99
- const path = join(root, "package.json");
100
- if (!existsSync(path)) return {};
120
+ function readManifest(root) {
101
121
  try {
102
- const pkg = JSON.parse(readFileSync(path, "utf8"));
103
- return {
104
- ...pkg.dependencies,
105
- ...pkg.devDependencies
106
- };
122
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
123
+ return typeof manifest === "object" && manifest !== null ? manifest : void 0;
107
124
  } catch {
108
- return {};
125
+ return;
109
126
  }
110
127
  }
128
+ function readDependencies(root) {
129
+ const manifest = readManifest(root);
130
+ return {
131
+ ...manifest?.dependencies,
132
+ ...manifest?.devDependencies
133
+ };
134
+ }
111
135
  const ADAPTERS = [
112
136
  ["@verbaly/react", [
113
137
  "react",
@@ -153,11 +177,9 @@ const LOCKFILES = [
153
177
  ["package-lock.json", "npm"]
154
178
  ];
155
179
  function packageManager(root) {
156
- try {
157
- const declared = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).packageManager;
158
- const name = typeof declared === "string" ? declared.split("@")[0] : void 0;
159
- if (name === "pnpm" || name === "npm" || name === "yarn" || name === "bun") return name;
160
- } catch {}
180
+ const declared = readManifest(root)?.packageManager;
181
+ const name = typeof declared === "string" ? declared.split("@")[0] : void 0;
182
+ if (name === "pnpm" || name === "npm" || name === "yarn" || name === "bun") return name;
161
183
  for (let dir = root;; dir = dirname(dir)) {
162
184
  const found = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
163
185
  if (found) return found[1];
@@ -200,6 +222,7 @@ function warnParseError(file, message) {
200
222
  }
201
223
  // src/config/config.ts
202
224
  const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}";
225
+ const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
203
226
  const PSEUDO_LOCALE = "en-XA";
204
227
  function resolveConfig(config = {}) {
205
228
  const root = resolve(config.root ?? process.cwd());
@@ -243,27 +266,19 @@ function findConfigFile(root) {
243
266
  return CONFIG_FILES.find((name) => existsSync(join(root, name)));
244
267
  }
245
268
  async function loadConfigFile(root) {
246
- for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
247
- const path = join(root, name);
248
- if (existsSync(path)) {
249
- const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
250
- const cache = createRequire(import.meta.url).cache;
251
- delete cache[realpathSync(path)];
252
- delete cache[resolve(path)];
253
- return (await import(url)).default ?? {};
254
- }
255
- }
256
- for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
257
- const path = join(root, name);
258
- if (existsSync(path)) return loadTsConfig(path);
259
- }
260
- const jsonPath = join(root, "verbaly.config.json");
261
- if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
262
- return {};
269
+ const name = findConfigFile(root);
270
+ if (!name) return {};
271
+ const path = join(root, name);
272
+ if (name.endsWith(".json")) return readJsonConfig(path);
273
+ if (name.endsWith("ts")) return loadTsConfig(path);
274
+ const url = `${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`;
275
+ const cache = createRequire(import.meta.url).cache;
276
+ delete cache[realpathSync(path)];
277
+ delete cache[resolve(path)];
278
+ return (await import(url)).default ?? {};
263
279
  }
264
280
  function readJsonConfig(path) {
265
- const content = readFileSync(path, "utf8");
266
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
281
+ const body = stripBom(readFileSync(path, "utf8"));
267
282
  try {
268
283
  return JSON.parse(body);
269
284
  } catch (error) {
@@ -380,16 +395,19 @@ function parseCatalog(content) {
380
395
  return tree === void 0 ? void 0 : flatten(tree);
381
396
  }
382
397
  function parseTree(content) {
383
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
398
+ const body = stripBom(content);
384
399
  try {
385
400
  return JSON.parse(body);
386
401
  } catch {
387
402
  return;
388
403
  }
389
404
  }
390
- function isTree(value) {
405
+ function isRecord(value) {
391
406
  return typeof value === "object" && value !== null && !Array.isArray(value);
392
407
  }
408
+ function isTree(value) {
409
+ return isRecord(value);
410
+ }
393
411
  function loadCatalogs(cfg) {
394
412
  const catalogs = emptyCatalog();
395
413
  for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
@@ -412,7 +430,7 @@ function pathsOf(tree, prefix = [], out = /* @__PURE__ */ new Map()) {
412
430
  function nest(catalog, shape) {
413
431
  const tree = group();
414
432
  const written = shape ? pathsOf(shape) : void 0;
415
- for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
433
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => byCodeUnit(a, b))) {
416
434
  const parts = written?.get(key) ?? key.split(".");
417
435
  const leaf = parts[parts.length - 1];
418
436
  let node = parts.length > 1 ? tree : void 0;
@@ -500,24 +518,6 @@ function someLeaf(tree, pattern) {
500
518
  } else if (isTree(value) && someLeaf(value, pattern)) return true;
501
519
  return false;
502
520
  }
503
- // src/util/text.ts
504
- function counted(count, noun, many = `${noun}s`) {
505
- return `${count} ${count === 1 ? noun : many}`;
506
- }
507
- function truncate(text, max) {
508
- return text.length > max ? text.slice(0, max - 1) + "…" : text;
509
- }
510
- function trimTrailingSlashes(text) {
511
- let end = text.length;
512
- while (end > 0 && text.charCodeAt(end - 1) === 47) end -= 1;
513
- return text.slice(0, end);
514
- }
515
- function singleQuoted(text) {
516
- return `'${text.replace(/[\\']/g, "\\$&")}'`;
517
- }
518
- function byCodeUnit(a, b) {
519
- return a < b ? -1 : a > b ? 1 : 0;
520
- }
521
521
  // src/emit/bundle.ts
522
522
  function isExcluded(key, prefixes) {
523
523
  return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
@@ -796,7 +796,7 @@ function loadsAtRuntime(node) {
796
796
  return specifiers.some((spec) => spec.importKind !== "type" && spec.exportKind !== "type");
797
797
  }
798
798
  function lineOf(node) {
799
- return node.loc?.start.line ?? 1;
799
+ return node.loc?.start?.line ?? 1;
800
800
  }
801
801
  const OTHER_I18N = /^(?:react-i18next|next-i18next|next-translate|ttag|@lingui\/[\w-]+)(?:\/.*)?$/;
802
802
  const TRANS = "Trans";
@@ -864,7 +864,7 @@ var Bindings = class {
864
864
  }
865
865
  foreign(name, at) {
866
866
  let theirs = this.other(name);
867
- let reach = Infinity;
867
+ let reach = 1e400;
868
868
  for (const { name: bound, init, scope } of [...this.declared, ...this.destructured]) {
869
869
  if (bound !== name || at < scope.start || at >= scope.end) continue;
870
870
  if (scope.end - scope.start >= reach) continue;
@@ -924,19 +924,25 @@ function renamedTag(tag, renamed) {
924
924
  if (renamed.size === 0) return void 0;
925
925
  const name = identifierName(tag);
926
926
  if (renamed.has(name)) return name;
927
+ const call = idCall(tag);
928
+ if (!call) return void 0;
929
+ const object = identifierName(call.object);
930
+ return renamed.has(object) ? object : void 0;
931
+ }
932
+ function idCall(tag) {
927
933
  if (tag.type !== "CallExpression") return void 0;
928
934
  const callee = tag.callee;
929
935
  if (callee.type !== "MemberExpression" || callee.computed) return void 0;
930
936
  if (identifierName(callee.property) !== "id") return void 0;
931
- const object = identifierName(callee.object);
932
- return renamed.has(object) ? object : void 0;
937
+ const args = tag.arguments;
938
+ return {
939
+ object: callee.object,
940
+ key: args.length === 1 ? staticString(args[0]) : void 0
941
+ };
933
942
  }
934
943
  function missedKey(code, node, names) {
935
944
  const tag = node.tag;
936
- if (tag.type === "CallExpression") {
937
- const args = tag.arguments;
938
- return args.length === 1 ? staticString(args[0]) : void 0;
939
- }
945
+ if (tag.type === "CallExpression") return idCall(tag)?.key;
940
946
  const message = buildMessage(code, node.quasi, names);
941
947
  return message ? stableKey(message.text) : void 0;
942
948
  }
@@ -1021,20 +1027,12 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
1021
1027
  push(stableKey(built.text), built);
1022
1028
  }
1023
1029
  function explicitId(tag, names) {
1024
- if (tag.type !== "CallExpression") return void 0;
1025
- const callee = tag.callee;
1026
- if (callee.type !== "MemberExpression" || callee.computed) return void 0;
1027
- const prop = callee.property;
1028
- if (prop.type !== "Identifier" || prop.name !== "id") return void 0;
1029
- const obj = callee.object;
1030
- if (!isTReference(obj, names)) return void 0;
1031
- const args = tag.arguments;
1032
- const key = args.length === 1 ? staticString(args[0]) : void 0;
1033
- if (key === void 0) return void 0;
1030
+ const call = idCall(tag);
1031
+ if (!call || !isTReference(call.object, names) || call.key === void 0) return void 0;
1034
1032
  return {
1035
- key,
1036
- refStart: obj.start,
1037
- refEnd: obj.end
1033
+ key: call.key,
1034
+ refStart: call.object.start,
1035
+ refEnd: call.object.end
1038
1036
  };
1039
1037
  }
1040
1038
  function buildTransMessage(code, children, names) {
@@ -1488,8 +1486,26 @@ function stringEnd(code, start) {
1488
1486
  else i += 1;
1489
1487
  return code.length;
1490
1488
  }
1489
+ // src/util/path.ts
1490
+ function slashed(path) {
1491
+ return path.replaceAll("\\", "/");
1492
+ }
1493
+ function relativePath(root, file) {
1494
+ return slashed(relative(root, file));
1495
+ }
1491
1496
  // src/scan/extract.ts
1492
1497
  const kept = /* @__PURE__ */ new WeakMap();
1498
+ async function readSources(files, each, platform = process.platform) {
1499
+ if (platform !== "win32") {
1500
+ for (const file of files) each(file, readFileSync(file, "utf8"));
1501
+ return;
1502
+ }
1503
+ for (let at = 0; at < files.length; at += 64) {
1504
+ const window = files.slice(at, at + 64);
1505
+ const read = await Promise.all(window.map(async (file) => [file, await readFile(file, "utf8")]));
1506
+ for (const [file, code] of read) each(file, code);
1507
+ }
1508
+ }
1493
1509
  async function extractProject(cfg, options = {}) {
1494
1510
  const files = await glob(cfg.include, {
1495
1511
  cwd: cfg.root,
@@ -1498,31 +1514,31 @@ async function extractProject(cfg, options = {}) {
1498
1514
  });
1499
1515
  const registry = new MessageRegistry();
1500
1516
  const read = options.keepSource ? /* @__PURE__ */ new Map() : null;
1501
- for (const file of files.sort()) {
1502
- const code = readFileSync(file, "utf8");
1517
+ await readSources(files.sort(), (file, code) => {
1503
1518
  const analysis = analyzeFile(code, file);
1504
1519
  registry.update(file, analysis);
1505
- read?.set(file.replaceAll("\\", "/"), {
1520
+ read?.set(slashed(file), {
1506
1521
  code,
1507
1522
  analysis
1508
1523
  });
1509
- }
1524
+ });
1510
1525
  if (read) kept.set(registry, read);
1511
1526
  return registry;
1512
1527
  }
1513
1528
  function scannedAnalysis(scan, file, code) {
1514
1529
  const read = kept.get(scan);
1515
- const key = file.replaceAll("\\", "/");
1530
+ const key = slashed(file);
1516
1531
  const entry = read?.get(key);
1517
1532
  read?.delete(key);
1518
1533
  return entry?.code === code ? entry.analysis : void 0;
1519
1534
  }
1520
1535
  async function collectOrigins(cfg, reuse) {
1521
1536
  const registry = reuse ?? await extractProject(cfg);
1522
- const origins = Object.create(null);
1523
- for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
1537
+ const origins = emptyCatalog();
1538
+ for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relativePath(cfg.root, file));
1524
1539
  return origins;
1525
1540
  }
1541
+ // src/scan/sync.ts
1526
1542
  function syncCatalogs(cfg, catalogs, registry) {
1527
1543
  const added = emptyCatalog();
1528
1544
  const replaced = [];
@@ -1583,12 +1599,14 @@ function read(message) {
1583
1599
  return tree;
1584
1600
  }
1585
1601
  function gatePass(run) {
1586
- reading = /* @__PURE__ */ new Map();
1602
+ const outer = reading;
1603
+ const pass = /* @__PURE__ */ new Map();
1604
+ reading = pass;
1587
1605
  try {
1588
1606
  return run();
1589
1607
  } finally {
1590
- remembered = reading;
1591
- reading = void 0;
1608
+ remembered = pass;
1609
+ reading = outer;
1592
1610
  }
1593
1611
  }
1594
1612
  const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
@@ -1781,6 +1799,13 @@ function reachableCategories(locale, ordinal) {
1781
1799
  reachable.set(cacheKey, out);
1782
1800
  return out;
1783
1801
  }
1802
+ function structureMatches(source, translated) {
1803
+ try {
1804
+ return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
1805
+ } catch {
1806
+ return false;
1807
+ }
1808
+ }
1784
1809
  // src/emit/params.ts
1785
1810
  const NUMBER_FORMATS = /* @__PURE__ */ new Set([
1786
1811
  "number",
@@ -1860,7 +1885,7 @@ function formatting(text) {
1860
1885
  function typesIncluded(root, file) {
1861
1886
  const read = readTsconfig(root);
1862
1887
  if (typeof read === "string") return read;
1863
- const entry = relative(root, file).replaceAll("\\", "/");
1888
+ const entry = relativePath(root, file);
1864
1889
  const { include, files } = read.json;
1865
1890
  if (covered(include, entry) || covered(files, entry)) return "present";
1866
1891
  return "missing";
@@ -1868,7 +1893,7 @@ function typesIncluded(root, file) {
1868
1893
  function includeTypes(root, file) {
1869
1894
  const read = readTsconfig(root);
1870
1895
  if (typeof read === "string") return read;
1871
- const entry = relative(root, file).replaceAll("\\", "/");
1896
+ const entry = relativePath(root, file);
1872
1897
  const { include, files } = read.json;
1873
1898
  if (covered(include, entry) || covered(files, entry)) return "present";
1874
1899
  const options = { formattingOptions: formatting(read.text) };
@@ -2145,7 +2170,7 @@ function writeDts(cfg, catalog, file) {
2145
2170
  const ignore = join(cfg.root, ".verbaly", ".gitignore");
2146
2171
  if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
2147
2172
  const state = includeTypes(cfg.root, target);
2148
- const entry = relative(cfg.root, target).replaceAll("\\", "/");
2173
+ const entry = relativePath(cfg.root, target);
2149
2174
  if (state === "added") warnOnce(`added "${entry}" to the include of tsconfig.json, so TypeScript reads the types`);
2150
2175
  else if (state === "unreadable") warnOnce(`tsconfig.json could not be read, so add "${entry}" to its include yourself`);
2151
2176
  }
@@ -2165,9 +2190,9 @@ function removeRootDts(cfg, target) {
2165
2190
  }
2166
2191
  if (head !== "// generated by verbaly: do not edit") return;
2167
2192
  rmSync(old);
2168
- warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
2193
+ warnOnce(`the types live in ${relativePath(cfg.root, target)} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
2169
2194
  }
2170
- // src/catalog/state.ts
2195
+ // src/catalog/lock.ts
2171
2196
  const STATE_FILE = "verbaly.lock";
2172
2197
  const LOCK_VERSION = 1;
2173
2198
  const README = "Written by Verbaly: the source text each translation was made for, which ones are drafts, and which languages migrate converted. Commit it with your catalogs and never edit it: deleting it marks every draft as reviewed.";
@@ -2278,77 +2303,6 @@ function readText(path) {
2278
2303
  return;
2279
2304
  }
2280
2305
  }
2281
- function updateState(cfg, catalogs) {
2282
- const next = refreshState(cfg, catalogs, loadState(cfg));
2283
- saveState(cfg, next);
2284
- return next;
2285
- }
2286
- function refreshState(cfg, catalogs, previous) {
2287
- const flat = flatCatalogs(catalogs);
2288
- const source = flat[cfg.sourceLocale] ?? {};
2289
- const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
2290
- const drafts = emptyCatalog();
2291
- for (const [locale, keys] of Object.entries(previous.drafts)) {
2292
- if (!shown.has(locale)) {
2293
- drafts[locale] = keys;
2294
- continue;
2295
- }
2296
- const live = keys.filter((key) => own(flat[locale], key));
2297
- if (live.length) drafts[locale] = live;
2298
- }
2299
- const fingerprints = emptyCatalog();
2300
- for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
2301
- for (const locale of shown) {
2302
- const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
2303
- if (Object.keys(stamps).length) fingerprints[locale] = stamps;
2304
- }
2305
- return {
2306
- drafts,
2307
- fingerprints,
2308
- migrated: previous.migrated
2309
- };
2310
- }
2311
- function refreshStamps(source, catalog, before) {
2312
- const after = emptyCatalog();
2313
- for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
2314
- const translated = own(catalog, key);
2315
- if (!translated) continue;
2316
- const was = own(before, key);
2317
- if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
2318
- after[key] = was;
2319
- continue;
2320
- }
2321
- const text = own(source, key);
2322
- if (text && tracked(key, text)) after[key] = stamp(text, translated);
2323
- else if (was !== void 0) after[key] = was;
2324
- }
2325
- return after;
2326
- }
2327
- function recordTranslations(cfg, source, writes) {
2328
- const state = loadState(cfg);
2329
- for (const { locale, entries, draft } of writes) {
2330
- if (entries.length === 0) continue;
2331
- const stamps = state.fingerprints[locale] ??= emptyCatalog();
2332
- for (const entry of entries) {
2333
- const from = entry.source || own(source, entry.key);
2334
- if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
2335
- }
2336
- const keys = entries.map((entry) => entry.key);
2337
- if (draft === true) markDrafts(state.drafts, locale, keys);
2338
- else if (draft === false) clearDrafts(state.drafts, locale, keys);
2339
- }
2340
- saveState(cfg, state);
2341
- return state;
2342
- }
2343
- function effectiveDrafts(drafts, catalogs) {
2344
- const out = emptyCatalog();
2345
- for (const [locale, keys] of Object.entries(drafts)) {
2346
- const catalog = catalogs[locale] ?? {};
2347
- const live = keys.filter((key) => own(catalog, key));
2348
- if (live.length) out[locale] = live;
2349
- }
2350
- return out;
2351
- }
2352
2306
  function markDrafts(drafts, locale, keys) {
2353
2307
  if (!keys.length) return;
2354
2308
  drafts[locale] = [.../* @__PURE__ */ new Set([...drafts[locale] ?? [], ...keys])];
@@ -2366,50 +2320,15 @@ function clearDrafts(drafts, locale, keys) {
2366
2320
  function fingerprint(text) {
2367
2321
  return stableKey(text);
2368
2322
  }
2369
- function tracked(key, text) {
2370
- return stableKey(text) !== key;
2371
- }
2372
2323
  function stamp(source, translated) {
2373
2324
  return `${fingerprint(source)}.${fingerprint(translated)}`;
2374
2325
  }
2375
- function outdatedTranslations(cfg, catalogs, fingerprints) {
2376
- const source = catalogs[cfg.sourceLocale] ?? {};
2377
- const out = [];
2378
- for (const locale of targetLocales(cfg)) {
2379
- const catalog = catalogs[locale] ?? {};
2380
- for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
2381
- const text = own(source, key);
2382
- const translated = own(catalog, key);
2383
- if (!text || !translated) continue;
2384
- if (translationOf(was) !== fingerprint(translated)) continue;
2385
- if (sourceOf(was) !== fingerprint(text)) out.push({
2386
- locale,
2387
- key
2388
- });
2389
- }
2390
- }
2391
- return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));
2392
- }
2393
- function acceptOutdated(cfg, catalogs, fingerprints, entries) {
2394
- const source = catalogs[cfg.sourceLocale] ?? {};
2395
- for (const { locale, key } of entries) {
2396
- const text = own(source, key);
2397
- const translated = own(catalogs[locale] ?? {}, key);
2398
- if (!text || !translated) continue;
2399
- (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
2400
- }
2401
- }
2402
2326
  function sourceOf(stamped) {
2403
2327
  return stamped.slice(0, stamped.indexOf("."));
2404
2328
  }
2405
2329
  function translationOf(stamped) {
2406
2330
  return stamped.slice(stamped.indexOf(".") + 1);
2407
2331
  }
2408
- function flatCatalogs(catalogs) {
2409
- const out = emptyCatalog();
2410
- for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
2411
- return out;
2412
- }
2413
2332
  function serializeState(state) {
2414
2333
  const drafts = emptyCatalog();
2415
2334
  for (const locale of Object.keys(state.drafts).sort()) {
@@ -2437,7 +2356,7 @@ function serializeState(state) {
2437
2356
  function readSides(path) {
2438
2357
  const content = readText(path);
2439
2358
  if (content === void 0) return void 0;
2440
- const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
2359
+ const body = stripBom(content);
2441
2360
  const sides = conflictSides(body);
2442
2361
  return (sides ?? [body]).map((text) => parseObject(path, text, sides !== void 0));
2443
2362
  }
@@ -2448,7 +2367,7 @@ function parseObject(path, text, conflicted) {
2448
2367
  } catch (error) {
2449
2368
  throw corrupt(path, conflicted, error);
2450
2369
  }
2451
- if (!isObject(value)) throw corrupt(path, conflicted);
2370
+ if (!isRecord(value)) throw corrupt(path, conflicted);
2452
2371
  return value;
2453
2372
  }
2454
2373
  const CONFLICT = {
@@ -2476,12 +2395,9 @@ function conflictSides(text) {
2476
2395
  function corrupt(path, conflicted, cause) {
2477
2396
  return new Error(conflicted ? `[verbaly] ${path} has a merge conflict Verbaly cannot read: resolve it by hand and keep the entries of both sides (dropping a side, or the file, approves its drafts)` : `[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
2478
2397
  }
2479
- function isObject(value) {
2480
- return typeof value === "object" && value !== null && !Array.isArray(value);
2481
- }
2482
2398
  function readDrafts(value) {
2483
2399
  const out = emptyCatalog();
2484
- if (!isObject(value)) return out;
2400
+ if (!isRecord(value)) return out;
2485
2401
  for (const [locale, keys] of Object.entries(value)) if (Array.isArray(keys)) out[locale] = keys.filter((key) => typeof key === "string");
2486
2402
  return out;
2487
2403
  }
@@ -2492,37 +2408,144 @@ function readMigrated(value) {
2492
2408
  }
2493
2409
  function readFingerprints(value) {
2494
2410
  const out = emptyCatalog();
2495
- if (!isObject(value)) return out;
2411
+ if (!isRecord(value)) return out;
2496
2412
  for (const [locale, entries] of Object.entries(value)) {
2497
- if (!isObject(entries)) continue;
2413
+ if (!isRecord(entries)) continue;
2498
2414
  const kept = emptyCatalog();
2499
2415
  for (const [key, stamped] of Object.entries(entries)) if (typeof stamped === "string" && stamped.includes(".")) kept[key] = stamped;
2500
2416
  out[locale] = kept;
2501
2417
  }
2502
2418
  return out;
2503
2419
  }
2504
- // src/gate/findings.ts
2505
- function siteOf(msg) {
2420
+ // src/catalog/state.ts
2421
+ function updateState(cfg, catalogs) {
2422
+ const next = refreshState(cfg, catalogs, loadState(cfg));
2423
+ saveState(cfg, next);
2424
+ return next;
2425
+ }
2426
+ function refreshState(cfg, catalogs, previous) {
2427
+ const flat = flatCatalogs(catalogs);
2428
+ const source = flat[cfg.sourceLocale] ?? {};
2429
+ const shown = new Set(targetLocales(cfg).filter((locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale))));
2430
+ const drafts = emptyCatalog();
2431
+ for (const [locale, keys] of Object.entries(previous.drafts)) {
2432
+ if (!shown.has(locale)) {
2433
+ drafts[locale] = keys;
2434
+ continue;
2435
+ }
2436
+ const live = keys.filter((key) => own(flat[locale], key));
2437
+ if (live.length) drafts[locale] = live;
2438
+ }
2439
+ const fingerprints = emptyCatalog();
2440
+ for (const [locale, stamps] of Object.entries(previous.fingerprints)) if (!shown.has(locale)) fingerprints[locale] = stamps;
2441
+ for (const locale of shown) {
2442
+ const stamps = refreshStamps(source, flat[locale], previous.fingerprints[locale] ?? {});
2443
+ if (Object.keys(stamps).length) fingerprints[locale] = stamps;
2444
+ }
2506
2445
  return {
2507
- file: msg.file,
2508
- line: msg.line,
2509
- message: msg.message
2446
+ drafts,
2447
+ fingerprints,
2448
+ migrated: previous.migrated
2510
2449
  };
2511
2450
  }
2512
- function collisionEntries(registry) {
2513
- return registry.collisions().map(({ key, kept, dropped }) => ({
2514
- key,
2515
- sites: [kept, ...dropped].map(siteOf)
2516
- }));
2451
+ function refreshStamps(source, catalog, before) {
2452
+ const after = emptyCatalog();
2453
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(source)])) {
2454
+ const translated = own(catalog, key);
2455
+ if (!translated) continue;
2456
+ const was = own(before, key);
2457
+ if (was !== void 0 && translationOf(was) === fingerprint(translated)) {
2458
+ after[key] = was;
2459
+ continue;
2460
+ }
2461
+ const text = own(source, key);
2462
+ if (text && tracked(key, text)) after[key] = stamp(text, translated);
2463
+ else if (was !== void 0) after[key] = was;
2464
+ }
2465
+ return after;
2517
2466
  }
2518
- function scanFindings(cfg, registry, replaced = []) {
2519
- const messages = registry.messages();
2520
- const out = [];
2521
- for (const { key, before } of replaced) {
2522
- const msg = messages.get(key);
2523
- if (msg) out.push({
2524
- kind: "replaced",
2525
- locale: cfg.sourceLocale,
2467
+ function recordTranslations(cfg, source, writes) {
2468
+ const state = loadState(cfg);
2469
+ for (const { locale, entries, draft } of writes) {
2470
+ if (entries.length === 0) continue;
2471
+ const stamps = state.fingerprints[locale] ??= emptyCatalog();
2472
+ for (const entry of entries) {
2473
+ const from = entry.source || own(source, entry.key);
2474
+ if (from && entry.text && tracked(entry.key, from)) stamps[entry.key] = stamp(from, entry.text);
2475
+ }
2476
+ const keys = entries.map((entry) => entry.key);
2477
+ if (draft === true) markDrafts(state.drafts, locale, keys);
2478
+ else if (draft === false) clearDrafts(state.drafts, locale, keys);
2479
+ }
2480
+ saveState(cfg, state);
2481
+ return state;
2482
+ }
2483
+ function effectiveDrafts(drafts, catalogs) {
2484
+ const out = emptyCatalog();
2485
+ for (const [locale, keys] of Object.entries(drafts)) {
2486
+ const catalog = catalogs[locale] ?? {};
2487
+ const live = keys.filter((key) => own(catalog, key));
2488
+ if (live.length) out[locale] = live;
2489
+ }
2490
+ return out;
2491
+ }
2492
+ function tracked(key, text) {
2493
+ return stableKey(text) !== key;
2494
+ }
2495
+ function outdatedTranslations(cfg, catalogs, fingerprints) {
2496
+ const source = catalogs[cfg.sourceLocale] ?? {};
2497
+ const out = [];
2498
+ for (const locale of targetLocales(cfg)) {
2499
+ const catalog = catalogs[locale] ?? {};
2500
+ for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {
2501
+ const text = own(source, key);
2502
+ const translated = own(catalog, key);
2503
+ if (!text || !translated) continue;
2504
+ if (translationOf(was) !== fingerprint(translated)) continue;
2505
+ if (sourceOf(was) !== fingerprint(text)) out.push({
2506
+ locale,
2507
+ key
2508
+ });
2509
+ }
2510
+ }
2511
+ return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));
2512
+ }
2513
+ function acceptOutdated(cfg, catalogs, fingerprints, entries) {
2514
+ const source = catalogs[cfg.sourceLocale] ?? {};
2515
+ for (const { locale, key } of entries) {
2516
+ const text = own(source, key);
2517
+ const translated = own(catalogs[locale] ?? {}, key);
2518
+ if (!text || !translated) continue;
2519
+ (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);
2520
+ }
2521
+ }
2522
+ function flatCatalogs(catalogs) {
2523
+ const out = emptyCatalog();
2524
+ for (const [locale, catalog] of Object.entries(catalogs)) out[locale] = flatten(catalog);
2525
+ return out;
2526
+ }
2527
+ // src/gate/findings.ts
2528
+ function siteOf(msg) {
2529
+ return {
2530
+ file: msg.file,
2531
+ line: msg.line,
2532
+ message: msg.message
2533
+ };
2534
+ }
2535
+ function collisionEntries(registry) {
2536
+ return registry.collisions().map(({ key, kept, dropped }) => ({
2537
+ key,
2538
+ sites: [kept, ...dropped].map(siteOf)
2539
+ }));
2540
+ }
2541
+ function scanFindings(cfg, registry, replaced = []) {
2542
+ const messages = registry.messages();
2543
+ const out = [];
2544
+ for (const { key, before } of replaced) {
2545
+ const msg = messages.get(key);
2546
+ if (msg) out.push({
2547
+ kind: "replaced",
2548
+ locale: cfg.sourceLocale,
2526
2549
  key,
2527
2550
  before,
2528
2551
  site: siteOf(msg)
@@ -2560,7 +2583,7 @@ function scanFindings(cfg, registry, replaced = []) {
2560
2583
  return out;
2561
2584
  }
2562
2585
  function sourcePlace(at, root) {
2563
- const file = root ? relative(root, at.file).replaceAll("\\", "/") : at.file;
2586
+ const file = root ? relativePath(root, at.file) : at.file;
2564
2587
  return at.line ? `${file}:${at.line}` : file;
2565
2588
  }
2566
2589
  function quoted(at, root) {
@@ -2661,7 +2684,7 @@ async function syncProject(cfg, options = {}) {
2661
2684
  const result = {
2662
2685
  registry,
2663
2686
  catalogs,
2664
- messages: Object.keys(catalogs[cfg.sourceLocale] ?? {}).length,
2687
+ messages: Object.keys(catalogs[cfg.sourceLocale] ?? emptyCatalog()).length,
2665
2688
  inCode: registry.messages().size,
2666
2689
  added,
2667
2690
  replaced,
@@ -2675,9 +2698,9 @@ async function syncProject(cfg, options = {}) {
2675
2698
  if (replaced.length > 0) changed.add(cfg.sourceLocale);
2676
2699
  for (const locale of cfg.locales) {
2677
2700
  if (options.write === "changed" && !changed.has(locale)) continue;
2678
- result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});
2701
+ result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? emptyCatalog());
2679
2702
  }
2680
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
2703
+ writeDts(cfg, catalogs[cfg.sourceLocale] ?? emptyCatalog());
2681
2704
  const before = stateFile(cfg);
2682
2705
  try {
2683
2706
  result.state = updateState(cfg, catalogs);
@@ -2692,7 +2715,7 @@ async function syncProject(cfg, options = {}) {
2692
2715
  return result;
2693
2716
  }
2694
2717
  function confirmFromDisk(cfg, catalogs, registry) {
2695
- const source = catalogs[cfg.sourceLocale] ?? {};
2718
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
2696
2719
  const stale = /* @__PURE__ */ new Set();
2697
2720
  for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) stale.add(msg.file);
2698
2721
  for (const file of stale) {
@@ -2749,7 +2772,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2749
2772
  const retries = Math.max(0, options.retries ?? 2);
2750
2773
  const retryDelay = options.retryDelay ?? 500;
2751
2774
  const targets = targetLocales(cfg, options.locales);
2752
- const source = catalogs[cfg.sourceLocale] ?? {};
2775
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
2753
2776
  const result = {
2754
2777
  translated: emptyCatalog(),
2755
2778
  invalid: emptyCatalog(),
@@ -2826,7 +2849,7 @@ function mergeTranslations(cfg, locale, translated, keys) {
2826
2849
  const current = readCatalog(cfg, locale);
2827
2850
  const written = [];
2828
2851
  for (const key of keys) {
2829
- const text = translated[key];
2852
+ const text = own(translated, key);
2830
2853
  if (!source[key] || current[key] || !text) continue;
2831
2854
  current[key] = text;
2832
2855
  written.push(key);
@@ -2838,7 +2861,8 @@ function writeDrafts(cfg, locale, entries, options = {}) {
2838
2861
  const targets = targetLocales(cfg);
2839
2862
  if (!targets.includes(locale)) throw new Error(`[verbaly] "${locale}" is not a language this project translates into (${targets.join(", ") || "none yet"})`);
2840
2863
  loadState(cfg);
2841
- const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
2864
+ const catalogs = emptyCatalog();
2865
+ catalogs[cfg.sourceLocale] = readCatalog(cfg, cfg.sourceLocale);
2842
2866
  const source = options.registry ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale] : catalogs[cfg.sourceLocale];
2843
2867
  const current = readCatalog(cfg, locale);
2844
2868
  const result = {
@@ -2889,16 +2913,9 @@ function formatTranslateFailures(failed) {
2889
2913
  async function resolveProvider(cfg, model) {
2890
2914
  const configured = cfg.translate.provider;
2891
2915
  if (typeof configured === "function") return configured;
2892
- const { claudeProvider } = await import("./claude-D31sQLmS.js");
2916
+ const { claudeProvider } = await import("./claude-DvjHi7np.js");
2893
2917
  return claudeProvider({ model: model ?? cfg.translate.model });
2894
2918
  }
2895
- function structureMatches(source, translated) {
2896
- try {
2897
- return ![...validateMessage(translated), ...validatePair(source, translated)].some((issue) => issue.severity === "error");
2898
- } catch {
2899
- return false;
2900
- }
2901
- }
2902
2919
  function progressOf(job) {
2903
2920
  return {
2904
2921
  locale: job.locale,
@@ -2970,7 +2987,7 @@ function gatePasses(result) {
2970
2987
  return result.missing.length === 0 && result.unknown.length === 0 && result.collisions.length === 0 && !result.broken.some((entry) => entry.severity === "error");
2971
2988
  }
2972
2989
  function relativeCheck(root, result) {
2973
- const rel = (file) => relative(root, file).replaceAll("\\", "/");
2990
+ const rel = (file) => relativePath(root, file);
2974
2991
  return {
2975
2992
  ...result,
2976
2993
  unknown: result.unknown.map((entry) => ({
@@ -3003,13 +3020,25 @@ function warningCount(result) {
3003
3020
  function check(cfg, catalogs, registry, fingerprints = emptyCatalog()) {
3004
3021
  return gatePass(() => checkPass(cfg, catalogs, registry, fingerprints));
3005
3022
  }
3006
- function checkPass(cfg, catalogs, registry, fingerprints) {
3007
- const extracted = registry.messages();
3023
+ function gateViews(cfg, catalogs, registry) {
3008
3024
  const flat = emptyCatalog();
3009
3025
  for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
3010
3026
  const source = flat[cfg.sourceLocale] ?? {};
3011
3027
  const shipped = shippedCatalogs(cfg, flat, registry);
3012
- const sourceText = shipped[cfg.sourceLocale];
3028
+ return {
3029
+ flat,
3030
+ source,
3031
+ shipped,
3032
+ sourceText: shipped[cfg.sourceLocale]
3033
+ };
3034
+ }
3035
+ function translationIssues(locale, translated, text) {
3036
+ const issues = validateMessage(translated, locale);
3037
+ return text ? [...issues, ...validatePair(text, translated)] : issues;
3038
+ }
3039
+ function checkPass(cfg, catalogs, registry, fingerprints) {
3040
+ const extracted = registry.messages();
3041
+ const { flat, source, shipped, sourceText } = gateViews(cfg, catalogs, registry);
3013
3042
  const used = registry.usedKeys();
3014
3043
  const unknown = [];
3015
3044
  for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
@@ -3054,9 +3083,7 @@ function checkPass(cfg, catalogs, registry, fingerprints) {
3054
3083
  if (locale === cfg.sourceLocale) continue;
3055
3084
  for (const [key, translated] of Object.entries(flat[locale] ?? {})) {
3056
3085
  if (!translated) continue;
3057
- add(locale, key, validateMessage(translated, locale));
3058
- const text = sourceText[key];
3059
- if (text) add(locale, key, validatePair(text, translated));
3086
+ add(locale, key, translationIssues(locale, translated, sourceText[key]));
3060
3087
  }
3061
3088
  }
3062
3089
  const extra = [];
@@ -3088,8 +3115,9 @@ function checkPass(cfg, catalogs, registry, fingerprints) {
3088
3115
  outdated: outdatedTranslations(cfg, shipped, fingerprints)
3089
3116
  };
3090
3117
  }
3118
+ // src/gate/report.ts
3091
3119
  function formatCheckResult(result, root) {
3092
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
3120
+ const show = (file) => root ? relativePath(root, file) : file;
3093
3121
  const lines = [];
3094
3122
  if (result.missing.length > 0) {
3095
3123
  lines.push("missing translations:");
@@ -3114,7 +3142,7 @@ function formatCheckResult(result, root) {
3114
3142
  return lines.join("\n");
3115
3143
  }
3116
3144
  function formatBuildReport(result, sourceLocale, root, cap = 5) {
3117
- const show = (file) => root ? relative(root, file).replaceAll("\\", "/") : file;
3145
+ const show = (file) => root ? relativePath(root, file) : file;
3118
3146
  const lines = [];
3119
3147
  const list = (entries, line) => {
3120
3148
  for (const entry of entries.slice(0, cap)) lines.push(` ${line(entry)}`);
@@ -3164,7 +3192,7 @@ function formatCheckWarnings(result, root, options = {}) {
3164
3192
  }
3165
3193
  function githubCheckAnnotations(result, registry, cfg, options = {}) {
3166
3194
  const messages = registry.messages();
3167
- const rel = (file) => escapeProperty(relative(cfg.root, file).replaceAll("\\", "/"));
3195
+ const rel = (file) => escapeProperty(relativePath(cfg.root, file));
3168
3196
  const at = (file, line) => `file=${rel(file)}${line ? `,line=${line}` : ""}`;
3169
3197
  const lines = [];
3170
3198
  const byKey = /* @__PURE__ */ new Map();
@@ -3225,148 +3253,6 @@ function escapeData(text) {
3225
3253
  function escapeProperty(text) {
3226
3254
  return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
3227
3255
  }
3228
- // src/scan/transform.ts
3229
- function quote(text, single) {
3230
- return single ? singleQuoted(text) : JSON.stringify(text);
3231
- }
3232
- function transformCode(code, file, analysis, options = {}) {
3233
- const own = analysis ?? analyzeFile(code, file);
3234
- if (!analysis && own.parseError) warnParseError(file, own.parseError);
3235
- const { tagged } = own;
3236
- const appAt = options.appImport && !own.appImported ? own.adapterImport : void 0;
3237
- if (tagged.length === 0 && appAt === void 0) return null;
3238
- const s = new MagicString(code);
3239
- if (appAt !== void 0) s.appendLeft(appAt, `import '${APP_ID}'; `);
3240
- for (const msg of tagged) {
3241
- const seen = /* @__PURE__ */ new Set();
3242
- const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));
3243
- const pairs = entries.map((p) => `${quote(p.name, msg.singleQuote)}: ${code.slice(p.start, p.end)}`).join(", ");
3244
- if (msg.jsx) {
3245
- const values = entries.length ? ` values={{ ${pairs} }}` : "";
3246
- const components = msg.jsx.components.length ? ` components={{ ${msg.jsx.components.map((c) => `${JSON.stringify(c.name)}: ${c.source}`).join(", ")} }}` : "";
3247
- const quoted = JSON.stringify(msg.key);
3248
- const id = quoted === `"${msg.key}"` ? quoted : `{${quoted}}`;
3249
- s.overwrite(msg.start, msg.end, `<${msg.jsx.name} id=${id}${values}${components} />`);
3250
- continue;
3251
- }
3252
- const tagSource = code.slice(msg.tagStart, msg.tagEnd);
3253
- const args = entries.length ? `, { ${pairs} }` : "";
3254
- s.overwrite(msg.start, msg.end, `${tagSource}(${quote(msg.key, msg.singleQuote)}${args})`);
3255
- }
3256
- return {
3257
- code: s.toString(),
3258
- map: s.generateMap({ hires: true })
3259
- };
3260
- }
3261
- // src/emit/plugin.ts
3262
- const RESOLVED_VIRTUAL_ID = "\0" + VIRTUAL_ID;
3263
- const LOCALE_MODULE_PREFIX = `${RESOLVED_VIRTUAL_ID}/locale/`;
3264
- const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
3265
- function resolveVirtualId(id) {
3266
- if (isAppModule(id)) return RESOLVED_VIRTUAL_ID;
3267
- if (id.startsWith("@verbaly/app/locale/")) return LOCALE_MODULE_PREFIX + id.slice(20);
3268
- if (id.startsWith(`virtual:verbaly/`)) return "\0" + id;
3269
- }
3270
- function clientModules(cfg, catalogs, options = {}) {
3271
- const client = clientCatalogs(cfg, catalogs);
3272
- return {
3273
- runtime: () => generateRuntimeModule(cfg, {
3274
- ...options,
3275
- icu: cfg.icu ?? needsIcu(client),
3276
- relative: cfg.relative ?? needsRelative(client),
3277
- inlineCatalog: cfg.render.inlineCatalog === true
3278
- }),
3279
- locale: (locale) => generateLocaleModule(own(client, locale) ?? {})
3280
- };
3281
- }
3282
- function loadVirtualModule(id, cfg, catalogs) {
3283
- if (id === RESOLVED_VIRTUAL_ID) return clientModules(cfg, catalogs).runtime();
3284
- if (id.startsWith(LOCALE_MODULE_PREFIX)) return clientModules(cfg, catalogs).locale(id.slice(LOCALE_MODULE_PREFIX.length));
3285
- }
3286
- function isTransformTarget(id) {
3287
- return SOURCE_FILE_RE.test(id) && !id.includes("node_modules") && !id.startsWith("\0");
3288
- }
3289
- function createSourceFilter(cfg) {
3290
- if (cfg.include.length === 0) return () => false;
3291
- const matches = picomatch(cfg.include, { ignore: cfg.exclude });
3292
- return (id) => {
3293
- const rel = relative(cfg.root, id).replaceAll("\\", "/");
3294
- return !rel.startsWith("..") && matches(rel);
3295
- };
3296
- }
3297
- function transformSource(code, id, registry, scan) {
3298
- const analysis = (scan && scannedAnalysis(scan, id, code)) ?? analyzeFile(code, id);
3299
- registry.update(id, analysis);
3300
- if (analysis.parseError) warnParseError(id, analysis.parseError);
3301
- const messages = emptyCatalog();
3302
- for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;
3303
- return {
3304
- messages,
3305
- result: transformCode(code, id, analysis, { appImport: true }) ?? null
3306
- };
3307
- }
3308
- function writeBuildTypes(cfg, catalogs) {
3309
- try {
3310
- writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
3311
- } catch (error) {
3312
- const code = error?.code;
3313
- if (typeof code !== "string") throw error;
3314
- warnOnce(`could not write the types to ${cfg.dts === false ? "" : relative(cfg.root, cfg.dts).replaceAll("\\", "/")} (${code}): run \`npx verbaly typegen\` where the project can be written`, `types:${cfg.root}`);
3315
- }
3316
- }
3317
- function runBuildGate(cfg, registry, failOnMissing) {
3318
- const catalogs = loadCatalogs(cfg);
3319
- for (const issue of auditBundle(cfg, catalogs, registry)) warnOnce(`${formatBundleIssue(issue)}\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);
3320
- const found = check(cfg, catalogs, registry, buildFingerprints(cfg));
3321
- if (failOnMissing === true && !gatePasses(found)) throw new Error(`[verbaly] build blocked\n${formatCheckResult(found, cfg.root)}\n${checkNextSteps(found, cliReachable(cfg.root))}`);
3322
- reportGate(cfg, found);
3323
- const warnings = warningCount(found);
3324
- if (warnings > 0) {
3325
- const once = onceMoved(cfg.root);
3326
- const read = once ? `\`npx verbaly check\` reads them${once}` : "run `npx verbaly check` to read them";
3327
- warnOnce(`check has ${counted(warnings, "warning")}, and the build still passes: ${read}`, "gate:warnings");
3328
- }
3329
- }
3330
- function onceMoved(root) {
3331
- const moved = pluginOnlyOptions(root);
3332
- if (!moved) return "";
3333
- return ` once ${moved} ${moved.includes(" and ") ? "move" : "moves"} to verbaly.config`;
3334
- }
3335
- const reported = /* @__PURE__ */ new Map();
3336
- function reportGate(cfg, found) {
3337
- const before = reported.get(cfg.root) ?? /* @__PURE__ */ new Set();
3338
- const now = /* @__PURE__ */ new Set();
3339
- const fresh = (entries, id) => entries.filter((entry) => {
3340
- const key = id(entry);
3341
- now.add(key);
3342
- return !before.has(key);
3343
- });
3344
- const report = {
3345
- broken: fresh(found.broken.filter((entry) => entry.severity === "error"), (entry) => `broken:${entry.locale}:${entry.key}:${entry.issue}`),
3346
- missing: fresh(found.missing, (entry) => `missing:${entry.locale}:${entry.key}`),
3347
- unknown: fresh(found.unknown, (entry) => `unknown:${entry.key}`),
3348
- collisions: fresh(found.collisions, (entry) => `collision:${entry.key}`)
3349
- };
3350
- reported.set(cfg.root, now);
3351
- const lines = formatBuildReport(report, cfg.sourceLocale, cfg.root);
3352
- if (lines.length === 0) return;
3353
- const steps = checkNextSteps({
3354
- ...found,
3355
- ...report
3356
- }, cliReachable(cfg.root));
3357
- const block = [
3358
- ...lines.map((line) => line.startsWith(" ") ? line : `[verbaly] ${line}`),
3359
- "[verbaly] to fix them:",
3360
- ...steps.split("\n").map((step) => ` ${step}`),
3361
- `[verbaly] \`npx verbaly check\` lists every one${onceMoved(cfg.root)}, and in your CI it stops a release on them`
3362
- ];
3363
- console.warn(block.join("\n"));
3364
- }
3365
- function buildFingerprints(cfg) {
3366
- const { state, problem } = readState(cfg);
3367
- if (problem) warnOnce(`${problem}, so outdated translations are not reported`, "gate:state");
3368
- return state.fingerprints;
3369
- }
3370
3256
  // src/scan/scope.ts
3371
3257
  const TAGGED_HINT = /(?<![\w$.])\$?t(?:\.id\s*\([^)]*\))?\s*`/;
3372
3258
  const NOT_SOURCE = [
@@ -3377,7 +3263,7 @@ const NOT_SOURCE = [
3377
3263
  "**/coverage/**"
3378
3264
  ];
3379
3265
  function relativeId(cfg, id) {
3380
- return relative(cfg.root, id).replaceAll("\\", "/");
3266
+ return relativePath(cfg.root, id);
3381
3267
  }
3382
3268
  function suggestedPattern(rel) {
3383
3269
  const slash = rel.indexOf("/");
@@ -3436,13 +3322,9 @@ async function filesOutsideInclude(cfg) {
3436
3322
  // src/gate/status.ts
3437
3323
  function status(cfg, catalogs, registry, drafts = emptyCatalog(), fingerprints = emptyCatalog()) {
3438
3324
  const extracted = registry.messages();
3439
- const flat = emptyCatalog();
3440
- for (const locale of cfg.locales) flat[locale] = flatView(catalogs[locale] ?? {});
3441
- const source = flat[cfg.sourceLocale] ?? {};
3325
+ const { flat, source, shipped, sourceText } = gateViews(cfg, catalogs, registry);
3442
3326
  const needed = /* @__PURE__ */ new Set([...extracted.keys(), ...Object.keys(source)]);
3443
3327
  const live = effectiveDrafts(drafts, flat);
3444
- const shipped = shippedCatalogs(cfg, flat, registry);
3445
- const sourceText = shipped[cfg.sourceLocale];
3446
3328
  const outdated = outdatedTranslations(cfg, shipped, fingerprints);
3447
3329
  const locales = [];
3448
3330
  for (const locale of cfg.locales) {
@@ -3453,8 +3335,7 @@ function status(cfg, catalogs, registry, drafts = emptyCatalog(), fingerprints =
3453
3335
  let broken = 0;
3454
3336
  for (const [key, text] of Object.entries(catalog)) {
3455
3337
  if (!text) continue;
3456
- const from = sourceText[key];
3457
- if ([...validateMessage(text, locale), ...from ? validatePair(from, text) : []].some((issue) => issue.severity === "error")) broken += 1;
3338
+ if (translationIssues(locale, text, sourceText[key]).some((issue) => issue.severity === "error")) broken += 1;
3458
3339
  }
3459
3340
  locales.push({
3460
3341
  locale,
@@ -3562,7 +3443,7 @@ async function checkCommand(cfg, values) {
3562
3443
  }
3563
3444
  const registry = await extractProject(cfg);
3564
3445
  const catalogs = loadCatalogs(cfg);
3565
- const state = checkState(cfg, values.drafts === true || values.outdated === true);
3446
+ const state = checkState$1(cfg, values.drafts === true || values.outdated === true);
3566
3447
  const result = check(cfg, catalogs, registry, state.fingerprints);
3567
3448
  const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};
3568
3449
  const outdated = values.outdated ? result.outdated : [];
@@ -3588,7 +3469,7 @@ async function checkCommand(cfg, values) {
3588
3469
  }
3589
3470
  process.exitCode = 1;
3590
3471
  }
3591
- function checkState(cfg, gating) {
3472
+ function checkState$1(cfg, gating) {
3592
3473
  if (gating) return loadState(cfg);
3593
3474
  const { state, problem } = readState(cfg);
3594
3475
  if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);
@@ -3666,31 +3547,63 @@ function formatDoctorHealth(result) {
3666
3547
  const warnings = result.entries.filter((entry) => entry.level === "warn").length;
3667
3548
  return warnings > 0 ? `setup works, with ${counted(warnings, "warning")} to read` : "setup looks healthy";
3668
3549
  }
3669
- async function doctor(cfg) {
3550
+ function createReport(cfg) {
3670
3551
  const entries = [];
3671
- const ok = (name, message) => entries.push({
3672
- level: "ok",
3673
- check: name,
3674
- message
3675
- });
3676
- const warn = (name, message, fix) => entries.push({
3677
- level: "warn",
3678
- check: name,
3679
- message,
3680
- fix
3681
- });
3682
- const error = (name, message, fix) => entries.push({
3683
- level: "error",
3684
- check: name,
3685
- message,
3686
- fix
3687
- });
3688
- const rel = (path) => relative(cfg.root, path).replaceAll("\\", "/");
3552
+ return {
3553
+ entries,
3554
+ ok: (name, message) => void entries.push({
3555
+ level: "ok",
3556
+ check: name,
3557
+ message
3558
+ }),
3559
+ warn: (name, message, fix) => void entries.push({
3560
+ level: "warn",
3561
+ check: name,
3562
+ message,
3563
+ fix
3564
+ }),
3565
+ error: (name, message, fix) => void entries.push({
3566
+ level: "error",
3567
+ check: name,
3568
+ message,
3569
+ fix
3570
+ }),
3571
+ rel: (path) => relativePath(cfg.root, path)
3572
+ };
3573
+ }
3574
+ async function doctor(cfg) {
3575
+ const report = createReport(cfg);
3576
+ const { ok } = report;
3577
+ const configFile = checkSetup(report, cfg);
3578
+ const { catalogs, catalogsHealthy, source } = checkCatalogs(report, cfg);
3579
+ checkRouting(report, cfg, configFile);
3580
+ const host = checkPlugin(report, cfg);
3581
+ const scanning = cfg.include.length > 0;
3582
+ if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
3583
+ const registry = await extractProject(cfg);
3584
+ const messages = registry.messages();
3585
+ if (source && scanning) checkTypes(report, cfg, host, catalogs, registry, source);
3586
+ if (scanning) await checkSources(report, cfg, registry, messages);
3587
+ if (source && scanning) checkOrphans(report, source, registry, messages);
3588
+ if (catalogsHealthy) checkBundle(report, cfg, catalogs, registry);
3589
+ const state = checkState(report, cfg, catalogs, catalogsHealthy);
3590
+ if (catalogsHealthy) mirrorGate(report, cfg, catalogs, registry, state, scanning);
3591
+ return {
3592
+ ok: report.entries.every((entry) => entry.level !== "error"),
3593
+ entries: report.entries
3594
+ };
3595
+ }
3596
+ function checkSetup(report, cfg) {
3597
+ const { ok, warn } = report;
3689
3598
  const configFile = findConfigFile(cfg.root);
3690
3599
  if (configFile) ok("config", `${configFile} found`);
3691
3600
  else warn("config", "no config file, running on defaults", "run `npx verbaly init`");
3692
3601
  if (cliReachable(cfg.root)) ok("cli", "the verbaly command is available in this project");
3693
3602
  else warn("cli", "the verbaly command is not linked in node_modules/.bin", CLI_INSTALL_FIX);
3603
+ return configFile;
3604
+ }
3605
+ function checkCatalogs(report, cfg) {
3606
+ const { ok, warn, error, rel } = report;
3694
3607
  const catalogs = emptyCatalog();
3695
3608
  let catalogsHealthy = true;
3696
3609
  if (!existsSync(cfg.dir)) {
@@ -3734,7 +3647,15 @@ async function doctor(cfg) {
3734
3647
  }
3735
3648
  const source = catalogs[cfg.sourceLocale];
3736
3649
  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`");
3737
- const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
3650
+ return {
3651
+ catalogs,
3652
+ catalogsHealthy,
3653
+ source
3654
+ };
3655
+ }
3656
+ function checkRouting(report, cfg, configFile) {
3657
+ const { ok, warn } = report;
3658
+ const mirrors = Object.keys(cfg.render).length > 0;
3738
3659
  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");
3739
3660
  else if (cfg.routing === "prefix-all" && mirrors) warn("routing", `routing is "prefix-all" but render keeps ${cfg.sourceLocale} at the root, so its links point at a /${cfg.sourceLocale}/ tree nobody wrote`, "set routing to \"prefix-except-source\", the url tree render writes");
3740
3661
  else {
@@ -3749,77 +3670,86 @@ async function doctor(cfg) {
3749
3670
  ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
3750
3671
  }
3751
3672
  }
3673
+ }
3674
+ function checkPlugin(report, cfg) {
3675
+ const { ok, warn } = report;
3752
3676
  const deps = readDependencies(cfg.root);
3753
3677
  const host = detectHost(cfg.root);
3754
3678
  const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
3755
3679
  if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
3756
3680
  else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
3757
3681
  else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
3758
- const scanning = cfg.include.length > 0;
3759
- if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
3760
- const registry = await extractProject(cfg);
3761
- if (source && scanning && cfg.dts !== false) {
3762
- const dtsPath = cfg.dts;
3763
- const shown = rel(dtsPath);
3764
- const regenerate = host?.name === "astro" ? "run `npx astro sync`, which writes the types and links them" : host?.name === "nuxt" ? "run `npx nuxi prepare`, which writes the types and links them" : "run `npx verbaly typegen`";
3765
- const expected = generateDts(shippedCatalogs(cfg, catalogs, registry)[cfg.sourceLocale] ?? source, projectDtsOptions(cfg));
3766
- if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
3767
- else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
3768
- else ok("types", `${shown} is up to date`);
3769
- if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
3770
- const state = typesIncluded(cfg.root, dtsPath);
3771
- if (state === "missing" || state === "unreadable") warn("types", state === "missing" ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types` : `tsconfig.json could not be read, so it may not include ${shown}`, `run \`npx verbaly typegen\`, which adds the line, or add "${shown}" to include`);
3772
- }
3773
- const old = join(cfg.root, "verbaly.d.ts");
3774
- if (dtsPath !== old && existsSync(old) && readFileSync(old, "utf8").startsWith("// generated by verbaly: do not edit")) warn("types", `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`, "run `npx verbaly typegen`, which removes it");
3775
- }
3776
- if (scanning) {
3777
- const unreadable = registry.parseErrors();
3778
- if (unreadable.length > 0) {
3779
- const first = unreadable[0];
3780
- 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");
3781
- }
3782
- const outside = await filesOutsideInclude(cfg);
3783
- if (outside.length > 0) {
3784
- const files = outside.map((entry) => rel(entry.file));
3785
- const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
3786
- warn("sources", `t\`…\` is written in ${counted(outside.length, "file")} outside include, and those texts are never extracted or translated (${preview(files)})`, `add ${patterns.join(" and ")} to include in your verbaly config, or the files to exclude if they are not app code`);
3787
- }
3788
- const stray = registry.strayImports();
3789
- if (stray.length > 0) {
3790
- const files = [...new Set(stray.map((entry) => rel(entry.file)))];
3791
- 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 verbaly/app");
3792
- }
3793
- const missed = registry.missed();
3794
- if (missed.length > 0) {
3795
- const first = missed[0];
3796
- warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
3797
- }
3798
- const positional = [...registry.messages().values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
3799
- if (positional.length > 0) {
3800
- const first = positional[0];
3801
- warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
3802
- }
3803
- const escaped = [...registry.messages().values()].map((msg) => ({
3804
- file: rel(msg.file),
3805
- slice: escapedSyntax(msg.message)
3806
- })).filter((entry) => entry.slice !== void 0);
3807
- if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${shownSlice(escaped[0].slice)})`, `in a tagged template, write ${inlineBlock(escaped[0].slice)}`);
3808
- }
3809
- if (source && scanning) {
3810
- const extracted = registry.messages();
3811
- const used = registry.usedKeys();
3812
- const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
3813
- const unread = registry.parseErrors().length > 0;
3814
- if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
3815
- else ok("orphans", "no orphan keys");
3682
+ return host;
3683
+ }
3684
+ function checkTypes(report, cfg, host, catalogs, registry, source) {
3685
+ const { ok, warn, rel } = report;
3686
+ if (cfg.dts === false) return;
3687
+ const dtsPath = cfg.dts;
3688
+ const shown = rel(dtsPath);
3689
+ const regenerate = host?.name === "astro" ? "run `npx astro sync`, which writes the types and links them" : host?.name === "nuxt" ? "run `npx nuxi prepare`, which writes the types and links them" : "run `npx verbaly typegen`";
3690
+ const expected = generateDts(shippedCatalogs(cfg, catalogs, registry)[cfg.sourceLocale] ?? source, projectDtsOptions(cfg));
3691
+ if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
3692
+ else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
3693
+ else ok("types", `${shown} is up to date`);
3694
+ if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
3695
+ const state = typesIncluded(cfg.root, dtsPath);
3696
+ if (state === "missing" || state === "unreadable") warn("types", state === "missing" ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types` : `tsconfig.json could not be read, so it may not include ${shown}`, `run \`npx verbaly typegen\`, which adds the line, or add "${shown}" to include`);
3816
3697
  }
3698
+ const old = join(cfg.root, "verbaly.d.ts");
3699
+ if (dtsPath !== old && existsSync(old) && readFileSync(old, "utf8").startsWith("// generated by verbaly: do not edit")) warn("types", `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`, "run `npx verbaly typegen`, which removes it");
3700
+ }
3701
+ async function checkSources(report, cfg, registry, messages) {
3702
+ const { warn, error, rel } = report;
3703
+ const unreadable = registry.parseErrors();
3704
+ if (unreadable.length > 0) {
3705
+ const first = unreadable[0];
3706
+ 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");
3707
+ }
3708
+ const outside = await filesOutsideInclude(cfg);
3709
+ if (outside.length > 0) {
3710
+ const files = outside.map((entry) => rel(entry.file));
3711
+ const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
3712
+ warn("sources", `t\`…\` is written in ${counted(outside.length, "file")} outside include, and those texts are never extracted or translated (${preview(files)})`, `add ${patterns.join(" and ")} to include in your verbaly config, or the files to exclude if they are not app code`);
3713
+ }
3714
+ const stray = registry.strayImports();
3715
+ if (stray.length > 0) {
3716
+ const files = [...new Set(stray.map((entry) => rel(entry.file)))];
3717
+ 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 verbaly/app");
3718
+ }
3719
+ const missed = registry.missed();
3720
+ if (missed.length > 0) {
3721
+ const first = missed[0];
3722
+ warn("sources", `a t under another name keeps ${counted(missed.length, "text")} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\`…\`)`, "name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog");
3723
+ }
3724
+ const positional = [...messages.values()].filter((msg) => msg.params.some((param) => /^_\d+$/.test(param.name)));
3725
+ if (positional.length > 0) {
3726
+ const first = positional[0];
3727
+ warn("messages", `a translator gets a nameless value like {_0} in ${counted(positional.length, "message")} (${sourcePlace(first, cfg.root)}: "${first.message}")`, "put the value in a named variable first (const date = formatDate(d)), so the message says {date}");
3728
+ }
3729
+ const escaped = [...messages.values()].map((msg) => ({
3730
+ file: rel(msg.file),
3731
+ slice: escapedSyntax(msg.message)
3732
+ })).filter((entry) => entry.slice !== void 0);
3733
+ if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${shownSlice(escaped[0].slice)})`, `in a tagged template, write ${inlineBlock(escaped[0].slice)}`);
3734
+ }
3735
+ function checkOrphans(report, source, registry, extracted) {
3736
+ const { ok, warn } = report;
3737
+ const used = registry.usedKeys();
3738
+ const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
3739
+ const unread = registry.parseErrors().length > 0;
3740
+ if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
3741
+ else ok("orphans", "no orphan keys");
3742
+ }
3743
+ function checkBundle(report, cfg, catalogs, registry) {
3744
+ const { ok, warn } = report;
3817
3745
  const excluded = cfg.bundle.exclude ?? [];
3818
- if (excluded.length > 0 && catalogsHealthy) {
3819
- const issues = auditBundle(cfg, catalogs, registry);
3820
- for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
3821
- if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
3822
- }
3746
+ if (excluded.length === 0) return;
3747
+ const issues = auditBundle(cfg, catalogs, registry);
3748
+ for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
3749
+ if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
3750
+ }
3751
+ function checkState(report, cfg, catalogs, catalogsHealthy) {
3752
+ const { warn } = report;
3823
3753
  const { state, problem, conflict } = readState(cfg);
3824
3754
  if (problem) warn("state", problem, conflict ? "resolve it by hand, keeping the entries of both sides: taking one side approves the drafts of the other" : `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
3825
3755
  else if (conflict) warn("state", `${STATE_FILE} has a merge conflict, and both sides were read`, "run `npx verbaly extract`, which writes both sides into it, then commit it");
@@ -3830,42 +3760,40 @@ async function doctor(cfg) {
3830
3760
  });
3831
3761
  if (stale.length > 0) warn("drafts", `${STATE_FILE} lists ${counted(stale.length, "draft")} whose translation is gone (${preview(stale)})`, "run `npx verbaly extract`, which drops them");
3832
3762
  }
3833
- if (catalogsHealthy) {
3834
- const result = check(cfg, catalogs, registry, state.fingerprints);
3835
- 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)");
3836
- if (result.missing.length > 0) {
3837
- const locales = [...new Set(result.missing.map((m) => m.locale))];
3838
- warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
3839
- }
3840
- const broken = result.broken.filter((entry) => entry.severity === "error");
3841
- if (broken.length > 0) {
3842
- const locales = [...new Set(broken.map((b) => b.locale))];
3843
- 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");
3844
- }
3845
- if (result.extra.length > 0) {
3846
- const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);
3847
- warn("extras", `a translation has ${counted(result.extra.length, "key")} the source catalog does not (${preview(shown)})`, scanning ? "add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest" : "add them to the source catalog if your code uses them, or delete them from the translations");
3848
- }
3849
- const warnings = result.broken.filter((entry) => entry.severity === "warning");
3850
- 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");
3851
- if (result.collisions.length > 0) {
3852
- const first = result.collisions[0];
3853
- error("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
3854
- }
3855
- if (result.divergent.length > 0) {
3856
- const first = result.divergent[0];
3857
- warn("source texts", `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, "text")}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`, "edit those texts in the code; `npx verbaly extract` writes them into the catalog");
3858
- }
3859
- if (result.outdated.length > 0) {
3860
- const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
3861
- warn("outdated", `${counted(result.outdated.length, "translation")} written for an older source text (${preview(shown)})`, "update them, or keep them with `npx verbaly review --approve`");
3862
- }
3863
- if (result.ok) ok("translations", "all translations complete");
3763
+ return state;
3764
+ }
3765
+ function mirrorGate(report, cfg, catalogs, registry, state, scanning) {
3766
+ const { ok, warn, error } = report;
3767
+ const result = check(cfg, catalogs, registry, state.fingerprints);
3768
+ 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)");
3769
+ if (result.missing.length > 0) {
3770
+ const locales = [...new Set(result.missing.map((m) => m.locale))];
3771
+ warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
3864
3772
  }
3865
- return {
3866
- ok: entries.every((entry) => entry.level !== "error"),
3867
- entries
3868
- };
3773
+ const broken = result.broken.filter((entry) => entry.severity === "error");
3774
+ if (broken.length > 0) {
3775
+ const locales = [...new Set(broken.map((b) => b.locale))];
3776
+ 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");
3777
+ }
3778
+ if (result.extra.length > 0) {
3779
+ const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);
3780
+ warn("extras", `a translation has ${counted(result.extra.length, "key")} the source catalog does not (${preview(shown)})`, scanning ? "add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest" : "add them to the source catalog if your code uses them, or delete them from the translations");
3781
+ }
3782
+ const warnings = result.broken.filter((entry) => entry.severity === "warning");
3783
+ 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");
3784
+ if (result.collisions.length > 0) {
3785
+ const first = result.collisions[0];
3786
+ error("keys", `${counted(result.collisions.length, "key")} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(", ")})`, "give each text its own key (`npx verbaly check` lists every place)");
3787
+ }
3788
+ if (result.divergent.length > 0) {
3789
+ const first = result.divergent[0];
3790
+ warn("source texts", `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, "text")}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`, "edit those texts in the code; `npx verbaly extract` writes them into the catalog");
3791
+ }
3792
+ if (result.outdated.length > 0) {
3793
+ const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);
3794
+ warn("outdated", `${counted(result.outdated.length, "translation")} written for an older source text (${preview(shown)})`, "update them, or keep them with `npx verbaly review --approve`");
3795
+ }
3796
+ if (result.ok) ok("translations", "all translations complete");
3869
3797
  }
3870
3798
  function preview(keys) {
3871
3799
  const head = keys.slice(0, PREVIEW).join(", ");
@@ -3887,42 +3815,245 @@ async function doctorCommand(cfg) {
3887
3815
  process.exitCode = 1;
3888
3816
  }
3889
3817
  }
3890
- // src/util/markup.ts
3891
- const NAME$1 = `[^\\s=/"'<>]+`;
3892
- const ATTRIBUTE = new RegExp(`(${NAME$1})(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`, "g");
3893
- const ATTRIBUTE_NAME = new RegExp(`^${NAME$1}$`);
3894
- const TAG_REST = `(?:"[^"]*"|'[^']*'|[^"'>])*`;
3895
- function isAttributeName(name) {
3896
- return ATTRIBUTE_NAME.test(name);
3818
+ // src/exchange/mobile.ts
3819
+ function androidValuesDir(locale, sourceLocale) {
3820
+ if (locale === sourceLocale) return "values";
3821
+ const parts = locale.split("-");
3822
+ if (parts.length === 1) return `values-${locale}`;
3823
+ if (parts.length === 2 && /^[a-zA-Z]{2}$/.test(parts[1])) return `values-${parts[0]}-r${parts[1].toUpperCase()}`;
3824
+ return `values-b+${parts.join("+")}`;
3897
3825
  }
3898
- function readAttributes(chunk, lowerCase = false) {
3899
- const attributes = /* @__PURE__ */ new Map();
3900
- ATTRIBUTE.lastIndex = 0;
3901
- let match;
3902
- while ((match = ATTRIBUTE.exec(chunk)) !== null) {
3903
- const name = lowerCase ? match[1].toLowerCase() : match[1];
3904
- if (attributes.has(name)) continue;
3905
- const quoted = match[2] ?? match[3];
3906
- const value = quoted ?? match[4] ?? "";
3907
- const end = match.index + match[0].length;
3908
- const written = quoted !== void 0 ? value.length + 2 : value.length;
3909
- attributes.set(name, {
3910
- value,
3911
- start: end - written,
3912
- end
3913
- });
3914
- }
3915
- return attributes;
3826
+ function toAndroidXml(entries) {
3827
+ const names = /* @__PURE__ */ new Map();
3828
+ return [
3829
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
3830
+ "<resources>",
3831
+ ...entries.map(({ key, text }) => {
3832
+ const name = androidName(key);
3833
+ const clash = names.get(name);
3834
+ if (clash !== void 0) throw new Error(`[verbaly] android-xml: keys "${clash}" and "${key}" both become resource name "${name}", rename one of them`);
3835
+ names.set(name, key);
3836
+ return ` <string name="${name}">${androidText(text)}</string>`;
3837
+ }),
3838
+ "</resources>",
3839
+ ""
3840
+ ].join("\n");
3916
3841
  }
3917
- const ENTITY = /&(?:(lt|gt|amp|quot|apos)|#(\d+)|#[xX]([0-9a-fA-F]+));/g;
3918
- const NAMED = {
3919
- lt: "<",
3920
- gt: ">",
3921
- amp: "&",
3922
- quot: "\"",
3923
- apos: "'"
3924
- };
3925
- function decodeEntities(text) {
3842
+ function toIosStrings(entries) {
3843
+ return [...entries.map(({ key, text }) => `"${iosText(key)}" = "${iosText(text)}";`), ""].join("\n");
3844
+ }
3845
+ function androidName(key) {
3846
+ const name = key.replace(/[^A-Za-z0-9_]/g, "_");
3847
+ return /^[0-9]/.test(name) ? `_${name}` : name;
3848
+ }
3849
+ function androidText(text) {
3850
+ const escaped = text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3851
+ return /^[@?]/.test(escaped) ? `\\${escaped}` : escaped;
3852
+ }
3853
+ function iosText(text) {
3854
+ return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
3855
+ }
3856
+ // src/exchange/csv.ts
3857
+ function toCsv(entries) {
3858
+ return [
3859
+ "key,source,target,location",
3860
+ ...entries.map(({ key, source, target, location }) => `${csvField(key)},${csvField(source)},${csvField(target)},${csvField(location?.join("; ") ?? "")}`),
3861
+ ""
3862
+ ].join("\r\n");
3863
+ }
3864
+ function csvField(text) {
3865
+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
3866
+ }
3867
+ function parseCsv(content) {
3868
+ const rows = csvRows(content, csvSeparator(content));
3869
+ const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
3870
+ const keyCol = header.indexOf("key");
3871
+ const targetCol = header.indexOf("target");
3872
+ const sourceCol = header.indexOf("source");
3873
+ if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns");
3874
+ const entries = emptyCatalog();
3875
+ const sources = emptyCatalog();
3876
+ for (const row of rows.slice(1)) {
3877
+ const key = row[keyCol];
3878
+ if (!key) continue;
3879
+ entries[key] = row[targetCol] ?? "";
3880
+ const source = sourceCol === -1 ? void 0 : row[sourceCol];
3881
+ if (source) sources[key] = source;
3882
+ }
3883
+ return {
3884
+ entries,
3885
+ sources
3886
+ };
3887
+ }
3888
+ function csvSeparator(content) {
3889
+ let quoted = false;
3890
+ const seen = /* @__PURE__ */ new Set();
3891
+ for (const char of content) if (char === "\"") quoted = !quoted;
3892
+ else if (!quoted && (char === "\n" || char === "\r")) break;
3893
+ else if (!quoted) seen.add(char);
3894
+ return seen.has(",") ? "," : seen.has(";") ? ";" : seen.has(" ") ? " " : ",";
3895
+ }
3896
+ function csvRows(content, separator) {
3897
+ const rows = [];
3898
+ let row = [];
3899
+ let field = "";
3900
+ let quoted = false;
3901
+ for (let i = 0; i < content.length; i++) {
3902
+ const char = content[i];
3903
+ if (quoted) {
3904
+ if (char === "\"") {
3905
+ if (content[i + 1] === "\"") {
3906
+ field += "\"";
3907
+ i++;
3908
+ } else quoted = false;
3909
+ } else field += char;
3910
+ } else if (char === "\"") quoted = true;
3911
+ else if (char === separator) {
3912
+ row.push(field);
3913
+ field = "";
3914
+ } else if (char === "\n" || char === "\r") {
3915
+ if (char === "\r" && content[i + 1] === "\n") i++;
3916
+ row.push(field);
3917
+ field = "";
3918
+ if (row.some((cell) => cell !== "")) rows.push(row);
3919
+ row = [];
3920
+ } else field += char;
3921
+ }
3922
+ row.push(field);
3923
+ if (row.some((cell) => cell !== "")) rows.push(row);
3924
+ return rows;
3925
+ }
3926
+ // src/exchange/po.ts
3927
+ function toPo(sourceLocale, locale, entries) {
3928
+ return [
3929
+ [
3930
+ "msgid \"\"",
3931
+ "msgstr \"\"",
3932
+ `${poString("Project-Id-Version: verbaly\n")}`,
3933
+ `${poString("MIME-Version: 1.0\n")}`,
3934
+ `${poString("Content-Type: text/plain; charset=UTF-8\n")}`,
3935
+ `${poString("Content-Transfer-Encoding: 8bit\n")}`,
3936
+ `${poString(`Language: ${locale}\n`)}`,
3937
+ `${poString(`X-Source-Language: ${sourceLocale}\n`)}`
3938
+ ].join("\n"),
3939
+ ...entries.map(({ key, source, target, location }) => [
3940
+ ...location?.length ? [`#: ${location.join(" ")}`] : [],
3941
+ `msgctxt ${poString(key)}`,
3942
+ `msgid ${poString(source)}`,
3943
+ `msgstr ${poString(target)}`
3944
+ ].join("\n")),
3945
+ ""
3946
+ ].join("\n\n");
3947
+ }
3948
+ function parsePo(content) {
3949
+ const entries = emptyCatalog();
3950
+ const sources = emptyCatalog();
3951
+ let locale;
3952
+ let msgctxt;
3953
+ let msgid;
3954
+ let msgstr;
3955
+ let fuzzy = false;
3956
+ let field;
3957
+ const finish = () => {
3958
+ if (msgid === "" && msgctxt === void 0) {
3959
+ const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
3960
+ if (lang) locale = lang;
3961
+ } else if (msgctxt !== void 0 && msgid !== void 0) {
3962
+ entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
3963
+ sources[msgctxt] = msgid;
3964
+ }
3965
+ msgctxt = msgid = msgstr = field = void 0;
3966
+ fuzzy = false;
3967
+ };
3968
+ for (const raw of stripBom(content).split(/\r\n|[\r\n]/)) {
3969
+ const line = raw.trim();
3970
+ if (line === "") {
3971
+ finish();
3972
+ continue;
3973
+ }
3974
+ if (line.startsWith("#")) {
3975
+ if (/^#,.*\bfuzzy\b/.test(line)) fuzzy = true;
3976
+ continue;
3977
+ }
3978
+ const keyword = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/.exec(line);
3979
+ if (keyword) {
3980
+ const [, name, rest] = keyword;
3981
+ const value = poUnquote(rest);
3982
+ if (value === void 0) continue;
3983
+ if (name === "msgctxt") {
3984
+ msgctxt = value;
3985
+ field = "msgctxt";
3986
+ } else if (name === "msgid") {
3987
+ msgid = value;
3988
+ field = "msgid";
3989
+ } else if (name === "msgstr" || name === "msgstr[0]") {
3990
+ msgstr = value;
3991
+ field = "msgstr";
3992
+ } else field = "other";
3993
+ continue;
3994
+ }
3995
+ const continuation = poUnquote(line);
3996
+ if (continuation === void 0 || field === void 0 || field === "other") continue;
3997
+ if (field === "msgctxt") msgctxt = (msgctxt ?? "") + continuation;
3998
+ else if (field === "msgid") msgid = (msgid ?? "") + continuation;
3999
+ else msgstr = (msgstr ?? "") + continuation;
4000
+ }
4001
+ finish();
4002
+ return {
4003
+ locale,
4004
+ entries,
4005
+ sources
4006
+ };
4007
+ }
4008
+ function poString(text) {
4009
+ return `"${text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r")}"`;
4010
+ }
4011
+ function poUnquote(text) {
4012
+ const match = /^"((?:[^"\\]|\\.)*)"$/.exec(text);
4013
+ if (!match) return void 0;
4014
+ return match[1].replace(/\\(.)/g, (_, ch) => {
4015
+ if (ch === "n") return "\n";
4016
+ if (ch === "t") return " ";
4017
+ if (ch === "r") return "\r";
4018
+ return ch;
4019
+ });
4020
+ }
4021
+ // src/util/markup.ts
4022
+ const NAME$1 = `[^\\s=/"'<>]+`;
4023
+ const ATTRIBUTE = new RegExp(`(${NAME$1})(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?`, "g");
4024
+ const ATTRIBUTE_NAME = new RegExp(`^${NAME$1}$`);
4025
+ const TAG_REST = `(?:"[^"]*"|'[^']*'|[^"'>])*`;
4026
+ function isAttributeName(name) {
4027
+ return ATTRIBUTE_NAME.test(name);
4028
+ }
4029
+ function readAttributes(chunk, lowerCase = false) {
4030
+ const attributes = /* @__PURE__ */ new Map();
4031
+ ATTRIBUTE.lastIndex = 0;
4032
+ let match;
4033
+ while ((match = ATTRIBUTE.exec(chunk)) !== null) {
4034
+ const name = lowerCase ? match[1].toLowerCase() : match[1];
4035
+ if (attributes.has(name)) continue;
4036
+ const quoted = match[2] ?? match[3];
4037
+ const value = quoted ?? match[4] ?? "";
4038
+ const end = match.index + match[0].length;
4039
+ const written = quoted !== void 0 ? value.length + 2 : value.length;
4040
+ attributes.set(name, {
4041
+ value,
4042
+ start: end - written,
4043
+ end
4044
+ });
4045
+ }
4046
+ return attributes;
4047
+ }
4048
+ const ENTITY = /&(?:(lt|gt|amp|quot|apos)|#(\d+)|#[xX]([0-9a-fA-F]+));/g;
4049
+ const NAMED = {
4050
+ lt: "<",
4051
+ gt: ">",
4052
+ amp: "&",
4053
+ quot: "\"",
4054
+ apos: "'"
4055
+ };
4056
+ function decodeEntities(text) {
3926
4057
  return text.replace(ENTITY, (whole, name, decimal, hex) => {
3927
4058
  if (name) return NAMED[name];
3928
4059
  const code = decimal ? parseInt(decimal, 10) : parseInt(hex, 16);
@@ -4159,138 +4290,59 @@ function attr(attrs, name) {
4159
4290
  const value = attrs.get(name)?.value;
4160
4291
  return value === void 0 ? void 0 : decodeEntities(value);
4161
4292
  }
4162
- // src/exchange/mobile.ts
4163
- function androidValuesDir(locale, sourceLocale) {
4164
- if (locale === sourceLocale) return "values";
4165
- const parts = locale.split("-");
4166
- if (parts.length === 1) return `values-${locale}`;
4167
- if (parts.length === 2 && /^[a-zA-Z]{2}$/.test(parts[1])) return `values-${parts[0]}-r${parts[1].toUpperCase()}`;
4168
- return `values-b+${parts.join("+")}`;
4169
- }
4170
- function toAndroidXml(entries) {
4171
- const names = /* @__PURE__ */ new Map();
4293
+ // src/exchange/xliff.ts
4294
+ function toXliff(sourceLocale, locale, entries) {
4295
+ const units = entries.map(({ key, source, target, location }) => [
4296
+ ` <unit id="${escapeXml(key)}">`,
4297
+ ...location?.length ? [
4298
+ " <notes>",
4299
+ ...location.map((file) => ` <note category="location">${escapeXml(file)}</note>`),
4300
+ " </notes>"
4301
+ ] : [],
4302
+ ` <segment state="${target ? "translated" : "initial"}">`,
4303
+ ` <source>${messageToInline(source)}</source>`,
4304
+ ` <target>${messageToInline(target)}</target>`,
4305
+ " </segment>",
4306
+ " </unit>"
4307
+ ].join("\n")).join("\n");
4172
4308
  return [
4173
4309
  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
4174
- "<resources>",
4175
- ...entries.map(({ key, text }) => {
4176
- const name = androidName(key);
4177
- const clash = names.get(name);
4178
- if (clash !== void 0) throw new Error(`[verbaly] android-xml: keys "${clash}" and "${key}" both become resource name "${name}", rename one of them.`);
4179
- names.set(name, key);
4180
- return ` <string name="${name}">${androidText(text)}</string>`;
4181
- }),
4182
- "</resources>",
4310
+ `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
4311
+ ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
4312
+ units,
4313
+ " </file>",
4314
+ "</xliff>",
4183
4315
  ""
4184
4316
  ].join("\n");
4185
4317
  }
4186
- function toIosStrings(entries) {
4187
- return [...entries.map(({ key, text }) => `"${iosText(key)}" = "${iosText(text)}";`), ""].join("\n");
4188
- }
4189
- function androidName(key) {
4190
- const name = key.replace(/[^A-Za-z0-9_]/g, "_");
4191
- return /^[0-9]/.test(name) ? `_${name}` : name;
4192
- }
4193
- function androidText(text) {
4194
- const escaped = text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
4195
- return /^[@?]/.test(escaped) ? `\\${escaped}` : escaped;
4196
- }
4197
- function iosText(text) {
4198
- return text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
4199
- }
4200
- // src/exchange/po.ts
4201
- function toPo(sourceLocale, locale, entries) {
4202
- return [
4203
- [
4204
- "msgid \"\"",
4205
- "msgstr \"\"",
4206
- `${poString("Project-Id-Version: verbaly\n")}`,
4207
- `${poString("MIME-Version: 1.0\n")}`,
4208
- `${poString("Content-Type: text/plain; charset=UTF-8\n")}`,
4209
- `${poString("Content-Transfer-Encoding: 8bit\n")}`,
4210
- `${poString(`Language: ${locale}\n`)}`,
4211
- `${poString(`X-Source-Language: ${sourceLocale}\n`)}`
4212
- ].join("\n"),
4213
- ...entries.map(({ key, source, target, location }) => [
4214
- ...location?.length ? [`#: ${location.join(" ")}`] : [],
4215
- `msgctxt ${poString(key)}`,
4216
- `msgid ${poString(source)}`,
4217
- `msgstr ${poString(target)}`
4218
- ].join("\n")),
4219
- ""
4220
- ].join("\n\n");
4318
+ const UNIT = `<(?:trans-)?unit\\b(${TAG_REST})>([\\s\\S]*?)</(?:trans-)?unit>`;
4319
+ const TARGET = new RegExp(`<target\\b${TAG_REST}>([\\s\\S]*?)</target>`);
4320
+ const SOURCE = new RegExp(`<source\\b${TAG_REST}>([\\s\\S]*?)</source>`);
4321
+ function tagAttribute(content, tag, name) {
4322
+ const open = new RegExp(`<${tag}\\b(${TAG_REST})>`).exec(content);
4323
+ return open && readAttributes(open[1]).get(name)?.value || void 0;
4221
4324
  }
4222
- function parsePo(content) {
4223
- const entries = Object.create(null);
4224
- const sources = Object.create(null);
4225
- let locale;
4226
- let msgctxt;
4227
- let msgid;
4228
- let msgstr;
4229
- let fuzzy = false;
4230
- let field;
4231
- const finish = () => {
4232
- if (msgid === "" && msgctxt === void 0) {
4233
- const lang = /^Language:[ \t]*(.+?)[ \t]*$/m.exec(msgstr ?? "")?.[1];
4234
- if (lang) locale = lang;
4235
- } else if (msgctxt !== void 0 && msgid !== void 0) {
4236
- entries[msgctxt] = fuzzy ? "" : msgstr ?? "";
4237
- sources[msgctxt] = msgid;
4238
- }
4239
- msgctxt = msgid = msgstr = field = void 0;
4240
- fuzzy = false;
4241
- };
4242
- for (const raw of content.replace(/^\uFEFF/, "").split(/\r\n|[\r\n]/)) {
4243
- const line = raw.trim();
4244
- if (line === "") {
4245
- finish();
4246
- continue;
4247
- }
4248
- if (line.startsWith("#")) {
4249
- if (/^#,.*\bfuzzy\b/.test(line)) fuzzy = true;
4250
- continue;
4251
- }
4252
- const keyword = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/.exec(line);
4253
- if (keyword) {
4254
- const [, name, rest] = keyword;
4255
- const value = poUnquote(rest);
4256
- if (value === void 0) continue;
4257
- if (name === "msgctxt") {
4258
- msgctxt = value;
4259
- field = "msgctxt";
4260
- } else if (name === "msgid") {
4261
- msgid = value;
4262
- field = "msgid";
4263
- } else if (name === "msgstr" || name === "msgstr[0]") {
4264
- msgstr = value;
4265
- field = "msgstr";
4266
- } else field = "other";
4267
- continue;
4268
- }
4269
- const continuation = poUnquote(line);
4270
- if (continuation === void 0 || field === void 0 || field === "other") continue;
4271
- if (field === "msgctxt") msgctxt = (msgctxt ?? "") + continuation;
4272
- else if (field === "msgid") msgid = (msgid ?? "") + continuation;
4273
- else msgstr = (msgstr ?? "") + continuation;
4325
+ function parseXliff(content) {
4326
+ const head = (name) => tagAttribute(content, "xliff", name) ?? tagAttribute(content, "file", name);
4327
+ const locale = head("trgLang") ?? head("target-language");
4328
+ const entries = emptyCatalog();
4329
+ const sources = emptyCatalog();
4330
+ for (const match of content.matchAll(new RegExp(UNIT, "g"))) {
4331
+ const id = readAttributes(match[1]).get("id")?.value;
4332
+ if (!id) continue;
4333
+ const target = TARGET.exec(match[2])?.[1];
4334
+ entries[decodeEntities(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
4335
+ const source = SOURCE.exec(match[2])?.[1];
4336
+ if (source !== void 0) sources[decodeEntities(id)] = inlineToMessage(stripCdata(source));
4274
4337
  }
4275
- finish();
4276
4338
  return {
4277
4339
  locale,
4278
4340
  entries,
4279
4341
  sources
4280
4342
  };
4281
4343
  }
4282
- function poString(text) {
4283
- return `"${text.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r")}"`;
4284
- }
4285
- function poUnquote(text) {
4286
- const match = /^"((?:[^"\\]|\\.)*)"$/.exec(text);
4287
- if (!match) return void 0;
4288
- return match[1].replace(/\\(.)/g, (_, ch) => {
4289
- if (ch === "n") return "\n";
4290
- if (ch === "t") return " ";
4291
- if (ch === "r") return "\r";
4292
- return ch;
4293
- });
4344
+ function stripCdata(text) {
4345
+ return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
4294
4346
  }
4295
4347
  // src/exchange/exchange.ts
4296
4348
  function isMobileFormat(format) {
@@ -4299,7 +4351,7 @@ function isMobileFormat(format) {
4299
4351
  function exportCatalogs(cfg, catalogs, options = {}) {
4300
4352
  const format = options.format ?? "xliff";
4301
4353
  const dir = resolve(cfg.root, options.out ?? "verbaly-export");
4302
- const source = catalogs[cfg.sourceLocale] ?? {};
4354
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
4303
4355
  const targets = targetLocales(cfg, options.locales);
4304
4356
  if (isMobileFormat(format)) return exportMobile(cfg, catalogs, format, dir, source, targets);
4305
4357
  const files = [];
@@ -4307,7 +4359,7 @@ function exportCatalogs(cfg, catalogs, options = {}) {
4307
4359
  mkdirSync(dir, { recursive: true });
4308
4360
  for (const locale of targets) {
4309
4361
  const catalog = catalogs[locale] ?? emptyCatalog();
4310
- const all = Object.keys(source).filter((key) => source[key]).sort().map((key) => ({
4362
+ const all = translatable(source).map((key) => ({
4311
4363
  key,
4312
4364
  source: source[key],
4313
4365
  target: own(catalog, key) ?? "",
@@ -4331,11 +4383,14 @@ function exportCatalogs(cfg, catalogs, options = {}) {
4331
4383
  files
4332
4384
  };
4333
4385
  }
4386
+ function translatable(source) {
4387
+ return Object.keys(source).filter((key) => source[key]).sort();
4388
+ }
4334
4389
  function exportMobile(cfg, catalogs, format, dir, source, targets) {
4335
- const keys = Object.keys(source).filter((key) => source[key]).sort();
4390
+ const keys = translatable(source);
4336
4391
  const files = [];
4337
4392
  for (const locale of [cfg.sourceLocale, ...targets]) {
4338
- const catalog = locale === cfg.sourceLocale ? source : catalogs[locale] ?? {};
4393
+ const catalog = locale === cfg.sourceLocale ? source : catalogs[locale] ?? emptyCatalog();
4339
4394
  const entries = keys.map((key) => ({
4340
4395
  key,
4341
4396
  text: own(catalog, key) ?? ""
@@ -4358,7 +4413,7 @@ function exportMobile(cfg, catalogs, format, dir, source, targets) {
4358
4413
  };
4359
4414
  }
4360
4415
  function importCatalogs(cfg, catalogs, files, options = {}) {
4361
- const source = catalogs[cfg.sourceLocale] ?? {};
4416
+ const source = catalogs[cfg.sourceLocale] ?? emptyCatalog();
4362
4417
  const result = {
4363
4418
  imported: emptyCatalog(),
4364
4419
  rejected: emptyCatalog(),
@@ -4371,9 +4426,9 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
4371
4426
  for (const file of files) {
4372
4427
  const parsed = parseExchangeFile(file, options.locale);
4373
4428
  const detected = parsed.locale;
4374
- if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(detected)) throw new Error(`[verbaly] ${file}: "${detected}" doesn't look like a locale, pass --locale <id>.`);
4429
+ if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(detected)) throw new Error(`[verbaly] ${file}: "${detected}" doesn't look like a locale, pass --locale <id>`);
4375
4430
  const locale = projectLocale(detected, cfg.locales) ?? newLocale(cfg, detected);
4376
- if (locale === cfg.sourceLocale) throw new Error(`[verbaly] ${file} targets the source locale "${locale}": import fills translations, not the source. Pass --locale if the detection is wrong.`);
4431
+ if (locale === cfg.sourceLocale) throw new Error(`[verbaly] ${file} targets the source locale "${locale}": import fills translations, not the source, so pass --locale if the detection is wrong`);
4377
4432
  if (locale === void 0) {
4378
4433
  const near = isLocaleTag(detected) ? detected : suggestTag(detected);
4379
4434
  result.unmatched.push(near ? {
@@ -4406,167 +4461,45 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
4406
4461
  }
4407
4462
  if (!structureMatches(from, text)) {
4408
4463
  (result.rejected[locale] ??= []).push(key);
4409
- continue;
4410
- }
4411
- if (!options.dryRun) catalog[key] = text;
4412
- (result.imported[locale] ??= []).push(key);
4413
- const seen = parsed.sources[key];
4414
- if (seen) (result.sources[locale] ??= emptyCatalog())[key] = seen;
4415
- }
4416
- }
4417
- return result;
4418
- }
4419
- function parseExchangeFile(file, localeOverride) {
4420
- const content = readFileSync(file, "utf8");
4421
- if (/\.(xlf|xliff)$/i.test(file)) {
4422
- const parsed = parseXliff(content);
4423
- const locale = localeOverride ?? parsed.locale;
4424
- if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>.`);
4425
- return {
4426
- locale,
4427
- entries: parsed.entries,
4428
- sources: parsed.sources
4429
- };
4430
- }
4431
- if (/\.csv$/i.test(file)) return {
4432
- locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
4433
- ...parseCsv(content)
4434
- };
4435
- if (/\.po$/i.test(file)) {
4436
- const parsed = parsePo(content);
4437
- return {
4438
- locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
4439
- entries: parsed.entries,
4440
- sources: parsed.sources
4441
- };
4442
- }
4443
- throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po.`);
4444
- }
4445
- function toXliff(sourceLocale, locale, entries) {
4446
- const units = entries.map(({ key, source, target, location }) => [
4447
- ` <unit id="${escapeXml(key)}">`,
4448
- ...location?.length ? [
4449
- " <notes>",
4450
- ...location.map((file) => ` <note category="location">${escapeXml(file)}</note>`),
4451
- " </notes>"
4452
- ] : [],
4453
- ` <segment state="${target ? "translated" : "initial"}">`,
4454
- ` <source>${messageToInline(source)}</source>`,
4455
- ` <target>${messageToInline(target)}</target>`,
4456
- " </segment>",
4457
- " </unit>"
4458
- ].join("\n")).join("\n");
4459
- return [
4460
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
4461
- `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
4462
- ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
4463
- units,
4464
- " </file>",
4465
- "</xliff>",
4466
- ""
4467
- ].join("\n");
4468
- }
4469
- function newLocale(cfg, detected) {
4470
- if (cfg.localesDeclared) return void 0;
4471
- return isLocaleTag(detected) ? detected : suggestTag(detected);
4472
- }
4473
- const UNIT = `<(?:trans-)?unit\\b(${TAG_REST})>([\\s\\S]*?)</(?:trans-)?unit>`;
4474
- const TARGET = new RegExp(`<target\\b${TAG_REST}>([\\s\\S]*?)</target>`);
4475
- const SOURCE = new RegExp(`<source\\b${TAG_REST}>([\\s\\S]*?)</source>`);
4476
- function tagAttribute(content, tag, name) {
4477
- const open = new RegExp(`<${tag}\\b(${TAG_REST})>`).exec(content);
4478
- return open && readAttributes(open[1]).get(name)?.value || void 0;
4479
- }
4480
- function parseXliff(content) {
4481
- const head = (name) => tagAttribute(content, "xliff", name) ?? tagAttribute(content, "file", name);
4482
- const locale = head("trgLang") ?? head("target-language");
4483
- const entries = Object.create(null);
4484
- const sources = Object.create(null);
4485
- for (const match of content.matchAll(new RegExp(UNIT, "g"))) {
4486
- const id = readAttributes(match[1]).get("id")?.value;
4487
- if (!id) continue;
4488
- const target = TARGET.exec(match[2])?.[1];
4489
- entries[decodeEntities(id)] = target === void 0 ? "" : inlineToMessage(stripCdata(target));
4490
- const source = SOURCE.exec(match[2])?.[1];
4491
- if (source !== void 0) sources[decodeEntities(id)] = inlineToMessage(stripCdata(source));
4492
- }
4493
- return {
4494
- locale,
4495
- entries,
4496
- sources
4497
- };
4498
- }
4499
- function stripCdata(text) {
4500
- return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
4501
- }
4502
- function toCsv(entries) {
4503
- return [
4504
- "key,source,target,location",
4505
- ...entries.map(({ key, source, target, location }) => `${csvField(key)},${csvField(source)},${csvField(target)},${csvField(location?.join("; ") ?? "")}`),
4506
- ""
4507
- ].join("\r\n");
4508
- }
4509
- function csvField(text) {
4510
- return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
4511
- }
4512
- function parseCsv(content) {
4513
- const rows = csvRows(content, csvSeparator(content));
4514
- const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
4515
- const keyCol = header.indexOf("key");
4516
- const targetCol = header.indexOf("target");
4517
- const sourceCol = header.indexOf("source");
4518
- if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
4519
- const entries = Object.create(null);
4520
- const sources = Object.create(null);
4521
- for (const row of rows.slice(1)) {
4522
- const key = row[keyCol];
4523
- if (!key) continue;
4524
- entries[key] = row[targetCol] ?? "";
4525
- const source = sourceCol === -1 ? void 0 : row[sourceCol];
4526
- if (source) sources[key] = source;
4464
+ continue;
4465
+ }
4466
+ if (!options.dryRun) catalog[key] = text;
4467
+ (result.imported[locale] ??= []).push(key);
4468
+ const seen = parsed.sources[key];
4469
+ if (seen) (result.sources[locale] ??= emptyCatalog())[key] = seen;
4470
+ }
4527
4471
  }
4528
- return {
4529
- entries,
4530
- sources
4531
- };
4532
- }
4533
- function csvSeparator(content) {
4534
- let quoted = false;
4535
- const seen = /* @__PURE__ */ new Set();
4536
- for (const char of content) if (char === "\"") quoted = !quoted;
4537
- else if (!quoted && (char === "\n" || char === "\r")) break;
4538
- else if (!quoted) seen.add(char);
4539
- return seen.has(",") ? "," : seen.has(";") ? ";" : seen.has(" ") ? " " : ",";
4472
+ return result;
4540
4473
  }
4541
- function csvRows(content, separator) {
4542
- const rows = [];
4543
- let row = [];
4544
- let field = "";
4545
- let quoted = false;
4546
- for (let i = 0; i < content.length; i++) {
4547
- const char = content[i];
4548
- if (quoted) {
4549
- if (char === "\"") {
4550
- if (content[i + 1] === "\"") {
4551
- field += "\"";
4552
- i++;
4553
- } else quoted = false;
4554
- } else field += char;
4555
- } else if (char === "\"") quoted = true;
4556
- else if (char === separator) {
4557
- row.push(field);
4558
- field = "";
4559
- } else if (char === "\n" || char === "\r") {
4560
- if (char === "\r" && content[i + 1] === "\n") i++;
4561
- row.push(field);
4562
- field = "";
4563
- if (row.some((cell) => cell !== "")) rows.push(row);
4564
- row = [];
4565
- } else field += char;
4474
+ function parseExchangeFile(file, localeOverride) {
4475
+ const content = readFileSync(file, "utf8");
4476
+ if (/\.(xlf|xliff)$/i.test(file)) {
4477
+ const parsed = parseXliff(content);
4478
+ const locale = localeOverride ?? parsed.locale;
4479
+ if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language, pass --locale <id>`);
4480
+ return {
4481
+ locale,
4482
+ entries: parsed.entries,
4483
+ sources: parsed.sources
4484
+ };
4566
4485
  }
4567
- row.push(field);
4568
- if (row.some((cell) => cell !== "")) rows.push(row);
4569
- return rows;
4486
+ if (/\.csv$/i.test(file)) return {
4487
+ locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
4488
+ ...parseCsv(content)
4489
+ };
4490
+ if (/\.po$/i.test(file)) {
4491
+ const parsed = parsePo(content);
4492
+ return {
4493
+ locale: localeOverride ?? parsed.locale ?? basename(file).replace(/\.po$/i, ""),
4494
+ entries: parsed.entries,
4495
+ sources: parsed.sources
4496
+ };
4497
+ }
4498
+ throw new Error(`[verbaly] ${file}: unsupported format, expected .xlf, .xliff, .csv or .po`);
4499
+ }
4500
+ function newLocale(cfg, detected) {
4501
+ if (cfg.localesDeclared) return void 0;
4502
+ return isLocaleTag(detected) ? detected : suggestTag(detected);
4570
4503
  }
4571
4504
  // src/cli/commands/export.ts
4572
4505
  async function exportCommand(cfg, values) {
@@ -4650,7 +4583,7 @@ function watchTree(root, options, onFile) {
4650
4583
  };
4651
4584
  }
4652
4585
  function watchProject(cfg, run, options = {}) {
4653
- const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
4586
+ const catalogDir = relativePath(cfg.root, cfg.dir);
4654
4587
  let timer;
4655
4588
  let running = false;
4656
4589
  let queued = false;
@@ -4678,7 +4611,7 @@ function watchProject(cfg, run, options = {}) {
4678
4611
  }
4679
4612
  const close = watchTree(cfg.root, {}, (filename) => {
4680
4613
  if (!filename) return;
4681
- const file = filename.replaceAll("\\", "/");
4614
+ const file = slashed(filename);
4682
4615
  if (file.includes("node_modules/") || file.endsWith(".d.ts")) return;
4683
4616
  if (catalogDir && file.startsWith(`${catalogDir}/`)) return;
4684
4617
  if (SOURCE_FILE_RE.test(file)) schedule();
@@ -4790,18 +4723,7 @@ const KNOWN = [
4790
4723
  "svelte-i18n"
4791
4724
  ];
4792
4725
  function detectLibraries(root) {
4793
- const path = join(root, "package.json");
4794
- if (!existsSync(path)) return [];
4795
- let manifest;
4796
- try {
4797
- manifest = JSON.parse(readFileSync(path, "utf8"));
4798
- } catch {
4799
- return [];
4800
- }
4801
- const deps = {
4802
- ...manifest.dependencies,
4803
- ...manifest.devDependencies
4804
- };
4726
+ const deps = readDependencies(root);
4805
4727
  return KNOWN.filter((name) => deps[name] !== void 0);
4806
4728
  }
4807
4729
  const PLAIN = /\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}/g;
@@ -5090,7 +5012,7 @@ async function init(input = {}) {
5090
5012
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
5091
5013
  for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
5092
5014
  const file = join(dir, `${locale}.json`);
5093
- const label = relative(root, file).replaceAll("\\", "/");
5015
+ const label = relativePath(root, file);
5094
5016
  if (existsSync(file)) skipped.push(label);
5095
5017
  else {
5096
5018
  writeFileSync(file, "{}\n");
@@ -5422,7 +5344,7 @@ function renderHtml(html, options) {
5422
5344
  };
5423
5345
  }
5424
5346
  function pageSlice(v, locale, used) {
5425
- const slice = Object.create(null);
5347
+ const slice = emptyCatalog();
5426
5348
  for (const key of used) {
5427
5349
  const found = v.inspect(key);
5428
5350
  slice[key] = found?.from === locale ? found.source : "";
@@ -5440,7 +5362,7 @@ function linkFor(links, name) {
5440
5362
  return links && Object.hasOwn(links, name) ? links[name] : void 0;
5441
5363
  }
5442
5364
  function usedLinks(nodes, links) {
5443
- const out = {};
5365
+ const out = emptyCatalog();
5444
5366
  const walk = (list) => {
5445
5367
  for (const node of list) {
5446
5368
  if (typeof node === "string") continue;
@@ -5454,7 +5376,7 @@ function usedLinks(nodes, links) {
5454
5376
  }
5455
5377
  function mirroredLinks(links, mirror) {
5456
5378
  if (!links) return links;
5457
- const out = {};
5379
+ const out = emptyCatalog();
5458
5380
  for (const [name, link] of Object.entries(links)) {
5459
5381
  const inside = mirroredHref(typeof link === "string" ? link : link.href, mirror);
5460
5382
  if (inside === void 0) out[name] = link;
@@ -5501,51 +5423,114 @@ function redirectScript(options) {
5501
5423
  `N=${options.trailingSlash === "never" ? 1 : 0}`
5502
5424
  ].join(",")};${REDIRECT_BODY};<\/script>`;
5503
5425
  }
5504
- function injectRedirect(ms, html, options) {
5505
- const block = `${REDIRECT_OPEN}${redirectScript(options)}${REDIRECT_CLOSE}`;
5506
- const from = html.indexOf(REDIRECT_OPEN);
5507
- if (from !== -1) {
5508
- const to = html.indexOf(REDIRECT_CLOSE, from);
5509
- if (to !== -1) {
5510
- const end = to + 24;
5511
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5512
- return;
5513
- }
5426
+ const HEAD_OPEN = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i;
5427
+ const HEAD_CLOSE = /<\/head\s*>/i;
5428
+ function betweenMarkers(ms, html, [open, close], content, where) {
5429
+ const block = `${open}${content}${close}`;
5430
+ const from = html.indexOf(open);
5431
+ const to = from === -1 ? -1 : html.indexOf(close, from);
5432
+ if (to !== -1) {
5433
+ const end = to + close.length;
5434
+ if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5435
+ return;
5514
5436
  }
5515
- const head = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i.exec(html);
5516
- if (head) ms.appendRight(head.index + head[0].length, block);
5437
+ const head = (where === "first" ? HEAD_OPEN : HEAD_CLOSE).exec(html);
5438
+ if (!head) return;
5439
+ if (where === "first") ms.appendRight(head.index + head[0].length, block);
5440
+ else ms.appendLeft(head.index, block);
5441
+ }
5442
+ function injectRedirect(ms, html, options) {
5443
+ betweenMarkers(ms, html, [REDIRECT_OPEN, REDIRECT_CLOSE], redirectScript(options), "first");
5517
5444
  }
5518
5445
  function injectAlternates(ms, html, alternates) {
5519
5446
  const links = alternates.map((a) => `<link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}">`).join("");
5520
- const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;
5521
- const from = html.indexOf(HREFLANG_OPEN);
5522
- if (from !== -1) {
5523
- const to = html.indexOf(HREFLANG_CLOSE, from);
5524
- if (to !== -1) {
5525
- const end = to + 24;
5526
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5527
- return;
5528
- }
5529
- }
5530
- const head = /<\/head\s*>/i.exec(html);
5531
- if (head) ms.appendLeft(head.index, block);
5447
+ betweenMarkers(ms, html, [HREFLANG_OPEN, HREFLANG_CLOSE], links, "last");
5532
5448
  }
5533
5449
  function injectCatalog(ms, html, messages) {
5534
5450
  const json = JSON.stringify(messages).replace(/<\//g, "<\\/").replace(/<!--/g, "\\u003c!--");
5535
5451
  const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
5536
- const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
5537
- const from = html.indexOf(CATALOG_OPEN);
5538
- if (from !== -1) {
5539
- const to = html.indexOf(CATALOG_CLOSE, from);
5540
- if (to !== -1) {
5541
- const end = to + 23;
5542
- if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
5543
- return;
5544
- }
5452
+ betweenMarkers(ms, html, [CATALOG_OPEN, CATALOG_CLOSE], tag, "last");
5453
+ }
5454
+ function parseArgs(raw, attribute) {
5455
+ if (!raw) return void 0;
5456
+ try {
5457
+ return JSON.parse(decodeEntities(raw));
5458
+ } catch {
5459
+ warnOnce(`invalid JSON in ${attribute}: ${raw}`, `${attribute}:${raw}`);
5460
+ return;
5461
+ }
5462
+ }
5463
+ const OPAQUE_BLOCKS = [
5464
+ {
5465
+ open: "<!--",
5466
+ close: /(?<=<!--)-?>|--!?>/g
5467
+ },
5468
+ {
5469
+ open: /<script\b/gi,
5470
+ close: /<\/script(?=[\t\n\f\r />])/gi,
5471
+ closeTag: true
5472
+ },
5473
+ {
5474
+ open: /<style\b/gi,
5475
+ close: /<\/style(?=[\t\n\f\r />])/gi,
5476
+ closeTag: true
5477
+ }
5478
+ ];
5479
+ function protectedRanges(html) {
5480
+ return blocks(html, OPAQUE_BLOCKS).map(({ start, end }) => {
5481
+ return [html.startsWith("<!--", start) ? start : html.indexOf(">", start) + 1, end];
5482
+ });
5483
+ }
5484
+ function findClose(html, tagName, from, inSkip) {
5485
+ const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
5486
+ re.lastIndex = from;
5487
+ let depth = 1;
5488
+ let m;
5489
+ while ((m = re.exec(html)) !== null) {
5490
+ if (inSkip(m.index)) continue;
5491
+ if (m[0][1] === "/") {
5492
+ depth -= 1;
5493
+ if (depth === 0) return { contentEnd: m.index };
5494
+ } else if (!m[0].endsWith("/>")) depth += 1;
5495
+ }
5496
+ return null;
5497
+ }
5498
+ function setAttribute(ms, html, chunkStart, openEnd, attrs, name, value) {
5499
+ const written = `"${escapeAttr(value)}"`;
5500
+ const existing = attrs.get(name.toLowerCase());
5501
+ if (existing) {
5502
+ const from = chunkStart + existing.start;
5503
+ const to = chunkStart + existing.end;
5504
+ if (from === to) ms.appendLeft(from, `=${written}`);
5505
+ else if (html.slice(from, to) !== written) ms.overwrite(from, to, written);
5506
+ return;
5507
+ }
5508
+ const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
5509
+ ms.appendLeft(insertAt, ` ${name}=${written}`);
5510
+ }
5511
+ function richToHtml(nodes, allowed, links) {
5512
+ let out = "";
5513
+ for (const node of nodes) {
5514
+ const link = typeof node === "string" ? void 0 : linkFor(links, node.name);
5515
+ if (typeof node === "string") out += escapeHtml(node);
5516
+ else if (link !== void 0) {
5517
+ const { href, target, rel } = normalizeLink(link);
5518
+ let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
5519
+ if (target) attrs += ` target="${escapeAttr(target)}"`;
5520
+ if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
5521
+ out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
5522
+ } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
5523
+ else out += richToHtml(node.children, allowed, links);
5545
5524
  }
5546
- const head = /<\/head\s*>/i.exec(html);
5547
- if (head) ms.appendLeft(head.index, block);
5525
+ return out;
5526
+ }
5527
+ function escapeHtml(text) {
5528
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5529
+ }
5530
+ function escapeAttr(text) {
5531
+ return escapeHtml(text).replace(/"/g, "&quot;");
5548
5532
  }
5533
+ // src/emit/site.ts
5549
5534
  const TITLE_TAG = /<title\b([^>]*)>/i;
5550
5535
  const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
5551
5536
  const NOINDEX_META = /<meta\b[^>]*name\s*=\s*["']?robots["']?[^>]*content\s*=\s*["'][^"']*noindex/i;
@@ -5592,13 +5577,13 @@ async function renderSite(cfg, options = {}) {
5592
5577
  absolute: true,
5593
5578
  ignore: locales.map((locale) => `${locale}/**`)
5594
5579
  });
5595
- const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
5596
- const missing = emptyCatalog();
5580
+ const pages = new Set(files.map((file) => publicPath(relativePath(site, file))));
5581
+ const unfilled = emptyCatalog();
5597
5582
  const untranslatedHead = [];
5598
5583
  const urls = [];
5599
5584
  for (const file of files) {
5600
5585
  const html = readFileSync(file, "utf8");
5601
- const rel = relative(site, file).replace(/\\/g, "/");
5586
+ const rel = relativePath(site, file);
5602
5587
  if (locales.length > 1 && !headIsBound(html, attribute ?? "data-verbaly")) untranslatedHead.push(rel);
5603
5588
  const alternates = wantHreflang ? pageAlternates(baseUrl, rel, locales, cfg.sourceLocale, cfg.trailingSlash) : [];
5604
5589
  if (wantHreflang && isIndexable(html) && !excluded(rel)) urls.push({
@@ -5624,16 +5609,15 @@ async function renderSite(cfg, options = {}) {
5624
5609
  redirect: routed && locale === cfg.sourceLocale ? script : void 0,
5625
5610
  inlineCatalog: cfg.render.inlineCatalog === true
5626
5611
  });
5627
- for (const key of result.missing) {
5628
- const list = missing[locale] ??= [];
5629
- if (!list.includes(key)) list.push(key);
5630
- }
5612
+ for (const key of result.missing) (unfilled[locale] ??= /* @__PURE__ */ new Set()).add(key);
5631
5613
  const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);
5632
5614
  mkdirSync(dirname(out), { recursive: true });
5633
5615
  writeFileSync(out, result.html);
5634
5616
  }
5635
5617
  }
5636
5618
  if (wantSitemap && urls.length) writeFileSync(join(site, typeof sitemap === "string" ? sitemap : "sitemap-i18n.xml"), buildSitemap(urls));
5619
+ const missing = emptyCatalog();
5620
+ for (const [locale, keys] of Object.entries(unfilled)) missing[locale] = [...keys];
5637
5621
  return {
5638
5622
  files: files.length,
5639
5623
  locales: [...locales],
@@ -5663,89 +5647,10 @@ function pageAlternates(baseUrl, rel, locales, sourceLocale, trailingSlash) {
5663
5647
  }
5664
5648
  function buildSitemap(urls) {
5665
5649
  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 }) => {
5666
- const alts = alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${a.hreflang}" href="${escapeAttr(a.href)}"/>`).join("");
5650
+ const alts = alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}"/>`).join("");
5667
5651
  return alternates.filter((a) => a.hreflang !== "x-default").map((self) => `<url><loc>${escapeAttr(self.href)}</loc>${alts}</url>`);
5668
5652
  }).join("")}</urlset>\n`;
5669
5653
  }
5670
- function parseArgs(raw, attribute) {
5671
- if (!raw) return void 0;
5672
- try {
5673
- return JSON.parse(decodeEntities(raw));
5674
- } catch {
5675
- warnOnce(`invalid JSON in ${attribute}: ${raw}`, `${attribute}:${raw}`);
5676
- return;
5677
- }
5678
- }
5679
- const OPAQUE_BLOCKS = [
5680
- {
5681
- open: "<!--",
5682
- close: /(?<=<!--)-?>|--!?>/g
5683
- },
5684
- {
5685
- open: /<script\b/gi,
5686
- close: /<\/script(?=[\t\n\f\r />])/gi,
5687
- closeTag: true
5688
- },
5689
- {
5690
- open: /<style\b/gi,
5691
- close: /<\/style(?=[\t\n\f\r />])/gi,
5692
- closeTag: true
5693
- }
5694
- ];
5695
- function protectedRanges(html) {
5696
- return blocks(html, OPAQUE_BLOCKS).map(({ start, end }) => {
5697
- return [html.startsWith("<!--", start) ? start : html.indexOf(">", start) + 1, end];
5698
- });
5699
- }
5700
- function findClose(html, tagName, from, inSkip) {
5701
- const re = new RegExp(`<${tagName}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>|</${tagName}\\s*>`, "gi");
5702
- re.lastIndex = from;
5703
- let depth = 1;
5704
- let m;
5705
- while ((m = re.exec(html)) !== null) {
5706
- if (inSkip(m.index)) continue;
5707
- if (m[0][1] === "/") {
5708
- depth -= 1;
5709
- if (depth === 0) return { contentEnd: m.index };
5710
- } else if (!m[0].endsWith("/>")) depth += 1;
5711
- }
5712
- return null;
5713
- }
5714
- function setAttribute(ms, html, chunkStart, openEnd, attrs, name, value) {
5715
- const written = `"${escapeAttr(value)}"`;
5716
- const existing = attrs.get(name.toLowerCase());
5717
- if (existing) {
5718
- const from = chunkStart + existing.start;
5719
- const to = chunkStart + existing.end;
5720
- if (from === to) ms.appendLeft(from, `=${written}`);
5721
- else if (html.slice(from, to) !== written) ms.overwrite(from, to, written);
5722
- return;
5723
- }
5724
- const insertAt = openEnd - (html.slice(openEnd - 2, openEnd) === "/>" ? 2 : 1);
5725
- ms.appendLeft(insertAt, ` ${name}=${written}`);
5726
- }
5727
- function richToHtml(nodes, allowed, links) {
5728
- let out = "";
5729
- for (const node of nodes) {
5730
- const link = typeof node === "string" ? void 0 : linkFor(links, node.name);
5731
- if (typeof node === "string") out += escapeHtml(node);
5732
- else if (link !== void 0) {
5733
- const { href, target, rel } = normalizeLink(link);
5734
- let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
5735
- if (target) attrs += ` target="${escapeAttr(target)}"`;
5736
- if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
5737
- out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
5738
- } else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
5739
- else out += richToHtml(node.children, allowed, links);
5740
- }
5741
- return out;
5742
- }
5743
- function escapeHtml(text) {
5744
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5745
- }
5746
- function escapeAttr(text) {
5747
- return escapeHtml(text).replace(/"/g, "&quot;");
5748
- }
5749
5654
  // src/cli/commands/render.ts
5750
5655
  async function renderCommand(cfg, values) {
5751
5656
  const result = await renderSite(cfg, {
@@ -5864,7 +5769,7 @@ async function typegenCommand(cfg) {
5864
5769
  console.log("[verbaly] no types written: dts is false in your verbaly config");
5865
5770
  return;
5866
5771
  }
5867
- const where = relative(cfg.root, written.file).replaceAll("\\", "/");
5772
+ const where = relativePath(cfg.root, written.file);
5868
5773
  const how = written.changed ? "written to" : "up to date in";
5869
5774
  console.log(`[verbaly] types ${how} ${where} (${counted(Object.keys(source).length, "message")})`);
5870
5775
  }
@@ -5913,7 +5818,7 @@ async function wrapProject(cfg, options = {}) {
5913
5818
  const adapters = () => found ??= jsxAdapters(cfg.root);
5914
5819
  for (const file of files) {
5915
5820
  const code = readFileSync(file, "utf8");
5916
- const label = relative(cfg.root, file).replaceAll("\\", "/");
5821
+ const label = relativePath(cfg.root, file);
5917
5822
  const out = wrapCode(code, label);
5918
5823
  result.wrapped.push(...out.wrapped);
5919
5824
  result.skipped.push(...out.skipped);
@@ -6051,7 +5956,7 @@ function wrapCode(code, file) {
6051
5956
  write(start, end, template);
6052
5957
  wrapped.push({
6053
5958
  file,
6054
- line: line(first),
5959
+ line: lineOf(first),
6055
5960
  text: report,
6056
5961
  kind: "text"
6057
5962
  });
@@ -6068,7 +5973,7 @@ function wrapCode(code, file) {
6068
5973
  write(value.start, value.end, escapeTemplate(raw));
6069
5974
  wrapped.push({
6070
5975
  file,
6071
- line: line(value),
5976
+ line: lineOf(value),
6072
5977
  text: raw,
6073
5978
  kind: "attribute",
6074
5979
  attribute: name.name
@@ -6078,7 +5983,7 @@ function wrapCode(code, file) {
6078
5983
  function skip(node, text, reason) {
6079
5984
  skipped.push({
6080
5985
  file,
6081
- line: line(node),
5986
+ line: lineOf(node),
6082
5987
  text,
6083
5988
  reason
6084
5989
  });
@@ -6146,7 +6051,7 @@ function tReaches(scopes, position) {
6146
6051
  for (const scope of scopes) {
6147
6052
  if (position < scope.start || position >= scope.end) continue;
6148
6053
  const size = scope.end - scope.start;
6149
- const best = nearest ? nearest.end - nearest.start : Infinity;
6054
+ const best = nearest ? nearest.end - nearest.start : 1e400;
6150
6055
  if (size < best || size === best && scope.bound) nearest = scope;
6151
6056
  }
6152
6057
  return nearest?.bound ?? false;
@@ -6200,9 +6105,6 @@ function leadingWs(text) {
6200
6105
  function trailingWs(text) {
6201
6106
  return text.length - text.trimEnd().length;
6202
6107
  }
6203
- function line(node) {
6204
- return node.loc?.start?.line ?? 1;
6205
- }
6206
6108
  function formatWrapResult(result, write) {
6207
6109
  const blocked = new Set(result.blocked.map((entry) => entry.file));
6208
6110
  const done = result.changed.filter((file) => !blocked.has(file));
@@ -6350,7 +6252,7 @@ async function runCli(args = process.argv.slice(2)) {
6350
6252
  function strangers(cfg, flag, named) {
6351
6253
  const unknown = named.filter((locale) => !cfg.locales.includes(locale));
6352
6254
  if (unknown.length === 0) return void 0;
6353
- const dir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
6255
+ const dir = relativePath(cfg.root, cfg.dir);
6354
6256
  const start = cfg.localesDeclared ? `add ${unknown.join(", ")} to locales in your verbaly config` : `create ${unknown.map((locale) => `${dir}/${locale}.json`).join(", ")} holding {}`;
6355
6257
  return `[verbaly] --${flag} names ${unknown.map((locale) => `"${locale}"`).join(", ")}, and this project has ${cfg.locales.join(", ")}\n fix: check the spelling, or ${start} to start a new language`;
6356
6258
  }
@@ -6415,4 +6317,4 @@ function rejectStrayFlags(command, values) {
6415
6317
  process.exitCode = 1;
6416
6318
  return true;
6417
6319
  }
6418
- export { generateLocaleModule as $, relativeCheck as A, formatCollision as B, runBuildGate as C, resolveConfig as Ct, check as D, transformCode as E, translateCatalogs as F, loadState as G, STATE_FILE as H, writeDrafts as I, readState as J, markDrafts as K, syncProject as L, formatTranslateFailures as M, mergeTranslations as N, formatCheckResult as O, resolveProvider as P, generateDts as Q, collisionEntries as R, resolveVirtualId as S, loadConfig as St, writeBuildTypes as T, clearDrafts as U, formatFinding as V, effectiveDrafts as W, saveState as X, recordTranslations as Y, updateState as Z, SOURCE_FILE_RE as _, needsRelative as _t, formatRenderWarnings as a, extractProject as at, isTransformTarget as b, writeCatalog as bt, watchTree as c, syncCatalogs as ct, formatDoctorHealth as d, LOCALE_IMPORT as dt, generateRuntimeModule as et, formatStatusResult as f, MessageRegistry as ft, RESOLVED_VIRTUAL_ID as g, needsIcu as gt, LOCALE_MODULE_PREFIX as h, loadCatalogs as ht, wrapProject as i, collectOrigins as it, translateProject as j, formatCheckWarnings as k, doctor as l, stableKey as lt, reportOutsideInclude as m, counted as mt, runCli as n, validateMessage as nt, renderSite as o, pruneCatalogs as ot, status as p, clientCatalogs as pt, outdatedTranslations as q, formatWrapResult as r, validatePair as rt, init as s, shippedCatalogs as st, formatCliError as t, writeDts as tt, formatDoctorEntry as u, APP_ID as ut, clientModules as v, parseCatalog as vt, transformSource as w, targetLocales as wt, loadVirtualModule as x, isModuleNotFound as xt, createSourceFilter as y, readCatalog as yt, createDevReporter as z };
6320
+ export { collectOrigins as $, collisionEntries as A, counted as At, loadState as B, translateProject as C, loadConfig as Ct, translateCatalogs as D, warnOnce as Dt, resolveProvider as E, targetLocales as Et, outdatedTranslations as F, generateLocaleModule as G, readState as H, recordTranslations as I, validateMessage as J, generateRuntimeModule as K, updateState as L, formatCollision as M, formatFinding as N, writeDrafts as O, warnParseError as Ot, effectiveDrafts as P, syncCatalogs as Q, STATE_FILE as R, warningCount as S, isModuleNotFound as St, mergeTranslations as T, resolveConfig as Tt, saveState as U, markDrafts as V, generateDts as W, pruneCatalogs as X, validatePair as Y, shippedCatalogs as Z, formatCheckResult as _, own as _t, formatRenderWarnings as a, APP_ID as at, gatePasses as b, writeCatalog as bt, watchTree as c, isAppModule as ct, formatDoctorHealth as d, clientCatalogs as dt, extractProject as et, formatStatusResult as f, formatBundleIssue as ft, formatBuildReport as g, needsRelative as gt, checkNextSteps as h, needsIcu as ht, wrapProject as i, stableKey as it, createDevReporter as j, singleQuoted as jt, syncProject as k, cliReachable as kt, doctor as l, MessageRegistry as lt, reportOutsideInclude as m, loadCatalogs as mt, runCli as n, relativePath as nt, renderSite as o, LOCALE_IMPORT as ot, status as p, emptyCatalog as pt, writeDts as q, formatWrapResult as r, analyzeFile as rt, init as s, VIRTUAL_ID as st, formatCliError as t, scannedAnalysis as tt, formatDoctorEntry as u, auditBundle as ut, formatCheckWarnings as v, parseCatalog as vt, formatTranslateFailures as w, pluginOnlyOptions as wt, relativeCheck as x, SOURCE_FILE_RE as xt, check as y, readCatalog as yt, clearDrafts as z };