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