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,433 @@
1
+ import * as path from "node:path";
2
+ import { XMLBuilder, XMLParser } from "fast-xml-parser";
3
+ export class XliffHandler {
4
+ parser;
5
+ builder;
6
+ constructor() {
7
+ this.parser = new XMLParser({
8
+ ignoreAttributes: false,
9
+ attributeNamePrefix: "@_",
10
+ textNodeName: "#text",
11
+ allowBooleanAttributes: true,
12
+ parseTagValue: false, // Keep as strings to preserve original values
13
+ parseAttributeValue: false, // Keep attributes as strings
14
+ trimValues: true,
15
+ preserveOrder: false,
16
+ commentPropName: "#comment",
17
+ cdataPropName: "#cdata",
18
+ processEntities: true,
19
+ });
20
+ this.builder = new XMLBuilder({
21
+ ignoreAttributes: false,
22
+ attributeNamePrefix: "@_",
23
+ textNodeName: "#text",
24
+ format: true,
25
+ indentBy: " ",
26
+ suppressEmptyNode: false,
27
+ commentPropName: "#comment",
28
+ cdataPropName: "#cdata",
29
+ processEntities: true,
30
+ suppressBooleanAttributes: false,
31
+ });
32
+ }
33
+ canHandle(filePath, content) {
34
+ const extension = path.extname(filePath).toLowerCase();
35
+ if (extension !== ".xlf" && extension !== ".xliff") {
36
+ return false;
37
+ }
38
+ // If content is provided, check for XLIFF structure
39
+ if (content) {
40
+ const trimmed = content.trim();
41
+ if (trimmed.includes("<xliff") || trimmed.includes("xliff")) {
42
+ try {
43
+ const parsed = this.parser.parse(content);
44
+ return parsed.xliff !== undefined;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ return false;
51
+ }
52
+ return true;
53
+ }
54
+ parse(content) {
55
+ try {
56
+ const parsed = this.parser.parse(content);
57
+ if (!parsed.xliff) {
58
+ throw new Error("Invalid XLIFF format: missing xliff root element");
59
+ }
60
+ // Detect XLIFF version
61
+ const version = this.detectXliffVersion(parsed.xliff);
62
+ // Transform based on version
63
+ const transformed = version.startsWith("2.")
64
+ ? this.transformXliff2x(parsed.xliff)
65
+ : this.transformXliff12(parsed.xliff);
66
+ // Add metadata
67
+ const result = {
68
+ ...transformed,
69
+ _metadata: {
70
+ format: "xliff",
71
+ version: version,
72
+ sourceLanguage: this.extractSourceLanguage(parsed.xliff),
73
+ targetLanguage: this.extractTargetLanguage(parsed.xliff),
74
+ originalStructure: parsed,
75
+ preserveComments: true,
76
+ preserveAttributes: true,
77
+ },
78
+ };
79
+ return result;
80
+ }
81
+ catch (error) {
82
+ throw new Error(`Failed to parse XLIFF: ${error instanceof Error ? error.message : String(error)}`);
83
+ }
84
+ }
85
+ serialize(data, options) {
86
+ try {
87
+ let xliffData;
88
+ if (data._metadata?.originalStructure) {
89
+ // Update the original structure with translated values
90
+ xliffData = this.updateOriginalStructure(data._metadata.originalStructure, data);
91
+ }
92
+ else {
93
+ // Reconstruct XLIFF structure (default to 1.2 format)
94
+ xliffData = this.reconstructXliff12Structure(data);
95
+ }
96
+ // Apply formatting options
97
+ if (options?.indentation) {
98
+ this.builder = new XMLBuilder({
99
+ ...this.builder,
100
+ indentBy: typeof options.indentation === "string"
101
+ ? options.indentation
102
+ : " ".repeat(options.indentation),
103
+ });
104
+ }
105
+ let result = this.builder.build(xliffData);
106
+ // Add XML declaration if needed
107
+ if (options?.xmlDeclaration !== false && !result.startsWith("<?xml")) {
108
+ result = `<?xml version="1.0" encoding="UTF-8"?>\n${result}`;
109
+ }
110
+ return result;
111
+ }
112
+ catch (error) {
113
+ throw new Error(`Failed to serialize XLIFF: ${error instanceof Error ? error.message : String(error)}`);
114
+ }
115
+ }
116
+ getFileExtension() {
117
+ return ".xlf";
118
+ }
119
+ validateStructure(data) {
120
+ const errors = [];
121
+ const warnings = [];
122
+ // Basic XLIFF structure validation
123
+ if (!data || typeof data !== "object") {
124
+ errors.push({
125
+ code: "INVALID_STRUCTURE",
126
+ message: "XLIFF data must be an object",
127
+ });
128
+ return { isValid: false, errors, warnings };
129
+ }
130
+ // Check if this is an EnhancedTranslationFile with metadata
131
+ const enhancedData = data;
132
+ if (enhancedData._metadata?.originalStructure) {
133
+ const originalStructure = enhancedData._metadata.originalStructure;
134
+ if (!originalStructure.xliff) {
135
+ errors.push({
136
+ code: "MISSING_XLIFF_ROOT",
137
+ message: "XLIFF file must have an 'xliff' root element",
138
+ });
139
+ return { isValid: false, errors, warnings };
140
+ }
141
+ const version = enhancedData._metadata.version ||
142
+ this.detectXliffVersion(originalStructure.xliff);
143
+ if (version.startsWith("2.")) {
144
+ this.validateXliff2x(originalStructure.xliff, errors, warnings);
145
+ }
146
+ else {
147
+ this.validateXliff12(originalStructure.xliff, errors, warnings);
148
+ }
149
+ }
150
+ else {
151
+ // Validate flattened data - check for required translation keys
152
+ if (Object.keys(data).length === 0) {
153
+ warnings.push({
154
+ code: "EMPTY_XLIFF",
155
+ message: "XLIFF file appears to be empty or contains no translatable content",
156
+ });
157
+ }
158
+ }
159
+ return {
160
+ isValid: errors.length === 0,
161
+ errors,
162
+ warnings,
163
+ };
164
+ }
165
+ detectXliffVersion(xliff) {
166
+ const version = xliff["@_version"];
167
+ if (version) {
168
+ return version;
169
+ }
170
+ // Try to detect based on structure
171
+ if (xliff.file && xliff.file.unit) {
172
+ return "2.0"; // XLIFF 2.x uses 'unit' elements
173
+ }
174
+ else if (xliff.file && xliff.file.body && xliff.file.body["trans-unit"]) {
175
+ return "1.2"; // XLIFF 1.2 uses 'trans-unit' elements
176
+ }
177
+ return "1.2"; // Default to 1.2
178
+ }
179
+ extractSourceLanguage(xliff) {
180
+ return xliff["@_srcLang"] || xliff.file?.["@_source-language"];
181
+ }
182
+ extractTargetLanguage(xliff) {
183
+ return xliff["@_trgLang"] || xliff.file?.["@_target-language"];
184
+ }
185
+ transformXliff12(xliff) {
186
+ const result = {};
187
+ if (!xliff.file || !xliff.file.body) {
188
+ return result;
189
+ }
190
+ const body = xliff.file.body;
191
+ const transUnits = body["trans-unit"];
192
+ if (!transUnits) {
193
+ return result;
194
+ }
195
+ const units = Array.isArray(transUnits) ? transUnits : [transUnits];
196
+ for (const unit of units) {
197
+ const transUnit = unit;
198
+ const id = transUnit["@_id"];
199
+ if (!id) {
200
+ continue;
201
+ }
202
+ // Extract source text
203
+ const source = this.extractTextContent(transUnit.source);
204
+ // Extract target text if available
205
+ const target = transUnit.target
206
+ ? this.extractTextContent(transUnit.target)
207
+ : source;
208
+ // Only include if not approved (to allow translation) or if no target exists
209
+ const isApproved = transUnit["@_approved"] === "yes";
210
+ const hasTarget = transUnit.target !== undefined;
211
+ if (!isApproved || !hasTarget) {
212
+ result[id] = target || source;
213
+ }
214
+ }
215
+ return result;
216
+ }
217
+ transformXliff2x(xliff) {
218
+ const result = {};
219
+ if (!xliff.file) {
220
+ return result;
221
+ }
222
+ const file = xliff.file;
223
+ const units = file.unit;
224
+ if (!units) {
225
+ return result;
226
+ }
227
+ const unitArray = Array.isArray(units) ? units : [units];
228
+ for (const unit of unitArray) {
229
+ const xliffUnit = unit;
230
+ const id = xliffUnit["@_id"];
231
+ if (!id) {
232
+ continue;
233
+ }
234
+ // Handle segments
235
+ if (xliffUnit.segment) {
236
+ const segments = Array.isArray(xliffUnit.segment)
237
+ ? xliffUnit.segment
238
+ : [xliffUnit.segment];
239
+ for (let i = 0; i < segments.length; i++) {
240
+ const segment = segments[i];
241
+ const segmentId = segments.length > 1 ? `${id}.${i}` : id;
242
+ // Extract source text
243
+ const source = this.extractTextContent(segment.source);
244
+ // Extract target text if available
245
+ const target = segment.target
246
+ ? this.extractTextContent(segment.target)
247
+ : source;
248
+ // Only include if not approved or if no target exists
249
+ const isApproved = xliffUnit["@_approved"] === "yes";
250
+ const hasTarget = segment.target !== undefined;
251
+ if (!isApproved || !hasTarget) {
252
+ result[segmentId] = target || source;
253
+ }
254
+ }
255
+ }
256
+ }
257
+ return result;
258
+ }
259
+ extractTextContent(element) {
260
+ if (typeof element === "string") {
261
+ return element;
262
+ }
263
+ if (typeof element === "object" && element !== null) {
264
+ if (element["#text"] !== undefined) {
265
+ return element["#text"];
266
+ }
267
+ if (element["#cdata"] !== undefined) {
268
+ return element["#cdata"];
269
+ }
270
+ }
271
+ return "";
272
+ }
273
+ updateOriginalStructure(original, translated) {
274
+ // Deep clone the original structure
275
+ const updated = JSON.parse(JSON.stringify(original));
276
+ if (!updated.xliff) {
277
+ return updated;
278
+ }
279
+ const version = this.detectXliffVersion(updated.xliff);
280
+ if (version.startsWith("2.")) {
281
+ this.updateXliff2xStructure(updated.xliff, translated);
282
+ }
283
+ else {
284
+ this.updateXliff12Structure(updated.xliff, translated);
285
+ }
286
+ return updated;
287
+ }
288
+ updateXliff12Structure(xliff, translations) {
289
+ if (!xliff.file || !xliff.file.body || !xliff.file.body["trans-unit"]) {
290
+ return;
291
+ }
292
+ const transUnits = Array.isArray(xliff.file.body["trans-unit"])
293
+ ? xliff.file.body["trans-unit"]
294
+ : [xliff.file.body["trans-unit"]];
295
+ for (const unit of transUnits) {
296
+ const id = unit["@_id"];
297
+ if (id && translations[id] !== undefined) {
298
+ // Don't update if already approved
299
+ if (unit["@_approved"] === "yes") {
300
+ continue;
301
+ }
302
+ // Update or create target element
303
+ if (!unit.target) {
304
+ unit.target = {};
305
+ }
306
+ if (typeof unit.target === "object") {
307
+ unit.target["#text"] = translations[id];
308
+ }
309
+ else {
310
+ unit.target = { "#text": translations[id] };
311
+ }
312
+ // Update translation state
313
+ unit["@_approved"] = "no"; // Mark as not approved since it's a new translation
314
+ }
315
+ }
316
+ }
317
+ updateXliff2xStructure(xliff, translations) {
318
+ if (!xliff.file || !xliff.file.unit) {
319
+ return;
320
+ }
321
+ const units = Array.isArray(xliff.file.unit)
322
+ ? xliff.file.unit
323
+ : [xliff.file.unit];
324
+ for (const unit of units) {
325
+ const id = unit["@_id"];
326
+ if (!id || !unit.segment) {
327
+ continue;
328
+ }
329
+ const segments = Array.isArray(unit.segment)
330
+ ? unit.segment
331
+ : [unit.segment];
332
+ for (let i = 0; i < segments.length; i++) {
333
+ const segment = segments[i];
334
+ const segmentId = segments.length > 1 ? `${id}.${i}` : id;
335
+ if (translations[segmentId] !== undefined) {
336
+ // Don't update if already approved
337
+ if (unit["@_approved"] === "yes") {
338
+ continue;
339
+ }
340
+ // Update or create target element
341
+ if (!segment.target) {
342
+ segment.target = {};
343
+ }
344
+ if (typeof segment.target === "object") {
345
+ segment.target["#text"] = translations[segmentId];
346
+ }
347
+ else {
348
+ segment.target = { "#text": translations[segmentId] };
349
+ }
350
+ // Update translation state
351
+ unit["@_approved"] = "no"; // Mark as not approved since it's a new translation
352
+ }
353
+ }
354
+ }
355
+ }
356
+ reconstructXliff12Structure(data) {
357
+ // Remove metadata for reconstruction
358
+ const { _metadata, ...cleanData } = data;
359
+ // Create XLIFF 1.2 structure
360
+ const transUnits = Object.entries(cleanData).map(([id, text]) => ({
361
+ "@_id": id,
362
+ "@_approved": "no",
363
+ source: { "#text": String(text) },
364
+ target: { "#text": String(text) },
365
+ }));
366
+ return {
367
+ xliff: {
368
+ "@_version": "1.2",
369
+ "@_xmlns": "urn:oasis:names:tc:xliff:document:1.2",
370
+ file: {
371
+ "@_original": "unknown",
372
+ "@_source-language": _metadata?.sourceLanguage || "en",
373
+ "@_target-language": _metadata?.targetLanguage || "es",
374
+ "@_datatype": "plaintext",
375
+ body: {
376
+ "trans-unit": transUnits,
377
+ },
378
+ },
379
+ },
380
+ };
381
+ }
382
+ validateXliff12(xliff, errors, warnings) {
383
+ if (!xliff.file) {
384
+ errors.push({
385
+ code: "MISSING_FILE_ELEMENT",
386
+ message: "XLIFF 1.2 must have a 'file' element",
387
+ });
388
+ return;
389
+ }
390
+ if (!xliff.file.body) {
391
+ errors.push({
392
+ code: "MISSING_BODY_ELEMENT",
393
+ message: "XLIFF 1.2 file must have a 'body' element",
394
+ });
395
+ return;
396
+ }
397
+ if (!xliff.file.body["trans-unit"]) {
398
+ warnings.push({
399
+ code: "NO_TRANS_UNITS",
400
+ message: "No trans-unit elements found in XLIFF 1.2 file",
401
+ });
402
+ }
403
+ // Validate required attributes
404
+ if (!xliff.file["@_source-language"]) {
405
+ warnings.push({
406
+ code: "MISSING_SOURCE_LANGUAGE",
407
+ message: "XLIFF file should specify source-language attribute",
408
+ });
409
+ }
410
+ }
411
+ validateXliff2x(xliff, errors, warnings) {
412
+ if (!xliff.file) {
413
+ errors.push({
414
+ code: "MISSING_FILE_ELEMENT",
415
+ message: "XLIFF 2.x must have a 'file' element",
416
+ });
417
+ return;
418
+ }
419
+ if (!xliff.file.unit) {
420
+ warnings.push({
421
+ code: "NO_UNITS",
422
+ message: "No unit elements found in XLIFF 2.x file",
423
+ });
424
+ }
425
+ // Validate required attributes
426
+ if (!xliff["@_srcLang"]) {
427
+ warnings.push({
428
+ code: "MISSING_SOURCE_LANGUAGE",
429
+ message: "XLIFF 2.x file should specify srcLang attribute",
430
+ });
431
+ }
432
+ }
433
+ }
@@ -0,0 +1,33 @@
1
+ import type { EnhancedTranslationFile, FormatOptions, IFormatHandler, ValidationResult } from "../format.interface.js";
2
+ import type { TranslationFile } from "../translate.interface.js";
3
+ export declare class XmbHandler implements IFormatHandler {
4
+ private parser;
5
+ private builder;
6
+ constructor();
7
+ canHandle(filePath: string, content?: string): boolean;
8
+ parse(content: string): EnhancedTranslationFile;
9
+ serialize(data: EnhancedTranslationFile, options?: FormatOptions): string;
10
+ getFileExtension(): string;
11
+ validateStructure(data: TranslationFile): ValidationResult;
12
+ /**
13
+ * Generate XTB file content from XMB source for a target language
14
+ */
15
+ generateXtbFromXmb(xmbContent: string, targetLanguage: string, translations: TranslationFile): string;
16
+ private preservePlaceholders;
17
+ private validatePlaceholders;
18
+ /**
19
+ * Extract and validate placeholder information from message text
20
+ */
21
+ private extractPlaceholderInfo;
22
+ /**
23
+ * Validate message integrity by checking placeholder consistency
24
+ */
25
+ validateMessageIntegrity(originalText: string, translatedText: string): ValidationResult;
26
+ private extractMessageMetadata;
27
+ private updateOriginalStructure;
28
+ private reconstructXmbStructure;
29
+ /**
30
+ * Extract text content from mixed XML content (text + elements)
31
+ */
32
+ private extractMixedContent;
33
+ }