@verbaly/compiler 0.68.0 → 0.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,14 +1,21 @@
1
1
  #!/usr/bin/env node
2
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
2
3
  import { parseArgs } from "node:util";
3
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
4
- import { basename, dirname, join, relative, resolve } from "node:path";
4
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
5
5
  import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
6
6
  import { glob } from "tinyglobby";
7
7
  import { parse as parse$1 } from "@babel/parser";
8
8
  import { createHash } from "node:crypto";
9
9
  import { pathToFileURL } from "node:url";
10
- import MagicString from "magic-string";
10
+ import { applyEdits, modify, parse as parse$2 } from "jsonc-parser";
11
11
  import picomatch from "picomatch";
12
+ import MagicString from "magic-string";
13
+ //#region src/eol.ts
14
+ function withLineEndings(text, existing) {
15
+ const first = existing?.indexOf("\n") ?? -1;
16
+ return first > 0 && existing[first - 1] === "\r" ? text.replace(/\r?\n/g, "\r\n") : text;
17
+ }
18
+ //#endregion
12
19
  //#region src/catalog.ts
13
20
  function emptyCatalog() {
14
21
  return Object.create(null);
@@ -128,7 +135,7 @@ function writeCatalog(cfg, locale, catalog) {
128
135
  }
129
136
  const parsed = existing === void 0 ? void 0 : parseTree(existing);
130
137
  const previous = isTree(parsed) ? parsed : void 0;
131
- const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous);
138
+ const serialized = withLineEndings(serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous), existing);
132
139
  if (existing === serialized) return serialized;
133
140
  writeFileSync(path, serialized);
134
141
  return serialized;
@@ -968,6 +975,9 @@ function counted(count, noun, many = `${noun}s`) {
968
975
  function truncate(text, max) {
969
976
  return text.length > max ? text.slice(0, max - 1) + "…" : text;
970
977
  }
978
+ function byCodeUnit(a, b) {
979
+ return a < b ? -1 : a > b ? 1 : 0;
980
+ }
971
981
  //#endregion
972
982
  //#region src/validate.ts
973
983
  const read = (message) => parse(message, parseIcu);
@@ -1248,6 +1258,142 @@ function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${lin
1248
1258
  } };
1249
1259
  }
1250
1260
  //#endregion
