@verbaly/compiler 0.37.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 +24 -4
- 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 +271 -86
- 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 +68 -1
- package/dist/index.js +648 -53
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
- 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,10 +1,10 @@
|
|
|
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
|
+
import { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
|
|
4
5
|
import { glob } from "tinyglobby";
|
|
5
|
-
import { parse } from "@babel/parser";
|
|
6
|
+
import { parse as parse$1 } from "@babel/parser";
|
|
6
7
|
import { createHash } from "node:crypto";
|
|
7
|
-
import { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse as parse$1, parseTags, safeAttribute } from "verbaly";
|
|
8
8
|
import picomatch from "picomatch";
|
|
9
9
|
import MagicString from "magic-string";
|
|
10
10
|
//#region src/catalog.ts
|
|
@@ -12,16 +12,37 @@ function catalogPath(cfg, locale) {
|
|
|
12
12
|
return join(cfg.dir, `${locale}.json`);
|
|
13
13
|
}
|
|
14
14
|
function readCatalog(cfg, locale) {
|
|
15
|
+
const tree = readTree(cfg, locale);
|
|
16
|
+
const bad = badLeaf(tree);
|
|
17
|
+
if (bad) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} has a non-string value at "${bad}", catalog values are text (groups of text are fine): fix the value`);
|
|
18
|
+
return flatten(tree);
|
|
19
|
+
}
|
|
20
|
+
function badLeaf(tree, prefix = "") {
|
|
21
|
+
for (const [key, value] of Object.entries(tree)) {
|
|
22
|
+
const path = prefix ? `${prefix}.${key}` : key;
|
|
23
|
+
if (typeof value === "string") continue;
|
|
24
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return path;
|
|
25
|
+
const bad = badLeaf(value, path);
|
|
26
|
+
if (bad) return bad;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function readTree(cfg, locale) {
|
|
15
30
|
let content;
|
|
16
31
|
try {
|
|
17
32
|
content = readFileSync(catalogPath(cfg, locale), "utf8");
|
|
18
33
|
} catch {
|
|
19
34
|
return {};
|
|
20
35
|
}
|
|
36
|
+
const parsed = parseTree(content);
|
|
37
|
+
if (parsed) return parsed;
|
|
38
|
+
throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`);
|
|
39
|
+
}
|
|
40
|
+
function parseTree(content) {
|
|
41
|
+
const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
21
42
|
try {
|
|
22
|
-
return JSON.parse(
|
|
23
|
-
} catch
|
|
24
|
-
|
|
43
|
+
return JSON.parse(body);
|
|
44
|
+
} catch {
|
|
45
|
+
return;
|
|
25
46
|
}
|
|
26
47
|
}
|
|
27
48
|
function loadCatalogs(cfg) {
|
|
@@ -29,25 +50,68 @@ function loadCatalogs(cfg) {
|
|
|
29
50
|
for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
|
|
30
51
|
return catalogs;
|
|
31
52
|
}
|
|
32
|
-
function
|
|
53
|
+
function isNested(tree) {
|
|
54
|
+
return Object.values(tree).some((value) => typeof value === "object" && value !== null);
|
|
55
|
+
}
|
|
56
|
+
function nest(catalog) {
|
|
57
|
+
const tree = {};
|
|
58
|
+
for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
|
|
59
|
+
const parts = key.split(".");
|
|
60
|
+
const leaf = parts[parts.length - 1];
|
|
61
|
+
let node = parts.length > 1 ? tree : void 0;
|
|
62
|
+
for (let i = 0; node && i < parts.length - 1; i++) {
|
|
63
|
+
const next = node[parts[i]] ??= {};
|
|
64
|
+
node = typeof next === "object" && next !== null ? next : void 0;
|
|
65
|
+
}
|
|
66
|
+
if (node && typeof node[leaf] !== "object") node[leaf] = message;
|
|
67
|
+
else tree[key] = message;
|
|
68
|
+
}
|
|
69
|
+
return tree;
|
|
70
|
+
}
|
|
71
|
+
function sortTree(tree) {
|
|
33
72
|
const sorted = {};
|
|
34
|
-
for (const key of Object.keys(
|
|
35
|
-
const value =
|
|
36
|
-
if (value
|
|
73
|
+
for (const key of Object.keys(tree).sort()) {
|
|
74
|
+
const value = tree[key];
|
|
75
|
+
if (typeof value === "string") sorted[key] = value;
|
|
76
|
+
else if (value !== void 0) sorted[key] = sortTree(value);
|
|
37
77
|
}
|
|
38
|
-
return
|
|
78
|
+
return sorted;
|
|
79
|
+
}
|
|
80
|
+
function serializeCatalog(catalog, nested = false) {
|
|
81
|
+
return JSON.stringify(sortTree(nested ? nest(catalog) : catalog), null, 2) + "\n";
|
|
39
82
|
}
|
|
40
83
|
function writeCatalog(cfg, locale, catalog) {
|
|
41
|
-
const serialized = serializeCatalog(catalog);
|
|
42
84
|
const path = catalogPath(cfg, locale);
|
|
85
|
+
let existing;
|
|
43
86
|
try {
|
|
44
|
-
|
|
87
|
+
existing = readFileSync(path, "utf8");
|
|
45
88
|
} catch {
|
|
46
89
|
mkdirSync(cfg.dir, { recursive: true });
|
|
47
90
|
}
|
|
91
|
+
const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing));
|
|
92
|
+
if (existing === serialized) return serialized;
|
|
48
93
|
writeFileSync(path, serialized);
|
|
49
94
|
return serialized;
|
|
50
95
|
}
|
|
96
|
+
function wantsNesting(cfg, locale, existing) {
|
|
97
|
+
if (existing !== void 0) {
|
|
98
|
+
const tree = parseTree(existing);
|
|
99
|
+
return tree !== void 0 && isNested(tree);
|
|
100
|
+
}
|
|
101
|
+
if (locale === cfg.sourceLocale) return false;
|
|
102
|
+
return isNested(readTree(cfg, cfg.sourceLocale));
|
|
103
|
+
}
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/warn.ts
|
|
106
|
+
const warned = /* @__PURE__ */ new Set();
|
|
107
|
+
function warnOnce(message, dedupeKey = message) {
|
|
108
|
+
if (warned.has(dedupeKey)) return;
|
|
109
|
+
warned.add(dedupeKey);
|
|
110
|
+
console.warn(`[verbaly] ${message}`);
|
|
111
|
+
}
|
|
112
|
+
function warnParseError(file, message) {
|
|
113
|
+
warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);
|
|
114
|
+
}
|
|
51
115
|
//#endregion
|
|
52
116
|
//#region src/registry.ts
|
|
53
117
|
var MessageRegistry = class {
|
|
@@ -63,7 +127,7 @@ var MessageRegistry = class {
|
|
|
63
127
|
for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
|
|
64
128
|
const existing = out.get(msg.key);
|
|
65
129
|
if (existing) {
|
|
66
|
-
if (existing.message !== msg.message)
|
|
130
|
+
if (existing.message !== msg.message) warnOnce(`key collision "${msg.key}": ${JSON.stringify(existing.message)} vs ${JSON.stringify(msg.message)}, second dropped`, `collision:${msg.key}`);
|
|
67
131
|
continue;
|
|
68
132
|
}
|
|
69
133
|
out.set(msg.key, msg);
|
|
@@ -121,7 +185,7 @@ const DEFAULT_T_NAMES = ["t"];
|
|
|
121
185
|
const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
|
|
122
186
|
function analyze(code, file, options = {}) {
|
|
123
187
|
const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
|
|
124
|
-
const ast = parse(code, {
|
|
188
|
+
const ast = parse$1(code, {
|
|
125
189
|
sourceType: "module",
|
|
126
190
|
errorRecovery: true,
|
|
127
191
|
plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
|
|
@@ -606,7 +670,7 @@ const PLURAL_CATEGORIES = /* @__PURE__ */ new Set([
|
|
|
606
670
|
const EXACT = /^=\d+$/;
|
|
607
671
|
function shapes(message) {
|
|
608
672
|
const out = /* @__PURE__ */ new Map();
|
|
609
|
-
walk(parse
|
|
673
|
+
walk(parse(message), out);
|
|
610
674
|
return out;
|
|
611
675
|
}
|
|
612
676
|
function walk(nodes, out) {
|
|
@@ -623,7 +687,7 @@ function walk(nodes, out) {
|
|
|
623
687
|
}
|
|
624
688
|
function paramNames(message) {
|
|
625
689
|
const names = /* @__PURE__ */ new Set();
|
|
626
|
-
collect(parse
|
|
690
|
+
collect(parse(message), names);
|
|
627
691
|
return [...names].sort();
|
|
628
692
|
}
|
|
629
693
|
function collect(nodes, out) {
|
|
@@ -657,6 +721,10 @@ function surplus(a, b) {
|
|
|
657
721
|
function list(items) {
|
|
658
722
|
return items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}` : items[0];
|
|
659
723
|
}
|
|
724
|
+
const ESCAPED_SYNTAX = /(?<!\{)\{\{\s*[\w.]+\s*[|:][^{}]*\}\}/;
|
|
725
|
+
function escapedSyntax(message) {
|
|
726
|
+
return ESCAPED_SYNTAX.exec(message)?.[0];
|
|
727
|
+
}
|
|
660
728
|
function validateMessage(message, locale) {
|
|
661
729
|
const issues = [];
|
|
662
730
|
for (const [name, shape] of shapes(message)) {
|
|
@@ -763,7 +831,7 @@ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
|
|
|
763
831
|
const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
|
|
764
832
|
function collectParams(message) {
|
|
765
833
|
const out = /* @__PURE__ */ new Map();
|
|
766
|
-
visit(parse
|
|
834
|
+
visit(parse(message), out);
|
|
767
835
|
return out;
|
|
768
836
|
}
|
|
769
837
|
function visit(nodes, out) {
|
|
@@ -1013,15 +1081,6 @@ function truncate(text, max) {
|
|
|
1013
1081
|
return text.length > max ? text.slice(0, max - 1) + "…" : text;
|
|
1014
1082
|
}
|
|
1015
1083
|
//#endregion
|
|
1016
|
-
//#region src/warn.ts
|
|
1017
|
-
const warned = /* @__PURE__ */ new Set();
|
|
1018
|
-
function warnParseError(file, message) {
|
|
1019
|
-
const line = `[verbaly] ${file}: could not be parsed (${message}), its messages were not extracted`;
|
|
1020
|
-
if (warned.has(line)) return;
|
|
1021
|
-
warned.add(line);
|
|
1022
|
-
console.warn(line);
|
|
1023
|
-
}
|
|
1024
|
-
//#endregion
|
|
1025
1084
|
//#region src/transform.ts
|
|
1026
1085
|
function quote(text, single) {
|
|
1027
1086
|
if (!single) return JSON.stringify(text);
|
|
@@ -1146,6 +1205,11 @@ function effectiveDrafts(drafts, catalogs) {
|
|
|
1146
1205
|
return out;
|
|
1147
1206
|
}
|
|
1148
1207
|
//#endregion
|
|
1208
|
+
//#region src/text.ts
|
|
1209
|
+
function counted(count, noun, many = `${noun}s`) {
|
|
1210
|
+
return `${count} ${count === 1 ? noun : many}`;
|
|
1211
|
+
}
|
|
1212
|
+
//#endregion
|
|
1149
1213
|
//#region src/status.ts
|
|
1150
1214
|
function status(cfg, catalogs, registry, drafts = {}) {
|
|
1151
1215
|
const extracted = registry.messages();
|
|
@@ -1181,7 +1245,7 @@ function status(cfg, catalogs, registry, drafts = {}) {
|
|
|
1181
1245
|
};
|
|
1182
1246
|
}
|
|
1183
1247
|
function formatStatusResult(result) {
|
|
1184
|
-
const lines = [`[verbaly] ${result.messages}
|
|
1248
|
+
const lines = [`[verbaly] ${counted(result.messages, "message")} · source: ${result.source}`];
|
|
1185
1249
|
if (result.locales.length === 0) {
|
|
1186
1250
|
lines.push(" no target locales (add locales to your config)");
|
|
1187
1251
|
return lines.join("\n");
|
|
@@ -1197,15 +1261,56 @@ function formatStatusResult(result) {
|
|
|
1197
1261
|
}
|
|
1198
1262
|
//#endregion
|
|
1199
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
|
+
}
|
|
1200
1300
|
async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
1201
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;
|
|
1202
1305
|
const targets = targetLocales(cfg, options.locales);
|
|
1203
1306
|
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
1204
1307
|
const result = {
|
|
1205
1308
|
translated: {},
|
|
1206
1309
|
invalid: {},
|
|
1207
|
-
pending: {}
|
|
1310
|
+
pending: {},
|
|
1311
|
+
failed: []
|
|
1208
1312
|
};
|
|
1313
|
+
const jobs = [];
|
|
1209
1314
|
for (const locale of targets) {
|
|
1210
1315
|
const catalog = catalogs[locale] ??= {};
|
|
1211
1316
|
const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
|
|
@@ -1214,31 +1319,78 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
|
1214
1319
|
result.pending[locale] = missing;
|
|
1215
1320
|
continue;
|
|
1216
1321
|
}
|
|
1322
|
+
const batches = Math.ceil(missing.length / batchSize);
|
|
1217
1323
|
for (let i = 0; i < missing.length; i += batchSize) {
|
|
1218
|
-
const
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
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({
|
|
1222
1341
|
sourceLocale: cfg.sourceLocale,
|
|
1223
1342
|
targetLocale: locale,
|
|
1224
1343
|
messages,
|
|
1225
|
-
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
|
|
1226
1354
|
});
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
} else (result.invalid[locale] ??= []).push(key);
|
|
1233
|
-
}
|
|
1355
|
+
options.onProgress?.({
|
|
1356
|
+
...progressOf(job),
|
|
1357
|
+
error: message
|
|
1358
|
+
});
|
|
1359
|
+
return;
|
|
1234
1360
|
}
|
|
1235
|
-
|
|
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));
|
|
1236
1373
|
return result;
|
|
1237
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
|
+
}
|
|
1238
1390
|
async function resolveProvider(cfg, model) {
|
|
1239
1391
|
const configured = cfg.translate.provider;
|
|
1240
1392
|
if (typeof configured === "function") return configured;
|
|
1241
|
-
const { claudeProvider } = await import("./claude-
|
|
1393
|
+
const { claudeProvider } = await import("./claude-0MJOMelz.js");
|
|
1242
1394
|
return claudeProvider({ model: model ?? cfg.translate.model });
|
|
1243
1395
|
}
|
|
1244
1396
|
function structureMatches(source, translated) {
|
|
@@ -1248,8 +1400,452 @@ function structureMatches(source, translated) {
|
|
|
1248
1400
|
return false;
|
|
1249
1401
|
}
|
|
1250
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
|
+
}
|
|
1251
1840
|
//#endregion
|
|
1252
1841
|
//#region src/render.ts
|
|
1842
|
+
function localeInstance(catalogs, locale, sourceLocale) {
|
|
1843
|
+
return createVerbaly({
|
|
1844
|
+
locale,
|
|
1845
|
+
fallback: sourceLocale,
|
|
1846
|
+
messages: catalogs
|
|
1847
|
+
});
|
|
1848
|
+
}
|
|
1253
1849
|
const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
|
|
1254
1850
|
const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
|
|
1255
1851
|
const REDIRECT_OPEN = "<!--verbaly:redirect-->";
|
|
@@ -1266,11 +1862,7 @@ function renderHtml(html, options) {
|
|
|
1266
1862
|
const richTags = new Set(options.richTags ?? RICH_TAGS);
|
|
1267
1863
|
const globalLinks = options.richLinks;
|
|
1268
1864
|
const sourceLocale = options.sourceLocale ?? "en";
|
|
1269
|
-
const v =
|
|
1270
|
-
locale: options.locale,
|
|
1271
|
-
fallback: sourceLocale,
|
|
1272
|
-
messages: options.catalogs
|
|
1273
|
-
});
|
|
1865
|
+
const v = options.instance ?? localeInstance(options.catalogs, options.locale, sourceLocale);
|
|
1274
1866
|
const t = v.t;
|
|
1275
1867
|
const ms = new MagicString(html);
|
|
1276
1868
|
const missing = /* @__PURE__ */ new Set();
|
|
@@ -1325,8 +1917,10 @@ function renderHtml(html, options) {
|
|
|
1325
1917
|
...own
|
|
1326
1918
|
} : own : globalLinks;
|
|
1327
1919
|
const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
|
|
1328
|
-
if (html.slice(openEnd, close.contentEnd) !== content)
|
|
1329
|
-
|
|
1920
|
+
if (html.slice(openEnd, close.contentEnd) !== content) {
|
|
1921
|
+
if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
|
|
1922
|
+
else ms.overwrite(openEnd, close.contentEnd, content);
|
|
1923
|
+
}
|
|
1330
1924
|
filled.push([openEnd, close.contentEnd]);
|
|
1331
1925
|
}
|
|
1332
1926
|
}
|
|
@@ -1437,6 +2031,7 @@ async function renderSite(cfg, options = {}) {
|
|
|
1437
2031
|
storageKey: redirect.storageKey
|
|
1438
2032
|
};
|
|
1439
2033
|
const catalogs = loadCatalogs(cfg);
|
|
2034
|
+
const instances = new Map(locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]));
|
|
1440
2035
|
if (clean) {
|
|
1441
2036
|
for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
|
|
1442
2037
|
recursive: true,
|
|
@@ -1463,7 +2058,7 @@ async function renderSite(cfg, options = {}) {
|
|
|
1463
2058
|
for (const locale of locales) {
|
|
1464
2059
|
const result = renderHtml(html, {
|
|
1465
2060
|
locale,
|
|
1466
|
-
|
|
2061
|
+
instance: instances.get(locale),
|
|
1467
2062
|
sourceLocale: cfg.sourceLocale,
|
|
1468
2063
|
attribute,
|
|
1469
2064
|
richTags: options.richTags,
|
|
@@ -1592,6 +2187,6 @@ function decodeEntities(text) {
|
|
|
1592
2187
|
return text.replace(/"/g, "\"").replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
1593
2188
|
}
|
|
1594
2189
|
//#endregion
|
|
1595
|
-
export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, collectOrigins, 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 };
|
|
1596
2191
|
|
|
1597
2192
|
//# sourceMappingURL=index.js.map
|