@verbaly/compiler 0.14.5 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { parse } from "@babel/parser";
2
2
  import { createHash } from "node:crypto";
3
3
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
- import { dirname, join, relative, resolve } from "node:path";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
5
5
  import { RICH_TAGS, createVerbaly, parse as parse$1, parseTags, safeHref } from "verbaly";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { glob } from "tinyglobby";
@@ -794,6 +794,247 @@ function readDeps(root) {
794
794
  }
795
795
  }
796
796
  //#endregion
797
+ //#region src/translate.ts
798
+ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
799
+ const batchSize = options.batchSize ?? 20;
800
+ const targets = (options.locales ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
801
+ const source = catalogs[cfg.sourceLocale] ?? {};
802
+ const result = {
803
+ translated: {},
804
+ invalid: {},
805
+ pending: {}
806
+ };
807
+ for (const locale of targets) {
808
+ const catalog = catalogs[locale] ??= {};
809
+ const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
810
+ if (missing.length === 0) continue;
811
+ if (options.dryRun) {
812
+ result.pending[locale] = missing;
813
+ continue;
814
+ }
815
+ for (let i = 0; i < missing.length; i += batchSize) {
816
+ const keys = missing.slice(i, i + batchSize);
817
+ const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
818
+ const out = await provider({
819
+ sourceLocale: cfg.sourceLocale,
820
+ targetLocale: locale,
821
+ messages
822
+ });
823
+ for (const key of keys) {
824
+ const text = out[key];
825
+ if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
826
+ catalog[key] = text;
827
+ (result.translated[locale] ??= []).push(key);
828
+ } else (result.invalid[locale] ??= []).push(key);
829
+ }
830
+ }
831
+ }
832
+ return result;
833
+ }
834
+ function structureMatches(source, translated) {
835
+ return sameMembers(paramNames(source), paramNames(translated)) && sameMembers(tagTokens(source), tagTokens(translated));
836
+ }
837
+ function paramNames(message) {
838
+ try {
839
+ return [...collectParams(message).keys()].sort();
840
+ } catch {
841
+ return ["\0invalid"];
842
+ }
843
+ }
844
+ const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
845
+ function tagTokens(message) {
846
+ const out = [];
847
+ for (const match of message.matchAll(TAG)) out.push(`${match[1]}${match[2]}${match[3]}`);
848
+ return out.sort();
849
+ }
850
+ function sameMembers(a, b) {
851
+ return a.length === b.length && a.every((value, i) => value === b[i]);
852
+ }
853
+ //#endregion
854
+ //#region src/exchange.ts
855
+ function exportCatalogs(cfg, catalogs, options = {}) {
856
+ const format = options.format ?? "xliff";
857
+ const dir = resolve(cfg.root, options.out ?? "verbaly-export");
858
+ const source = catalogs[cfg.sourceLocale] ?? {};
859
+ const targets = (options.locales ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
860
+ const files = [];
861
+ mkdirSync(dir, { recursive: true });
862
+ for (const locale of targets) {
863
+ const catalog = catalogs[locale] ?? {};
864
+ let entries = Object.keys(source).filter((key) => source[key]).sort().map((key) => ({
865
+ key,
866
+ source: source[key],
867
+ target: catalog[key] ?? ""
868
+ }));
869
+ if (options.missing) entries = entries.filter((entry) => !entry.target);
870
+ const path = join(dir, `${locale}.${format === "csv" ? "csv" : "xlf"}`);
871
+ writeFileSync(path, format === "csv" ? toCsv(entries) : toXliff(cfg.sourceLocale, locale, entries));
872
+ files.push({
873
+ locale,
874
+ path,
875
+ total: entries.length,
876
+ untranslated: entries.filter((entry) => !entry.target).length
877
+ });
878
+ }
879
+ return {
880
+ format,
881
+ dir,
882
+ files
883
+ };
884
+ }
885
+ function importCatalogs(cfg, catalogs, files, options = {}) {
886
+ const source = catalogs[cfg.sourceLocale] ?? {};
887
+ const result = {
888
+ imported: {},
889
+ rejected: {},
890
+ skipped: {},
891
+ unknown: {}
892
+ };
893
+ for (const file of files) {
894
+ const parsed = parseExchangeFile(file, options.locale);
895
+ const locale = parsed.locale;
896
+ if (!/^[a-zA-Z]{2,3}([-_][a-zA-Z0-9]+)*$/.test(locale)) throw new Error(`[verbaly] ${file}: "${locale}" doesn't look like a locale — pass --locale <id>.`);
897
+ 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.`);
898
+ const catalog = catalogs[locale] ??= {};
899
+ for (const [key, text] of Object.entries(parsed.entries)) {
900
+ if (!text.trim()) continue;
901
+ if (!source[key]) {
902
+ (result.unknown[locale] ??= []).push(key);
903
+ continue;
904
+ }
905
+ if (catalog[key] && !options.overwrite) {
906
+ (result.skipped[locale] ??= []).push(key);
907
+ continue;
908
+ }
909
+ if (!structureMatches(source[key], text)) {
910
+ (result.rejected[locale] ??= []).push(key);
911
+ continue;
912
+ }
913
+ if (!options.dryRun) catalog[key] = text;
914
+ (result.imported[locale] ??= []).push(key);
915
+ }
916
+ }
917
+ return result;
918
+ }
919
+ function parseExchangeFile(file, localeOverride) {
920
+ const content = readFileSync(file, "utf8");
921
+ if (/\.(xlf|xliff)$/i.test(file)) {
922
+ const parsed = parseXliff(content);
923
+ const locale = localeOverride ?? parsed.locale;
924
+ if (!locale) throw new Error(`[verbaly] ${file} has no trgLang/target-language — pass --locale <id>.`);
925
+ return {
926
+ locale,
927
+ entries: parsed.entries
928
+ };
929
+ }
930
+ if (/\.csv$/i.test(file)) return {
931
+ locale: localeOverride ?? basename(file).replace(/\.csv$/i, ""),
932
+ entries: parseCsv(content)
933
+ };
934
+ throw new Error(`[verbaly] ${file}: unsupported format — expected .xlf, .xliff or .csv.`);
935
+ }
936
+ function toXliff(sourceLocale, locale, entries) {
937
+ const units = entries.map(({ key, source, target }) => [
938
+ ` <unit id="${escapeXml(key)}">`,
939
+ ` <segment state="${target ? "translated" : "initial"}">`,
940
+ ` <source>${escapeXml(source)}</source>`,
941
+ ` <target>${escapeXml(target)}</target>`,
942
+ " </segment>",
943
+ " </unit>"
944
+ ].join("\n")).join("\n");
945
+ return [
946
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
947
+ `<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0" srcLang="${escapeXml(sourceLocale)}" trgLang="${escapeXml(locale)}">`,
948
+ ` <file id="verbaly" original="${escapeXml(`${locale}.json`)}">`,
949
+ units,
950
+ " </file>",
951
+ "</xliff>",
952
+ ""
953
+ ].join("\n");
954
+ }
955
+ function parseXliff(content) {
956
+ const locale = /\btrgLang\s*=\s*"([^"]+)"/.exec(content)?.[1] ?? /\btarget-language\s*=\s*"([^"]+)"/.exec(content)?.[1];
957
+ const entries = {};
958
+ for (const match of content.matchAll(/<(?:trans-)?unit\b([^>]*)>([\s\S]*?)<\/(?:trans-)?unit>/g)) {
959
+ const id = /\bid\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
960
+ if (!id) continue;
961
+ const target = /<target\b[^>]*>([\s\S]*?)<\/target>/.exec(match[2])?.[1];
962
+ entries[unescapeXml(id)] = target === void 0 ? "" : unescapeXml(stripCdata(target));
963
+ }
964
+ return {
965
+ locale,
966
+ entries
967
+ };
968
+ }
969
+ function escapeXml(text) {
970
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
971
+ }
972
+ function stripCdata(text) {
973
+ return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
974
+ }
975
+ function unescapeXml(text) {
976
+ return text.replace(/&(lt|gt|amp|quot|apos|#x?[0-9a-fA-F]+);/g, (_, entity) => {
977
+ if (entity === "lt") return "<";
978
+ if (entity === "gt") return ">";
979
+ if (entity === "amp") return "&";
980
+ if (entity === "quot") return "\"";
981
+ if (entity === "apos") return "'";
982
+ const code = entity.startsWith("#x") ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);
983
+ return String.fromCodePoint(code);
984
+ });
985
+ }
986
+ function toCsv(entries) {
987
+ return [
988
+ "key,source,target",
989
+ ...entries.map(({ key, source, target }) => `${csvField(key)},${csvField(source)},${csvField(target)}`),
990
+ ""
991
+ ].join("\r\n");
992
+ }
993
+ function csvField(text) {
994
+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
995
+ }
996
+ function parseCsv(content) {
997
+ const rows = csvRows(content);
998
+ const header = rows[0]?.map((cell) => cell.trim().toLowerCase()) ?? [];
999
+ const keyCol = header.indexOf("key");
1000
+ const targetCol = header.indexOf("target");
1001
+ if (keyCol === -1 || targetCol === -1) throw new Error("[verbaly] CSV needs a header row with \"key\" and \"target\" columns.");
1002
+ const entries = {};
1003
+ for (const row of rows.slice(1)) {
1004
+ const key = row[keyCol];
1005
+ if (key) entries[key] = row[targetCol] ?? "";
1006
+ }
1007
+ return entries;
1008
+ }
1009
+ function csvRows(content) {
1010
+ const rows = [];
1011
+ let row = [];
1012
+ let field = "";
1013
+ let quoted = false;
1014
+ for (let i = 0; i < content.length; i++) {
1015
+ const char = content[i];
1016
+ if (quoted) if (char === "\"") if (content[i + 1] === "\"") {
1017
+ field += "\"";
1018
+ i++;
1019
+ } else quoted = false;
1020
+ else field += char;
1021
+ else if (char === "\"") quoted = true;
1022
+ else if (char === ",") {
1023
+ row.push(field);
1024
+ field = "";
1025
+ } else if (char === "\n" || char === "\r") {
1026
+ if (char === "\r" && content[i + 1] === "\n") i++;
1027
+ row.push(field);
1028
+ field = "";
1029
+ if (row.some((cell) => cell !== "")) rows.push(row);
1030
+ row = [];
1031
+ } else field += char;
1032
+ }
1033
+ row.push(field);
1034
+ if (row.some((cell) => cell !== "")) rows.push(row);
1035
+ return rows;
1036
+ }
1037
+ //#endregion
797
1038
  //#region src/providers/claude.ts