1261
+ //#region src/host.ts
1262
+ const HOSTS = [
1263
+ {
1264
+ name: "nuxt",
1265
+ dep: "nuxt",
1266
+ pkg: "@verbaly/nuxt",
1267
+ install: [
1268
+ "verbaly",
1269
+ "@verbaly/nuxt",
1270
+ "@verbaly/vue"
1271
+ ],
1272
+ wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
1273
+ },
1274
+ {
1275
+ name: "next",
1276
+ dep: "next",
1277
+ pkg: "@verbaly/next",
1278
+ install: [
1279
+ "verbaly",
1280
+ "@verbaly/next",
1281
+ "@verbaly/react"
1282
+ ],
1283
+ wire: "wrap the export of next.config with withVerbaly"
1284
+ },
1285
+ {
1286
+ name: "sveltekit",
1287
+ dep: "@sveltejs/kit",
1288
+ pkg: "@verbaly/vite",
1289
+ install: [
1290
+ "verbaly",
1291
+ "@verbaly/sveltekit",
1292
+ "@verbaly/svelte",
1293
+ "@verbaly/vite"
1294
+ ],
1295
+ wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
1296
+ },
1297
+ {
1298
+ name: "astro",
1299
+ dep: "astro",
1300
+ pkg: "@verbaly/astro",
1301
+ install: ["verbaly", "@verbaly/astro"],
1302
+ wire: "add verbaly() to the integrations in astro.config"
1303
+ },
1304
+ {
1305
+ name: "vite",
1306
+ dep: "vite",
1307
+ pkg: "@verbaly/vite",
1308
+ install: ["verbaly", "@verbaly/vite"],
1309
+ wire: "add verbaly() to the plugins in vite.config"
1310
+ },
1311
+ {
1312
+ name: "webpack",
1313
+ dep: "webpack",
1314
+ pkg: "@verbaly/unplugin",
1315
+ install: ["verbaly", "@verbaly/unplugin"],
1316
+ wire: "add the verbaly webpack plugin to your build config"
1317
+ },
1318
+ {
1319
+ name: "rspack",
1320
+ dep: "@rspack/core",
1321
+ pkg: "@verbaly/unplugin",
1322
+ install: ["verbaly", "@verbaly/unplugin"],
1323
+ wire: "add the verbaly rspack plugin to your build config"
1324
+ },
1325
+ {
1326
+ name: "rollup",
1327
+ dep: "rollup",
1328
+ pkg: "@verbaly/unplugin",
1329
+ install: ["verbaly", "@verbaly/unplugin"],
1330
+ wire: "add the verbaly rollup plugin to your build config"
1331
+ },
1332
+ {
1333
+ name: "esbuild",
1334
+ dep: "esbuild",
1335
+ pkg: "@verbaly/unplugin",
1336
+ install: ["verbaly", "@verbaly/unplugin"],
1337
+ wire: "add the verbaly esbuild plugin to your build config"
1338
+ }
1339
+ ];
1340
+ const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
1341
+ function readDependencies(root) {
1342
+ const path = join(root, "package.json");
1343
+ if (!existsSync(path)) return {};
1344
+ try {
1345
+ const pkg = JSON.parse(readFileSync(path, "utf8"));
1346
+ return {
1347
+ ...pkg.dependencies,
1348
+ ...pkg.devDependencies
1349
+ };
1350
+ } catch {
1351
+ return {};
1352
+ }
1353
+ }
1354
+ function detectHost(root) {
1355
+ const deps = readDependencies(root);
1356
+ return HOSTS.find((host) => deps[host.dep]);
1357
+ }
1358
+ const LOCKFILES = [
1359
+ ["pnpm-lock.yaml", "pnpm"],
1360
+ ["yarn.lock", "yarn"],
1361
+ ["bun.lock", "bun"],
1362
+ ["bun.lockb", "bun"],
1363
+ ["package-lock.json", "npm"]
1364
+ ];
1365
+ function packageManager(root) {
1366
+ try {
1367
+ const declared = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).packageManager;
1368
+ const name = typeof declared === "string" ? declared.split("@")[0] : void 0;
1369
+ if (name === "pnpm" || name === "npm" || name === "yarn" || name === "bun") return name;
1370
+ } catch {}
1371
+ for (let dir = root;; dir = dirname(dir)) {
1372
+ const found = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
1373
+ if (found) return found[1];
1374
+ if (dirname(dir) === dir) return "npm";
1375
+ }
1376
+ }
1377
+ function installCommand(root, packages, dev = false) {
1378
+ const manager = packageManager(root);
1379
+ return `${manager} ${manager === "npm" ? "install" : "add"}${dev ? manager === "bun" ? " -d" : " -D" : ""} ${packages.join(" ")}`;
1380
+ }
1381
+ const TYPE_SLOTS = {
1382
+ next: [".verbaly", "types.d.ts"],
1383
+ astro: [
1384
+ ".astro",
1385
+ "integrations",
1386
+ "_verbaly_astro",
1387
+ "verbaly.d.ts"
1388
+ ],
1389
+ nuxt: [".nuxt", "verbaly.d.ts"]
1390
+ };
1391
+ function defaultTypesPath(root, host = detectHost(root)?.name) {
1392
+ const slot = host && TYPE_SLOTS[host];
1393
+ if (slot) return join(root, ...slot);
1394
+ return existsSync(join(root, "src")) ? join(root, "src", "verbaly.d.ts") : join(root, "verbaly.d.ts");
1395
+ }
1396
+ //#endregion
1251
1397
  //#region src/pseudo.ts
1252
1398
  const PSEUDO_LOCALE = "en-XA";
1253
1399
  const ACCENTS = {
@@ -1368,6 +1514,7 @@ function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
1368
1514
  }
1369
1515
  //#endregion
1370
1516
  //#region src/config.ts
