auto-translate-json-library 2.3.0 → 2.4.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.
@@ -1,12 +1,37 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, readFileSync, writeSync } from "node:fs";
3
3
  import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { config as dotenvConfig } from "dotenv";
4
6
  import minimist from "minimist";
5
7
  import c from "picocolors";
6
- import packageJson from "../../package.json" with { type: "json" };
7
- const { version } = packageJson;
8
- import { config as dotenvConfig } from "dotenv";
9
- dotenvConfig();
8
+ /**
9
+ * Resolve the CLI version from the nearest package.json above this module.
10
+ *
11
+ * A static `import "../../package.json"` only works for one of the two
12
+ * layouts the CLI runs in: `src/bin/cli.ts` under ts-node, or the shipped
13
+ * `build/src/bin/cli.js` (one directory deeper). This lookup works for both,
14
+ * so the build does not need to copy package.json into build/.
15
+ */
16
+ function readVersion() {
17
+ let dir = path.dirname(fileURLToPath(import.meta.url));
18
+ for (let depth = 0; depth < 6; depth += 1) {
19
+ const candidate = path.join(dir, "package.json");
20
+ if (existsSync(candidate)) {
21
+ try {
22
+ const pkg = JSON.parse(readFileSync(candidate, "utf8"));
23
+ return pkg.version ?? "0.0.0";
24
+ }
25
+ catch {
26
+ return "0.0.0";
27
+ }
28
+ }
29
+ dir = path.dirname(dir);
30
+ }
31
+ return "0.0.0";
32
+ }
33
+ const version = readVersion();
34
+ dotenvConfig({ quiet: true });
10
35
  const formatDetails = {
11
36
  json: { extensions: [".json"], description: "JSON translation files" },
12
37
  arb: {
@@ -56,8 +81,10 @@ function displayHelp() {
56
81
  console.log("");
57
82
  console.log("Options:");
58
83
  console.log(" --help, -h Display this help message");
84
+ console.log(" --version, -v Print the CLI version and exit");
59
85
  console.log(" --list-formats List all supported file formats");
60
86
  console.log(" --json, -j Output in JSON format (LLM-friendly)");
87
+ console.log(" --debug, -d Include stack traces in errors (JSON: `stack` field)");
61
88
  console.log(" --mode, -m <mode> Specify the translation mode:file or folder");
62
89
  console.log(" --engine, -e <engine> Specify the translation engine:aws,azure,google,deepLPro,deepLFree,openai,huggingface,huggingface-local");
63
90
  console.log(" --sourceLocale, -s <locale> Specify the source locale");
@@ -157,6 +184,21 @@ function displayHelp() {
157
184
  }
158
185
  // Define a function to list supported formats
159
186
  function listFormats() {
187
+ if (jsonOutput) {
188
+ emitJson({
189
+ command: "list-formats",
190
+ version,
191
+ formats: [...supportedFormats].sort().map((format) => {
192
+ const details = formatDetails[format];
193
+ return {
194
+ format,
195
+ extensions: details?.extensions ?? [],
196
+ description: details?.description ?? "",
197
+ };
198
+ }),
199
+ });
200
+ return;
201
+ }
160
202
  console.log(`🔨 Auto translate json/xml cli v${version}`);
161
203
  console.log("");
162
204
  console.log("Supported file formats:");
@@ -203,15 +245,19 @@ const flags = minimist(arguments_, {
203
245
  sourceLocale: ["s"],
204
246
  format: ["f"],
205
247
  help: ["h"],
248
+ version: ["v"],
206
249
  json: ["j"],
250
+ debug: ["d"],
207
251
  },
208
252
  string: ["mode", "engine", "sourceLocale", "format"],
209
253
  boolean: [
210
254
  "keepTranslations",
211
255
  "keepExtraTranslations",
212
256
  "help",
257
+ "version",
213
258
  "list-formats",
214
259
  "json",
260
+ "debug",
215
261
  ],
216
262
  default: {
217
263
  engine: "aws",
@@ -222,34 +268,150 @@ const flags = minimist(arguments_, {
222
268
  json: false,
223
269
  },
224
270
  });
225
- console.log(c.green(`🔨 Auto translate json cli v${version}`));
271
+ const nativeConsole = {
272
+ log: console.log.bind(console),
273
+ warn: console.warn.bind(console),
274
+ error: console.error.bind(console),
275
+ };
276
+ const capturedLogs = [];
277
+ let jsonOutput = false;
278
+ /** Strip ANSI escapes so captured log lines stay valid JSON text. */
279
+ function stripAnsi(value) {
280
+ // eslint-disable-next-line no-control-regex -- ANSI escapes
281
+ return value.replace(/\u001B\[[0-9;]*m/g, "");
282
+ }
283
+ function stringifyArg(arg) {
284
+ if (typeof arg === "string") {
285
+ return stripAnsi(arg);
286
+ }
287
+ if (arg instanceof Error) {
288
+ return stripAnsi(arg.message);
289
+ }
290
+ try {
291
+ return stripAnsi(JSON.stringify(arg) ?? String(arg));
292
+ }
293
+ catch {
294
+ return stripAnsi(String(arg));
295
+ }
296
+ }
297
+ function captureConsoleOutput() {
298
+ jsonOutput = true;
299
+ const record = (type) => (...args) => {
300
+ capturedLogs.push({
301
+ type,
302
+ message: args.map(stringifyArg).join(" "),
303
+ timestamp: Date.now(),
304
+ });
305
+ };
306
+ console.log = record("log");
307
+ console.warn = record("warn");
308
+ console.error = record("error");
309
+ }
310
+ function restoreConsole() {
311
+ console.log = nativeConsole.log;
312
+ console.warn = nativeConsole.warn;
313
+ console.error = nativeConsole.error;
314
+ }
315
+ /** process.exit() drops buffered pipe output; write the document synchronously. */
316
+ function writeStdout(text) {
317
+ const payload = text.endsWith("\n") ? text : `${text}\n`;
318
+ try {
319
+ writeSync(1, payload);
320
+ }
321
+ catch {
322
+ // Fall back to the stream if the descriptor cannot be written directly.
323
+ process.stdout.write(payload);
324
+ }
325
+ }
326
+ function currentInput() {
327
+ return {
328
+ path: inputPath ? path.join(process.cwd(), inputPath) : null,
329
+ mode,
330
+ engine,
331
+ sourceLocale,
332
+ format: format || "auto",
333
+ keepTranslations,
334
+ keepExtraTranslations,
335
+ };
336
+ }
337
+ function emitJson(payload) {
338
+ restoreConsole();
339
+ writeStdout(JSON.stringify(payload, null, 2));
340
+ }
341
+ /**
342
+ * The single failure path: a JSON envelope in --json mode, coloured text
343
+ * otherwise. Always exits with status 1.
344
+ */
345
+ function exitWithError(message, hints = [], extra = {}) {
346
+ if (jsonOutput) {
347
+ const payload = {
348
+ command: "translate",
349
+ version,
350
+ timestamp: new Date().toISOString(),
351
+ input: currentInput(),
352
+ status: "error",
353
+ error: message,
354
+ ...extra,
355
+ logs: capturedLogs,
356
+ };
357
+ if (hints.length > 0) {
358
+ payload.hints = hints;
359
+ }
360
+ emitJson(payload);
361
+ }
362
+ else {
363
+ nativeConsole.error(c.red(`❌ ${message}`));
364
+ for (const hint of hints) {
365
+ nativeConsole.error(c.yellow(`💡 ${hint}`));
366
+ }
367
+ if (debug && extra.stack) {
368
+ nativeConsole.error(extra.stack);
369
+ }
370
+ }
371
+ process.exit(1);
372
+ }
373
+ // Keep stdout parseable in --json mode: the machine-readable result is the
374
+ // only thing that may go to stdout there.
226
375
  if (flags.help) {
227
376
  displayHelp();
228
377
  process.exit(0);
229
378
  }
379
+ if (flags.version) {
380
+ // Machine-readable when combined with --json, human-readable otherwise.
381
+ console.log(flags.json ? JSON.stringify({ command: "version", version }) : version);
382
+ process.exit(0);
383
+ }
384
+ if (!flags.json) {
385
+ console.log(c.green(`🔨 Auto translate json cli v${version}`));
386
+ }
230
387
  if (flags["list-formats"]) {
388
+ // Capture before printing so the JSON listing goes through emitJson().
389
+ if (flags.json) {
390
+ captureConsoleOutput();
391
+ }
231
392
  listFormats();
232
393
  process.exit(0);
233
394
  }
234
395
  const inputPath = flags._[0];
235
- const { mode, engine, sourceLocale, keepTranslations, keepExtraTranslations, format, json, } = flags;
396
+ const { mode, engine, sourceLocale, keepTranslations, keepExtraTranslations, format, json, debug, } = flags;
397
+ if (json) {
398
+ captureConsoleOutput();
399
+ }
236
400
  // Validate input path
237
401
  if (!inputPath) {
238
- console.error(c.red("❌ Input path is required"));
239
- console.error(c.yellow("💡 Usage: atj [options] <inputPath>"));
240
- process.exit(1);
402
+ exitWithError("Input path is required", ["Usage: atj [options] <inputPath>"]);
241
403
  }
242
404
  // Validate format if specified
243
405
  if (format && !supportedFormats.includes(format)) {
244
- console.error(c.red(`❌ Unsupported format: ${format}`));
245
- console.error(c.yellow("💡 Use --list-formats to see all supported formats"));
246
- process.exit(1);
406
+ exitWithError(`Unsupported format: ${format}`, [
407
+ "Use --list-formats to see all supported formats",
408
+ ]);
247
409
  }
248
410
  // Validate mode
249
411
  if (mode && !["file", "folder"].includes(mode)) {
250
- console.error(c.red(`❌ Invalid mode: ${mode}`));
251
- console.error(c.yellow("💡 Mode must be either 'file' or 'folder'"));
252
- process.exit(1);
412
+ exitWithError(`Invalid mode: ${mode}`, [
413
+ "Mode must be either 'file' or 'folder'",
414
+ ]);
253
415
  }
254
416
  // Validate engine
255
417
  const validEngines = [
@@ -263,14 +425,13 @@ const validEngines = [
263
425
  "huggingface-local",
264
426
  ];
265
427
  if (engine && !validEngines.includes(engine)) {
266
- console.error(c.red(`❌ Invalid engine: ${engine}`));
267
- console.error(c.yellow(`💡 Supported engines: ${validEngines.join(", ")}`));
268
- process.exit(1);
428
+ exitWithError(`Invalid engine: ${engine}`, [
429
+ `Supported engines: ${validEngines.join(", ")}`,
430
+ ]);
269
431
  }
270
432
  // Check if input path exists
271
433
  if (!existsSync(inputPath)) {
272
- console.error(c.red(`❌ Input path does not exist: ${inputPath}`));
273
- process.exit(1);
434
+ exitWithError(`Input path does not exist: ${inputPath}`);
274
435
  }
275
436
  const config = {};
276
437
  // set translate engine config
@@ -278,10 +439,10 @@ switch (engine) {
278
439
  case "google": {
279
440
  const googleApiKey = process.env.ATJ_GOOGLE_API_KEY;
280
441
  if (!googleApiKey) {
281
- console.error(c.red("❌ Google API key not found in environment variable ATJ_GOOGLE_API_KEY"));
282
- console.error(c.yellow("💡 Get API key: https://cloud.google.com/translate/docs/setup"));
283
- console.error(c.yellow("💡 Set ATJ_GOOGLE_API_KEY in .env file or environment"));
284
- process.exit(1);
442
+ exitWithError("Google API key not found in environment variable ATJ_GOOGLE_API_KEY", [
443
+ "Get API key: https://cloud.google.com/translate/docs/setup",
444
+ "Set ATJ_GOOGLE_API_KEY in .env file or environment",
445
+ ]);
285
446
  }
286
447
  config.translationKeyInfo = {
287
448
  kind: "google",
@@ -294,8 +455,7 @@ switch (engine) {
294
455
  const awsSecretAccessKey = process.env.ATJ_AWS_SECRET_ACCESS_KEY;
295
456
  const awsRegion = process.env.ATJ_AWS_REGION;
296
457
  if (!awsAccessKeyId || !awsSecretAccessKey || !awsRegion) {
297
- console.error(c.red("❌ AWS credentials not found in environment variables ATJ_AWS_ACCESS_KEY_ID, ATJ_AWS_SECRET_ACCESS_KEY, ATJ_AWS_REGION"));
298
- process.exit(1);
458
+ exitWithError("AWS credentials not found in environment variables ATJ_AWS_ACCESS_KEY_ID, ATJ_AWS_SECRET_ACCESS_KEY, ATJ_AWS_REGION");
299
459
  }
300
460
  config.translationKeyInfo = {
301
461
  kind: "aws",
@@ -309,8 +469,7 @@ switch (engine) {
309
469
  const azureSecretKey = process.env.ATJ_AZURE_SECRET_KEY;
310
470
  const azureRegion = process.env.ATJ_AZURE_REGION;
311
471
  if (!azureSecretKey || !azureRegion) {
312
- console.error(c.red("❌ Azure credentials not found in environment variables ATJ_AZURE_SECRET_KEY, ATJ_AZURE_REGION"));
313
- process.exit(1);
472
+ exitWithError("Azure credentials not found in environment variables ATJ_AZURE_SECRET_KEY, ATJ_AZURE_REGION");
314
473
  }
315
474
  config.translationKeyInfo = {
316
475
  kind: "azure",
@@ -322,11 +481,11 @@ switch (engine) {
322
481
  case "openai": {
323
482
  const openaiApiKey = process.env.ATJ_OPEN_AI_SECRET_KEY;
324
483
  if (!openaiApiKey) {
325
- console.error(c.red("❌ OpenAI API key not found in environment variable ATJ_OPEN_AI_SECRET_KEY"));
326
- console.error(c.yellow("💡 For OpenAI: Set ATJ_OPEN_AI_SECRET_KEY to your OpenAI API key"));
327
- console.error(c.yellow("💡 For local Ollama: Set ATJ_OPEN_AI_SECRET_KEY to 'ollama' and ATJ_OPEN_AI_BASE_URL to 'http://localhost:11434'"));
328
- console.error(c.yellow("💡 Example for Ollama: ATJ_OPEN_AI_SECRET_KEY=ollama ATJ_OPEN_AI_BASE_URL=http://localhost:11434"));
329
- process.exit(1);
484
+ exitWithError("OpenAI API key not found in environment variable ATJ_OPEN_AI_SECRET_KEY", [
485
+ "For OpenAI: Set ATJ_OPEN_AI_SECRET_KEY to your OpenAI API key",
486
+ "For local Ollama: Set ATJ_OPEN_AI_SECRET_KEY to 'ollama' and ATJ_OPEN_AI_BASE_URL to 'http://localhost:11434'",
487
+ "Example for Ollama: ATJ_OPEN_AI_SECRET_KEY=ollama ATJ_OPEN_AI_BASE_URL=http://localhost:11434",
488
+ ]);
330
489
  }
331
490
  config.translationKeyInfo = {
332
491
  kind: "openai",
@@ -345,8 +504,7 @@ switch (engine) {
345
504
  case "deepLPro": {
346
505
  const deepLProSecretKey = process.env.ATJ_DEEPL_PRO_SECRET_KEY;
347
506
  if (!deepLProSecretKey) {
348
- console.log(c.red("❌ DeepL pro api key not found in environment variable ATJ_DEEPL_PRO_SECRET_KEY"));
349
- process.exit(1);
507
+ exitWithError("DeepL pro api key not found in environment variable ATJ_DEEPL_PRO_SECRET_KEY");
350
508
  }
351
509
  config.translationKeyInfo = {
352
510
  kind: "deepLPro",
@@ -357,8 +515,7 @@ switch (engine) {
357
515
  case "deepLFree": {
358
516
  const deepLFreeSecretKey = process.env.ATJ_DEEPL_FREE_SECRET_KEY;
359
517
  if (!deepLFreeSecretKey) {
360
- console.error(c.red("❌ DeepL free api key not found in environment variable ATJ_DEEPL_FREE_SECRET_KEY"));
361
- process.exit(1);
518
+ exitWithError("DeepL free api key not found in environment variable ATJ_DEEPL_FREE_SECRET_KEY");
362
519
  }
363
520
  config.translationKeyInfo = {
364
521
  kind: "deepLFree",
@@ -369,8 +526,7 @@ switch (engine) {
369
526
  case "huggingface": {
370
527
  const huggingFaceApiKey = process.env.ATJ_HUGGING_FACE_API_KEY;
371
528
  if (!huggingFaceApiKey) {
372
- console.error(c.red("❌ Hugging Face API key not found in environment variable ATJ_HUGGING_FACE_API_KEY"));
373
- process.exit(1);
529
+ exitWithError("Hugging Face API key not found in environment variable ATJ_HUGGING_FACE_API_KEY");
374
530
  }
375
531
  config.translationKeyInfo = {
376
532
  kind: "huggingface",
@@ -383,11 +539,11 @@ switch (engine) {
383
539
  case "huggingface-local": {
384
540
  const huggingFaceLocalModel = process.env.ATJ_HUGGING_FACE_LOCAL_MODEL;
385
541
  if (!huggingFaceLocalModel) {
386
- console.error(c.red("❌ Hugging Face local model not found in environment variable ATJ_HUGGING_FACE_LOCAL_MODEL"));
387
- console.error(c.yellow("💡 Set ATJ_HUGGING_FACE_LOCAL_MODEL in .env file or environment"));
388
- console.error(c.yellow("💡 Example: ATJ_HUGGING_FACE_LOCAL_MODEL=Xenova/opus-mt-en-fr"));
389
- console.error(c.yellow("💡 Available models: https://huggingface.co/models?pipeline_tag=translation"));
390
- process.exit(1);
542
+ exitWithError("Hugging Face local model not found in environment variable ATJ_HUGGING_FACE_LOCAL_MODEL", [
543
+ "Set ATJ_HUGGING_FACE_LOCAL_MODEL in .env file or environment",
544
+ "Example: ATJ_HUGGING_FACE_LOCAL_MODEL=Xenova/opus-mt-en-fr",
545
+ "Available models: https://huggingface.co/models?pipeline_tag=translation",
546
+ ]);
391
547
  }
392
548
  config.translationKeyInfo = {
393
549
  kind: "huggingface-local",
@@ -396,8 +552,7 @@ switch (engine) {
396
552
  break;
397
553
  }
398
554
  default:
399
- console.error(c.red(`❌ Engine ${engine} not supported`));
400
- process.exit(1);
555
+ exitWithError(`Engine ${engine} not supported`);
401
556
  }
402
557
  if (process.env.ATJ_START_DELIMITER) {
403
558
  config.startDelimiter = process.env.ATJ_START_DELIMITER;
@@ -417,111 +572,43 @@ async function main() {
417
572
  await import("../format/index.js");
418
573
  const { translate } = await import("../lib.js");
419
574
  const sourcePath = path.join(process.cwd(), inputPath);
420
- if (json) {
421
- // JSON output mode - capture console output
422
- const originalConsoleLog = console.log;
423
- const originalConsoleError = console.error;
424
- const originalConsoleWarn = console.warn;
425
- const logs = [];
426
- console.log = (...args) => {
427
- logs.push({
428
- type: "log",
429
- message: args
430
- .map((arg) => typeof arg === "object" ? JSON.stringify(arg) : String(arg))
431
- .join(" "),
432
- timestamp: Date.now(),
433
- });
434
- };
435
- console.error = (...args) => {
436
- logs.push({
437
- type: "error",
438
- message: args
439
- .map((arg) => typeof arg === "object" ? JSON.stringify(arg) : String(arg))
440
- .join(" "),
441
- timestamp: Date.now(),
442
- });
443
- };
444
- console.warn = (...args) => {
445
- logs.push({
446
- type: "warn",
447
- message: args
448
- .map((arg) => typeof arg === "object" ? JSON.stringify(arg) : String(arg))
449
- .join(" "),
450
- timestamp: Date.now(),
451
- });
452
- };
453
- const startTime = Date.now();
454
- try {
455
- await translate(sourcePath, config);
456
- const endTime = Date.now();
457
- const result = {
458
- command: "translate",
459
- version,
460
- timestamp: new Date().toISOString(),
461
- input: {
462
- path: sourcePath,
463
- mode,
464
- engine,
465
- sourceLocale,
466
- format: format || "auto",
467
- keepTranslations,
468
- keepExtraTranslations,
469
- },
470
- performance: {
471
- startTime,
472
- endTime,
473
- totalMs: endTime - startTime,
474
- },
475
- logs,
476
- status: "success",
477
- message: "Translation completed successfully",
478
- };
479
- // Restore console
480
- console.log = originalConsoleLog;
481
- console.error = originalConsoleError;
482
- console.warn = originalConsoleWarn;
483
- console.log(JSON.stringify(result, null, 2));
484
- }
485
- catch (error) {
486
- const errorTime = Date.now();
487
- const result = {
488
- command: "translate",
489
- version,
490
- timestamp: new Date().toISOString(),
491
- input: {
492
- path: sourcePath,
493
- mode,
494
- engine,
495
- sourceLocale,
496
- format: format || "auto",
497
- keepTranslations,
498
- keepExtraTranslations,
499
- },
500
- performance: {
501
- startTime,
502
- errorTime,
503
- totalMs: errorTime - startTime,
504
- },
505
- logs,
506
- status: "error",
507
- error: error instanceof Error ? error.message : String(error),
508
- stack: error instanceof Error ? error.stack : undefined,
509
- };
510
- // Restore console
511
- console.log = originalConsoleLog;
512
- console.error = originalConsoleError;
513
- console.warn = originalConsoleWarn;
514
- console.log(JSON.stringify(result, null, 2));
515
- process.exit(1);
516
- }
517
- }
518
- else {
575
+ const startTime = Date.now();
576
+ if (!json) {
519
577
  // Normal output mode
520
578
  console.log(c.green(`🌐 Translating ${sourcePath}`));
579
+ }
580
+ try {
521
581
  await translate(sourcePath, config);
522
582
  }
583
+ catch (error) {
584
+ const errorTime = Date.now();
585
+ exitWithError(error instanceof Error ? error.message : String(error), [], {
586
+ performance: {
587
+ startTime,
588
+ errorTime,
589
+ totalMs: errorTime - startTime,
590
+ },
591
+ ...(debug && error instanceof Error ? { stack: error.stack } : {}),
592
+ });
593
+ }
594
+ if (json) {
595
+ const endTime = Date.now();
596
+ emitJson({
597
+ command: "translate",
598
+ version,
599
+ timestamp: new Date().toISOString(),
600
+ input: currentInput(),
601
+ performance: {
602
+ startTime,
603
+ endTime,
604
+ totalMs: endTime - startTime,
605
+ },
606
+ logs: capturedLogs,
607
+ status: "success",
608
+ message: "Translation completed successfully",
609
+ });
610
+ }
523
611
  }
524
612
  main().catch((error) => {
525
- console.error(c.red("❌ Translate error:\n"), error);
526
- process.exit(1);
613
+ exitWithError(error instanceof Error ? error.message : String(error), [], error instanceof Error && debug ? { stack: error.stack } : {});
527
614
  });
@@ -55,7 +55,8 @@ export class DeepLTranslate {
55
55
  let args;
56
56
  ({ args, text } = Util.replaceContextVariables(text));
57
57
  let result = "";
58
- const translator = new deepl.Translator(this.subscriptionKey, {
58
+ // deepl-node 2.x renamed `Translator` to `DeepLClient`.
59
+ const translator = new deepl.DeepLClient(this.subscriptionKey, {
59
60
  serverUrl: this.endpoint,
60
61
  minTimeout: 10000,
61
62
  maxRetries: 5,
@@ -10,6 +10,21 @@ export declare class JsonHandler implements IFormatHandler {
10
10
  private reconstructNestedStructure;
11
11
  private updateNestedValues;
12
12
  private reconstructFromFlatStructure;
13
+ /**
14
+ * Returns the set of flat keys that cannot be safely expanded into a nested
15
+ * structure because another key is a dot-boundary ancestor of them. Both
16
+ * sides of every such collision are returned so callers can preserve them as
17
+ * literal flat keys instead of splitting on ".".
18
+ *
19
+ * Example: for `["a.b.c", "a.b.c.d"]`, `"a.b.c"` is an ancestor of
20
+ * `"a.b.c.d"`, so both are returned.
21
+ */
22
+ private findConflictingKeys;
23
+ /**
24
+ * Sets a value at a dot/bracket path, creating intermediate objects/arrays as
25
+ * needed. Returns `false` (instead of throwing) when the path collides with an
26
+ * incompatible existing shape, so the caller can preserve the key literally.
27
+ */
13
28
  private setNestedValue;
14
29
  private parsePath;
15
30
  private validateTranslatableContent;
@@ -174,17 +174,72 @@ export class JsonHandler {
174
174
  }
175
175
  reconstructFromFlatStructure(flatData) {
176
176
  const result = {};
177
- for (const [key, value] of Object.entries(flatData)) {
178
- this.setNestedValue(result, key, value);
177
+ const keys = Object.keys(flatData);
178
+ // Some flat keys contain literal dots and are ALSO dot-boundary prefixes of
179
+ // other flat keys (e.g. "a.b.c" and "a.b.c.d"). Such a set cannot be
180
+ // expressed as a nested tree: the shared path would have to be both a
181
+ // string leaf and an object at the same time. Splitting them blindly either
182
+ // crashes ("Cannot create property 'x' on string") or silently drops data.
183
+ // Keep the colliding keys as literal (flat) keys so the output is lossless.
184
+ const conflicting = this.findConflictingKeys(keys);
185
+ for (const key of keys) {
186
+ const value = flatData[key];
187
+ if (conflicting.has(key)) {
188
+ result[key] = value;
189
+ continue;
190
+ }
191
+ // If nesting still hits an unexpected collision (e.g. a mixed
192
+ // array/object shape), fall back to a literal key rather than throwing
193
+ // or losing the value.
194
+ if (!this.setNestedValue(result, key, value)) {
195
+ result[key] = value;
196
+ }
179
197
  }
180
198
  return result;
181
199
  }
200
+ /**
201
+ * Returns the set of flat keys that cannot be safely expanded into a nested
202
+ * structure because another key is a dot-boundary ancestor of them. Both
203
+ * sides of every such collision are returned so callers can preserve them as
204
+ * literal flat keys instead of splitting on ".".
205
+ *
206
+ * Example: for `["a.b.c", "a.b.c.d"]`, `"a.b.c"` is an ancestor of
207
+ * `"a.b.c.d"`, so both are returned.
208
+ */
209
+ findConflictingKeys(keys) {
210
+ const conflicting = new Set();
211
+ const keySet = new Set(keys);
212
+ for (const key of keys) {
213
+ const segments = key.split(".");
214
+ // Walk every dot-boundary ancestor path of this key. If an ancestor path
215
+ // is itself a full key, then that ancestor is a string leaf while this
216
+ // key needs it to be an object: both collide.
217
+ let prefix = "";
218
+ for (let i = 0; i < segments.length - 1; i++) {
219
+ prefix = i === 0 ? segments[0] : `${prefix}.${segments[i]}`;
220
+ if (keySet.has(prefix)) {
221
+ conflicting.add(prefix);
222
+ conflicting.add(key);
223
+ }
224
+ }
225
+ }
226
+ return conflicting;
227
+ }
228
+ /**
229
+ * Sets a value at a dot/bracket path, creating intermediate objects/arrays as
230
+ * needed. Returns `false` (instead of throwing) when the path collides with an
231
+ * incompatible existing shape, so the caller can preserve the key literally.
232
+ */
182
233
  setNestedValue(obj, path, value) {
183
234
  const keys = this.parsePath(path);
184
235
  let current = obj;
185
236
  for (let i = 0; i < keys.length - 1; i++) {
186
237
  const key = keys[i];
187
238
  if (key.isArray) {
239
+ if (current[key.name] !== undefined &&
240
+ !Array.isArray(current[key.name])) {
241
+ return false; // expected an array here, found something else
242
+ }
188
243
  if (!Array.isArray(current[key.name])) {
189
244
  current[key.name] = [];
190
245
  }
@@ -192,9 +247,18 @@ export class JsonHandler {
192
247
  while (current[key.name].length <= key.index) {
193
248
  current[key.name].push({});
194
249
  }
195
- current = current[key.name][key.index];
250
+ const next = current[key.name][key.index];
251
+ if (next === null || typeof next !== "object") {
252
+ return false; // slot already holds a primitive, cannot descend
253
+ }
254
+ current = next;
196
255
  }
197
256
  else {
257
+ const existing = current[key.name];
258
+ if (existing !== undefined &&
259
+ (typeof existing !== "object" || existing === null)) {
260
+ return false; // cannot descend into a primitive leaf
261
+ }
198
262
  if (!(key.name in current)) {
199
263
  current[key.name] = {};
200
264
  }
@@ -203,14 +267,25 @@ export class JsonHandler {
203
267
  }
204
268
  const lastKey = keys[keys.length - 1];
205
269
  if (lastKey.isArray) {
270
+ if (current[lastKey.name] !== undefined &&
271
+ !Array.isArray(current[lastKey.name])) {
272
+ return false;
273
+ }
206
274
  if (!Array.isArray(current[lastKey.name])) {
207
275
  current[lastKey.name] = [];
208
276
  }
209
277
  current[lastKey.name][lastKey.index] = value;
210
278
  }
211
279
  else {
280
+ const existing = current[lastKey.name];
281
+ if (existing !== undefined &&
282
+ typeof existing === "object" &&
283
+ existing !== null) {
284
+ return false; // would clobber an object/array with a scalar leaf
285
+ }
212
286
  current[lastKey.name] = value;
213
287
  }
288
+ return true;
214
289
  }
215
290
  parsePath(path) {
216
291
  const parts = path.split(".");