auto-translate-json-library 1.5.4 → 2.0.2

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.
Files changed (108) hide show
  1. package/README.MD +1141 -148
  2. package/build/package.json +97 -21
  3. package/build/src/aws.d.ts +1 -1
  4. package/build/src/aws.js +27 -38
  5. package/build/src/azure.d.ts +1 -1
  6. package/build/src/azure.js +50 -63
  7. package/build/src/bin/cli.d.ts +1 -1
  8. package/build/src/bin/cli.js +196 -37
  9. package/build/src/config.d.ts +1 -0
  10. package/build/src/config.js +1 -2
  11. package/build/src/deepl.d.ts +1 -1
  12. package/build/src/deepl.js +18 -64
  13. package/build/src/files.d.ts +11 -2
  14. package/build/src/files.js +356 -69
  15. package/build/src/folderFiles.d.ts +6 -3
  16. package/build/src/folderFiles.js +33 -44
  17. package/build/src/format/arb-handler.d.ts +33 -0
  18. package/build/src/format/arb-handler.js +679 -0
  19. package/build/src/format/base-format-handler.d.ts +75 -0
  20. package/build/src/format/base-format-handler.js +166 -0
  21. package/build/src/format/csv-handler.d.ts +38 -0
  22. package/build/src/format/csv-handler.js +604 -0
  23. package/build/src/format/index.d.ts +17 -0
  24. package/build/src/format/index.js +48 -0
  25. package/build/src/format/json-handler.d.ts +17 -0
  26. package/build/src/format/json-handler.js +294 -0
  27. package/build/src/format/po-handler.d.ts +17 -0
  28. package/build/src/format/po-handler.js +338 -0
  29. package/build/src/format/po-utils.d.ts +86 -0
  30. package/build/src/format/po-utils.js +385 -0
  31. package/build/src/format/pot-handler.d.ts +22 -0
  32. package/build/src/format/pot-handler.js +331 -0
  33. package/build/src/format/properties-handler.d.ts +26 -0
  34. package/build/src/format/properties-handler.js +500 -0
  35. package/build/src/format/tsv-handler.d.ts +13 -0
  36. package/build/src/format/tsv-handler.js +67 -0
  37. package/build/src/format/xliff-handler.d.ts +24 -0
  38. package/build/src/format/xliff-handler.js +433 -0
  39. package/build/src/format/xmb-handler.d.ts +33 -0
  40. package/build/src/format/xmb-handler.js +484 -0
  41. package/build/src/format/xmb-xtb-utils.d.ts +43 -0
  42. package/build/src/format/xmb-xtb-utils.js +180 -0
  43. package/build/src/format/xml-handler.d.ts +28 -0
  44. package/build/src/format/xml-handler.js +561 -0
  45. package/build/src/format/xtb-handler.d.ts +33 -0
  46. package/build/src/format/xtb-handler.js +518 -0
  47. package/build/src/format/yaml-handler.d.ts +26 -0
  48. package/build/src/format/yaml-handler.js +522 -0
  49. package/build/src/format-detector.d.ts +7 -0
  50. package/build/src/format-detector.js +58 -0
  51. package/build/src/format-handler-factory.d.ts +9 -0
  52. package/build/src/format-handler-factory.js +18 -0
  53. package/build/src/format.interface.d.ts +56 -0
  54. package/build/src/format.interface.js +1 -0
  55. package/build/src/google.d.ts +1 -1
  56. package/build/src/google.js +32 -49
  57. package/build/src/index.d.ts +4 -3
  58. package/build/src/index.js +15 -17
  59. package/build/src/lib.d.ts +1 -1
  60. package/build/src/lib.js +188 -133
  61. package/build/src/openai.d.ts +2 -2
  62. package/build/src/openai.js +59 -50
  63. package/build/src/translate.interface.d.ts +1 -1
  64. package/build/src/translate.interface.js +1 -2
  65. package/build/src/util.js +4 -9
  66. package/build/src/validation/enhanced-validation-result.d.ts +96 -0
  67. package/build/src/validation/enhanced-validation-result.js +198 -0
  68. package/build/src/validation/error-messages.d.ts +88 -0
  69. package/build/src/validation/error-messages.js +436 -0
  70. package/build/src/validation/error-recovery.d.ts +78 -0
  71. package/build/src/validation/error-recovery.js +593 -0
  72. package/build/src/validation/example-usage.d.ts +31 -0
  73. package/build/src/validation/example-usage.js +148 -0
  74. package/build/src/validation/format-rules.d.ts +37 -0
  75. package/build/src/validation/format-rules.js +550 -0
  76. package/build/src/validation/format-validator.d.ts +70 -0
  77. package/build/src/validation/format-validator.js +279 -0
  78. package/build/src/validation/index.d.ts +13 -0
  79. package/build/src/validation/index.js +30 -0
  80. package/build/src/validation/validation-service.d.ts +56 -0
  81. package/build/src/validation/validation-service.js +262 -0
  82. package/build/tests/arb-handler.test.d.ts +1 -0
  83. package/build/tests/arb-handler.test.js +694 -0
  84. package/build/tests/cli-integration.test.d.ts +1 -0
  85. package/build/tests/cli-integration.test.js +352 -0
  86. package/build/tests/csv-handler.test.d.ts +1 -0
  87. package/build/tests/csv-handler.test.js +507 -0
  88. package/build/tests/error-handling.test.d.ts +1 -0
  89. package/build/tests/error-handling.test.js +456 -0
  90. package/build/tests/files-integration.test.d.ts +1 -0
  91. package/build/tests/files-integration.test.js +421 -0
  92. package/build/tests/json-handler.test.d.ts +1 -0
  93. package/build/tests/json-handler.test.js +526 -0
  94. package/build/tests/po-handler.test.d.ts +1 -0
  95. package/build/tests/po-handler.test.js +768 -0
  96. package/build/tests/properties-handler.test.d.ts +1 -0
  97. package/build/tests/properties-handler.test.js +316 -0
  98. package/build/tests/setup.d.ts +1 -0
  99. package/build/tests/setup.js +5 -0
  100. package/build/tests/xliff-handler.test.d.ts +1 -0
  101. package/build/tests/xliff-handler.test.js +459 -0
  102. package/build/tests/xmb-xtb-handler.test.d.ts +1 -0
  103. package/build/tests/xmb-xtb-handler.test.js +758 -0
  104. package/build/tests/xml-handler.test.d.ts +1 -0
  105. package/build/tests/xml-handler.test.js +570 -0
  106. package/build/tests/yaml-handler.test.d.ts +1 -0
  107. package/build/tests/yaml-handler.test.js +156 -0
  108. package/package.json +97 -21