1517
+ const SOURCE_EXTENSIONS = "{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}";
1371
1518
  function resolveConfig(config = {}) {
1372
1519
  const root = resolve(config.root ?? process.cwd());
1373
1520
  const dir = resolve(root, config.dir ?? "locales");
@@ -1386,9 +1533,9 @@ function resolveConfig(config = {}) {
1386
1533
  icu: config.icu,
1387
1534
  relative: config.relative,
1388
1535
  locales: [...locales],
1389
- include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
1536
+ include: config.include ?? [`{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}`],
1390
1537
  exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
1391
- dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts,
1538
+ dts: typeof config.dts === "string" ? resolve(root, config.dts) : config.dts === false ? false : defaultTypesPath(root),
1392
1539
  translate: config.translate ?? {},
1393
1540
  render: config.render ?? {},
1394
1541
  bundle: config.bundle ?? {}
@@ -1407,7 +1554,7 @@ function findConfigFile(root) {
1407
1554
  async function loadConfigFile(root) {
1408
1555
  for (const name of ["verbaly.config.js", "verbaly.config.mjs"]) {
1409
1556
  const path = join(root, name);
1410
- if (existsSync(path)) return (await import(pathToFileURL(path).href)).default ?? {};
1557
+ if (existsSync(path)) return (await import(`${pathToFileURL(path).href}?mtime=${statSync(path).mtimeMs}`)).default ?? {};
1411
1558
  }
1412
1559
  for (const name of ["verbaly.config.ts", "verbaly.config.mts"]) {
1413
1560
  const path = join(root, name);
@@ -1473,85 +1620,11 @@ function projectLocale(tag, locales) {
1473
1620
  }
1474
1621
  //#endregion
1475
1622
  //#region src/init.ts
1476
- const HOSTS = [
1477
- {
1478
- name: "nuxt",
1479
- dep: "nuxt",
1480
- pkg: "@verbaly/nuxt",
1481
- wire: "add '@verbaly/nuxt' to the modules in nuxt.config"
1482
- },
1483
- {
1484
- name: "next",
1485
- dep: "next",
1486
- pkg: "@verbaly/next",
1487
- wire: "wrap the export of next.config with withVerbaly"
1488
- },
1489
- {
1490
- name: "sveltekit",
1491
- dep: "@sveltejs/kit",
1492
- pkg: "@verbaly/vite",
1493
- wire: "add verbaly() to the plugins in vite.config (per-request locale: @verbaly/sveltekit)"
1494
- },
1495
- {
1496
- name: "astro",
1497
- dep: "astro",
1498
- pkg: "@verbaly/astro",
1499
- wire: "add verbaly() to the integrations in astro.config"
1500
- },
1501
- {
1502
- name: "vite",
1503
- dep: "vite",
1504
- pkg: "@verbaly/vite",
1505
- wire: "add verbaly() to the plugins in vite.config"
1506
- },
1507
- {
1508
- name: "webpack",
1509
- dep: "webpack",
1510
- pkg: "@verbaly/unplugin",
1511
- wire: "add the verbaly webpack plugin to your build config"
1512
- },
1513
- {
1514
- name: "rspack",
1515
- dep: "@rspack/core",
1516
- pkg: "@verbaly/unplugin",
1517
- wire: "add the verbaly rspack plugin to your build config"
1518
- },
1519
- {
1520
- name: "rollup",
1521
- dep: "rollup",
1522
- pkg: "@verbaly/unplugin",
1523
- wire: "add the verbaly rollup plugin to your build config"
1524
- },
1525
- {
1526
- name: "esbuild",
1527
- dep: "esbuild",
1528
- pkg: "@verbaly/unplugin",
1529
- wire: "add the verbaly esbuild plugin to your build config"
1530
- }
1531
- ];
1532
- const WIRING_PACKAGES = [...new Set(HOSTS.map((host) => host.pkg))];
1533
- function readDependencies(root) {
1534
- const path = join(root, "package.json");
1535
- if (!existsSync(path)) return {};
1536
- try {
1537
- const pkg = JSON.parse(readFileSync(path, "utf8"));
1538
- return {
1539
- ...pkg.dependencies,
1540
- ...pkg.devDependencies
1541
- };
1542
- } catch {
1543
- return {};
1544
- }
1545
- }
1546
1623
  function cliReachable(root) {
1547
1624
  const bin = join(root, "node_modules", ".bin");
1548
1625
  return existsSync(join(bin, "verbaly")) || existsSync(join(bin, "verbaly.CMD"));
1549
1626
  }
1550
1627
  const CLI_INSTALL_FIX = "add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves";
1551
- function detectHost(root) {
1552
- const deps = readDependencies(root);
1553
- return HOSTS.find((host) => deps[host.dep]);
1554
- }
1555
1628
  function configSource(options, typescript) {
1556
1629
  const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
1557
1630
  if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
@@ -1618,7 +1691,7 @@ async function init(input = {}) {
1618
1691
  }
1619
1692
  }
1620
1693
  const host = detectHost(root);
1621
- const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1694
+ const next = host ? [installCommand(root, host.install), host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1622
1695
  return {
1623
1696
  created,
1624
1697
  skipped,
@@ -1665,10 +1738,10 @@ function readState(cfg) {
1665
1738
  }
1666
1739
  }
1667
1740
  function saveState(cfg, state) {
1668
- const serialized = serializeState(state);
1741
+ const fresh = serializeState(state);
1669
1742
  const path = statePath(cfg);
1670
1743
  const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);
1671
- if (serialized === void 0) {
1744
+ if (fresh === void 0) {
1672
1745
  rmSync(path, { force: true });
1673
1746
  rmSync(legacy, { force: true });
1674
1747
  return;
@@ -1679,6 +1752,7 @@ function saveState(cfg, state) {
1679
1752
  } catch {
1680
1753
  mkdirSync(cfg.dir, { recursive: true });
1681
1754
  }
1755
+ const serialized = withLineEndings(fresh, existing);
1682
1756
  if (existing !== serialized) writeFileSync(path, serialized);
1683
1757
  if (existsSync(legacy)) rmSync(legacy);
1684
1758
  }
@@ -1791,7 +1865,7 @@ function outdatedTranslations(cfg, catalogs, fingerprints) {
1791
1865
  });
1792
1866
  }
1793
1867
  }
1794
- return out.sort((a, b) => a.locale.localeCompare(b.locale) || a.key.localeCompare(b.key));
1868
+ return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));
1795
1869
  }
1796
1870
  function acceptOutdated(cfg, catalogs, fingerprints, entries) {
1797
1871
  const source = catalogs[cfg.sourceLocale] ?? {};
@@ -2063,39 +2137,6 @@ function escapeProperty(text) {
2063
2137
  return escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
2064
2138
  }
2065
2139
  //#endregion
2066
- //#region src/bundle.ts
2067
- function isExcluded(key, prefixes) {
2068
- return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
2069
- }
2070
- function auditBundle(cfg, catalogs, registry) {
2071
- const prefixes = cfg.bundle.exclude ?? [];
2072
- if (prefixes.length === 0) return [];
2073
- const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
2074
- const used = registry.usedKeys();
2075
- const issues = [];
2076
- for (const prefix of prefixes) {
2077
- if (!source.some((key) => isExcluded(key, [prefix]))) {
2078
- issues.push({
2079
- prefix,
2080
- problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
2081
- fix: "check the spelling against your catalog, or drop it from bundle.exclude"
2082
- });
2083
- continue;
2084
- }
2085
- const files = /* @__PURE__ */ new Set();
2086
- for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
2087
- if (files.size > 0) issues.push({
2088
- prefix,
2089
- problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
2090
- fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
2091
- });
2092
- }
2093
- return issues;
2094
- }
2095
- function formatBundleIssue(issue) {
2096
- return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
2097
- }
2098
- //#endregion
2099
2140
  //#region src/params.ts
2100
2141
  const NUMBER_FORMATS = /* @__PURE__ */ new Set([
2101
2142
  "number",
@@ -2138,9 +2179,79 @@ function renderParamType(types) {
2138
2179
  ]) members.add(m);
2139
2180
  return [...members].join(" | ");
2140
2181
  }
2182
+ //#endregion
2183
+ //#region src/tsconfig.ts
2184
+ function readTsconfig(root) {
2185
+ const path = join(root, "tsconfig.json");
2186
+ let text;
2187
+ try {
2188
+ text = readFileSync(path, "utf8");
2189
+ } catch {
2190
+ return "no-tsconfig";
2191
+ }
2192
+ const errors = [];
2193
+ const json = parse$2(text, errors, { allowTrailingComma: true });
2194
+ if (errors.length > 0 || typeof json !== "object" || json === null || Array.isArray(json)) return "unreadable";
2195
+ return {
2196
+ path,
2197
+ text,
2198
+ json
2199
+ };
2200
+ }
2201
+ function covered(list, entry) {
2202
+ if (!Array.isArray(list)) return false;
2203
+ return list.some((item) => {
2204
+ if (typeof item !== "string") return false;
2205
+ const pattern = item.replace(/^\.\//, "").replace(/\/+$/, "");
2206
+ return picomatch(pattern)(entry) || picomatch(`${pattern}/**/*`)(entry);
2207
+ });
2208
+ }
2209
+ function formatting(text) {
2210
+ const indent = /\n([ \t]+)\S/.exec(text)?.[1] ?? " ";
2211
+ return {
2212
+ insertSpaces: !indent.startsWith(" "),
2213
+ tabSize: indent.startsWith(" ") ? 1 : indent.length,
2214
+ eol: text.includes("\r\n") ? "\r\n" : "\n"
2215
+ };
2216
+ }
2217
+ function typesIncluded(root, file) {
2218
+ const read = readTsconfig(root);
2219
+ if (typeof read === "string") return read;
2220
+ const entry = relative(root, file).replaceAll("\\", "/");
2221
+ const { include, files } = read.json;
2222
+ if (covered(include, entry) || covered(files, entry)) return "present";
2223
+ return "missing";
2224
+ }
2225
+ function includeTypes(root, file) {
2226
+ const read = readTsconfig(root);
2227
+ if (typeof read === "string") return read;
2228
+ const entry = relative(root, file).replaceAll("\\", "/");
2229
+ const { include, files } = read.json;
2230
+ if (covered(include, entry) || covered(files, entry)) return "present";
2231
+ const options = { formattingOptions: formatting(read.text) };
2232
+ const edits = Array.isArray(include) ? modify(read.text, ["include", -1], entry, {
2233
+ ...options,
2234
+ isArrayInsertion: true
2235
+ }) : Array.isArray(files) && include === void 0 ? modify(read.text, ["files", -1], entry, {
2236
+ ...options,
2237
+ isArrayInsertion: true
2238
+ }) : modify(read.text, ["include"], ["**/*", entry], options);
2239
+ writeFileSync(read.path, applyEdits(read.text, edits));
2240
+ return "added";
2241
+ }
2242
+ //#endregion
2243
+ //#region src/warn.ts
2244
+ const warned = /* @__PURE__ */ new Set();
2245
+ function warnOnce(message, dedupeKey = message) {
2246
+ if (warned.has(dedupeKey)) return;
2247
+ warned.add(dedupeKey);
2248
+ console.warn(`[verbaly] ${message}`);
2249
+ }
2250
+ const DTS_HEADER = "// generated by verbaly: do not edit";
2141
2251
  function generateDts(catalog, options = {}) {
2142
2252
  const lines = [];
2143
- for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
2253
+ const locales = options.locales?.length ? [...options.locales].sort(byCodeUnit).map((locale) => JSON.stringify(locale)).join(" | ") : "string";
2254
+ for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => byCodeUnit(a, b))) {
2144
2255
  const params = collectParams(message);
2145
2256
  if (params.size === 0) lines.push(` ${JSON.stringify(key)}: never;`);
2146
2257
  else {
@@ -2148,19 +2259,20 @@ function generateDts(catalog, options = {}) {
2148
2259
  lines.push(` ${JSON.stringify(key)}: { ${fields} };`);
2149
2260
  }
2150
2261
  }
2151
- return `// generated by verbaly: do not edit
2262
+ return `${DTS_HEADER}
2152
2263
  declare module 'virtual:verbaly' {
2153
2264
  export interface VerbalyMessages {
2154
2265
  ${lines.join("\n")}
2155
2266
  }
2156
2267
  export type VerbalyKey = keyof VerbalyMessages & string;
2268
+ export type VerbalyLocale = ${locales};
2157
2269
 
2158
2270
  export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };
2159
2271
  export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;
2160
2272
 
2161
- export const verbaly: import('verbaly').Verbaly<VerbalyKey>;
2273
+ export const verbaly: import('verbaly').Verbaly;
2162
2274
 
2163
- export const sourceLocale: string;
2275
+ export const sourceLocale: VerbalyLocale;
2164
2276
  export const locales: string[];
2165
2277
  export const routing: import('verbaly').Routing;
2166
2278
  export function localePath(
@@ -2173,17 +2285,16 @@ ${lines.join("\n")}
2173
2285
  }): string | undefined;
2174
2286
  export function loadMessages(locale: string): Promise<Record<string, string>>;${options.inlineCatalog ? "\n export function adoptPage(options?: {\n root?: ParentNode;\n path?: string;\n }): string | undefined;" : ""}
2175
2287
  export function createInstance(
2176
- options?: import('verbaly').VerbalyOptions<VerbalyKey>,
2177
- ): import('verbaly').Verbaly<VerbalyKey>;
2178
- export function createRequestInstance(
2179
- locale: string,
2180
- ): Promise<import('verbaly').Verbaly<VerbalyKey>>;
2288
+ options?: import('verbaly').VerbalyOptions,
2289
+ ): import('verbaly').Verbaly;
2290
+ export function createRequestInstance(locale: string): Promise<import('verbaly').Verbaly>;
2181
2291
 
2182
- export function t<K extends VerbalyKey>(
2183
- key: K,
2184
- ...args: [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
2292
+ export function t<K extends VerbalyKey | TemplateStringsArray>(
2293
+ first: K,
2294
+ ...rest: K extends VerbalyKey
2295
+ ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]
2296
+ : unknown[]
2185
2297
  ): string;
2186
- export function t(strings: TemplateStringsArray, ...values: unknown[]): string;
2187
2298
  export namespace t {
2188
2299
  export function id(
2189
2300
  key: string,
@@ -2200,6 +2311,14 @@ ${lines.join("\n")}
2200
2311
  ): Promise<void>;
2201
2312
  export function getLocale(): string;
2202
2313
  export function subscribe(listener: () => void): () => void;
2314
+
2315
+ // nested, so it augments verbaly: at the top of a script it would replace the real module
2316
+ module 'verbaly' {
2317
+ interface Register {
2318
+ t: typeof t;
2319
+ locale: VerbalyLocale;
2320
+ }
2321
+ }
2203
2322
  }
2204
2323
 
2205
2324
  declare module 'virtual:verbaly/locale/*' {
@@ -2208,16 +2327,137 @@ declare module 'virtual:verbaly/locale/*' {
2208
2327
  }
2209
2328
  `;
2210
2329
  }
2330
+ function projectDtsOptions(cfg) {
2331
+ return {
2332
+ inlineCatalog: cfg.render.inlineCatalog === true,
2333
+ locales: cfg.locales
2334
+ };
2335
+ }
2211
2336
  function writeDts(cfg, catalog, file) {
2212
2337
  const target = file === void 0 ? cfg.dts : file;
2213
- if (target === false) return;
2214
- file = target ?? join(cfg.root, "verbaly.d.ts");
2215
- const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
2338
+ if (target === false) return void 0;
2339
+ let existing;
2216
2340
  try {
2217
- if (readFileSync(file, "utf8") === content) return;
2341
+ existing = readFileSync(target, "utf8");
2218
2342
  } catch {}
2219
- mkdirSync(dirname(file), { recursive: true });
2220
- writeFileSync(file, content);
2343
+ const content = withLineEndings(generateDts(catalog, projectDtsOptions(cfg)), existing);
2344
+ const changed = existing !== content;
2345
+ if (changed) {
2346
+ mkdirSync(dirname(target), { recursive: true });
2347
+ writeFileSync(target, content);
2348
+ }
2349
+ removeRootDts(cfg, target);
2350
+ if (resolve(target).startsWith(resolve(cfg.root, ".verbaly") + sep)) {
2351
+ const ignore = join(cfg.root, ".verbaly", ".gitignore");
2352
+ if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
2353
+ const state = includeTypes(cfg.root, target);
2354
+ const entry = relative(cfg.root, target).replaceAll("\\", "/");
2355
+ if (state === "added") warnOnce(`added "${entry}" to the include of tsconfig.json, so TypeScript reads the types`);
2356
+ else if (state === "unreadable") warnOnce(`tsconfig.json could not be read, so add "${entry}" to its include yourself`);
2357
+ }
2358
+ return {
2359
+ file: target,
2360
+ changed
2361
+ };
2362
+ }
2363
+ function removeRootDts(cfg, target) {
2364
+ const old = join(cfg.root, "verbaly.d.ts");
2365
+ if (resolve(target) === resolve(old)) return;
2366
+ let head;
2367
+ try {
2368
+ head = readFileSync(old, "utf8").slice(0, 36);
2369
+ } catch {
2370
+ return;
2371
+ }
2372
+ if (head !== "// generated by verbaly: do not edit") return;
2373
+ rmSync(old);
2374
+ warnOnce(`the types live in ${relative(cfg.root, target).replaceAll("\\", "/")} now, so the verbaly.d.ts Verbaly wrote at the root was removed`);
2375
+ }
2376
+ //#endregion
2377
+ //#region src/bundle.ts
2378
+ function isExcluded(key, prefixes) {
2379
+ return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));
2380
+ }
2381
+ function auditBundle(cfg, catalogs, registry) {
2382
+ const prefixes = cfg.bundle.exclude ?? [];
2383
+ if (prefixes.length === 0) return [];
2384
+ const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});
2385
+ const used = registry.usedKeys();
2386
+ const issues = [];
2387
+ for (const prefix of prefixes) {
2388
+ if (!source.some((key) => isExcluded(key, [prefix]))) {
2389
+ issues.push({
2390
+ prefix,
2391
+ problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,
2392
+ fix: "check the spelling against your catalog, or drop it from bundle.exclude"
2393
+ });
2394
+ continue;
2395
+ }
2396
+ const files = /* @__PURE__ */ new Set();
2397
+ for (const [key, where] of used) if (isExcluded(key, [prefix])) for (const file of where) files.add(file);
2398
+ if (files.size > 0) issues.push({
2399
+ prefix,
2400
+ problem: `is read by t() in ${counted(files.size, "file")}, where it resolves to the key itself`,
2401
+ fix: "pre-render those pages with render, load the group with addMessages, or stop excluding it"
2402
+ });
2403
+ }
2404
+ return issues;
2405
+ }
2406
+ function formatBundleIssue(issue) {
2407
+ return `bundle.exclude "${issue.prefix}" ${issue.problem}`;
2408
+ }
2409
+ //#endregion
2410
+ //#region src/scope.ts
2411
+ const TAGGED_HINT = /(?<![\w$.])\$?t(?:\.id\s*\([^)]*\))?\s*`/;
2412
+ const NOT_SOURCE = [
2413
+ "**/node_modules/**",
2414
+ "**/dist/**",
2415
+ "**/build/**",
2416
+ "**/out/**",
2417
+ "**/coverage/**"
2418
+ ];
2419
+ function relativeId(cfg, id) {
2420
+ return relative(cfg.root, id).replaceAll("\\", "/");
2421
+ }
2422
+ function suggestedPattern(rel) {
2423
+ const slash = rel.indexOf("/");
2424
+ return slash < 0 ? rel : `${rel.slice(0, slash)}/**/*.${SOURCE_EXTENSIONS}`;
2425
+ }
2426
+ function createOutsideCheck(cfg) {
2427
+ if (cfg.include.length === 0) return () => void 0;
2428
+ const included = picomatch(cfg.include);
2429
+ const excluded = picomatch(cfg.exclude);
2430
+ return (code, id) => {
2431
+ const rel = relativeId(cfg, id);
2432
+ if (rel.startsWith("..") || included(rel) || excluded(rel)) return void 0;
2433
+ if (!TAGGED_HINT.test(code)) return void 0;
2434
+ if (analyzeFile(code, id).tagged.length === 0) return void 0;
2435
+ return {
2436
+ file: id,
2437
+ pattern: suggestedPattern(rel)
2438
+ };
2439
+ };
2440
+ }
2441
+ async function filesOutsideInclude(cfg) {
2442
+ if (cfg.include.length === 0) return [];
2443
+ const check = createOutsideCheck(cfg);
2444
+ const files = await glob([`**/*.${SOURCE_EXTENSIONS}`], {
2445
+ cwd: cfg.root,
2446
+ ignore: [...NOT_SOURCE, ...cfg.exclude],
2447
+ absolute: true
2448
+ });
2449
+ const found = [];
2450
+ for (const file of files.sort()) {
2451
+ let code;
2452
+ try {
2453
+ code = readFileSync(file, "utf8");
2454
+ } catch {
2455
+ continue;
2456
+ }
2457
+ const outside = check(code, file);
2458
+ if (outside) found.push(outside);
2459
+ }
2460
+ return found;
2221
2461
  }
2222
2462
  //#endregion
2223
2463
  //#region src/doctor.ts
@@ -2324,14 +2564,23 @@ async function doctor(cfg) {
2324
2564
  const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
2325
2565
  if (!host) ok("plugin", "no framework or bundler detected, the CLI flow (extract/check) applies");
2326
2566
  else if (installed) ok("plugin", `${installed} installed for ${host.name}`);
2327
- else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `pnpm add -D ${host.pkg} and ${host.wire}`);
2567
+ else warn("plugin", `${host.name} detected but ${host.pkg} is not installed`, `${installCommand(cfg.root, host.install)}, then ${host.wire}`);
2328
2568
  const scanning = cfg.include.length > 0;
2329
2569
  if (!scanning) ok("sources", "source scanning is off (include: []), the catalogs are the source of truth");
2330
2570
  if (source && scanning && cfg.dts !== false) {
2331
- const dtsPath = cfg.dts ?? join(cfg.root, "verbaly.d.ts");
2332
- if (!existsSync(dtsPath)) warn("types", "verbaly.d.ts has not been generated", "run `npx verbaly extract`");
2333
- else if (readFileSync(dtsPath, "utf8") !== generateDts(source, { inlineCatalog: cfg.render.inlineCatalog === true })) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
2334
- else ok("types", "verbaly.d.ts is up to date");
2571
+ const dtsPath = cfg.dts;
2572
+ const shown = rel(dtsPath);
2573
+ 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`";
2574
+ const expected = generateDts(source, projectDtsOptions(cfg));
2575
+ if (!existsSync(dtsPath)) warn("types", `${shown} has not been generated`, regenerate);
2576
+ else if (readFileSync(dtsPath, "utf8").replace(/\r\n/g, "\n") !== expected) warn("types", `${shown} is stale`, "run `npx verbaly typegen`");
2577
+ else ok("types", `${shown} is up to date`);
2578
+ if (dtsPath.startsWith(join(cfg.root, ".verbaly"))) {
2579
+ const state = typesIncluded(cfg.root, dtsPath);
2580
+ 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`);
2581
+ }
2582
+ const old = join(cfg.root, "verbaly.d.ts");
2583
+ 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");
2335
2584
  }
2336
2585
  const registry = await extractProject(cfg);
2337
2586
  if (scanning) {
@@ -2340,6 +2589,12 @@ async function doctor(cfg) {
2340
2589
  const first = unreadable[0];
2341
2590
  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");
2342
2591
  }
2592
+ const outside = await filesOutsideInclude(cfg);
2593
+ if (outside.length > 0) {
2594
+ const files = outside.map((entry) => rel(entry.file));
2595
+ const patterns = [...new Set(outside.map((entry) => `"${entry.pattern}"`))];
2596
+ 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`);
2597
+ }
2343
2598
  const stray = registry.strayImports();
2344
2599
  if (stray.length > 0) {
2345
2600
  const files = [...new Set(stray.map((entry) => rel(entry.file)))];
@@ -2886,11 +3141,11 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
2886
3141
  });
2887
3142
  for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
2888
3143
  for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
2889
- result.failed.sort((a, b) => a.locale.localeCompare(b.locale) || compare(a.keys, b.keys));
3144
+ result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));
2890
3145
  return result;
2891
3146
  }
2892
3147
  function compare(a, b) {
2893
- return (a[0] ?? "").localeCompare(b[0] ?? "");
3148
+ return byCodeUnit(a[0] ?? "", b[0] ?? "");
2894
3149
  }
2895
3150
  function mergeTranslations(cfg, locale, translated, keys) {
2896
3151
  const source = readCatalog(cfg, cfg.sourceLocale);
@@ -3424,14 +3679,6 @@ function confirmFromDisk(cfg, catalogs, registry) {
3424
3679
  }
3425
3680
  }
3426
3681
  //#endregion
3427
- //#region src/warn.ts
3428
- const warned = /* @__PURE__ */ new Set();
3429
- function warnOnce(message, dedupeKey = message) {
3430
- if (warned.has(dedupeKey)) return;
3431
- warned.add(dedupeKey);
3432
- console.warn(`[verbaly] ${message}`);
3433
- }
3434
- //#endregion
3435
3682
  //#region src/render.ts
3436
3683
  function localeInstance(catalogs, locale, sourceLocale) {
3437
3684
  return createVerbaly({
@@ -3710,7 +3957,7 @@ async function renderSite(cfg, options = {}) {
3710
3957
  base,
3711
3958
  storageKey: redirect.storageKey
3712
3959
  };
3713
- const catalogs = loadCatalogs(cfg);
3960
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg));
3714
3961
  const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
3715
3962
  if (clean) {
3716
3963
  for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
@@ -4304,6 +4551,7 @@ Usage:
4304
4551
  verbaly wrap find hardcoded JSX text and wrap it in t\`…\` (report; --write applies)
4305
4552
  verbaly migrate port catalogs from another i18n library (report; --write applies)
4306
4553
  verbaly extract scan sources, update catalogs and types
4554
+ verbaly typegen write the TypeScript types only (CI: run it before tsc)
4307
4555
  verbaly status translation coverage per locale, at a glance
4308
4556
  verbaly check verify translations are complete (CI)
4309
4557
  verbaly translate fill missing translations via a provider (default: claude)
@@ -4465,6 +4713,19 @@ async function runCli(args = process.argv.slice(2)) {
4465
4713
  }
4466
4714
  return;
4467
4715
  }
4716
+ if (command === "typegen") {
4717
+ const registry = await extractProject(cfg);
4718
+ const source = shippedCatalogs(cfg, loadCatalogs(cfg), registry)[cfg.sourceLocale] ?? {};
4719
+ const written = writeDts(cfg, source);
4720
+ if (!written) {
4721
+ console.log("[verbaly] no types written: dts is false in your verbaly config");
4722
+ return;
4723
+ }
4724
+ const where = relative(cfg.root, written.file).replaceAll("\\", "/");
4725
+ const how = written.changed ? "written to" : "up to date in";
4726
+ console.log(`[verbaly] types ${how} ${where} (${counted(Object.keys(source).length, "message")})`);
4727
+ return;
4728
+ }
4468
4729
  if (command === "migrate") {
4469
4730
  const result = migrateCatalogs(cfg, {
4470
4731
  write: values.write,
@@ -4760,7 +5021,7 @@ async function runCli(args = process.argv.slice(2)) {
4760
5021
  return;
4761
5022
  }
4762
5023
  if (command === "pseudo") {
4763
- const catalogs = loadCatalogs(cfg);
5024
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg), { newKeys: false });
4764
5025
  const locale = values.locale ?? "en-XA";
4765
5026
  const keys = pseudoCatalogs(cfg, catalogs, locale);
4766
5027
  writeCatalog(cfg, locale, catalogs[locale] ?? {});
@@ -4812,6 +5073,7 @@ const COMMAND_FLAGS = {
4812
5073
  "dry-run",
4813
5074
  "watch"
4814
5075
  ],
5076
+ typegen: [],
4815
5077
  wrap: ["write"],
4816
5078
  migrate: ["write", "plurals"],
4817
5079
  status: ["json"],