798
1039
  const DEFAULT_MODEL = "claude-sonnet-5";
799
1040
  const SYSTEM = `You translate UI strings for the Verbaly i18n library.
@@ -1258,63 +1499,6 @@ function transformCode(code, file, analysis) {
1258
1499
  };
1259
1500
  }
1260
1501
  //#endregion
1261
- //#region src/translate.ts
1262
- async function translateCatalogs(cfg, catalogs, provider, options = {}) {
1263
- const batchSize = options.batchSize ?? 20;
1264
- const targets = (options.locales ?? cfg.locales).filter((locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale));
1265
- const source = catalogs[cfg.sourceLocale] ?? {};
1266
- const result = {
1267
- translated: {},
1268
- invalid: {},
1269
- pending: {}
1270
- };
1271
- for (const locale of targets) {
1272
- const catalog = catalogs[locale] ??= {};
1273
- const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
1274
- if (missing.length === 0) continue;
1275
- if (options.dryRun) {
1276
- result.pending[locale] = missing;
1277
- continue;
1278
- }
1279
- for (let i = 0; i < missing.length; i += batchSize) {
1280
- const keys = missing.slice(i, i + batchSize);
1281
- const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
1282
- const out = await provider({
1283
- sourceLocale: cfg.sourceLocale,
1284
- targetLocale: locale,
1285
- messages
1286
- });
1287
- for (const key of keys) {
1288
- const text = out[key];
1289
- if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
1290
- catalog[key] = text;
1291
- (result.translated[locale] ??= []).push(key);
1292
- } else (result.invalid[locale] ??= []).push(key);
1293
- }
1294
- }
1295
- }
1296
- return result;
1297
- }
1298
- function structureMatches(source, translated) {
1299
- return sameMembers(paramNames(source), paramNames(translated)) && sameMembers(tagTokens(source), tagTokens(translated));
1300
- }
1301
- function paramNames(message) {
1302
- try {
1303
- return [...collectParams(message).keys()].sort();
1304
- } catch {
1305
- return ["\0invalid"];
1306
- }
1307
- }
1308
- const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
1309
- function tagTokens(message) {
1310
- const out = [];
1311
- for (const match of message.matchAll(TAG)) out.push(`${match[1]}${match[2]}${match[3]}`);
1312
- return out.sort();
1313
- }
1314
- function sameMembers(a, b) {
1315
- return a.length === b.length && a.every((value, i) => value === b[i]);
1316
- }
1317
- //#endregion
1318
- export { MessageRegistry, PSEUDO_LOCALE, VIRTUAL_ID, analyze, catalogPath, check, claudeProvider, collectParams, detectBundler, doctor, extractProject, findConfigFile, formatCheckResult, generateDts, generateLocaleModule, generateRuntimeModule, init, loadCatalogs, loadConfig, loadConfigFile, pruneCatalogs, pseudoCatalogs, pseudoLocalize, readCatalog, renderHtml, renderParamType, renderSite, resolveConfig, serializeCatalog, stableKey, structureMatches, syncCatalogs, transformCode, translateCatalogs, writeCatalog, writeDts };
1502
+ export { MessageRegistry, PSEUDO_LOCALE, VIRTUAL_ID, analyze, catalogPath, check, claudeProvider, collectParams, detectBundler, doctor, exportCatalogs, extractProject, findConfigFile, formatCheckResult, generateDts, generateLocaleModule, generateRuntimeModule, importCatalogs, init, loadCatalogs, loadConfig, loadConfigFile, parseExchangeFile, pruneCatalogs, pseudoCatalogs, pseudoLocalize, readCatalog, renderHtml, renderParamType, renderSite, resolveConfig, serializeCatalog, stableKey, structureMatches, syncCatalogs, transformCode, translateCatalogs, writeCatalog, writeDts };
1319
1503
 
1320
1504
  //# sourceMappingURL=index.js.map