@verbaly/compiler 0.64.0 → 0.66.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 +12 -6
- package/dist/{claude-ByRATJ03.js → claude-BmD8W9uW.js} +29 -7
- package/dist/claude-BmD8W9uW.js.map +1 -0
- package/dist/{claude-CbKynSMc.js → claude-D-j-ZiYH.js} +29 -7
- package/dist/claude-D-j-ZiYH.js.map +1 -0
- package/dist/cli.js +336 -102
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +25 -4
- package/dist/index.js +251 -81
- package/dist/index.js.map +1 -1
- package/dist/{config-DYlbHrPc.js → text-M4XbWU6N.js} +17 -3
- package/dist/text-M4XbWU6N.js.map +1 -0
- package/package.json +4 -4
- package/dist/claude-ByRATJ03.js.map +0 -1
- package/dist/claude-CbKynSMc.js.map +0 -1
- package/dist/config-DYlbHrPc.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
|
|
4
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, 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 { pathToFileURL } from "node:url";
|
|
7
7
|
import { glob } from "tinyglobby";
|
|
@@ -10,6 +10,12 @@ import { createHash } from "node:crypto";
|
|
|
10
10
|
import MagicString from "magic-string";
|
|
11
11
|
import picomatch from "picomatch";
|
|
12
12
|
//#region src/catalog.ts
|
|
13
|
+
function emptyCatalog() {
|
|
14
|
+
return Object.create(null);
|
|
15
|
+
}
|
|
16
|
+
function own(catalog, key) {
|
|
17
|
+
return Object.hasOwn(catalog, key) ? catalog[key] : void 0;
|
|
18
|
+
}
|
|
13
19
|
function catalogPath(cfg, locale) {
|
|
14
20
|
return join(cfg.dir, `${locale}.json`);
|
|
15
21
|
}
|
|
@@ -36,8 +42,9 @@ function readTree(cfg, locale) {
|
|
|
36
42
|
return {};
|
|
37
43
|
}
|
|
38
44
|
const parsed = parseTree(content);
|
|
39
|
-
if (parsed)
|
|
40
|
-
throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not
|
|
45
|
+
if (parsed === void 0) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`);
|
|
46
|
+
if (!isTree(parsed)) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not a JSON object of messages, fix or delete the file`);
|
|
47
|
+
return parsed;
|
|
41
48
|
}
|
|
42
49
|
function parseTree(content) {
|
|
43
50
|
const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
@@ -47,6 +54,9 @@ function parseTree(content) {
|
|
|
47
54
|
return;
|
|
48
55
|
}
|
|
49
56
|
}
|
|
57
|
+
function isTree(value) {
|
|
58
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
59
|
+
}
|
|
50
60
|
function loadCatalogs(cfg) {
|
|
51
61
|
const catalogs = {};
|
|
52
62
|
for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
|
|
@@ -55,14 +65,17 @@ function loadCatalogs(cfg) {
|
|
|
55
65
|
function isNested(tree) {
|
|
56
66
|
return Object.values(tree).some((value) => typeof value === "object" && value !== null);
|
|
57
67
|
}
|
|
68
|
+
function group() {
|
|
69
|
+
return Object.create(null);
|
|
70
|
+
}
|
|
58
71
|
function nest(catalog) {
|
|
59
|
-
const tree =
|
|
72
|
+
const tree = group();
|
|
60
73
|
for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a < b ? -1 : 1)) {
|
|
61
74
|
const parts = key.split(".");
|
|
62
75
|
const leaf = parts[parts.length - 1];
|
|
63
76
|
let node = parts.length > 1 ? tree : void 0;
|
|
64
77
|
for (let i = 0; node && i < parts.length - 1; i++) {
|
|
65
|
-
const next = node[parts[i]] ??=
|
|
78
|
+
const next = node[parts[i]] ??= group();
|
|
66
79
|
node = typeof next === "object" && next !== null ? next : void 0;
|
|
67
80
|
}
|
|
68
81
|
if (node && typeof node[leaf] !== "object") node[leaf] = message;
|
|
@@ -71,7 +84,7 @@ function nest(catalog) {
|
|
|
71
84
|
return tree;
|
|
72
85
|
}
|
|
73
86
|
function sortTree(tree) {
|
|
74
|
-
const sorted =
|
|
87
|
+
const sorted = group();
|
|
75
88
|
for (const key of Object.keys(tree).sort()) {
|
|
76
89
|
const value = tree[key];
|
|
77
90
|
if (typeof value === "string") sorted[key] = value;
|
|
@@ -86,7 +99,7 @@ function isSorted(keys) {
|
|
|
86
99
|
function orderLike(tree, previous) {
|
|
87
100
|
const had = Object.keys(previous);
|
|
88
101
|
if (isSorted(had)) return sortTree(tree);
|
|
89
|
-
const out =
|
|
102
|
+
const out = group();
|
|
90
103
|
const take = (key) => {
|
|
91
104
|
const value = tree[key];
|
|
92
105
|
if (typeof value === "string") {
|
|
@@ -97,8 +110,8 @@ function orderLike(tree, previous) {
|
|
|
97
110
|
const before = previous[key];
|
|
98
111
|
out[key] = typeof before === "object" && before !== null ? orderLike(value, before) : sortTree(value);
|
|
99
112
|
};
|
|
100
|
-
for (const key of had) if (key
|
|
101
|
-
for (const key of Object.keys(tree).sort()) if (!(key
|
|
113
|
+
for (const key of had) if (Object.hasOwn(tree, key)) take(key);
|
|
114
|
+
for (const key of Object.keys(tree).sort()) if (!Object.hasOwn(previous, key)) take(key);
|
|
102
115
|
return out;
|
|
103
116
|
}
|
|
104
117
|
function serializeCatalog(catalog, nested = false, previous) {
|
|
@@ -113,7 +126,8 @@ function writeCatalog(cfg, locale, catalog) {
|
|
|
113
126
|
} catch {
|
|
114
127
|
mkdirSync(cfg.dir, { recursive: true });
|
|
115
128
|
}
|
|
116
|
-
const
|
|
129
|
+
const parsed = existing === void 0 ? void 0 : parseTree(existing);
|
|
130
|
+
const previous = isTree(parsed) ? parsed : void 0;
|
|
117
131
|
const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous);
|
|
118
132
|
if (existing === serialized) return serialized;
|
|
119
133
|
writeFileSync(path, serialized);
|
|
@@ -238,7 +252,7 @@ function matchBrace$1(message, start) {
|
|
|
238
252
|
}
|
|
239
253
|
function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
|
|
240
254
|
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
241
|
-
const target =
|
|
255
|
+
const target = emptyCatalog();
|
|
242
256
|
for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
|
|
243
257
|
catalogs[locale] = target;
|
|
244
258
|
return Object.keys(target).filter((key) => target[key]);
|
|
@@ -291,9 +305,18 @@ async function loadConfigFile(root) {
|
|
|
291
305
|
if (existsSync(path)) return loadTsConfig(path);
|
|
292
306
|
}
|
|
293
307
|
const jsonPath = join(root, "verbaly.config.json");
|
|
294
|
-
if (existsSync(jsonPath)) return
|
|
308
|
+
if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
|
|
295
309
|
return {};
|
|
296
310
|
}
|
|
311
|
+
function readJsonConfig(path) {
|
|
312
|
+
const content = readFileSync(path, "utf8");
|
|
313
|
+
const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
314
|
+
try {
|
|
315
|
+
return JSON.parse(body);
|
|
316
|
+
} catch (error) {
|
|
317
|
+
throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
297
320
|
async function loadTsConfig(path) {
|
|
298
321
|
try {
|
|
299
322
|
const { bundleRequire } = await import("bundle-require");
|
|
@@ -321,6 +344,25 @@ function definedOnly(config) {
|
|
|
321
344
|
return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
|
|
322
345
|
}
|
|
323
346
|
//#endregion
|
|
347
|
+
//#region src/tag.ts
|
|
348
|
+
function isLocaleTag(tag) {
|
|
349
|
+
try {
|
|
350
|
+
Intl.getCanonicalLocales(tag);
|
|
351
|
+
return true;
|
|
352
|
+
} catch {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function suggestTag(tag) {
|
|
357
|
+
const near = tag.replace(/_/g, "-");
|
|
358
|
+
return near !== tag && isLocaleTag(near) ? near : void 0;
|
|
359
|
+
}
|
|
360
|
+
function projectLocale(tag, locales) {
|
|
361
|
+
if (locales.includes(tag)) return tag;
|
|
362
|
+
const plain = (value) => value.replace(/_/g, "-").toLowerCase();
|
|
363
|
+
return locales.find((locale) => plain(locale) === plain(tag));
|
|
364
|
+
}
|
|
365
|
+
//#endregion
|
|
324
366
|
//#region src/init.ts
|
|
325
367
|
const HOSTS = [
|
|
326
368
|
{
|
|
@@ -409,10 +451,38 @@ function configSource(options, typescript) {
|
|
|
409
451
|
if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
|
|
410
452
|
return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
|
|
411
453
|
}
|
|
412
|
-
async function init(
|
|
413
|
-
const root =
|
|
454
|
+
async function init(input = {}) {
|
|
455
|
+
const root = input.root ?? process.cwd();
|
|
414
456
|
const created = [];
|
|
415
457
|
const skipped = [];
|
|
458
|
+
const renamed = [];
|
|
459
|
+
const refused = [];
|
|
460
|
+
const typed = input.locales?.flatMap((locale) => {
|
|
461
|
+
if (isLocaleTag(locale)) return [locale];
|
|
462
|
+
const near = suggestTag(locale);
|
|
463
|
+
if (near) renamed.push({
|
|
464
|
+
from: locale,
|
|
465
|
+
to: near
|
|
466
|
+
});
|
|
467
|
+
else refused.push(locale);
|
|
468
|
+
return near ? [near] : [];
|
|
469
|
+
});
|
|
470
|
+
const locales = typed && [...new Set(typed)];
|
|
471
|
+
let sourceLocale = input.sourceLocale;
|
|
472
|
+
if (sourceLocale !== void 0 && !isLocaleTag(sourceLocale)) {
|
|
473
|
+
const near = suggestTag(sourceLocale);
|
|
474
|
+
if (!near) throw new Error(`[verbaly] "${sourceLocale}" is not a locale tag: pass --source with one like en or pt-BR`);
|
|
475
|
+
renamed.push({
|
|
476
|
+
from: sourceLocale,
|
|
477
|
+
to: near
|
|
478
|
+
});
|
|
479
|
+
sourceLocale = near;
|
|
480
|
+
}
|
|
481
|
+
const options = {
|
|
482
|
+
...input,
|
|
483
|
+
locales,
|
|
484
|
+
sourceLocale
|
|
485
|
+
};
|
|
416
486
|
const existing = findConfigFile(root);
|
|
417
487
|
const typescript = existsSync(join(root, "tsconfig.json"));
|
|
418
488
|
const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
|
|
@@ -445,7 +515,9 @@ async function init(options = {}) {
|
|
|
445
515
|
skipped,
|
|
446
516
|
host: host?.name,
|
|
447
517
|
configFile,
|
|
448
|
-
next
|
|
518
|
+
next,
|
|
519
|
+
renamed,
|
|
520
|
+
refused
|
|
449
521
|
};
|
|
450
522
|
}
|
|
451
523
|
//#endregion
|
|
@@ -601,7 +673,7 @@ function reachableCategories(locale, ordinal) {
|
|
|
601
673
|
if (hit) return hit;
|
|
602
674
|
let out;
|
|
603
675
|
try {
|
|
604
|
-
const rules = new Intl.PluralRules(locale, { type });
|
|
676
|
+
const rules = new Intl.PluralRules(locale.replace(/_/g, "-"), { type });
|
|
605
677
|
const seen = /* @__PURE__ */ new Set();
|
|
606
678
|
for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));
|
|
607
679
|
out = [...seen];
|
|
@@ -621,8 +693,9 @@ function check(cfg, catalogs, registry) {
|
|
|
621
693
|
const flat = {};
|
|
622
694
|
for (const locale of cfg.locales) flat[locale] = flatten(catalogs[locale] ?? {});
|
|
623
695
|
const source = flat[cfg.sourceLocale] ?? {};
|
|
696
|
+
const used = registry.usedKeys();
|
|
624
697
|
const unknown = [];
|
|
625
|
-
for (const [key, files] of registry.usedKeys()) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
|
|
698
|
+
for (const [key, files] of registry.usedKeys(true)) if (!(extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== void 0))) unknown.push({
|
|
626
699
|
key,
|
|
627
700
|
files
|
|
628
701
|
});
|
|
@@ -650,7 +723,7 @@ function check(cfg, catalogs, registry) {
|
|
|
650
723
|
issue: issue.message
|
|
651
724
|
});
|
|
652
725
|
};
|
|
653
|
-
const sourceText =
|
|
726
|
+
const sourceText = Object.assign(emptyCatalog(), source);
|
|
654
727
|
for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
|
|
655
728
|
for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
|
|
656
729
|
for (const locale of cfg.locales) {
|
|
@@ -662,6 +735,18 @@ function check(cfg, catalogs, registry) {
|
|
|
662
735
|
if (text) add(locale, key, validatePair(text, translated));
|
|
663
736
|
}
|
|
664
737
|
}
|
|
738
|
+
const extra = [];
|
|
739
|
+
for (const locale of cfg.locales) {
|
|
740
|
+
if (locale === cfg.sourceLocale) continue;
|
|
741
|
+
for (const key of Object.keys(flat[locale] ?? {})) {
|
|
742
|
+
if (source[key] !== void 0 || extracted.has(key)) continue;
|
|
743
|
+
extra.push({
|
|
744
|
+
locale,
|
|
745
|
+
key,
|
|
746
|
+
files: used.get(key) ?? []
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
}
|
|
665
750
|
return {
|
|
666
751
|
ok: gatePasses({
|
|
667
752
|
missing,
|
|
@@ -670,7 +755,8 @@ function check(cfg, catalogs, registry) {
|
|
|
670
755
|
}),
|
|
671
756
|
missing,
|
|
672
757
|
unknown,
|
|
673
|
-
broken
|
|
758
|
+
broken,
|
|
759
|
+
extra
|
|
674
760
|
};
|
|
675
761
|
}
|
|
676
762
|
function formatCheckResult(result, root) {
|
|
@@ -703,7 +789,9 @@ function checkNextSteps(result, cliReachable = true) {
|
|
|
703
789
|
return steps.join("\n");
|
|
704
790
|
}
|
|
705
791
|
function formatCheckWarnings(result) {
|
|
706
|
-
|
|
792
|
+
const lines = result.broken.filter((entry) => entry.severity === "warning").map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);
|
|
793
|
+
for (const entry of result.extra) lines.push(entry.files.length > 0 ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself` : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`);
|
|
794
|
+
return lines.join("\n");
|
|
707
795
|
}
|
|
708
796
|
function truncate(text, max) {
|
|
709
797
|
return text.length > max ? text.slice(0, max - 1) + "…" : text;
|
|
@@ -758,6 +846,11 @@ function githubCheckAnnotations(result, registry, root) {
|
|
|
758
846
|
const line = content === void 0 ? void 0 : lineAt(content, origin.start);
|
|
759
847
|
lines.push(`::${command} file=${escapeProperty(file)}${line ? `,line=${line}` : ""}::${text}`);
|
|
760
848
|
}
|
|
849
|
+
for (const entry of result.extra) {
|
|
850
|
+
const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);
|
|
851
|
+
const file = entry.files[0];
|
|
852
|
+
lines.push(file ? `::warning file=${escapeProperty(relative(root, file).replaceAll("\\", "/"))}::${text}` : `::warning::${text}`);
|
|
853
|
+
}
|
|
761
854
|
return lines;
|
|
762
855
|
}
|
|
763
856
|
function lineAt(content, offset) {
|
|
@@ -783,7 +876,7 @@ const NUMBER_FORMATS = /* @__PURE__ */ new Set([
|
|
|
783
876
|
const DATE_FORMATS = /* @__PURE__ */ new Set(["date", "time"]);
|
|
784
877
|
function collectParams(message) {
|
|
785
878
|
const out = /* @__PURE__ */ new Map();
|
|
786
|
-
visit(parse(message), out);
|
|
879
|
+
visit(parse(message, parseIcu), out);
|
|
787
880
|
return out;
|
|
788
881
|
}
|
|
789
882
|
function visit(nodes, out) {
|
|
@@ -886,7 +979,9 @@ declare module 'virtual:verbaly/locale/*' {
|
|
|
886
979
|
`;
|
|
887
980
|
}
|
|
888
981
|
function writeDts(cfg, catalog, file) {
|
|
889
|
-
file
|
|
982
|
+
const target = file === void 0 ? cfg.dts : file;
|
|
983
|
+
if (target === false) return;
|
|
984
|
+
file = target ?? join(cfg.root, "verbaly.d.ts");
|
|
890
985
|
const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
|
|
891
986
|
try {
|
|
892
987
|
if (readFileSync(file, "utf8") === content) return;
|
|
@@ -962,9 +1057,10 @@ var MessageRegistry = class {
|
|
|
962
1057
|
}
|
|
963
1058
|
return out;
|
|
964
1059
|
}
|
|
965
|
-
usedKeys() {
|
|
1060
|
+
usedKeys(strict = false) {
|
|
966
1061
|
const out = /* @__PURE__ */ new Map();
|
|
967
1062
|
for (const analysis of this.files.values()) for (const used of analysis.usedKeys) {
|
|
1063
|
+
if (strict && used.loose) continue;
|
|
968
1064
|
const files = out.get(used.key) ?? [];
|
|
969
1065
|
if (!files.includes(used.file)) files.push(used.file);
|
|
970
1066
|
out.set(used.key, files);
|
|
@@ -1049,11 +1145,8 @@ function analyze(code, file, options = {}) {
|
|
|
1049
1145
|
return;
|
|
1050
1146
|
}
|
|
1051
1147
|
if (!isTReference(callee, names)) return;
|
|
1052
|
-
const
|
|
1053
|
-
if (
|
|
1054
|
-
key: first.value,
|
|
1055
|
-
file
|
|
1056
|
-
});
|
|
1148
|
+
const key = staticString(args[0]);
|
|
1149
|
+
if (key !== void 0) usedKeys.push(usedKey(key, file, args[0]));
|
|
1057
1150
|
} else if (node.type === "JSXElement") handleTrans(code, node, file, tagged, usedKeys, names);
|
|
1058
1151
|
});
|
|
1059
1152
|
return {
|
|
@@ -1067,14 +1160,28 @@ function collectDeclaredKeys(node, file, out) {
|
|
|
1067
1160
|
for (const property of node.properties) {
|
|
1068
1161
|
if (property.type !== "ObjectProperty") continue;
|
|
1069
1162
|
const value = property.value;
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
file
|
|
1074
|
-
});
|
|
1163
|
+
const key = staticString(value);
|
|
1164
|
+
if (key !== void 0) {
|
|
1165
|
+
if (key !== "") out.push(usedKey(key, file, value));
|
|
1075
1166
|
} else if (value.type === "ObjectExpression") collectDeclaredKeys(value, file, out);
|
|
1076
1167
|
}
|
|
1077
1168
|
}
|
|
1169
|
+
function usedKey(key, file, node) {
|
|
1170
|
+
return node?.type === "StringLiteral" ? {
|
|
1171
|
+
key,
|
|
1172
|
+
file
|
|
1173
|
+
} : {
|
|
1174
|
+
key,
|
|
1175
|
+
file,
|
|
1176
|
+
loose: true
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
function staticString(node) {
|
|
1180
|
+
if (!node) return void 0;
|
|
1181
|
+
if (node.type === "StringLiteral") return node.value;
|
|
1182
|
+
if (node.type === "TemplateLiteral" && node.expressions.length === 0) return cookedValue(node.quasis[0]);
|
|
1183
|
+
if (node.type === "JSXExpressionContainer") return staticString(node.expression);
|
|
1184
|
+
}
|
|
1078
1185
|
const VERBALY_PACKAGE = /^(?:verbaly|@verbaly\/[\w-]+)$/;
|
|
1079
1186
|
function collectStrayImports(node, file, out) {
|
|
1080
1187
|
const source = node.source;
|
|
@@ -1114,19 +1221,16 @@ function handleTrans(code, node, file, tagged, usedKeys, names) {
|
|
|
1114
1221
|
});
|
|
1115
1222
|
if (idAttr) {
|
|
1116
1223
|
const value = idAttr.value;
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
if (attrs.length === 1 && children?.length) {
|
|
1224
|
+
const id = staticString(value);
|
|
1225
|
+
if (id === void 0) return;
|
|
1226
|
+
if (value?.type === "StringLiteral" && attrs.length === 1 && children?.length) {
|
|
1120
1227
|
const built = buildTransMessage(code, children, names);
|
|
1121
1228
|
if (built?.text.trim()) {
|
|
1122
1229
|
push(id, built);
|
|
1123
1230
|
return;
|
|
1124
1231
|
}
|
|
1125
1232
|
}
|
|
1126
|
-
usedKeys.push(
|
|
1127
|
-
key: id,
|
|
1128
|
-
file
|
|
1129
|
-
});
|
|
1233
|
+
usedKeys.push(usedKey(id, file, value));
|
|
1130
1234
|
return;
|
|
1131
1235
|
}
|
|
1132
1236
|
if (attrs.length > 0) return;
|
|
@@ -1472,22 +1576,22 @@ async function extractProject(cfg) {
|
|
|
1472
1576
|
}
|
|
1473
1577
|
async function collectOrigins(cfg, reuse) {
|
|
1474
1578
|
const registry = reuse ?? await extractProject(cfg);
|
|
1475
|
-
const origins =
|
|
1579
|
+
const origins = Object.create(null);
|
|
1476
1580
|
for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
|
|
1477
1581
|
return origins;
|
|
1478
1582
|
}
|
|
1479
1583
|
function syncCatalogs(cfg, catalogs, registry) {
|
|
1480
1584
|
const added = {};
|
|
1481
|
-
const source = catalogs[cfg.sourceLocale] ??=
|
|
1482
|
-
for (const [key, msg] of registry.messages()) if (source
|
|
1585
|
+
const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
|
|
1586
|
+
for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) {
|
|
1483
1587
|
source[key] = msg.message;
|
|
1484
1588
|
(added[cfg.sourceLocale] ??= []).push(key);
|
|
1485
1589
|
}
|
|
1486
1590
|
const needed = Object.keys(source);
|
|
1487
1591
|
for (const locale of cfg.locales) {
|
|
1488
1592
|
if (locale === cfg.sourceLocale) continue;
|
|
1489
|
-
const catalog = catalogs[locale] ??=
|
|
1490
|
-
for (const key of needed) if (catalog
|
|
1593
|
+
const catalog = catalogs[locale] ??= emptyCatalog();
|
|
1594
|
+
for (const key of needed) if (own(catalog, key) === void 0) {
|
|
1491
1595
|
catalog[key] = "";
|
|
1492
1596
|
(added[locale] ??= []).push(key);
|
|
1493
1597
|
}
|
|
@@ -1495,8 +1599,9 @@ function syncCatalogs(cfg, catalogs, registry) {
|
|
|
1495
1599
|
return { added };
|
|
1496
1600
|
}
|
|
1497
1601
|
function pruneCatalogs(cfg, catalogs, registry) {
|
|
1498
|
-
const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
|
|
1499
1602
|
const removed = {};
|
|
1603
|
+
if (registry.parseErrors().length > 0) return removed;
|
|
1604
|
+
const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
|
|
1500
1605
|
for (const locale of cfg.locales) {
|
|
1501
1606
|
const catalog = catalogs[locale];
|
|
1502
1607
|
if (!catalog) continue;
|
|
@@ -1570,27 +1675,39 @@ async function doctor(cfg) {
|
|
|
1570
1675
|
error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
|
|
1571
1676
|
continue;
|
|
1572
1677
|
}
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
const bad = badLeaf(parsed);
|
|
1576
|
-
if (bad) {
|
|
1577
|
-
catalogsHealthy = false;
|
|
1578
|
-
error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
|
|
1579
|
-
} else catalogs[locale] = flatten(parsed);
|
|
1580
|
-
} catch {
|
|
1678
|
+
const parsed = parseTree(readFileSync(file, "utf8"));
|
|
1679
|
+
if (parsed === void 0) {
|
|
1581
1680
|
catalogsHealthy = false;
|
|
1582
1681
|
error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
|
|
1682
|
+
continue;
|
|
1583
1683
|
}
|
|
1684
|
+
if (!isTree(parsed)) {
|
|
1685
|
+
catalogsHealthy = false;
|
|
1686
|
+
error(`locale ${locale}`, `${rel(file)} is not a JSON object of messages`, "a catalog is an object of texts (groups of text are fine): fix the file");
|
|
1687
|
+
continue;
|
|
1688
|
+
}
|
|
1689
|
+
const bad = badLeaf(parsed);
|
|
1690
|
+
if (bad) {
|
|
1691
|
+
catalogsHealthy = false;
|
|
1692
|
+
error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
|
|
1693
|
+
} else catalogs[locale] = flatten(parsed);
|
|
1584
1694
|
}
|
|
1585
1695
|
if (catalogsHealthy) {
|
|
1586
1696
|
const how = cfg.localesDeclared ? "" : ", no locales set, so the catalog files decide";
|
|
1587
1697
|
ok("catalogs", `${counted(cfg.locales.length, "locale")} (${cfg.locales.join(", ")}) in ${rel(cfg.dir)}/${how}`);
|
|
1588
1698
|
}
|
|
1589
1699
|
}
|
|
1700
|
+
for (const locale of cfg.locales) {
|
|
1701
|
+
if (isLocaleTag(locale)) continue;
|
|
1702
|
+
const near = suggestTag(locale);
|
|
1703
|
+
const file = rel(join(cfg.dir, `${locale}.json`));
|
|
1704
|
+
warn("locales", `"${locale}" is not a locale tag, so numbers, dates and plurals in it format in a fallback`, near ? `rename it to ${near}: the file ${file} and your config` : `name it with a language tag like es or pt-BR, in ${file} and in your config`);
|
|
1705
|
+
}
|
|
1590
1706
|
const source = catalogs[cfg.sourceLocale];
|
|
1591
1707
|
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`");
|
|
1592
1708
|
const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
|
|
1593
1709
|
if (cfg.routing === "no-prefix" && mirrors) warn("routing", "routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale", "drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls");
|
|
1710
|
+
else if (cfg.routing === "prefix-all" && mirrors) warn("routing", `routing is "prefix-all" but render keeps ${cfg.sourceLocale} at the root, so its links point at a /${cfg.sourceLocale}/ tree nobody wrote`, "set routing to \"prefix-except-source\", the url tree render writes");
|
|
1594
1711
|
else {
|
|
1595
1712
|
const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
|
|
1596
1713
|
ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
|
|
@@ -1631,7 +1748,8 @@ async function doctor(cfg) {
|
|
|
1631
1748
|
const extracted = registry.messages();
|
|
1632
1749
|
const used = registry.usedKeys();
|
|
1633
1750
|
const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
|
|
1634
|
-
|
|
1751
|
+
const unread = registry.parseErrors().length > 0;
|
|
1752
|
+
if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
|
|
1635
1753
|
else ok("orphans", "no orphan keys");
|
|
1636
1754
|
}
|
|
1637
1755
|
const excluded = cfg.bundle.exclude ?? [];
|
|
@@ -1652,6 +1770,10 @@ async function doctor(cfg) {
|
|
|
1652
1770
|
const locales = [...new Set(broken.map((b) => b.locale))];
|
|
1653
1771
|
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");
|
|
1654
1772
|
}
|
|
1773
|
+
if (result.extra.length > 0) {
|
|
1774
|
+
const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);
|
|
1775
|
+
warn("extras", `a translation has ${counted(result.extra.length, "key")} the source catalog does not (${preview(shown)})`, scanning ? "add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest" : "add them to the source catalog if your code uses them, or delete them from the translations");
|
|
1776
|
+
}
|
|
1655
1777
|
const warnings = result.broken.filter((entry) => entry.severity === "warning");
|
|
1656
1778
|
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");
|
|
1657
1779
|
if (result.ok) ok("translations", "all translations complete");
|
|
@@ -1720,7 +1842,7 @@ function effectiveDrafts(drafts, catalogs) {
|
|
|
1720
1842
|
const out = {};
|
|
1721
1843
|
for (const [locale, keys] of Object.entries(drafts)) {
|
|
1722
1844
|
const catalog = catalogs[locale] ?? {};
|
|
1723
|
-
const live = keys.filter((key) => catalog
|
|
1845
|
+
const live = keys.filter((key) => own(catalog, key));
|
|
1724
1846
|
if (live.length) out[locale] = live;
|
|
1725
1847
|
}
|
|
1726
1848
|
return out;
|
|
@@ -2004,7 +2126,7 @@ function toPo(sourceLocale, locale, entries) {
|
|
|
2004
2126
|
].join("\n\n");
|
|
2005
2127
|
}
|
|
2006
2128
|
function parsePo(content) {
|
|
2007
|
-
const entries =
|
|
2129
|
+
const entries = Object.create(null);
|
|
2008
2130
|
let locale;
|
|
2009
2131
|
let msgctxt;
|
|
2010
2132
|
let msgid;
|
|
@@ -2124,8 +2246,8 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
|
2124
2246
|
};
|
|
2125
2247
|
const jobs = [];
|
|
2126
2248
|
for (const locale of targets) {
|
|
2127
|
-
const catalog = catalogs[locale] ??=
|
|
2128
|
-
const missing = Object.keys(source).filter((key) => source[key] && !catalog
|
|
2249
|
+
const catalog = catalogs[locale] ??= emptyCatalog();
|
|
2250
|
+
const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
|
|
2129
2251
|
if (missing.length === 0) continue;
|
|
2130
2252
|
if (options.dryRun) {
|
|
2131
2253
|
result.pending[locale] = missing;
|
|
@@ -2146,7 +2268,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
|
2146
2268
|
const { locale, keys } = job;
|
|
2147
2269
|
const catalog = catalogs[locale];
|
|
2148
2270
|
const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
|
|
2149
|
-
const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins
|
|
2271
|
+
const origins = options.origins ? Object.fromEntries(keys.filter((key) => Object.hasOwn(options.origins, key)).map((key) => [key, options.origins[key]])) : void 0;
|
|
2150
2272
|
let out;
|
|
2151
2273
|
try {
|
|
2152
2274
|
out = await attempt(() => provider({
|
|
@@ -2187,6 +2309,19 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
|
2187
2309
|
function compare(a, b) {
|
|
2188
2310
|
return (a[0] ?? "").localeCompare(b[0] ?? "");
|
|
2189
2311
|
}
|
|
2312
|
+
function mergeTranslations(cfg, locale, translated, keys) {
|
|
2313
|
+
const source = readCatalog(cfg, cfg.sourceLocale);
|
|
2314
|
+
const current = readCatalog(cfg, locale);
|
|
2315
|
+
const written = [];
|
|
2316
|
+
for (const key of keys) {
|
|
2317
|
+
const text = translated[key];
|
|
2318
|
+
if (!source[key] || current[key] || !text) continue;
|
|
2319
|
+
current[key] = text;
|
|
2320
|
+
written.push(key);
|
|
2321
|
+
}
|
|
2322
|
+
if (written.length > 0) writeCatalog(cfg, locale, current);
|
|
2323
|
+
return written;
|
|
2324
|
+
}
|
|
2190
2325
|
function formatTranslateFailures(failed) {
|
|
2191
2326
|
const grouped = [];
|
|
2192
2327
|
for (const entry of failed) {
|
|
@@ -2202,7 +2337,7 @@ function formatTranslateFailures(failed) {
|
|
|
2202
2337
|
async function resolveProvider(cfg, model) {
|
|
2203
2338
|
const configured = cfg.translate.provider;
|
|
2204
2339
|
if (typeof configured === "function") return configured;
|
|
2205
|
-
const { claudeProvider } = await import("./claude-
|
|
2340
|
+
const { claudeProvider } = await import("./claude-BmD8W9uW.js");
|
|
2206
2341
|
return claudeProvider({ model: model ?? cfg.translate.model });
|
|
2207
2342
|
}
|
|
2208
2343
|
function structureMatches(source, translated) {
|
|
@@ -2244,14 +2379,15 @@ function exportCatalogs(cfg, catalogs, options = {}) {
|
|
|
2244
2379
|
const targets = targetLocales(cfg, options.locales);
|
|
2245
2380
|
if (isMobileFormat(format)) return exportMobile(cfg, catalogs, format, dir, source, targets);
|
|
2246
2381
|
const files = [];
|
|
2382
|
+
const origins = options.origins;
|
|
2247
2383
|
mkdirSync(dir, { recursive: true });
|
|
2248
2384
|
for (const locale of targets) {
|
|
2249
|
-
const catalog = catalogs[locale] ??
|
|
2385
|
+
const catalog = catalogs[locale] ?? emptyCatalog();
|
|
2250
2386
|
const all = Object.keys(source).filter((key) => source[key]).sort().map((key) => ({
|
|
2251
2387
|
key,
|
|
2252
2388
|
source: source[key],
|
|
2253
|
-
target: catalog
|
|
2254
|
-
location:
|
|
2389
|
+
target: own(catalog, key) ?? "",
|
|
2390
|
+
location: origins && Object.hasOwn(origins, key) ? origins[key] : void 0
|
|
2255
2391
|
}));
|
|
2256
2392
|
const untranslated = all.filter((entry) => !entry.target);
|
|
2257
2393
|
const entries = options.missing ? untranslated : all;
|
|
@@ -2278,7 +2414,7 @@ function exportMobile(cfg, catalogs, format, dir, source, targets) {
|
|
|
2278
2414
|
const catalog = locale === cfg.sourceLocale ? source : catalogs[locale] ?? {};
|
|
2279
2415
|
const entries = keys.map((key) => ({
|
|
2280
2416
|
key,
|
|
2281
|
-
text: catalog
|
|
2417
|
+
text: own(catalog, key) ?? ""
|
|
2282
2418
|
})).filter((entry) => entry.text);
|
|
2283
2419
|
const relative = format === "android-xml" ? join(androidValuesDir(locale, cfg.sourceLocale), "strings.xml") : join(`${locale}.lproj`, "Localizable.strings");
|
|
2284
2420
|
const path = join(dir, relative);
|
|
@@ -2303,25 +2439,47 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
|
|
|
2303
2439
|
imported: {},
|
|
2304
2440
|
rejected: {},
|
|
2305
2441
|
skipped: {},
|
|
2306
|
-
unknown: {}
|
|
2442
|
+
unknown: {},
|
|
2443
|
+
unmatched: [],
|
|
2444
|
+
mapped: []
|
|
2307
2445
|
};
|
|
2308
2446
|
for (const file of files) {
|
|
2309
2447
|
const parsed = parseExchangeFile(file, options.locale);
|
|
2310
|
-
const
|
|
2311
|
-
if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(
|
|
2448
|
+
const detected = parsed.locale;
|
|
2449
|
+
if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(detected)) throw new Error(`[verbaly] ${file}: "${detected}" doesn't look like a locale, pass --locale <id>.`);
|
|
2450
|
+
const locale = projectLocale(detected, cfg.locales) ?? newLocale(cfg, detected);
|
|
2312
2451
|
if (locale === cfg.sourceLocale) throw new Error(`[verbaly] ${file} targets the source locale "${locale}": import fills translations, not the source. Pass --locale if the detection is wrong.`);
|
|
2313
|
-
|
|
2452
|
+
if (locale === void 0) {
|
|
2453
|
+
const near = isLocaleTag(detected) ? detected : suggestTag(detected);
|
|
2454
|
+
result.unmatched.push(near ? {
|
|
2455
|
+
file,
|
|
2456
|
+
locale: near,
|
|
2457
|
+
reason: "undeclared"
|
|
2458
|
+
} : {
|
|
2459
|
+
file,
|
|
2460
|
+
locale: detected,
|
|
2461
|
+
reason: "invalid"
|
|
2462
|
+
});
|
|
2463
|
+
continue;
|
|
2464
|
+
}
|
|
2465
|
+
if (locale !== detected) result.mapped.push({
|
|
2466
|
+
file,
|
|
2467
|
+
from: detected,
|
|
2468
|
+
to: locale
|
|
2469
|
+
});
|
|
2470
|
+
const catalog = catalogs[locale] ??= emptyCatalog();
|
|
2314
2471
|
for (const [key, text] of Object.entries(parsed.entries)) {
|
|
2315
2472
|
if (!text.trim()) continue;
|
|
2316
|
-
|
|
2473
|
+
const from = own(source, key);
|
|
2474
|
+
if (!from) {
|
|
2317
2475
|
(result.unknown[locale] ??= []).push(key);
|
|
2318
2476
|
continue;
|
|
2319
2477
|
}
|
|
2320
|
-
if (catalog
|
|
2478
|
+
if (own(catalog, key) && !options.overwrite) {
|
|
2321
2479
|
(result.skipped[locale] ??= []).push(key);
|
|
2322
2480
|
continue;
|
|
2323
2481
|
}
|
|
2324
|
-
if (!structureMatches(
|
|
2482
|
+
if (!structureMatches(from, text)) {
|
|
2325
2483
|
(result.rejected[locale] ??= []).push(key);
|
|
2326
2484
|
continue;
|
|
2327
2485
|
}
|
|
@@ -2379,9 +2537,13 @@ function toXliff(sourceLocale, locale, entries) {
|
|
|
2379
2537
|
""
|
|
2380
2538
|
].join("\n");
|
|
2381
2539
|
}
|
|
2540
|
+
function newLocale(cfg, detected) {
|
|
2541
|
+
if (cfg.localesDeclared) return void 0;
|
|
2542
|
+
return isLocaleTag(detected) ? detected : suggestTag(detected);
|
|
2543
|
+
}
|
|
2382
2544
|
function parseXliff(content) {
|
|
2383
2545
|
const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
|
|
2384
|
-
const entries =
|
|
2546
|
+
const entries = Object.create(null);
|
|
2385
2547
|
for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
|
|
2386
2548
|
const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
|
|
2387
2549
|
if (!id) continue;
|
|
@@ -2412,7 +2574,7 @@ function parseCsv(content) {
|
|
|
2412
2574
|
const keyCol = header.indexOf("key");
|
|
2413
2575
|
const targetCol = header.indexOf("target");
|
|
2414
2576
|
if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
|
|
2415
|
-
const entries =
|
|
2577
|
+
const entries = Object.create(null);
|
|
2416
2578
|
for (const row of rows.slice(1)) {
|
|
2417
2579
|
const key = row[keyCol];
|
|
2418
2580
|
if (key) entries[key] = row[targetCol] ?? "";
|
|
@@ -2560,7 +2722,7 @@ function migrateCatalogs(cfg, options = {}) {
|
|
|
2560
2722
|
const written = [];
|
|
2561
2723
|
for (const locale of cfg.locales) {
|
|
2562
2724
|
const catalog = readCatalog(cfg, locale);
|
|
2563
|
-
const out =
|
|
2725
|
+
const out = Object.assign(emptyCatalog(), catalog);
|
|
2564
2726
|
for (const [key, value] of Object.entries(catalog)) {
|
|
2565
2727
|
if (typeof value !== "string") continue;
|
|
2566
2728
|
if (NESTED.test(value)) {
|
|
@@ -2741,7 +2903,7 @@ function renderHtml(html, options) {
|
|
|
2741
2903
|
};
|
|
2742
2904
|
}
|
|
2743
2905
|
function pageSlice(v, locale, used) {
|
|
2744
|
-
const slice =
|
|
2906
|
+
const slice = Object.create(null);
|
|
2745
2907
|
for (const key of used) {
|
|
2746
2908
|
const found = v.inspect(key);
|
|
2747
2909
|
slice[key] = found?.from === locale ? found.source : "";
|
|
@@ -2752,12 +2914,16 @@ function publicPath(rel) {
|
|
|
2752
2914
|
const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
|
|
2753
2915
|
return path.length > 1 ? path.replace(/\/+$/, "") : path;
|
|
2754
2916
|
}
|
|
2917
|
+
function linkFor(links, name) {
|
|
2918
|
+
return links && Object.hasOwn(links, name) ? links[name] : void 0;
|
|
2919
|
+
}
|
|
2755
2920
|
function usedLinks(nodes, links) {
|
|
2756
2921
|
const out = {};
|
|
2757
2922
|
const walk = (list) => {
|
|
2758
2923
|
for (const node of list) {
|
|
2759
2924
|
if (typeof node === "string") continue;
|
|
2760
|
-
|
|
2925
|
+
const link = linkFor(links, node.name);
|
|
2926
|
+
if (link !== void 0) out[node.name] = link;
|
|
2761
2927
|
walk(node.children);
|
|
2762
2928
|
}
|
|
2763
2929
|
};
|
|
@@ -2841,7 +3007,7 @@ function injectAlternates(ms, html, alternates) {
|
|
|
2841
3007
|
if (head) ms.appendLeft(head.index, block);
|
|
2842
3008
|
}
|
|
2843
3009
|
function injectCatalog(ms, html, messages) {
|
|
2844
|
-
const json = JSON.stringify(messages).replace(/<\//g, "<\\/");
|
|
3010
|
+
const json = JSON.stringify(messages).replace(/<\//g, "<\\/").replace(/<!--/g, "\\u003c!--");
|
|
2845
3011
|
const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
|
|
2846
3012
|
const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
|
|
2847
3013
|
const from = html.indexOf(CATALOG_OPEN);
|
|
@@ -3027,15 +3193,18 @@ function setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value) {
|
|
|
3027
3193
|
}
|
|
3028
3194
|
function richToHtml(nodes, allowed, links) {
|
|
3029
3195
|
let out = "";
|
|
3030
|
-
for (const node of nodes)
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3196
|
+
for (const node of nodes) {
|
|
3197
|
+
const link = typeof node === "string" ? void 0 : linkFor(links, node.name);
|
|
3198
|
+
if (typeof node === "string") out += escapeHtml(node);
|
|
3199
|
+
else if (link !== void 0) {
|
|
3200
|
+
const { href, target, rel } = normalizeLink(link);
|
|
3201
|
+
let attrs = href !== void 0 ? ` href="${escapeAttr(href)}"` : "";
|
|
3202
|
+
if (target) attrs += ` target="${escapeAttr(target)}"`;
|
|
3203
|
+
if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
|
|
3204
|
+
out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
|
|
3205
|
+
} else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
|
|
3206
|
+
else out += richToHtml(node.children, allowed, links);
|
|
3207
|
+
}
|
|
3039
3208
|
return out;
|
|
3040
3209
|
}
|
|
3041
3210
|
function escapeHtml(text) {
|
|
@@ -3100,6 +3269,51 @@ function formatStatusResult(result) {
|
|
|
3100
3269
|
const SOURCE_FILE_RE = /\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;
|
|
3101
3270
|
//#endregion
|
|
3102
3271
|
//#region src/watch.ts
|
|
3272
|
+
const NATIVE_TREE = process.platform === "darwin" || process.platform === "win32";
|
|
3273
|
+
function watchTree(root, options, onFile) {
|
|
3274
|
+
const watchers = /* @__PURE__ */ new Map();
|
|
3275
|
+
const close = (name) => {
|
|
3276
|
+
watchers.get(name)?.close();
|
|
3277
|
+
watchers.delete(name);
|
|
3278
|
+
};
|
|
3279
|
+
const open = (name, recursive, listener) => {
|
|
3280
|
+
const watcher = watch(join(root, name), {
|
|
3281
|
+
recursive,
|
|
3282
|
+
persistent: options.persistent ?? true
|
|
3283
|
+
}, listener);
|
|
3284
|
+
watcher.on("error", (error) => {
|
|
3285
|
+
close(name);
|
|
3286
|
+
console.warn(`[verbaly] stopped watching ${name || "the project"}:`, error);
|
|
3287
|
+
});
|
|
3288
|
+
watchers.set(name, watcher);
|
|
3289
|
+
};
|
|
3290
|
+
if (options.native ?? NATIVE_TREE) open("", true, (_event, file) => {
|
|
3291
|
+
if (file) onFile(file);
|
|
3292
|
+
});
|
|
3293
|
+
else {
|
|
3294
|
+
const sync = (name) => {
|
|
3295
|
+
close(name);
|
|
3296
|
+
if (name !== options.keep && (name === "node_modules" || name.startsWith("."))) return;
|
|
3297
|
+
try {
|
|
3298
|
+
if (!lstatSync(join(root, name)).isDirectory()) return;
|
|
3299
|
+
open(name, true, (_event, file) => {
|
|
3300
|
+
if (file) onFile(`${name}/${file}`);
|
|
3301
|
+
});
|
|
3302
|
+
} catch (error) {
|
|
3303
|
+
if (error.code !== "ENOENT") console.warn(`[verbaly] could not watch ${name}:`, error);
|
|
3304
|
+
}
|
|
3305
|
+
};
|
|
3306
|
+
open("", false, (event, file) => {
|
|
3307
|
+
if (!file) return;
|
|
3308
|
+
if (event === "rename") sync(file);
|
|
3309
|
+
onFile(file);
|
|
3310
|
+
});
|
|
3311
|
+
for (const entry of readdirSync(root, { withFileTypes: true })) if (entry.isDirectory()) sync(entry.name);
|
|
3312
|
+
}
|
|
3313
|
+
return () => {
|
|
3314
|
+
for (const name of [...watchers.keys()]) close(name);
|
|
3315
|
+
};
|
|
3316
|
+
}
|
|
3103
3317
|
function watchProject(cfg, run, options = {}) {
|
|
3104
3318
|
const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
|
|
3105
3319
|
let timer;
|
|
@@ -3127,7 +3341,7 @@ function watchProject(cfg, run, options = {}) {
|
|
|
3127
3341
|
clearTimeout(timer);
|
|
3128
3342
|
timer = setTimeout(() => void refresh(), options.debounce ?? 150);
|
|
3129
3343
|
}
|
|
3130
|
-
const
|
|
3344
|
+
const close = watchTree(cfg.root, {}, (filename) => {
|
|
3131
3345
|
if (!filename) return;
|
|
3132
3346
|
const file = filename.replaceAll("\\", "/");
|
|
3133
3347
|
if (file.includes("node_modules/") || file.endsWith(".d.ts")) return;
|
|
@@ -3136,7 +3350,7 @@ function watchProject(cfg, run, options = {}) {
|
|
|
3136
3350
|
});
|
|
3137
3351
|
return () => {
|
|
3138
3352
|
clearTimeout(timer);
|
|
3139
|
-
|
|
3353
|
+
close();
|
|
3140
3354
|
};
|
|
3141
3355
|
}
|
|
3142
3356
|
//#endregion
|
|
@@ -3438,7 +3652,7 @@ Options:
|
|
|
3438
3652
|
--root <path> project root (default: cwd)
|
|
3439
3653
|
--dir <path> catalogs directory (default: locales)
|
|
3440
3654
|
--source <locale> source locale (default: en)
|
|
3441
|
-
--locales <csv>
|
|
3655
|
+
--locales <csv> run on these locales only, the source always included (init: the ones to create)
|
|
3442
3656
|
--prune drop keys no longer referenced (extract)
|
|
3443
3657
|
--watch keep extracting as source files change (extract)
|
|
3444
3658
|
--write apply the rewrites instead of only reporting (wrap, migrate)
|
|
@@ -3514,10 +3728,12 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3514
3728
|
root: values.root,
|
|
3515
3729
|
dir: values.dir,
|
|
3516
3730
|
sourceLocale: values.source,
|
|
3517
|
-
locales: values.locales
|
|
3731
|
+
locales: csv(values.locales)
|
|
3518
3732
|
});
|
|
3519
3733
|
if (result.created.length) console.log(`[verbaly] created: ${result.created.join(", ")}`);
|
|
3520
3734
|
if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(", ")}`);
|
|
3735
|
+
for (const { from, to } of result.renamed) console.log(` wrote ${to} for ${from}, since a locale tag takes a hyphen`);
|
|
3736
|
+
for (const locale of result.refused) console.warn(` left out "${locale}": it is not a locale tag, use one like es or pt-BR`);
|
|
3521
3737
|
if (result.host) console.log(` detected: ${result.host}`);
|
|
3522
3738
|
console.log([" next steps:", ...result.next.map((step, i) => ` ${i + 1}. ${step}`)].join("\n"));
|
|
3523
3739
|
return;
|
|
@@ -3525,7 +3741,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3525
3741
|
const cfg = await loadConfig(values.root ?? process.cwd(), {
|
|
3526
3742
|
dir: values.dir,
|
|
3527
3743
|
sourceLocale: values.source,
|
|
3528
|
-
locales: values.locales
|
|
3744
|
+
locales: csv(values.locales)
|
|
3529
3745
|
});
|
|
3530
3746
|
if (command === "doctor") {
|
|
3531
3747
|
const result = await doctor(cfg);
|
|
@@ -3555,12 +3771,14 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3555
3771
|
const catalogs = loadCatalogs(cfg);
|
|
3556
3772
|
if (values.prune) {
|
|
3557
3773
|
const removed = pruneCatalogs(cfg, catalogs, registry);
|
|
3774
|
+
const unread = registry.parseErrors().length;
|
|
3775
|
+
if (unread > 0) console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
|
|
3558
3776
|
for (const [locale, keys] of Object.entries(removed)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
|
|
3559
3777
|
}
|
|
3560
3778
|
const { added } = syncCatalogs(cfg, catalogs, registry);
|
|
3561
3779
|
if (!dryRun) {
|
|
3562
3780
|
for (const locale of cfg.locales) writeCatalog(cfg, locale, catalogs[locale] ?? {});
|
|
3563
|
-
|
|
3781
|
+
writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
|
|
3564
3782
|
}
|
|
3565
3783
|
const total = registry.messages().size;
|
|
3566
3784
|
console.log(`[verbaly] ${counted(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
|
|
@@ -3672,7 +3890,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3672
3890
|
if (command === "translate") {
|
|
3673
3891
|
const catalogs = loadCatalogs(cfg);
|
|
3674
3892
|
const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
|
|
3675
|
-
locales: values.locales
|
|
3893
|
+
locales: csv(values.locales),
|
|
3676
3894
|
batchSize: cfg.translate.batchSize,
|
|
3677
3895
|
concurrency: cfg.translate.concurrency,
|
|
3678
3896
|
retries: cfg.translate.retries,
|
|
@@ -3690,10 +3908,12 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3690
3908
|
return;
|
|
3691
3909
|
}
|
|
3692
3910
|
const drafts = loadDrafts(cfg);
|
|
3693
|
-
for (const locale of Object.
|
|
3694
|
-
|
|
3695
|
-
markDrafts(drafts, locale,
|
|
3696
|
-
console.log(` ${locale}: +${
|
|
3911
|
+
for (const [locale, keys] of Object.entries(result.translated)) {
|
|
3912
|
+
const written = mergeTranslations(cfg, locale, catalogs[locale] ?? {}, keys);
|
|
3913
|
+
markDrafts(drafts, locale, written);
|
|
3914
|
+
console.log(` ${locale}: +${written.length} translated (draft)`);
|
|
3915
|
+
const kept = keys.length - written.length;
|
|
3916
|
+
if (kept > 0) console.log(` ${locale}: ${counted(kept, "message")} kept as written while this ran`);
|
|
3697
3917
|
}
|
|
3698
3918
|
if (Object.keys(result.translated).length > 0) saveDrafts(cfg, drafts);
|
|
3699
3919
|
for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
|
|
@@ -3747,7 +3967,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3747
3967
|
return;
|
|
3748
3968
|
}
|
|
3749
3969
|
const result = exportCatalogs(cfg, loadCatalogs(cfg), {
|
|
3750
|
-
locales: values.locales
|
|
3970
|
+
locales: csv(values.locales),
|
|
3751
3971
|
format,
|
|
3752
3972
|
out: values.out,
|
|
3753
3973
|
missing: values.missing,
|
|
@@ -3775,6 +3995,17 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3775
3995
|
overwrite: values.overwrite,
|
|
3776
3996
|
dryRun: values["dry-run"]
|
|
3777
3997
|
});
|
|
3998
|
+
for (const { file, from, to } of result.mapped) console.log(` ${file}: "${from}" read as ${to}`);
|
|
3999
|
+
for (const { file, locale, reason } of result.unmatched) {
|
|
4000
|
+
if (reason === "undeclared") {
|
|
4001
|
+
console.warn(` ${file}: "${locale}" is not one of this project's locales (${cfg.locales.join(", ")}), so nothing was imported from it`);
|
|
4002
|
+
console.warn(` fix: add ${locale} to locales in your verbaly config, or pass --locale with one of them`);
|
|
4003
|
+
} else {
|
|
4004
|
+
console.warn(` ${file}: "${locale}" is not a locale tag, so nothing was imported from it`);
|
|
4005
|
+
console.warn(" fix: pass --locale with the tag it stands for, like pt-BR");
|
|
4006
|
+
}
|
|
4007
|
+
process.exitCode = 1;
|
|
4008
|
+
}
|
|
3778
4009
|
const drafts = loadDrafts(cfg);
|
|
3779
4010
|
let draftsChanged = false;
|
|
3780
4011
|
for (const [locale, keys] of Object.entries(result.imported)) {
|
|
@@ -3790,13 +4021,13 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3790
4021
|
for (const [locale, keys] of Object.entries(result.skipped)) console.log(` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`);
|
|
3791
4022
|
for (const [locale, keys] of Object.entries(result.rejected)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
|
|
3792
4023
|
for (const [locale, keys] of Object.entries(result.unknown)) console.warn(` ${locale}: ${counted(keys.length, "unknown key")} ignored (not in the source catalog): ${keys.join(", ")}`);
|
|
3793
|
-
if (Object.keys(result.imported).length === 0) console.log("[verbaly] nothing to import ✓");
|
|
4024
|
+
if (Object.keys(result.imported).length === 0 && result.unmatched.length === 0) console.log("[verbaly] nothing to import ✓");
|
|
3794
4025
|
return;
|
|
3795
4026
|
}
|
|
3796
4027
|
if (command === "render") {
|
|
3797
4028
|
const result = await renderSite(cfg, {
|
|
3798
4029
|
site: values.site,
|
|
3799
|
-
locales: values.locales
|
|
4030
|
+
locales: csv(values.locales),
|
|
3800
4031
|
attribute: values.attribute,
|
|
3801
4032
|
base: values.base,
|
|
3802
4033
|
baseUrl: values["base-url"],
|
|
@@ -3819,6 +4050,9 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3819
4050
|
console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
|
|
3820
4051
|
process.exitCode = 1;
|
|
3821
4052
|
}
|
|
4053
|
+
function csv(value) {
|
|
4054
|
+
return value?.split(",").map((item) => item.trim()).filter(Boolean);
|
|
4055
|
+
}
|
|
3822
4056
|
function reportProgress(progress) {
|
|
3823
4057
|
const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
|
|
3824
4058
|
if (progress.error) console.warn(`${head}: failed (${progress.error}), continuing`);
|
|
@@ -3902,6 +4136,6 @@ runCli().catch((error) => {
|
|
|
3902
4136
|
process.exitCode = 1;
|
|
3903
4137
|
});
|
|
3904
4138
|
//#endregion
|
|
3905
|
-
export { isModuleNotFound as t };
|
|
4139
|
+
export { isModuleNotFound as n, counted as t };
|
|
3906
4140
|
|
|
3907
4141
|
//# sourceMappingURL=cli.js.map
|