@@ -1,62 +1,45 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.GoogleTranslate = void 0;
13
- const v2_1 = require("@google-cloud/translate/build/src/v2");
14
- const util_1 = require("./util");
15
- class GoogleTranslate {
1
+ import { v2 as translate } from "@google-cloud/translate";
2
+ import { Util } from "./util.js";
3
+ export class GoogleTranslate {
4
+ googleTranslate;
5
+ supportedLanguages;
16
6
  constructor(googleTranslate, supportedLanguages = []) {
17
7
  this.googleTranslate = googleTranslate;
18
8
  this.supportedLanguages = supportedLanguages;
19
9
  }
20
- static initialize(apiKey) {
21
- return __awaiter(this, void 0, void 0, function* () {
22
- const googleTranslate = new v2_1.Translate({ key: apiKey });
23
- const supportedLanguages = yield GoogleTranslate.getSupportedLanguages(googleTranslate);
24
- return new GoogleTranslate(googleTranslate, supportedLanguages);
25
- });
10
+ static async initialize(apiKey) {
11
+ const googleTranslate = new translate.Translate({ key: apiKey });
12
+ const supportedLanguages = await GoogleTranslate.getSupportedLanguages(googleTranslate);
13
+ return new GoogleTranslate(googleTranslate, supportedLanguages);
26
14
  }
27
- static getSupportedLanguages(translate) {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- const [languages] = yield translate.getLanguages();
30
- return languages.map((language, _index, _array) => language.code.toLowerCase());
31
- });
15
+ static async getSupportedLanguages(translate) {
16
+ const [languages] = await translate.getLanguages();
17
+ return languages.map((language, _index, _array) => language.code.toLowerCase());
32
18
  }
33
19
  isValidLocale(targetLocale) {
34
20
  return this.supportedLanguages.includes(targetLocale);
35
21
  }
36
- translateText(text, _sourceLocale, targetLocale) {
37
- return __awaiter(this, void 0, void 0, function* () {
38
- let args;
39
- ({ args, text } = util_1.Util.replaceContextVariables(text));
40
- let result = "";
41
- try {
42
- const response = yield this.googleTranslate.translate(text, targetLocale);
43
- result = response[0];
44
- }
45
- catch (error) {
46
- if (error instanceof Error) {
47
- let message = error.message;
48
- if (error.message === "Invalid Value") {
49
- message = `Invalid Locale ${targetLocale}`;
50
- }
51
- console.error(message);
52
- return message;
22
+ async translateText(text, _sourceLocale, targetLocale) {
23
+ let args;
24
+ ({ args, text } = Util.replaceContextVariables(text));
25
+ let result = "";
26
+ try {
27
+ const response = await this.googleTranslate.translate(text, targetLocale);
28
+ result = response[0];
29
+ }
30
+ catch (error) {
31
+ if (error instanceof Error) {
32
+ let message = error.message;
33
+ if (error.message === "Invalid Value") {
34
+ message = `Invalid Locale ${targetLocale}`;
53
35
  }
54
- return "error";
36
+ console.error(message);
37
+ return message;
55
38
  }
56
- // replace arguments with numbers
57
- result = util_1.Util.replaceArgumentsWithNumbers(args, result);
58
- return result;
59
- });
39
+ return "error";
40
+ }
41
+ // replace arguments with numbers
42
+ result = Util.replaceArgumentsWithNumbers(args, result);
43
+ return result;
60
44
  }
61
45
  }
62
- exports.GoogleTranslate = GoogleTranslate;
@@ -1,3 +1,4 @@
1
- import { Configuration } from "./config";
2
- import { translate } from "./lib";
3
- export { Configuration, translate };
1
+ import { Configuration } from "./config.js";
2
+ import { translate } from "./lib.js";
3
+ export type { Configuration };
4
+ export { translate };
@@ -1,8 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.translate = void 0;
4
- const lib_1 = require("./lib");
5
- Object.defineProperty(exports, "translate", { enumerable: true, get: function () { return lib_1.translate; } });
1
+ import { translate } from "./lib.js";
2
+ export { translate };
6
3
  const config = {};
7
4
  setDefaultConfiguration();
8
5
  console.log(config);
@@ -20,8 +17,10 @@ catch (error) {
20
17
  console.log(config);
21
18
  console.log(error);
22
19
  }
20
+ import { config as dotenvConfig } from "dotenv";
21
+ import minimist from "minimist";
23
22
  function setConfigurationFromCLI() {
24
- const argv = require("yargs").argv;
23
+ const argv = minimist(process.argv.slice(2));
25
24
  if (argv === undefined) {
26
25
  console.log("No arguments provided in CLI");
27
26
  return;
@@ -57,7 +56,7 @@ function setConfigurationFromCLI() {
57
56
  config.ignorePrefix = argv.ignorePrefix;
58
57
  }
59
58
  if (argv.pivotTranslation !== undefined) {
60
- (0, lib_1.translate)(argv.pivotTranslation, config);
59
+ translate(argv.pivotTranslation, config);
61
60
  }
62
61
  else {
63
62
  console.log(argv);
@@ -74,8 +73,7 @@ function setDefaultConfiguration() {
74
73
  config.ignorePrefix = "";
75
74
  }
76
75
  function setConfigurationFromEnvironment() {
77
- var _a, _b, _c, _d, _e, _f, _g, _h;
78
- require("dotenv").config();
76
+ dotenvConfig();
79
77
  if (process.env.ATJ_GOOGLE_API_KEY) {
80
78
  config.translationKeyInfo = {
81
79
  kind: "google",
@@ -115,14 +113,14 @@ function setConfigurationFromEnvironment() {
115
113
  config.translationKeyInfo = {
116
114
  kind: "openai",
117
115
  apiKey: process.env.ATJ_OPEN_AI_SECRET_KEY,
118
- baseUrl: (_a = process.env.ATJ_OPEN_AI_BASE_URL) !== null && _a !== void 0 ? _a : "https://api.openai.com/v1",
119
- model: (_b = process.env.ATJ_OPEN_AI_MODEL) !== null && _b !== void 0 ? _b : "gpt-3.5-turbo",
120
- maxTokens: Number((_c = process.env.ATJ_OPEN_AI_MAX_TOKENS) !== null && _c !== void 0 ? _c : "256"),
121
- temperature: Number((_d = process.env.ATJ_OPEN_AI_TEMPERATURE) !== null && _d !== void 0 ? _d : "0.7"),
122
- topP: Number((_e = process.env.ATJ_OPEN_AI_TOP_P) !== null && _e !== void 0 ? _e : "0.9"),
123
- n: Number((_f = process.env.ATJ_OPEN_AI_N) !== null && _f !== void 0 ? _f : "1"),
124
- frequencyPenalty: Number((_g = process.env.ATJ_OPEN_AI_FREQUENCY_PENALTY) !== null && _g !== void 0 ? _g : "0"),
125
- presencePenalty: Number((_h = process.env.ATJ_OPEN_AI_PRESENCE_PENALTY) !== null && _h !== void 0 ? _h : "0"),
116
+ baseUrl: process.env.ATJ_OPEN_AI_BASE_URL ?? "https://api.openai.com/v1",
117
+ model: process.env.ATJ_OPEN_AI_MODEL ?? "gpt-3.5-turbo",
118
+ maxTokens: Number(process.env.ATJ_OPEN_AI_MAX_TOKENS ?? "256"),
119
+ temperature: Number(process.env.ATJ_OPEN_AI_TEMPERATURE ?? "0.7"),
120
+ topP: Number(process.env.ATJ_OPEN_AI_TOP_P ?? "0.9"),
121
+ n: Number(process.env.ATJ_OPEN_AI_N ?? "1"),
122
+ frequencyPenalty: Number(process.env.ATJ_OPEN_AI_FREQUENCY_PENALTY ?? "0"),
123
+ presencePenalty: Number(process.env.ATJ_OPEN_AI_PRESENCE_PENALTY ?? "0"),
126
124
  };
127
125
  }
128
126
  if (process.env.ATJ_START_DELIMITER) {
@@ -1,2 +1,2 @@
1
- import type { Configuration } from "./config";
1
+ import type { Configuration } from "./config.js";
2
2
  export declare function translate(sourceFile: string, config: Configuration): Promise<void>;
package/build/src/lib.js CHANGED
@@ -1,113 +1,122 @@
1
- "use strict";
2
1
  // The module 'vscode' contains the VS Code extensibility API
3
2
  // Import the module and reference it with the alias vscode in your code below
4
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
- return new (P || (P = Promise))(function (resolve, reject) {
7
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
- step((generator = generator.apply(thisArg, _arguments || [])).next());
11
- });
12
- };
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.translate = translate;
15
- const aws_1 = require("./aws");
16
- const azure_1 = require("./azure");
17
- const deepl_1 = require("./deepl");
18
- const files_1 = require("./files");
19
- const folderFiles_1 = require("./folderFiles");
20
- const google_1 = require("./google");
21
- const openai_1 = require("./openai");
22
- const util_1 = require("./util");
23
- function translate(sourceFile, config) {
24
- return __awaiter(this, void 0, void 0, function* () {
25
- var _a;
26
- // set the delimiters for named arguments
27
- const startDelimiter = config.startDelimiter || "{";
28
- if (startDelimiter) {
29
- util_1.Util.startDelimiter = startDelimiter;
30
- }
31
- const endDelimiter = config.endDelimiter || "}";
32
- if (endDelimiter) {
33
- util_1.Util.endDelimiter = endDelimiter;
34
- }
35
- let translateEngine;
36
- if (config.translationKeyInfo.kind === "google") {
37
- translateEngine = yield google_1.GoogleTranslate.initialize(config.translationKeyInfo.apiKey);
38
- }
39
- else if (config.translationKeyInfo.kind === "aws") {
40
- translateEngine = new aws_1.AWSTranslate(config.translationKeyInfo.accessKeyId, config.translationKeyInfo.secretAccessKey, config.translationKeyInfo.region);
41
- }
42
- else if (config.translationKeyInfo.kind === "azure") {
43
- translateEngine = new azure_1.AzureTranslate(config.translationKeyInfo.secretKey, config.translationKeyInfo.region);
44
- }
45
- else if (config.translationKeyInfo.kind === "deepLFree") {
46
- translateEngine = new deepl_1.DeepLTranslate(config.translationKeyInfo.secretKey, "free");
47
- }
48
- else if (config.translationKeyInfo.kind === "deepLPro") {
49
- translateEngine = new deepl_1.DeepLTranslate(config.translationKeyInfo.secretKey, "pro");
50
- }
51
- else if (config.translationKeyInfo.kind === "openai") {
52
- translateEngine = new openai_1.OpenAITranslate(config.translationKeyInfo.apiKey, config.translationKeyInfo.baseUrl, config.translationKeyInfo.model, config.translationKeyInfo.maxTokens, config.translationKeyInfo.temperature, config.translationKeyInfo.topP, config.translationKeyInfo.n, config.translationKeyInfo.presencePenalty, config.translationKeyInfo.frequencyPenalty);
53
- }
54
- else {
55
- console.warn("You must provide a Google, AWS, Azure, deepL, openai parameters first in the extension settings.");
56
- return;
57
- }
58
- const fileMode = (_a = config.mode) !== null && _a !== void 0 ? _a : "file";
59
- const files = readFiles(sourceFile, fileMode);
60
- if (files === null) {
61
- return;
62
- }
63
- // enforce source locale if provided in settings
64
- if (config.sourceLocale !== files.sourceLocale) {
65
- console.log(`You must use the ${config.sourceLocale}.json file due to your Source Locale setting.`);
66
- return;
3
+ import { AWSTranslate } from "./aws.js";
4
+ import { AzureTranslate } from "./azure.js";
5
+ import { DeepLTranslate } from "./deepl.js";
6
+ import { Files } from "./files.js";
7
+ import { FolderFiles } from "./folderFiles.js";
8
+ import { GoogleTranslate } from "./google.js";
9
+ import { OpenAITranslate } from "./openai.js";
10
+ import { Util } from "./util.js";
11
+ export async function translate(sourceFile, config) {
12
+ // set the delimiters for named arguments
13
+ const startDelimiter = config.startDelimiter || "{";
14
+ if (startDelimiter) {
15
+ Util.startDelimiter = startDelimiter;
16
+ }
17
+ const endDelimiter = config.endDelimiter || "}";
18
+ if (endDelimiter) {
19
+ Util.endDelimiter = endDelimiter;
20
+ }
21
+ let translateEngine;
22
+ if (config.translationKeyInfo.kind === "google") {
23
+ translateEngine = await GoogleTranslate.initialize(config.translationKeyInfo.apiKey);
24
+ }
25
+ else if (config.translationKeyInfo.kind === "aws") {
26
+ translateEngine = new AWSTranslate(config.translationKeyInfo.accessKeyId, config.translationKeyInfo.secretAccessKey, config.translationKeyInfo.region);
27
+ }
28
+ else if (config.translationKeyInfo.kind === "azure") {
29
+ translateEngine = new AzureTranslate(config.translationKeyInfo.secretKey, config.translationKeyInfo.region);
30
+ }
31
+ else if (config.translationKeyInfo.kind === "deepLFree") {
32
+ translateEngine = new DeepLTranslate(config.translationKeyInfo.secretKey, "free");
33
+ }
34
+ else if (config.translationKeyInfo.kind === "deepLPro") {
35
+ translateEngine = new DeepLTranslate(config.translationKeyInfo.secretKey, "pro");
36
+ }
37
+ else if (config.translationKeyInfo.kind === "openai") {
38
+ translateEngine = new OpenAITranslate(config.translationKeyInfo.apiKey, config.translationKeyInfo.baseUrl, config.translationKeyInfo.model, config.translationKeyInfo.maxTokens, config.translationKeyInfo.temperature, config.translationKeyInfo.topP, config.translationKeyInfo.n, config.translationKeyInfo.presencePenalty, config.translationKeyInfo.frequencyPenalty);
39
+ }
40
+ else {
41
+ console.warn("You must provide a Google, AWS, Azure, deepL, openai parameters first in the extension settings.");
42
+ return;
43
+ }
44
+ const fileMode = config.mode ?? "file";
45
+ const files = readFiles(sourceFile, fileMode, config.format);
46
+ if (files === null) {
47
+ return;
48
+ }
49
+ // enforce source locale if provided in settings
50
+ if (config.sourceLocale !== files.sourceLocale) {
51
+ console.log(`You must use the ${config.sourceLocale} file (matching extension) due to your Source Locale setting.`);
52
+ return;
53
+ }
54
+ const keepTranslations = config.keepTranslations === "keep";
55
+ const keepExtras = config.keepExtraTranslations === "keep";
56
+ // load source JSON
57
+ let source;
58
+ try {
59
+ console.log(`📖 Loading source file for locale '${files.sourceLocale}'...`);
60
+ source = await files.loadJsonFromLocale(files.sourceLocale);
61
+ console.log(`✅ Successfully loaded source file`);
62
+ }
63
+ catch (error) {
64
+ if (error instanceof Error) {
65
+ console.error(`❌ Source file malformed: ${error.message}`);
67
66
  }
68
- const keepTranslations = config.keepTranslations === "keep";
69
- const keepExtras = config.keepExtraTranslations === "keep";
70
- // load source JSON
71
- let source;
67
+ return;
68
+ }
69
+ // Iterate target Locales
70
+ console.log(`🌍 Processing ${files.targetLocales.length} target locale(s)...`);
71
+ for (let i = 0; i < files.targetLocales.length; i++) {
72
+ const targetLocale = files.targetLocales[i];
72
73
  try {
73
- source = yield files.loadJsonFromLocale(files.sourceLocale);
74
+ console.log(`🔄 [${i + 1}/${files.targetLocales.length}] Processing locale '${targetLocale}'...`);
75
+ const isValid = await translateEngine.isValidLocale(targetLocale);
76
+ if (!isValid) {
77
+ console.warn(`⚠️ Locale '${targetLocale}' is not supported by ${config.translationKeyInfo.kind}. Skipping.`);
78
+ continue;
79
+ }
80
+ console.log(`📖 Loading existing translations for '${targetLocale}'...`);
81
+ const targetOriginal = await files.loadJsonFromLocale(targetLocale);
82
+ console.log(`🔤 Translating content from '${files.sourceLocale}' to '${targetLocale}'...`);
83
+ // Iterate source terms
84
+ const targetNew = await recurseNode(source, targetOriginal, keepTranslations, keepExtras, files.sourceLocale, targetLocale, translateEngine, config.ignorePrefix);
85
+ console.log(`💾 Saving translations for '${targetLocale}'...`);
86
+ // save target
87
+ files.saveJsonToLocale(targetLocale, targetNew);
88
+ console.log(`✅ Successfully translated locale '${targetLocale}'`);
74
89
  }
75
90
  catch (error) {
76
91
  if (error instanceof Error) {
77
- console.log(error, "Source file malformed");
92
+ console.error(`❌ Error processing locale '${targetLocale}': ${error.message}`);
93
+ // Continue with other locales instead of stopping completely
94
+ continue;
78
95
  }
79
96
  return;
80
97
  }
81
- // Iterate target Locales
82
- for (const targetLocale of files.targetLocales) {
83
- try {
84
- const isValid = yield translateEngine.isValidLocale(targetLocale);
85
- if (!isValid) {
86
- throw Error(`${targetLocale} is not supported. Skipping.`);
87
- }
88
- const targetOriginal = yield files.loadJsonFromLocale(targetLocale);
89
- // Iterate source terms
90
- const targetNew = yield recurseNode(source, targetOriginal, keepTranslations, keepExtras, files.sourceLocale, targetLocale, translateEngine, config.ignorePrefix);
91
- // save target
92
- files.saveJsonToLocale(targetLocale, targetNew);
93
- const feedback = `Translated locale '${targetLocale}'`;
94
- console.log(feedback);
95
- }
96
- catch (error) {
97
- if (error instanceof Error) {
98
- console.error(error);
99
- }
100
- return;
101
- }
102
- }
103
- });
98
+ }
99
+ console.log(`🎉 Translation completed for all locales!`);
104
100
  }
105
- const readFiles = (filePath, mode) => {
101
+ const readFiles = (filePath, mode, format) => {
106
102
  try {
107
- const files = mode === "file" ? new files_1.Files(filePath) : new folderFiles_1.FolderFiles(filePath);
103
+ const files = mode === "file"
104
+ ? new Files(filePath, format)
105
+ : new FolderFiles(filePath, format);
108
106
  // log locale info
109
107
  console.log(`Source locale = ${files.sourceLocale}`);
110
108
  console.log(`Target locales = ${files.targetLocales}`);
109
+ // Log format information for better user feedback
110
+ if (files.getDetectedFormat && files.getFormatOverride) {
111
+ const detectedFormat = files.getDetectedFormat();
112
+ const formatOverride = files.getFormatOverride();
113
+ if (formatOverride) {
114
+ console.log(`Format override = ${formatOverride}`);
115
+ }
116
+ else if (detectedFormat) {
117
+ console.log(`Detected format = ${detectedFormat}`);
118
+ }
119
+ }
111
120
  return files;
112
121
  }
113
122
  catch (error) {
@@ -117,54 +126,100 @@ const readFiles = (filePath, mode) => {
117
126
  return null;
118
127
  }
119
128
  };
120
- function recurseNode(source_1, original_1, keepTranslations_1, keepExtras_1, sourceLocale_1, locale_1, translateEngine_1) {
121
- return __awaiter(this, arguments, void 0, function* (source, original, keepTranslations, keepExtras, sourceLocale, locale, translateEngine, ignorePrefix = "", isArray = false) {
122
- var _a;
123
- // biome-ignore lint/suspicious/noExplicitAny: array and object types are used for flexibility
124
- const destination = isArray ? [] : {};
125
- // defaults
126
- if (keepTranslations === null) {
127
- keepTranslations = true;
129
+ async function recurseNode(source, original, keepTranslations, keepExtras, sourceLocale, locale, translateEngine, ignorePrefix = "", isArray = false) {
130
+ const destination = isArray ? [] : {};
131
+ // defaults
132
+ if (keepTranslations === null) {
133
+ keepTranslations = true;
134
+ }
135
+ if (keepExtras === null) {
136
+ keepExtras = true;
137
+ }
138
+ for (const term in source) {
139
+ const node = source[term];
140
+ const isXmlNodeLike = typeof source === "object" &&
141
+ source !== null &&
142
+ Object.keys(source).some((k) => k === "#text" || k.startsWith("@_"));
143
+ // Handle metadata specially to prevent translation and ensure correctness
144
+ if (term === "_metadata") {
145
+ // Start with original metadata or clone source metadata
146
+ destination[term] = original[term]
147
+ ? JSON.parse(JSON.stringify(original[term]))
148
+ : JSON.parse(JSON.stringify(node));
149
+ // If ARB format, ensure @@locale matches the target locale
150
+ if (destination[term]?.arbMetadata) {
151
+ destination[term].arbMetadata["@@locale"] = locale;
152
+ }
153
+ continue;
128
154
  }
129
- if (keepExtras === null) {
130
- keepExtras = true;
155
+ if (node instanceof Object && node !== null) {
156
+ destination[term] = await recurseNode(node, original[term] ?? {}, keepTranslations, keepExtras, sourceLocale, locale, translateEngine, ignorePrefix, Array.isArray(node));
131
157
  }
132
- for (const term in source) {
133
- const node = source[term];
134
- if (node instanceof Object && node !== null) {
135
- destination[term] = yield recurseNode(node, (_a = original[term]) !== null && _a !== void 0 ? _a : {}, keepTranslations, keepExtras, sourceLocale, locale, translateEngine, ignorePrefix, Array.isArray(node));
158
+ else {
159
+ // For XML: do not translate attributes (fast-xml-parser uses "@_" prefix)
160
+ if (term.startsWith("@_")) {
161
+ destination[term] = original[term] ?? node;
162
+ continue;
163
+ }
164
+ // For XML-like nodes: only translate text content (#text), skip other keys
165
+ if (isXmlNodeLike && term !== "#text") {
166
+ destination[term] = original[term] ?? node;
167
+ continue;
168
+ }
169
+ // Skip translation for empty/whitespace-only text
170
+ if (term === "#text" &&
171
+ typeof node === "string" &&
172
+ node.trim().length === 0) {
173
+ destination[term] = original[term] ?? node;
174
+ continue;
175
+ }
176
+ // if we already have a translation, keep it
177
+ if (keepTranslations && original[term]) {
178
+ destination[term] = original[term];
179
+ }
180
+ else if (typeof node === "number" || typeof node === "boolean") {
181
+ // numbers and booleans do not need translations
182
+ destination[term] = node;
136
183
  }
137
184
  else {
138
- // if we already have a translation, keep it
139
- if (keepTranslations && original[term]) {
140
- destination[term] = original[term];
185
+ // Only translate non-empty strings
186
+ if (typeof node !== "string") {
187
+ destination[term] = original[term] ?? node;
188
+ continue;
141
189
  }
142
- else if (typeof node === "number" || typeof node === "boolean") {
143
- // numbers and booleans do not need translations
144
- destination[term] = node;
190
+ const textValue = node.trim();
191
+ if (textValue.length === 0) {
192
+ destination[term] = original[term] ?? node;
193
+ continue;
145
194
  }
146
- else {
147
- if (ignorePrefix === "" ||
148
- (ignorePrefix !== "" && !term.startsWith(ignorePrefix))) {
149
- const translation = yield translateEngine
150
- .translateText(node, sourceLocale, locale)
151
- .catch((err) => console.error(err));
152
- destination[term] = translation;
153
- }
154
- else {
155
- delete destination[term];
195
+ if (ignorePrefix === "" ||
196
+ (ignorePrefix !== "" && !term.startsWith(ignorePrefix))) {
197
+ // Extract context if available (e.g. from ARB metadata)
198
+ let context;
199
+ // @ts-ignore: _metadata is loosely typed
200
+ if (source._metadata?.resourceMetadata?.[`@${term}`]) {
201
+ // @ts-ignore
202
+ const meta = source._metadata.resourceMetadata[`@${term}`];
203
+ context = meta.description || meta.context;
156
204
  }
205
+ const translation = await translateEngine
206
+ .translateText(textValue, sourceLocale, locale, context)
207
+ .catch((err) => console.error(err));
208
+ destination[term] = translation ?? textValue;
209
+ }
210
+ else {
211
+ delete destination[term];
157
212
  }
158
213
  }
159
214
  }
160
- if (keepExtras) {
161
- // add back in any terms that were not in source
162
- for (const term in original) {
163
- if (!destination[term]) {
164
- destination[term] = original[term];
165
- }
215
+ }
216
+ if (keepExtras) {
217
+ // add back in any terms that were not in source
218
+ for (const term in original) {
219
+ if (!destination[term]) {
220
+ destination[term] = original[term];
166
221
  }
167
222
  }
168
- return destination;
169
- });
223
+ }
224
+ return destination;
170
225
  }
@@ -1,4 +1,4 @@
1
- import type { ITranslate } from "./translate.interface";
1
+ import type { ITranslate } from "./translate.interface.js";
2
2
  export declare class OpenAITranslate implements ITranslate {
3
3
  private model;
4
4
  private maxTokens;
@@ -10,5 +10,5 @@ export declare class OpenAITranslate implements ITranslate {
10
10
  private openai;
11
11
  constructor(apiKey: string, baseUrl: string, model: string, maxTokens: number, temperature: number, topP: number, n: number, frequencyPenalty: number, presencePenalty: number);
12
12
  isValidLocale(targetLocale: string): boolean;
13
- translateText(text: string, sourceLocale: string, targetLocale: string): Promise<string>;
13
+ translateText(text: string, sourceLocale: string, targetLocale: string, context?: string): Promise<string>;
14
14
  }