auto-translate-json-library 1.5.5 → 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 +96 -22
  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 -64
  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 +96 -22
@@ -0,0 +1,331 @@
1
+ import * as path from "node:path";
2
+ import * as gettextParser from "gettext-parser";
3
+ import { createContextKey, createPluralKey, formatPluralFormsHeader, parseContext, parsePluralIndex, validateContext, } from "./po-utils.js";
4
+ export class POTHandler {
5
+ canHandle(filePath, content) {
6
+ const extension = path.extname(filePath).toLowerCase();
7
+ if (extension !== ".pot") {
8
+ return false;
9
+ }
10
+ // If content is provided, check for POT format signatures
11
+ if (content) {
12
+ return (/^\s*#.*POT-Creation-Date/m.test(content) ||
13
+ (/^\s*msgid\s+"/m.test(content) && /^\s*msgstr\s+""/m.test(content)));
14
+ }
15
+ return true;
16
+ }
17
+ parse(content) {
18
+ try {
19
+ const parsed = gettextParser.po.parse(content);
20
+ // Extract template strings from POT structure
21
+ const templateStrings = this.extractTemplateStrings(parsed);
22
+ // Add metadata
23
+ const result = {
24
+ ...templateStrings,
25
+ _metadata: {
26
+ format: "pot",
27
+ encoding: parsed.charset || "utf-8",
28
+ originalStructure: parsed,
29
+ preserveComments: true,
30
+ preserveAttributes: true,
31
+ potHeaders: parsed.headers,
32
+ sourceLanguage: this.extractLanguageFromHeaders(parsed.headers),
33
+ isTemplate: true,
34
+ },
35
+ };
36
+ return result;
37
+ }
38
+ catch (error) {
39
+ throw new Error(`Failed to parse POT file: ${error instanceof Error ? error.message : String(error)}`);
40
+ }
41
+ }
42
+ serialize(data, options) {
43
+ try {
44
+ const { _metadata, ...translations } = data;
45
+ let potData;
46
+ if (_metadata?.originalStructure) {
47
+ // Use original structure - POT files typically don't get updated with translations
48
+ potData = JSON.parse(JSON.stringify(_metadata.originalStructure));
49
+ }
50
+ else {
51
+ // Create new POT structure from template data
52
+ potData = this.createPOTStructure(translations, _metadata);
53
+ }
54
+ // Apply encoding from options or metadata
55
+ const encoding = options?.encoding || _metadata?.encoding || "utf-8";
56
+ potData.charset = encoding;
57
+ return gettextParser.po.compile(potData, { foldLength: 76 }).toString();
58
+ }
59
+ catch (error) {
60
+ throw new Error(`Failed to serialize POT file: ${error instanceof Error ? error.message : String(error)}`);
61
+ }
62
+ }
63
+ getFileExtension() {
64
+ return ".pot";
65
+ }
66
+ validateStructure(data) {
67
+ const errors = [];
68
+ const warnings = [];
69
+ // Basic structure validation
70
+ if (!data || typeof data !== "object") {
71
+ errors.push({
72
+ code: "INVALID_STRUCTURE",
73
+ message: "POT data must be an object",
74
+ });
75
+ return { isValid: false, errors, warnings };
76
+ }
77
+ // Check for empty template
78
+ const templateKeys = Object.keys(data).filter((key) => key !== "_metadata");
79
+ if (templateKeys.length === 0) {
80
+ warnings.push({
81
+ code: "EMPTY_POT",
82
+ message: "POT template appears to have no translatable strings",
83
+ });
84
+ }
85
+ // Validate template structure - POT files should have empty msgstr values
86
+ for (const [key, value] of Object.entries(data)) {
87
+ if (key === "_metadata")
88
+ continue;
89
+ if (typeof value !== "string") {
90
+ errors.push({
91
+ code: "INVALID_TEMPLATE_VALUE",
92
+ message: `Template value for "${key}" must be a string, got ${typeof value}`,
93
+ });
94
+ }
95
+ else if (value !== "" && !key.includes("[")) {
96
+ // Non-empty values in templates might indicate this is not a proper template
97
+ warnings.push({
98
+ code: "NON_EMPTY_TEMPLATE_VALUE",
99
+ message: `Template value for "${key}" is not empty - POT templates typically have empty msgstr values`,
100
+ });
101
+ }
102
+ }
103
+ // Validate POT-specific headers
104
+ const metadata = data._metadata;
105
+ if (metadata?.potHeaders) {
106
+ this.validatePOTHeaders(metadata.potHeaders, warnings);
107
+ }
108
+ return {
109
+ isValid: errors.length === 0,
110
+ errors,
111
+ warnings,
112
+ };
113
+ }
114
+ /**
115
+ * Generate PO file content from POT template for a specific target language
116
+ */
117
+ generatePOFromTemplate(potContent, targetLanguage, translations) {
118
+ try {
119
+ const potData = gettextParser.po.parse(potContent);
120
+ // Clone the POT structure to create PO
121
+ const poData = JSON.parse(JSON.stringify(potData));
122
+ // Update headers for target language
123
+ this.updateHeadersForLanguage(poData.headers, targetLanguage);
124
+ // Apply translations if provided
125
+ if (translations) {
126
+ this.applyTranslationsToTemplate(poData, translations);
127
+ }
128
+ return gettextParser.po.compile(poData, { foldLength: 76 }).toString();
129
+ }
130
+ catch (error) {
131
+ throw new Error(`Failed to generate PO from POT template: ${error instanceof Error ? error.message : String(error)}`);
132
+ }
133
+ }
134
+ extractTemplateStrings(potData) {
135
+ const result = {};
136
+ for (const [context, translations] of Object.entries(potData.translations)) {
137
+ for (const [msgid, entry] of Object.entries(translations)) {
138
+ // Skip empty msgid (header entry)
139
+ if (!msgid)
140
+ continue;
141
+ // Create unique key for context + msgid using utility function
142
+ const key = createContextKey(context, msgid);
143
+ // Handle plural forms
144
+ if (entry.msgid_plural) {
145
+ // For plural forms in templates, all msgstr entries are typically empty
146
+ result[key] = ""; // Singular form
147
+ // Add plural form entries (typically empty in templates)
148
+ for (let i = 1; i < entry.msgstr.length; i++) {
149
+ const pluralKey = createPluralKey(key, i);
150
+ result[pluralKey] = "";
151
+ }
152
+ }
153
+ else {
154
+ // Regular singular form (typically empty in templates)
155
+ result[key] = "";
156
+ }
157
+ }
158
+ }
159
+ return result;
160
+ }
161
+ createPOTStructure(templateStrings, metadata) {
162
+ const potData = {
163
+ charset: metadata?.encoding || "utf-8",
164
+ headers: metadata?.potHeaders || this.getDefaultPOTHeaders(),
165
+ translations: {
166
+ "": {}, // Default context
167
+ },
168
+ };
169
+ // Add header entry
170
+ potData.translations[""][""] = {
171
+ msgid: "",
172
+ msgstr: [this.formatHeaders(potData.headers)],
173
+ };
174
+ // Process template strings
175
+ for (const [key, value] of Object.entries(templateStrings)) {
176
+ const { context, msgid, pluralIndex } = this.parseTranslationKey(key);
177
+ // Validate context
178
+ if (context && !validateContext(context)) {
179
+ throw new Error(`Invalid context in key "${key}": context cannot contain separator character`);
180
+ }
181
+ // Ensure context exists
182
+ if (!potData.translations[context]) {
183
+ potData.translations[context] = {};
184
+ }
185
+ // Ensure entry exists
186
+ if (!potData.translations[context][msgid]) {
187
+ potData.translations[context][msgid] = {
188
+ msgid,
189
+ msgstr: [""], // Empty in templates
190
+ };
191
+ }
192
+ const entry = potData.translations[context][msgid];
193
+ // Handle plural forms
194
+ if (pluralIndex !== undefined) {
195
+ // Ensure msgstr array is large enough
196
+ while (entry.msgstr.length <= pluralIndex) {
197
+ entry.msgstr.push("");
198
+ }
199
+ // Keep empty for templates
200
+ entry.msgstr[pluralIndex] = "";
201
+ // Set msgid_plural if this is a plural form
202
+ if (pluralIndex > 0 && !entry.msgid_plural) {
203
+ entry.msgid_plural = msgid;
204
+ }
205
+ }
206
+ else {
207
+ // Keep empty for templates
208
+ entry.msgstr[0] = "";
209
+ }
210
+ }
211
+ return potData;
212
+ }
213
+ parseTranslationKey(key) {
214
+ // Parse plural form index first
215
+ const { baseKey, pluralIndex } = parsePluralIndex(key);
216
+ // Parse context from base key
217
+ const { context, msgid } = parseContext(baseKey);
218
+ return {
219
+ context,
220
+ msgid,
221
+ pluralIndex,
222
+ };
223
+ }
224
+ extractLanguageFromHeaders(headers) {
225
+ const languageHeader = headers["Language"];
226
+ const localeHeader = headers["Language-Team"];
227
+ if (languageHeader) {
228
+ return languageHeader;
229
+ }
230
+ if (localeHeader) {
231
+ // Extract language code from Language-Team header
232
+ const match = localeHeader.match(/\(([^)]+)\)/);
233
+ return match ? match[1] : undefined;
234
+ }
235
+ return undefined;
236
+ }
237
+ getDefaultPOTHeaders() {
238
+ const now = new Date();
239
+ return {
240
+ "Project-Id-Version": "PACKAGE VERSION",
241
+ "Report-Msgid-Bugs-To": "",
242
+ "POT-Creation-Date": now
243
+ .toISOString()
244
+ .replace(/T/, " ")
245
+ .replace(/\..+/, " +0000"),
246
+ "PO-Revision-Date": "YEAR-MO-DA HO:MI+ZONE",
247
+ "Last-Translator": "FULL NAME <EMAIL@ADDRESS>",
248
+ "Language-Team": "LANGUAGE <LL@li.org>",
249
+ Language: "",
250
+ "MIME-Version": "1.0",
251
+ "Content-Type": "text/plain; charset=UTF-8",
252
+ "Content-Transfer-Encoding": "8bit",
253
+ "Plural-Forms": "nplurals=INTEGER; plural=EXPRESSION;",
254
+ };
255
+ }
256
+ formatHeaders(headers) {
257
+ return Object.entries(headers)
258
+ .map(([key, value]) => `${key}: ${value}\\n`)
259
+ .join("");
260
+ }
261
+ updateHeadersForLanguage(headers, targetLanguage) {
262
+ const now = new Date();
263
+ headers["Language"] = targetLanguage;
264
+ headers["PO-Revision-Date"] = now
265
+ .toISOString()
266
+ .replace(/T/, " ")
267
+ .replace(/\..+/, " +0000");
268
+ headers["Last-Translator"] = "auto-translate-json-library";
269
+ // Update Language-Team if it's still the template value
270
+ if (headers["Language-Team"] === "LANGUAGE <LL@li.org>") {
271
+ headers["Language-Team"] =
272
+ `${targetLanguage.toUpperCase()} <${targetLanguage}@li.org>`;
273
+ }
274
+ // Set appropriate plural forms based on language using utility function
275
+ headers["Plural-Forms"] = formatPluralFormsHeader(targetLanguage);
276
+ }
277
+ applyTranslationsToTemplate(poData, translations) {
278
+ for (const [context, contextTranslations] of Object.entries(poData.translations)) {
279
+ for (const [msgid, entry] of Object.entries(contextTranslations)) {
280
+ // Skip empty msgid (header entry)
281
+ if (!msgid)
282
+ continue;
283
+ const key = createContextKey(context, msgid);
284
+ // Update regular translation
285
+ if (translations[key] !== undefined) {
286
+ entry.msgstr[0] = translations[key];
287
+ }
288
+ // Update plural forms if they exist
289
+ if (entry.msgid_plural) {
290
+ for (let i = 1; i < entry.msgstr.length; i++) {
291
+ const pluralKey = createPluralKey(key, i);
292
+ if (translations[pluralKey] !== undefined) {
293
+ entry.msgstr[i] = translations[pluralKey];
294
+ }
295
+ }
296
+ }
297
+ }
298
+ }
299
+ }
300
+ validatePOTHeaders(headers, warnings) {
301
+ const requiredHeaders = [
302
+ "Project-Id-Version",
303
+ "POT-Creation-Date",
304
+ "Content-Type",
305
+ "Content-Transfer-Encoding",
306
+ ];
307
+ for (const header of requiredHeaders) {
308
+ if (!headers[header]) {
309
+ warnings.push({
310
+ code: "MISSING_POT_HEADER",
311
+ message: `Missing required POT header: ${header}`,
312
+ });
313
+ }
314
+ }
315
+ // Check for template placeholders that should be filled
316
+ const templatePlaceholders = [
317
+ "YEAR-MO-DA HO:MI+ZONE",
318
+ "FULL NAME <EMAIL@ADDRESS>",
319
+ "LANGUAGE <LL@li.org>",
320
+ "PACKAGE VERSION",
321
+ ];
322
+ for (const [key, value] of Object.entries(headers)) {
323
+ if (templatePlaceholders.some((placeholder) => value.includes(placeholder))) {
324
+ warnings.push({
325
+ code: "TEMPLATE_PLACEHOLDER",
326
+ message: `Header "${key}" contains template placeholder: ${value}`,
327
+ });
328
+ }
329
+ }
330
+ }
331
+ }
@@ -0,0 +1,26 @@
1
+ import type { EnhancedTranslationFile, FormatOptions, IFormatHandler, ValidationResult } from "../format.interface.js";
2
+ import type { TranslationFile } from "../translate.interface.js";
3
+ export declare class PropertiesHandler implements IFormatHandler {
4
+ canHandle(filePath: string, content?: string): boolean;
5
+ parse(content: string): EnhancedTranslationFile;
6
+ serialize(data: EnhancedTranslationFile, options?: FormatOptions): string;
7
+ getFileExtension(): string;
8
+ validateStructure(data: TranslationFile): ValidationResult;
9
+ private detectEncoding;
10
+ private hasUnicodeEscapes;
11
+ private unescapeUnicode;
12
+ private normalizeEncoding;
13
+ private extractComments;
14
+ private extractFormatting;
15
+ private escapeKey;
16
+ private escapeValue;
17
+ private applyUnicodeEscaping;
18
+ private escapeUnicode;
19
+ private isValidPropertyKey;
20
+ private containsPlaceholders;
21
+ private extractPlaceholders;
22
+ private validatePlaceholderIntegrity;
23
+ private analyzePlaceholders;
24
+ private categorizePlaceholders;
25
+ private isValidPlaceholderSyntax;
26
+ }