@intlayer/cli 7.3.5 → 7.3.7

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 (35) hide show
  1. package/dist/cjs/fill/deepMergeContent.cjs +27 -0
  2. package/dist/cjs/fill/deepMergeContent.cjs.map +1 -0
  3. package/dist/cjs/fill/fill.cjs +7 -1
  4. package/dist/cjs/fill/fill.cjs.map +1 -1
  5. package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs +26 -0
  6. package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs.map +1 -0
  7. package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs +50 -0
  8. package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs.map +1 -0
  9. package/dist/cjs/fill/translateDictionary.cjs +28 -11
  10. package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
  11. package/dist/cjs/fill/writeFill.cjs +9 -1
  12. package/dist/cjs/fill/writeFill.cjs.map +1 -1
  13. package/dist/esm/fill/deepMergeContent.mjs +26 -0
  14. package/dist/esm/fill/deepMergeContent.mjs.map +1 -0
  15. package/dist/esm/fill/fill.mjs +7 -1
  16. package/dist/esm/fill/fill.mjs.map +1 -1
  17. package/dist/esm/fill/getAvailableLocalesInDictionary.mjs +25 -0
  18. package/dist/esm/fill/getAvailableLocalesInDictionary.mjs.map +1 -0
  19. package/dist/esm/fill/getFilterMissingContentPerLocale.mjs +49 -0
  20. package/dist/esm/fill/getFilterMissingContentPerLocale.mjs.map +1 -0
  21. package/dist/esm/fill/translateDictionary.mjs +28 -11
  22. package/dist/esm/fill/translateDictionary.mjs.map +1 -1
  23. package/dist/esm/fill/writeFill.mjs +9 -1
  24. package/dist/esm/fill/writeFill.mjs.map +1 -1
  25. package/dist/types/config.d.ts.map +1 -1
  26. package/dist/types/fill/deepMergeContent.d.ts +13 -0
  27. package/dist/types/fill/deepMergeContent.d.ts.map +1 -0
  28. package/dist/types/fill/fill.d.ts.map +1 -1
  29. package/dist/types/fill/getAvailableLocalesInDictionary.d.ts +12 -0
  30. package/dist/types/fill/getAvailableLocalesInDictionary.d.ts.map +1 -0
  31. package/dist/types/fill/getFilterMissingContentPerLocale.d.ts +16 -0
  32. package/dist/types/fill/getFilterMissingContentPerLocale.d.ts.map +1 -0
  33. package/dist/types/fill/translateDictionary.d.ts.map +1 -1
  34. package/dist/types/fill/writeFill.d.ts.map +1 -1
  35. package/package.json +10 -10
@@ -0,0 +1,27 @@
1
+
2
+ //#region src/fill/deepMergeContent.ts
3
+ /**
4
+ * Deep merge two plain objects (for per-locale content).
5
+ * The second object's values take precedence over the first.
6
+ *
7
+ * @param target - The base object
8
+ * @param source - The object to merge in (takes precedence)
9
+ * @returns The merged object
10
+ */
11
+ const deepMergeContent = (target, source) => {
12
+ if (!target) return source;
13
+ if (!source) return target;
14
+ if (typeof target !== "object" || typeof source !== "object" || Array.isArray(target) || Array.isArray(source)) return source;
15
+ const result = { ...target };
16
+ for (const key in source) if (Object.hasOwn(source, key)) {
17
+ const sourceValue = source[key];
18
+ const targetValue = result[key];
19
+ if (typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue) && typeof targetValue === "object" && targetValue !== null && !Array.isArray(targetValue)) result[key] = deepMergeContent(targetValue, sourceValue);
20
+ else result[key] = sourceValue;
21
+ }
22
+ return result;
23
+ };
24
+
25
+ //#endregion
26
+ exports.deepMergeContent = deepMergeContent;
27
+ //# sourceMappingURL=deepMergeContent.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deepMergeContent.cjs","names":["result: any"],"sources":["../../../src/fill/deepMergeContent.ts"],"sourcesContent":["/**\n * Deep merge two plain objects (for per-locale content).\n * The second object's values take precedence over the first.\n *\n * @param target - The base object\n * @param source - The object to merge in (takes precedence)\n * @returns The merged object\n */\nexport const deepMergeContent = <T = any>(target: T, source: T): T => {\n // Handle null/undefined\n if (!target) return source;\n if (!source) return target;\n\n // Handle non-objects (primitives, arrays)\n if (\n typeof target !== 'object' ||\n typeof source !== 'object' ||\n Array.isArray(target) ||\n Array.isArray(source)\n ) {\n return source;\n }\n\n // Merge objects\n const result: any = { ...target };\n\n for (const key in source) {\n if (Object.hasOwn(source, key)) {\n const sourceValue = (source as any)[key];\n const targetValue = result[key];\n\n if (\n typeof sourceValue === 'object' &&\n sourceValue !== null &&\n !Array.isArray(sourceValue) &&\n typeof targetValue === 'object' &&\n targetValue !== null &&\n !Array.isArray(targetValue)\n ) {\n // Recursively merge nested objects\n result[key] = deepMergeContent(targetValue, sourceValue);\n } else {\n // Overwrite with source value\n result[key] = sourceValue;\n }\n }\n }\n\n return result;\n};\n"],"mappings":";;;;;;;;;;AAQA,MAAa,oBAA6B,QAAW,WAAiB;AAEpE,KAAI,CAAC,OAAQ,QAAO;AACpB,KAAI,CAAC,OAAQ,QAAO;AAGpB,KACE,OAAO,WAAW,YAClB,OAAO,WAAW,YAClB,MAAM,QAAQ,OAAO,IACrB,MAAM,QAAQ,OAAO,CAErB,QAAO;CAIT,MAAMA,SAAc,EAAE,GAAG,QAAQ;AAEjC,MAAK,MAAM,OAAO,OAChB,KAAI,OAAO,OAAO,QAAQ,IAAI,EAAE;EAC9B,MAAM,cAAe,OAAe;EACpC,MAAM,cAAc,OAAO;AAE3B,MACE,OAAO,gBAAgB,YACvB,gBAAgB,QAChB,CAAC,MAAM,QAAQ,YAAY,IAC3B,OAAO,gBAAgB,YACvB,gBAAgB,QAChB,CAAC,MAAM,QAAQ,YAAY,CAG3B,QAAO,OAAO,iBAAiB,aAAa,YAAY;MAGxD,QAAO,OAAO;;AAKpB,QAAO"}
@@ -57,7 +57,13 @@ const fill = async (options) => {
57
57
  });
58
58
  if (!translationTaskResult?.dictionaryOutput) return;
59
59
  const { dictionaryOutput, sourceLocale } = translationTaskResult;
60
- if (typeof dictionaryOutput.fill === "string" || typeof dictionaryOutput.fill === "object" || typeof dictionaryOutput.locale === "string" && dictionaryOutput.fill !== false) await require_fill_writeFill.writeFill(dictionaryOutput, outputLocales, [sourceLocale], configuration);
60
+ const hasDictionaryLevelFill = typeof dictionaryOutput.fill === "string" || typeof dictionaryOutput.fill === "object";
61
+ const isPerLocale = typeof dictionaryOutput.locale === "string";
62
+ const effectiveFill = hasDictionaryLevelFill ? dictionaryOutput.fill : isPerLocale ? configuration.dictionary?.fill ?? true : false;
63
+ if (typeof effectiveFill === "string" || typeof effectiveFill === "object") await require_fill_writeFill.writeFill({
64
+ ...dictionaryOutput,
65
+ fill: effectiveFill
66
+ }, outputLocales, [sourceLocale], configuration);
61
67
  else {
62
68
  await (0, __intlayer_chokidar.writeContentDeclaration)(dictionaryOutput, configuration);
63
69
  if (dictionaryOutput.filePath) appLogger(`${task.dictionaryPreset} Content declaration written to ${(0, __intlayer_chokidar.formatPath)((0, node_path.basename)(dictionaryOutput.filePath))}`, { level: "info" });
@@ -1 +1 @@
1
- {"version":3,"file":"fill.cjs","names":["ensureArray","setupAI","getTargetUnmergedDictionaries","ANSIColors","translationTasks: TranslationTask[]","listTranslationsTasks","translateDictionary","writeFill"],"sources":["../../../src/fill/fill.ts"],"sourcesContent":["import { basename, relative } from 'node:path';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n formatPath,\n getGlobalLimiter,\n getTaskLimiter,\n type ListGitFilesOptions,\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar';\nimport {\n ANSIColors,\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type { Locale } from '@intlayer/types';\nimport {\n ensureArray,\n type GetTargetDictionaryOptions,\n getTargetUnmergedDictionaries,\n} from '../getTargetDictionary';\nimport { setupAI } from '../utils/setupAI';\nimport {\n listTranslationsTasks,\n type TranslationTask,\n} from './listTranslationsTasks';\nimport { translateDictionary } from './translateDictionary';\nimport { writeFill } from './writeFill';\n\nconst NB_CONCURRENT_TRANSLATIONS = 7;\n\n// Arguments for the fill function\nexport type FillOptions = {\n sourceLocale?: Locale;\n outputLocales?: Locale | Locale[];\n mode?: 'complete' | 'review';\n gitOptions?: ListGitFilesOptions;\n aiOptions?: AIOptions; // Added aiOptions to be passed to translateJSON\n verbose?: boolean;\n nbConcurrentTranslations?: number;\n nbConcurrentTasks?: number; // NEW: number of tasks that may run at once\n build?: boolean;\n skipMetadata?: boolean;\n} & GetTargetDictionaryOptions;\n\n/**\n * Fill translations based on the provided options.\n */\nexport const fill = async (options?: FillOptions): Promise<void> => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n if (options?.build === true) {\n await prepareIntlayer(configuration, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(configuration);\n }\n\n const { defaultLocale, locales } = configuration.internationalization;\n const mode = options?.mode ?? 'complete';\n const baseLocale = options?.sourceLocale ?? defaultLocale;\n\n const outputLocales = options?.outputLocales\n ? ensureArray(options.outputLocales)\n : locales;\n\n const aiResult = await setupAI(configuration, options?.aiOptions);\n\n if (!aiResult?.hasAIAccess) return;\n\n const { aiClient, aiConfig } = aiResult;\n\n const targetUnmergedDictionaries =\n await getTargetUnmergedDictionaries(options);\n\n const affectedDictionaryKeys = new Set<string>();\n targetUnmergedDictionaries.forEach((dict) => {\n affectedDictionaryKeys.add(dict.key);\n });\n\n const keysToProcess = Array.from(affectedDictionaryKeys);\n\n appLogger([\n 'Affected dictionary keys for processing:',\n keysToProcess.length > 0\n ? keysToProcess.map((key) => colorizeKey(key)).join(', ')\n : colorize('No keys found', ANSIColors.YELLOW),\n ]);\n\n if (keysToProcess.length === 0) return;\n\n /**\n * List the translations tasks\n *\n * Create a list of per-locale dictionaries to translate\n *\n * In 'complete' mode, filter only the missing locales to translate\n */\n const translationTasks: TranslationTask[] = listTranslationsTasks(\n targetUnmergedDictionaries.map((dictionary) => dictionary.localId!),\n outputLocales,\n mode,\n baseLocale,\n configuration\n );\n\n // AI calls in flight at once (translateJSON + metadata audit)\n const nbConcurrentTranslations =\n options?.nbConcurrentTranslations ?? NB_CONCURRENT_TRANSLATIONS;\n const globalLimiter = getGlobalLimiter(nbConcurrentTranslations);\n\n // NEW: number of *tasks* that may run at once (start/prepare/log/write)\n const nbConcurrentTasks = Math.max(\n 1,\n Math.min(\n options?.nbConcurrentTasks ?? nbConcurrentTranslations,\n translationTasks.length\n )\n );\n\n const taskLimiter = getTaskLimiter(nbConcurrentTasks);\n\n const runners = translationTasks.map((task) =>\n taskLimiter(async () => {\n const relativePath = relative(\n configuration?.content?.baseDir ?? process.cwd(),\n task?.dictionaryFilePath ?? ''\n );\n\n // log AFTER acquiring a task slot\n appLogger(\n `${task.dictionaryPreset} Processing ${colorizePath(basename(relativePath))}`,\n { level: 'info' }\n );\n\n const translationTaskResult = await translateDictionary(\n task,\n configuration,\n {\n mode,\n aiOptions: options?.aiOptions,\n fillMetadata: !options?.skipMetadata,\n onHandle: globalLimiter, // <= AI calls go through here\n aiClient,\n aiConfig,\n }\n );\n\n if (!translationTaskResult?.dictionaryOutput) return;\n\n const { dictionaryOutput, sourceLocale } = translationTaskResult;\n\n const isFillOtherFile =\n typeof dictionaryOutput.fill === 'string' ||\n typeof dictionaryOutput.fill === 'object' ||\n (typeof dictionaryOutput.locale === 'string' &&\n dictionaryOutput.fill !== false);\n\n if (isFillOtherFile) {\n await writeFill(\n dictionaryOutput,\n outputLocales,\n [sourceLocale],\n configuration\n );\n } else {\n await writeContentDeclaration(dictionaryOutput, configuration);\n\n if (dictionaryOutput.filePath) {\n appLogger(\n `${task.dictionaryPreset} Content declaration written to ${formatPath(basename(dictionaryOutput.filePath))}`,\n { level: 'info' }\n );\n }\n }\n })\n );\n\n await Promise.all(runners);\n await (globalLimiter as any).onIdle();\n};\n"],"mappings":";;;;;;;;;;;AAgCA,MAAM,6BAA6B;;;;AAmBnC,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,wDAAiC,SAAS,cAAc;CAC9D,MAAM,gDAAyB,cAAc;AAE7C,KAAI,SAAS,UAAU,KACrB,gDAAsB,eAAe,EAAE,UAAU,MAAM,CAAC;UA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S;GACxB,UAAU;GACV;GACA;GACD,CACF;AAED,MAAI,CAAC,uBAAuB,iBAAkB;EAE9C,MAAM,EAAE,kBAAkB,iBAAiB;AAQ3C,MALE,OAAO,iBAAiB,SAAS,YACjC,OAAO,iBAAiB,SAAS,YAChC,OAAO,iBAAiB,WAAW,YAClC,iBAAiB,SAAS,MAG5B,OAAMC,iCACJ,kBACA,eACA,CAAC,aAAa,EACd,cACD;OACI;AACL,0DAA8B,kBAAkB,cAAc;AAE9D,OAAI,iBAAiB,SACnB,WACE,GAAG,KAAK,iBAAiB,8FAAsD,iBAAiB,SAAS,CAAC,IAC1G,EAAE,OAAO,QAAQ,CAClB;;GAGL,CACH;AAED,OAAM,QAAQ,IAAI,QAAQ;AAC1B,OAAO,cAAsB,QAAQ"}
1
+ {"version":3,"file":"fill.cjs","names":["ensureArray","setupAI","getTargetUnmergedDictionaries","ANSIColors","translationTasks: TranslationTask[]","listTranslationsTasks","translateDictionary","writeFill"],"sources":["../../../src/fill/fill.ts"],"sourcesContent":["import { basename, relative } from 'node:path';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n formatPath,\n getGlobalLimiter,\n getTaskLimiter,\n type ListGitFilesOptions,\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar';\nimport {\n ANSIColors,\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type { Locale } from '@intlayer/types';\nimport {\n ensureArray,\n type GetTargetDictionaryOptions,\n getTargetUnmergedDictionaries,\n} from '../getTargetDictionary';\nimport { setupAI } from '../utils/setupAI';\nimport {\n listTranslationsTasks,\n type TranslationTask,\n} from './listTranslationsTasks';\nimport { translateDictionary } from './translateDictionary';\nimport { writeFill } from './writeFill';\n\nconst NB_CONCURRENT_TRANSLATIONS = 7;\n\n// Arguments for the fill function\nexport type FillOptions = {\n sourceLocale?: Locale;\n outputLocales?: Locale | Locale[];\n mode?: 'complete' | 'review';\n gitOptions?: ListGitFilesOptions;\n aiOptions?: AIOptions; // Added aiOptions to be passed to translateJSON\n verbose?: boolean;\n nbConcurrentTranslations?: number;\n nbConcurrentTasks?: number; // NEW: number of tasks that may run at once\n build?: boolean;\n skipMetadata?: boolean;\n} & GetTargetDictionaryOptions;\n\n/**\n * Fill translations based on the provided options.\n */\nexport const fill = async (options?: FillOptions): Promise<void> => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n if (options?.build === true) {\n await prepareIntlayer(configuration, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(configuration);\n }\n\n const { defaultLocale, locales } = configuration.internationalization;\n const mode = options?.mode ?? 'complete';\n const baseLocale = options?.sourceLocale ?? defaultLocale;\n\n const outputLocales = options?.outputLocales\n ? ensureArray(options.outputLocales)\n : locales;\n\n const aiResult = await setupAI(configuration, options?.aiOptions);\n\n if (!aiResult?.hasAIAccess) return;\n\n const { aiClient, aiConfig } = aiResult;\n\n const targetUnmergedDictionaries =\n await getTargetUnmergedDictionaries(options);\n\n const affectedDictionaryKeys = new Set<string>();\n targetUnmergedDictionaries.forEach((dict) => {\n affectedDictionaryKeys.add(dict.key);\n });\n\n const keysToProcess = Array.from(affectedDictionaryKeys);\n\n appLogger([\n 'Affected dictionary keys for processing:',\n keysToProcess.length > 0\n ? keysToProcess.map((key) => colorizeKey(key)).join(', ')\n : colorize('No keys found', ANSIColors.YELLOW),\n ]);\n\n if (keysToProcess.length === 0) return;\n\n /**\n * List the translations tasks\n *\n * Create a list of per-locale dictionaries to translate\n *\n * In 'complete' mode, filter only the missing locales to translate\n */\n const translationTasks: TranslationTask[] = listTranslationsTasks(\n targetUnmergedDictionaries.map((dictionary) => dictionary.localId!),\n outputLocales,\n mode,\n baseLocale,\n configuration\n );\n\n // AI calls in flight at once (translateJSON + metadata audit)\n const nbConcurrentTranslations =\n options?.nbConcurrentTranslations ?? NB_CONCURRENT_TRANSLATIONS;\n const globalLimiter = getGlobalLimiter(nbConcurrentTranslations);\n\n // NEW: number of *tasks* that may run at once (start/prepare/log/write)\n const nbConcurrentTasks = Math.max(\n 1,\n Math.min(\n options?.nbConcurrentTasks ?? nbConcurrentTranslations,\n translationTasks.length\n )\n );\n\n const taskLimiter = getTaskLimiter(nbConcurrentTasks);\n\n const runners = translationTasks.map((task) =>\n taskLimiter(async () => {\n const relativePath = relative(\n configuration?.content?.baseDir ?? process.cwd(),\n task?.dictionaryFilePath ?? ''\n );\n\n // log AFTER acquiring a task slot\n appLogger(\n `${task.dictionaryPreset} Processing ${colorizePath(basename(relativePath))}`,\n { level: 'info' }\n );\n\n const translationTaskResult = await translateDictionary(\n task,\n configuration,\n {\n mode,\n aiOptions: options?.aiOptions,\n fillMetadata: !options?.skipMetadata,\n onHandle: globalLimiter, // <= AI calls go through here\n aiClient,\n aiConfig,\n }\n );\n\n if (!translationTaskResult?.dictionaryOutput) return;\n\n const { dictionaryOutput, sourceLocale } = translationTaskResult;\n\n // Determine if we should write to separate files\n // - If dictionary has explicit fill setting (string or object), use it\n // - If dictionary is per-locale AND has no explicit fill=false, use global fill config\n // - If dictionary is multilingual (no locale property), always write to same file\n const hasDictionaryLevelFill =\n typeof dictionaryOutput.fill === 'string' ||\n typeof dictionaryOutput.fill === 'object';\n\n const isPerLocale = typeof dictionaryOutput.locale === 'string';\n\n const effectiveFill = hasDictionaryLevelFill\n ? dictionaryOutput.fill\n : isPerLocale\n ? (configuration.dictionary?.fill ?? true)\n : false; // Multilingual dictionaries don't use fill by default\n\n const isFillOtherFile =\n typeof effectiveFill === 'string' || typeof effectiveFill === 'object';\n\n if (isFillOtherFile) {\n await writeFill(\n {\n ...dictionaryOutput,\n // Ensure fill is set on the dictionary for writeFill to use\n fill: effectiveFill,\n },\n outputLocales,\n [sourceLocale],\n configuration\n );\n } else {\n await writeContentDeclaration(dictionaryOutput, configuration);\n\n if (dictionaryOutput.filePath) {\n appLogger(\n `${task.dictionaryPreset} Content declaration written to ${formatPath(basename(dictionaryOutput.filePath))}`,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UAAU,iBAAiB,KAAK,SACpC,YAAY,YAAY;EACtB,MAAM,uCACJ,eAAe,SAAS,WAAW,QAAQ,KAAK,EAChD,MAAM,sBAAsB,GAC7B;AAGD,YACE,GAAG,KAAK,iBAAiB,0EAAoC,aAAa,CAAC,IAC3E,EAAE,OAAO,QAAQ,CAClB;EAED,MAAM,wBAAwB,MAAMC,qDAClC,MACA,eACA;GACE;GACA,WAAW,SAAS;GACpB,cAAc,CAAC,SAAS;GACxB,UAAU;GACV;GACA;GACD,CACF;AAED,MAAI,CAAC,uBAAuB,iBAAkB;EAE9C,MAAM,EAAE,kBAAkB,iBAAiB;EAM3C,MAAM,yBACJ,OAAO,iBAAiB,SAAS,YACjC,OAAO,iBAAiB,SAAS;EAEnC,MAAM,cAAc,OAAO,iBAAiB,WAAW;EAEvD,MAAM,gBAAgB,yBAClB,iBAAiB,OACjB,cACG,cAAc,YAAY,QAAQ,OACnC;AAKN,MAFE,OAAO,kBAAkB,YAAY,OAAO,kBAAkB,SAG9D,OAAMC,iCACJ;GACE,GAAG;GAEH,MAAM;GACP,EACD,eACA,CAAC,aAAa,EACd,cACD;OACI;AACL,0DAA8B,kBAAkB,cAAc;AAE9D,OAAI,iBAAiB,SACnB,WACE,GAAG,KAAK,iBAAiB,8FAAsD,iBAAiB,SAAS,CAAC,IAC1G,EAAE,OAAO,QAAQ,CAClB;;GAGL,CACH;AAED,OAAM,QAAQ,IAAI,QAAQ;AAC1B,OAAO,cAAsB,QAAQ"}
@@ -0,0 +1,26 @@
1
+
2
+ //#region src/fill/getAvailableLocalesInDictionary.ts
3
+ /**
4
+ * Recursively traverses dictionary content to find all locales that have actual translations.
5
+ * Returns a Set of locale strings that are present in the translation nodes.
6
+ */
7
+ const extractLocalesFromContent = (content, locales = /* @__PURE__ */ new Set()) => {
8
+ if (!content || typeof content !== "object") return locales;
9
+ if (content.nodeType === "translation" && content.translation) Object.keys(content.translation).forEach((locale) => {
10
+ locales.add(locale);
11
+ });
12
+ for (const value of Object.values(content)) if (value && typeof value === "object") extractLocalesFromContent(value, locales);
13
+ return locales;
14
+ };
15
+ /**
16
+ * Gets all locales that have actual translations in the dictionary content.
17
+ * Only returns locales that are present in at least one translation node.
18
+ */
19
+ const getAvailableLocalesInDictionary = (dictionary) => {
20
+ const localesSet = extractLocalesFromContent(dictionary.content);
21
+ return Array.from(localesSet);
22
+ };
23
+
24
+ //#endregion
25
+ exports.getAvailableLocalesInDictionary = getAvailableLocalesInDictionary;
26
+ //# sourceMappingURL=getAvailableLocalesInDictionary.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getAvailableLocalesInDictionary.cjs","names":[],"sources":["../../../src/fill/getAvailableLocalesInDictionary.ts"],"sourcesContent":["import type { Dictionary, Locale } from '@intlayer/types';\n\n/**\n * Recursively traverses dictionary content to find all locales that have actual translations.\n * Returns a Set of locale strings that are present in the translation nodes.\n */\nconst extractLocalesFromContent = (\n content: any,\n locales: Set<Locale> = new Set()\n): Set<Locale> => {\n if (!content || typeof content !== 'object') {\n return locales;\n }\n\n // Check if this is a translation node\n if (content.nodeType === 'translation' && content.translation) {\n // Add all locale keys from the translation map\n Object.keys(content.translation).forEach((locale) => {\n locales.add(locale as Locale);\n });\n }\n\n // Recursively check nested objects\n for (const value of Object.values(content)) {\n if (value && typeof value === 'object') {\n extractLocalesFromContent(value, locales);\n }\n }\n\n return locales;\n};\n\n/**\n * Gets all locales that have actual translations in the dictionary content.\n * Only returns locales that are present in at least one translation node.\n */\nexport const getAvailableLocalesInDictionary = (\n dictionary: Dictionary\n): Locale[] => {\n const localesSet = extractLocalesFromContent(dictionary.content);\n return Array.from(localesSet);\n};\n"],"mappings":";;;;;;AAMA,MAAM,6BACJ,SACA,0BAAuB,IAAI,KAAK,KAChB;AAChB,KAAI,CAAC,WAAW,OAAO,YAAY,SACjC,QAAO;AAIT,KAAI,QAAQ,aAAa,iBAAiB,QAAQ,YAEhD,QAAO,KAAK,QAAQ,YAAY,CAAC,SAAS,WAAW;AACnD,UAAQ,IAAI,OAAiB;GAC7B;AAIJ,MAAK,MAAM,SAAS,OAAO,OAAO,QAAQ,CACxC,KAAI,SAAS,OAAO,UAAU,SAC5B,2BAA0B,OAAO,QAAQ;AAI7C,QAAO;;;;;;AAOT,MAAa,mCACX,eACa;CACb,MAAM,aAAa,0BAA0B,WAAW,QAAQ;AAChE,QAAO,MAAM,KAAK,WAAW"}
@@ -0,0 +1,50 @@
1
+
2
+ //#region src/fill/getFilterMissingContentPerLocale.ts
3
+ /**
4
+ * Recursively compares source content with target content and returns only the missing parts.
5
+ * For per-locale files where content is simple JSON (not translation nodes).
6
+ *
7
+ * @param sourceContent - The source content to check
8
+ * @param targetContent - The existing target content
9
+ * @returns Only the content that's missing in the target
10
+ */
11
+ const filterMissingContent = (sourceContent, targetContent) => {
12
+ if (targetContent === void 0 || targetContent === null) return sourceContent;
13
+ if (typeof sourceContent !== "object" || sourceContent === null) return;
14
+ if (Array.isArray(sourceContent)) {
15
+ if (!Array.isArray(targetContent)) return sourceContent;
16
+ const missingItems = sourceContent.map((item, index) => filterMissingContent(item, targetContent[index])).filter((item) => item !== void 0);
17
+ return missingItems.length > 0 ? missingItems : void 0;
18
+ }
19
+ const result = {};
20
+ let hasMissingContent = false;
21
+ for (const [key, value] of Object.entries(sourceContent)) {
22
+ const targetValue = targetContent?.[key];
23
+ const missingValue = filterMissingContent(value, targetValue);
24
+ if (missingValue !== void 0) {
25
+ result[key] = missingValue;
26
+ hasMissingContent = true;
27
+ }
28
+ }
29
+ return hasMissingContent ? result : void 0;
30
+ };
31
+ /**
32
+ * Filters a dictionary to only include content that's missing in the target dictionary.
33
+ * Used for per-locale content declarations in 'complete' mode.
34
+ *
35
+ * @param sourceDictionary - The source dictionary with content to translate
36
+ * @param targetDictionary - The existing target dictionary
37
+ * @returns A dictionary with only the missing content
38
+ */
39
+ const getFilterMissingContentPerLocale = (sourceDictionary, targetDictionary) => {
40
+ if (!targetDictionary || !targetDictionary.content) return sourceDictionary;
41
+ const missingContent = filterMissingContent(sourceDictionary.content, targetDictionary.content);
42
+ return {
43
+ ...sourceDictionary,
44
+ content: missingContent ?? {}
45
+ };
46
+ };
47
+
48
+ //#endregion
49
+ exports.getFilterMissingContentPerLocale = getFilterMissingContentPerLocale;
50
+ //# sourceMappingURL=getFilterMissingContentPerLocale.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getFilterMissingContentPerLocale.cjs","names":["result: any"],"sources":["../../../src/fill/getFilterMissingContentPerLocale.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types';\n\n/**\n * Recursively compares source content with target content and returns only the missing parts.\n * For per-locale files where content is simple JSON (not translation nodes).\n *\n * @param sourceContent - The source content to check\n * @param targetContent - The existing target content\n * @returns Only the content that's missing in the target\n */\nconst filterMissingContent = (sourceContent: any, targetContent: any): any => {\n // If target doesn't exist, all source content is missing\n if (targetContent === undefined || targetContent === null) {\n return sourceContent;\n }\n\n // Primitive values: if target exists (even if empty string), consider it translated\n if (typeof sourceContent !== 'object' || sourceContent === null) {\n return undefined;\n }\n\n // Handle arrays\n if (Array.isArray(sourceContent)) {\n if (!Array.isArray(targetContent)) {\n return sourceContent;\n }\n\n const missingItems = sourceContent\n .map((item, index) => filterMissingContent(item, targetContent[index]))\n .filter((item) => item !== undefined);\n\n return missingItems.length > 0 ? missingItems : undefined;\n }\n\n // Handle objects\n const result: any = {};\n let hasMissingContent = false;\n\n for (const [key, value] of Object.entries(sourceContent)) {\n const targetValue = targetContent?.[key];\n const missingValue = filterMissingContent(value, targetValue);\n\n if (missingValue !== undefined) {\n result[key] = missingValue;\n hasMissingContent = true;\n }\n }\n\n return hasMissingContent ? result : undefined;\n};\n\n/**\n * Filters a dictionary to only include content that's missing in the target dictionary.\n * Used for per-locale content declarations in 'complete' mode.\n *\n * @param sourceDictionary - The source dictionary with content to translate\n * @param targetDictionary - The existing target dictionary\n * @returns A dictionary with only the missing content\n */\nexport const getFilterMissingContentPerLocale = (\n sourceDictionary: Dictionary,\n targetDictionary: Dictionary | undefined\n): Dictionary => {\n if (!targetDictionary || !targetDictionary.content) {\n // If no target exists, all source content is missing\n return sourceDictionary;\n }\n\n const missingContent = filterMissingContent(\n sourceDictionary.content,\n targetDictionary.content\n );\n\n return {\n ...sourceDictionary,\n content: missingContent ?? {},\n };\n};\n"],"mappings":";;;;;;;;;;AAUA,MAAM,wBAAwB,eAAoB,kBAA4B;AAE5E,KAAI,kBAAkB,UAAa,kBAAkB,KACnD,QAAO;AAIT,KAAI,OAAO,kBAAkB,YAAY,kBAAkB,KACzD;AAIF,KAAI,MAAM,QAAQ,cAAc,EAAE;AAChC,MAAI,CAAC,MAAM,QAAQ,cAAc,CAC/B,QAAO;EAGT,MAAM,eAAe,cAClB,KAAK,MAAM,UAAU,qBAAqB,MAAM,cAAc,OAAO,CAAC,CACtE,QAAQ,SAAS,SAAS,OAAU;AAEvC,SAAO,aAAa,SAAS,IAAI,eAAe;;CAIlD,MAAMA,SAAc,EAAE;CACtB,IAAI,oBAAoB;AAExB,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,EAAE;EACxD,MAAM,cAAc,gBAAgB;EACpC,MAAM,eAAe,qBAAqB,OAAO,YAAY;AAE7D,MAAI,iBAAiB,QAAW;AAC9B,UAAO,OAAO;AACd,uBAAoB;;;AAIxB,QAAO,oBAAoB,SAAS;;;;;;;;;;AAWtC,MAAa,oCACX,kBACA,qBACe;AACf,KAAI,CAAC,oBAAoB,CAAC,iBAAiB,QAEzC,QAAO;CAGT,MAAM,iBAAiB,qBACrB,iBAAiB,SACjB,iBAAiB,QAClB;AAED,QAAO;EACL,GAAG;EACH,SAAS,kBAAkB,EAAE;EAC9B"}
@@ -1,4 +1,6 @@
1
1
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_fill_deepMergeContent = require('./deepMergeContent.cjs');
3
+ const require_fill_getFilterMissingContentPerLocale = require('./getFilterMissingContentPerLocale.cjs');
2
4
  let __intlayer_api = require("@intlayer/api");
3
5
  let __intlayer_chokidar = require("@intlayer/chokidar");
4
6
  let __intlayer_config = require("@intlayer/config");
@@ -27,7 +29,8 @@ const translateDictionary = async (task, configuration, options) => {
27
29
  options?.onSuccess?.();
28
30
  };
29
31
  return await (0, __intlayer_config.retryManager)(async () => {
30
- const baseUnmergedDictionary = (0, __intlayer_unmerged_dictionaries_entry.getUnmergedDictionaries)(configuration)[task.dictionaryKey].find((dict) => dict.localId === task.dictionaryLocalId);
32
+ const unmergedDictionariesRecord = (0, __intlayer_unmerged_dictionaries_entry.getUnmergedDictionaries)(configuration);
33
+ const baseUnmergedDictionary = unmergedDictionariesRecord[task.dictionaryKey].find((dict) => dict.localId === task.dictionaryLocalId);
31
34
  if (!baseUnmergedDictionary) {
32
35
  appLogger(`${task.dictionaryPreset}Dictionary not found in unmergedDictionariesRecord. Skipping.`, { level: "warn" });
33
36
  return {
@@ -62,15 +65,22 @@ const translateDictionary = async (task, configuration, options) => {
62
65
  *
63
66
  */
64
67
  let dictionaryToProcess = structuredClone(baseUnmergedDictionary);
65
- if (mode === "complete" && typeof baseUnmergedDictionary.locale !== "string") dictionaryToProcess = (0, __intlayer_core.getFilterMissingTranslationsDictionary)(dictionaryToProcess, targetLocale);
66
- dictionaryToProcess = (0, __intlayer_core.getPerLocaleDictionary)(dictionaryToProcess, task.sourceLocale);
67
68
  let targetLocaleDictionary;
68
- if (typeof baseUnmergedDictionary.locale === "string") targetLocaleDictionary = {
69
- key: baseUnmergedDictionary.key,
70
- content: {},
71
- filePath: baseUnmergedDictionary.filePath
72
- };
73
- else targetLocaleDictionary = (0, __intlayer_core.getPerLocaleDictionary)(baseUnmergedDictionary, targetLocale);
69
+ if (typeof baseUnmergedDictionary.locale === "string") {
70
+ const targetLocaleFilePath = baseUnmergedDictionary.filePath?.replace(new RegExp(`/${task.sourceLocale}/`, "g"), `/${targetLocale}/`);
71
+ const targetUnmergedDictionary = targetLocaleFilePath ? unmergedDictionariesRecord[task.dictionaryKey]?.find((dict) => dict.filePath === targetLocaleFilePath && dict.locale === targetLocale) : void 0;
72
+ targetLocaleDictionary = targetUnmergedDictionary ?? {
73
+ key: baseUnmergedDictionary.key,
74
+ content: {},
75
+ filePath: targetLocaleFilePath,
76
+ locale: targetLocale
77
+ };
78
+ if (mode === "complete") dictionaryToProcess = require_fill_getFilterMissingContentPerLocale.getFilterMissingContentPerLocale(dictionaryToProcess, targetUnmergedDictionary);
79
+ } else {
80
+ if (mode === "complete") dictionaryToProcess = (0, __intlayer_core.getFilterMissingTranslationsDictionary)(dictionaryToProcess, targetLocale);
81
+ dictionaryToProcess = (0, __intlayer_core.getPerLocaleDictionary)(dictionaryToProcess, task.sourceLocale);
82
+ targetLocaleDictionary = (0, __intlayer_core.getPerLocaleDictionary)(baseUnmergedDictionary, targetLocale);
83
+ }
74
84
  const localePreset = (0, __intlayer_config.colon)([
75
85
  (0, __intlayer_config.colorize)("[", __intlayer_config.ANSIColors.GREY_DARK),
76
86
  (0, __intlayer_chokidar.formatLocale)(targetLocale),
@@ -98,6 +108,10 @@ const translateDictionary = async (task, configuration, options) => {
98
108
  const executeTranslation = async () => {
99
109
  return await (0, __intlayer_config.retryManager)(async () => {
100
110
  let translationResult;
111
+ console.dir({
112
+ chunkContent,
113
+ presetOutputContent
114
+ }, { depth: null });
101
115
  if (aiClient && aiConfig) translationResult = await aiClient.translateJSON({
102
116
  entryFileContent: chunkContent,
103
117
  presetOutputContent,
@@ -146,10 +160,13 @@ const translateDictionary = async (task, configuration, options) => {
146
160
  (await Promise.all(chunkPromises)).sort((chunkA, chunkB) => chunkA.chunk.index - chunkB.chunk.index).forEach(({ result }) => {
147
161
  chunkResult.push(result);
148
162
  });
149
- return [targetLocale, (0, __intlayer_core.mergeDictionaries)(chunkResult.map((chunk) => ({
163
+ const merged = (0, __intlayer_core.mergeDictionaries)(chunkResult.map((chunk) => ({
150
164
  ...dictionaryToProcess,
151
165
  content: chunk
152
- }))).content];
166
+ })));
167
+ let finalContent = merged.content;
168
+ if (typeof baseUnmergedDictionary.locale === "string") finalContent = require_fill_deepMergeContent.deepMergeContent(targetLocaleDictionary.content ?? {}, merged.content);
169
+ return [targetLocale, finalContent];
153
170
  }));
154
171
  const translatedContent = Object.fromEntries(translatedContentResults);
155
172
  let dictionaryOutput = {
@@ -1 +1 @@
1
- {"version":3,"file":"translateDictionary.cjs","names":["baseUnmergedDictionary: Dictionary | undefined","metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined","targetLocaleDictionary: Dictionary","ANSIColors","chunkedJsonContent: JsonChunk[]","chunkResult: JsonChunk[]","translationResult: any","chunkPreset","translatedContent: Partial<Record<Locale, Dictionary['content']>>","dictionaryOutput: Dictionary"],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport { type AIOptions, getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n chunkJSON,\n formatLocale,\n type JsonChunk,\n reconstructFromSingleChunk,\n reduceObjectFormat,\n verifyIdenticObjectFormat,\n} from '@intlayer/chokidar';\nimport {\n ANSIColors,\n colon,\n colorize,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n retryManager,\n} from '@intlayer/config';\nimport {\n getFilterMissingTranslationsDictionary,\n getMultilingualDictionary,\n getPerLocaleDictionary,\n insertContentInDictionary,\n mergeDictionaries,\n} from '@intlayer/core';\nimport type { Dictionary, IntlayerConfig, Locale } from '@intlayer/types';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport type { AIClient } from '../utils/setupAI';\nimport type { TranslationTask } from './listTranslationsTasks';\n\ntype TranslateDictionaryResult = TranslationTask & {\n dictionaryOutput: Dictionary | null;\n};\n\ntype TranslateDictionaryOptions = {\n mode: 'complete' | 'review';\n aiOptions?: AIOptions;\n fillMetadata?: boolean;\n onHandle?: ReturnType<typeof import('@intlayer/chokidar').getGlobalLimiter>;\n onSuccess?: () => void;\n onError?: (error: unknown) => void;\n getAbortError?: () => Error | null;\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n};\n\nconst hasMissingMetadata = (dictionary: Dictionary) =>\n !dictionary.description || !dictionary.title || !dictionary.tags;\n\nconst CHUNK_SIZE = 7000; // GPT-5 Mini safe input size\nconst GROUP_MAX_RETRY = 2;\nconst MAX_RETRY = 3;\nconst RETRY_DELAY = 1000 * 10; // 10 seconds\n\nconst MAX_FOLLOWING_ERRORS = 10; // 10 errors in a row, hard exit the process\nlet followingErrors = 0;\n\nexport const translateDictionary = async (\n task: TranslationTask,\n configuration: IntlayerConfig,\n options?: TranslateDictionaryOptions\n): Promise<TranslateDictionaryResult> => {\n const appLogger = getAppLogger(configuration);\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n const { mode, aiOptions, fillMetadata, aiClient, aiConfig } = {\n mode: 'complete',\n fillMetadata: true,\n ...options,\n } as const;\n\n const notifySuccess = () => {\n followingErrors = 0;\n options?.onSuccess?.();\n };\n\n const result = await retryManager(\n async () => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n\n const baseUnmergedDictionary: Dictionary | undefined =\n unmergedDictionariesRecord[task.dictionaryKey].find(\n (dict) => dict.localId === task.dictionaryLocalId\n );\n\n if (!baseUnmergedDictionary) {\n appLogger(\n `${task.dictionaryPreset}Dictionary not found in unmergedDictionariesRecord. Skipping.`,\n {\n level: 'warn',\n }\n );\n return { ...task, dictionaryOutput: null };\n }\n\n let metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined;\n\n if (\n fillMetadata &&\n (hasMissingMetadata(baseUnmergedDictionary) || mode === 'review')\n ) {\n const defaultLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n configuration.internationalization.defaultLocale\n );\n\n appLogger(\n `${task.dictionaryPreset} Filling missing metadata for ${colorizePath(basename(baseUnmergedDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const runAudit = async () => {\n if (aiClient && aiConfig) {\n const result = await aiClient.auditDictionaryMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiConfig,\n });\n\n return {\n data: result,\n };\n }\n\n return await intlayerAPI.ai.auditContentDeclarationMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiOptions,\n });\n };\n\n const metadataResult = options?.onHandle\n ? await options.onHandle(runAudit)\n : await runAudit();\n\n metadata = metadataResult.data?.fileContent;\n }\n\n const translatedContentResults = await Promise.all(\n task.targetLocales.map(async (targetLocale) => {\n /**\n * In complete mode, for large dictionaries, we want to filter all content that is already translated\n *\n * targetLocale: fr\n *\n * { test1: t({ ar: 'Hello', en: 'Hello', fr: 'Bonjour' } }) -> {}\n * { test2: t({ ar: 'Hello', en: 'Hello' }) } -> { test2: t({ ar: 'Hello', en: 'Hello' }) }\n *\n */\n // Reset to base dictionary for each locale to ensure we filter from the original\n let dictionaryToProcess = structuredClone(baseUnmergedDictionary);\n\n if (\n mode === 'complete' &&\n typeof baseUnmergedDictionary.locale !== 'string'\n ) {\n // Remove all nodes that don't have any content to translate\n dictionaryToProcess = getFilterMissingTranslationsDictionary(\n dictionaryToProcess,\n targetLocale\n );\n }\n\n dictionaryToProcess = getPerLocaleDictionary(\n dictionaryToProcess,\n task.sourceLocale\n );\n\n let targetLocaleDictionary: Dictionary;\n\n if (typeof baseUnmergedDictionary.locale === 'string') {\n targetLocaleDictionary = {\n key: baseUnmergedDictionary.key,\n content: {},\n filePath: baseUnmergedDictionary.filePath,\n };\n } else {\n targetLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n targetLocale\n );\n }\n\n const localePreset = colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n formatLocale(targetLocale),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 18 }\n );\n\n const createChunkPreset = (\n chunkIndex: number,\n totalChunks: number\n ) => {\n if (totalChunks <= 1) return '';\n return colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n colorizeNumber(chunkIndex + 1),\n colorize(`/${totalChunks}`, ANSIColors.GREY_DARK),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 5 }\n );\n };\n\n appLogger(\n `${task.dictionaryPreset}${localePreset} Preparing ${colorizePath(basename(targetLocaleDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const chunkedJsonContent: JsonChunk[] = chunkJSON(\n dictionaryToProcess.content,\n CHUNK_SIZE\n );\n\n const nbOfChunks = chunkedJsonContent.length;\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset} Split into ${colorizeNumber(nbOfChunks)} chunks for translation`,\n {\n level: 'info',\n }\n );\n }\n\n const chunkResult: JsonChunk[] = [];\n\n // Process chunks in parallel (globally throttled) to allow concurrent translation\n const chunkPromises = chunkedJsonContent.map((chunk) => {\n const chunkPreset = createChunkPreset(chunk.index, chunk.total);\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} Translating chunk`,\n {\n level: 'info',\n }\n );\n }\n\n // Reconstruct partial JSON content from this chunk's patches\n const chunkContent = reconstructFromSingleChunk(chunk);\n const presetOutputContent = reduceObjectFormat(\n targetLocaleDictionary.content,\n chunkContent\n ) as unknown as JSON;\n\n const executeTranslation = async () => {\n return await retryManager(\n async () => {\n let translationResult: any;\n\n if (aiClient && aiConfig) {\n translationResult = await aiClient.translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiConfig,\n });\n } else {\n translationResult = await intlayerAPI.ai\n .translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiOptions,\n })\n .then((result) => result.data);\n }\n\n if (!translationResult?.fileContent) {\n throw new Error('No content result');\n }\n\n const { isIdentic } = verifyIdenticObjectFormat(\n translationResult.fileContent,\n chunkContent\n );\n if (!isIdentic) {\n console.log(translationResult.fileContent);\n throw new Error(\n 'Translation result does not match expected format'\n );\n }\n\n notifySuccess();\n return translationResult.fileContent;\n },\n {\n maxRetry: MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) => {\n const chunkPreset = createChunkPreset(\n chunk.index,\n chunk.total\n );\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} ${colorize('Error filling:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n );\n\n followingErrors += 1;\n\n if (followingErrors >= MAX_FOLLOWING_ERRORS) {\n appLogger(`There is something wrong.`, {\n level: 'error',\n });\n process.exit(1); // 1 for error\n }\n },\n }\n )();\n };\n\n const wrapped = options?.onHandle\n ? options.onHandle(executeTranslation) // queued in global limiter\n : executeTranslation(); // no global limiter\n\n return wrapped.then((result) => ({ chunk, result }));\n });\n\n // Wait for all chunks for this locale in parallel (still capped by global limiter)\n const chunkResults = await Promise.all(chunkPromises);\n\n // Maintain order\n chunkResults\n .sort((chunkA, chunkB) => chunkA.chunk.index - chunkB.chunk.index)\n .forEach(({ result }) => {\n chunkResult.push(result);\n });\n\n // Merge partial JSON objects produced from each chunk into a single object\n const merged = mergeDictionaries(\n chunkResult.map((chunk) => ({\n ...dictionaryToProcess,\n content: chunk,\n }))\n );\n\n return [targetLocale, merged.content] as const;\n })\n );\n\n const translatedContent: Partial<Record<Locale, Dictionary['content']>> =\n Object.fromEntries(translatedContentResults);\n\n const baseDictionary = baseUnmergedDictionary.locale\n ? {\n ...baseUnmergedDictionary,\n key: baseUnmergedDictionary.key!,\n content: {},\n }\n : baseUnmergedDictionary;\n\n let dictionaryOutput: Dictionary = {\n ...getMultilingualDictionary(baseDictionary),\n locale: undefined, // Ensure the dictionary is multilingual\n ...metadata,\n };\n\n for (const targetLocale of task.targetLocales) {\n if (translatedContent[targetLocale]) {\n dictionaryOutput = insertContentInDictionary(\n dictionaryOutput,\n translatedContent[targetLocale],\n targetLocale\n );\n }\n }\n\n appLogger(\n `${task.dictionaryPreset} ${colorize('Translation completed successfully', ANSIColors.GREEN)} for ${colorizePath(basename(dictionaryOutput.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n if (\n baseUnmergedDictionary.locale &&\n (baseUnmergedDictionary.fill === true ||\n baseUnmergedDictionary.fill === undefined) &&\n baseUnmergedDictionary.location === 'local'\n ) {\n const dictionaryFilePath = baseUnmergedDictionary\n .filePath!.split('.')\n .slice(0, -1);\n\n const contentIndex = dictionaryFilePath[dictionaryFilePath.length - 1];\n\n return JSON.parse(\n JSON.stringify({\n ...task,\n dictionaryOutput: {\n ...dictionaryOutput,\n fill: undefined,\n filled: true,\n },\n }).replaceAll(\n new RegExp(`\\\\.${contentIndex}\\\\.[a-zA-Z0-9]+`, 'g'),\n `.filled.${contentIndex}.json`\n )\n );\n }\n\n return {\n ...task,\n dictionaryOutput,\n };\n },\n {\n maxRetry: GROUP_MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Error fill command:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n ),\n onMaxTryReached: ({ error }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Maximum number of retries reached:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n ),\n }\n )();\n\n return result as TranslateDictionaryResult;\n};\n"],"mappings":";;;;;;;;;AAgDA,MAAM,sBAAsB,eAC1B,CAAC,WAA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AAC,mDAA4B,UAAU,EAAE,CAAC,4CAAqB,SAAS,IAChP,EACE,OAAO,SACR,CACF;EACH,kBAAkB,EAAE,YAClB,UACE,GAAG,KAAK,iBAAiB,mCAAY,sCAAsCA,6BAAW,IAAI,CAAC,mCAAY,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,MAAM,EAAEA,6BAAW,UAAU,IACvL,EACE,OAAO,SACR,CACF;EACJ,CACF,EAAE"}
1
+ {"version":3,"file":"translateDictionary.cjs","names":["baseUnmergedDictionary: Dictionary | undefined","metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined","targetLocaleDictionary: Dictionary","getFilterMissingContentPerLocale","ANSIColors","chunkedJsonContent: JsonChunk[]","chunkResult: JsonChunk[]","translationResult: any","chunkPreset","deepMergeContent","translatedContent: Partial<Record<Locale, Dictionary['content']>>","dictionaryOutput: Dictionary"],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport { type AIOptions, getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n chunkJSON,\n formatLocale,\n type JsonChunk,\n reconstructFromSingleChunk,\n reduceObjectFormat,\n verifyIdenticObjectFormat,\n} from '@intlayer/chokidar';\nimport {\n ANSIColors,\n colon,\n colorize,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n retryManager,\n} from '@intlayer/config';\nimport {\n getFilterMissingTranslationsDictionary,\n getMultilingualDictionary,\n getPerLocaleDictionary,\n insertContentInDictionary,\n mergeDictionaries,\n} from '@intlayer/core';\nimport type { Dictionary, IntlayerConfig, Locale } from '@intlayer/types';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport type { AIClient } from '../utils/setupAI';\nimport { deepMergeContent } from './deepMergeContent';\nimport { getFilterMissingContentPerLocale } from './getFilterMissingContentPerLocale';\nimport type { TranslationTask } from './listTranslationsTasks';\n\ntype TranslateDictionaryResult = TranslationTask & {\n dictionaryOutput: Dictionary | null;\n};\n\ntype TranslateDictionaryOptions = {\n mode: 'complete' | 'review';\n aiOptions?: AIOptions;\n fillMetadata?: boolean;\n onHandle?: ReturnType<typeof import('@intlayer/chokidar').getGlobalLimiter>;\n onSuccess?: () => void;\n onError?: (error: unknown) => void;\n getAbortError?: () => Error | null;\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n};\n\nconst hasMissingMetadata = (dictionary: Dictionary) =>\n !dictionary.description || !dictionary.title || !dictionary.tags;\n\nconst CHUNK_SIZE = 7000; // GPT-5 Mini safe input size\nconst GROUP_MAX_RETRY = 2;\nconst MAX_RETRY = 3;\nconst RETRY_DELAY = 1000 * 10; // 10 seconds\n\nconst MAX_FOLLOWING_ERRORS = 10; // 10 errors in a row, hard exit the process\nlet followingErrors = 0;\n\nexport const translateDictionary = async (\n task: TranslationTask,\n configuration: IntlayerConfig,\n options?: TranslateDictionaryOptions\n): Promise<TranslateDictionaryResult> => {\n const appLogger = getAppLogger(configuration);\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n const { mode, aiOptions, fillMetadata, aiClient, aiConfig } = {\n mode: 'complete',\n fillMetadata: true,\n ...options,\n } as const;\n\n const notifySuccess = () => {\n followingErrors = 0;\n options?.onSuccess?.();\n };\n\n const result = await retryManager(\n async () => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n\n const baseUnmergedDictionary: Dictionary | undefined =\n unmergedDictionariesRecord[task.dictionaryKey].find(\n (dict) => dict.localId === task.dictionaryLocalId\n );\n\n if (!baseUnmergedDictionary) {\n appLogger(\n `${task.dictionaryPreset}Dictionary not found in unmergedDictionariesRecord. Skipping.`,\n {\n level: 'warn',\n }\n );\n return { ...task, dictionaryOutput: null };\n }\n\n let metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined;\n\n if (\n fillMetadata &&\n (hasMissingMetadata(baseUnmergedDictionary) || mode === 'review')\n ) {\n const defaultLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n configuration.internationalization.defaultLocale\n );\n\n appLogger(\n `${task.dictionaryPreset} Filling missing metadata for ${colorizePath(basename(baseUnmergedDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const runAudit = async () => {\n if (aiClient && aiConfig) {\n const result = await aiClient.auditDictionaryMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiConfig,\n });\n\n return {\n data: result,\n };\n }\n\n return await intlayerAPI.ai.auditContentDeclarationMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiOptions,\n });\n };\n\n const metadataResult = options?.onHandle\n ? await options.onHandle(runAudit)\n : await runAudit();\n\n metadata = metadataResult.data?.fileContent;\n }\n\n const translatedContentResults = await Promise.all(\n task.targetLocales.map(async (targetLocale) => {\n /**\n * In complete mode, for large dictionaries, we want to filter all content that is already translated\n *\n * targetLocale: fr\n *\n * { test1: t({ ar: 'Hello', en: 'Hello', fr: 'Bonjour' } }) -> {}\n * { test2: t({ ar: 'Hello', en: 'Hello' }) } -> { test2: t({ ar: 'Hello', en: 'Hello' }) }\n *\n */\n // Reset to base dictionary for each locale to ensure we filter from the original\n let dictionaryToProcess = structuredClone(baseUnmergedDictionary);\n\n let targetLocaleDictionary: Dictionary;\n\n if (typeof baseUnmergedDictionary.locale === 'string') {\n // For per-locale files, the content is already in simple JSON format (not translation nodes)\n // The base dictionary is already the source locale content\n\n // Load the existing target locale dictionary\n const targetLocaleFilePath =\n baseUnmergedDictionary.filePath?.replace(\n new RegExp(`/${task.sourceLocale}/`, 'g'),\n `/${targetLocale}/`\n );\n\n // Find the target locale dictionary in unmerged dictionaries\n const targetUnmergedDictionary = targetLocaleFilePath\n ? unmergedDictionariesRecord[task.dictionaryKey]?.find(\n (dict) =>\n dict.filePath === targetLocaleFilePath &&\n dict.locale === targetLocale\n )\n : undefined;\n\n targetLocaleDictionary = targetUnmergedDictionary ?? {\n key: baseUnmergedDictionary.key,\n content: {},\n filePath: targetLocaleFilePath,\n locale: targetLocale,\n };\n\n // In complete mode, filter out already translated content\n if (mode === 'complete') {\n dictionaryToProcess = getFilterMissingContentPerLocale(\n dictionaryToProcess,\n targetUnmergedDictionary\n );\n }\n } else {\n // For multilingual dictionaries\n if (mode === 'complete') {\n // Remove all nodes that don't have any content to translate\n dictionaryToProcess = getFilterMissingTranslationsDictionary(\n dictionaryToProcess,\n targetLocale\n );\n }\n\n dictionaryToProcess = getPerLocaleDictionary(\n dictionaryToProcess,\n task.sourceLocale\n );\n\n targetLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n targetLocale\n );\n }\n\n const localePreset = colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n formatLocale(targetLocale),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 18 }\n );\n\n const createChunkPreset = (\n chunkIndex: number,\n totalChunks: number\n ) => {\n if (totalChunks <= 1) return '';\n return colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n colorizeNumber(chunkIndex + 1),\n colorize(`/${totalChunks}`, ANSIColors.GREY_DARK),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 5 }\n );\n };\n\n appLogger(\n `${task.dictionaryPreset}${localePreset} Preparing ${colorizePath(basename(targetLocaleDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const chunkedJsonContent: JsonChunk[] = chunkJSON(\n dictionaryToProcess.content,\n CHUNK_SIZE\n );\n\n const nbOfChunks = chunkedJsonContent.length;\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset} Split into ${colorizeNumber(nbOfChunks)} chunks for translation`,\n {\n level: 'info',\n }\n );\n }\n\n const chunkResult: JsonChunk[] = [];\n\n // Process chunks in parallel (globally throttled) to allow concurrent translation\n const chunkPromises = chunkedJsonContent.map((chunk) => {\n const chunkPreset = createChunkPreset(chunk.index, chunk.total);\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} Translating chunk`,\n {\n level: 'info',\n }\n );\n }\n\n // Reconstruct partial JSON content from this chunk's patches\n const chunkContent = reconstructFromSingleChunk(chunk);\n const presetOutputContent = reduceObjectFormat(\n targetLocaleDictionary.content,\n chunkContent\n ) as unknown as JSON;\n\n const executeTranslation = async () => {\n return await retryManager(\n async () => {\n let translationResult: any;\n\n console.dir(\n { chunkContent, presetOutputContent },\n { depth: null }\n );\n\n if (aiClient && aiConfig) {\n translationResult = await aiClient.translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiConfig,\n });\n } else {\n translationResult = await intlayerAPI.ai\n .translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiOptions,\n })\n .then((result) => result.data);\n }\n\n if (!translationResult?.fileContent) {\n throw new Error('No content result');\n }\n\n const { isIdentic } = verifyIdenticObjectFormat(\n translationResult.fileContent,\n chunkContent\n );\n if (!isIdentic) {\n console.log(translationResult.fileContent);\n throw new Error(\n 'Translation result does not match expected format'\n );\n }\n\n notifySuccess();\n return translationResult.fileContent;\n },\n {\n maxRetry: MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) => {\n const chunkPreset = createChunkPreset(\n chunk.index,\n chunk.total\n );\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} ${colorize('Error filling:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n );\n\n followingErrors += 1;\n\n if (followingErrors >= MAX_FOLLOWING_ERRORS) {\n appLogger(`There is something wrong.`, {\n level: 'error',\n });\n process.exit(1); // 1 for error\n }\n },\n }\n )();\n };\n\n const wrapped = options?.onHandle\n ? options.onHandle(executeTranslation) // queued in global limiter\n : executeTranslation(); // no global limiter\n\n return wrapped.then((result) => ({ chunk, result }));\n });\n\n // Wait for all chunks for this locale in parallel (still capped by global limiter)\n const chunkResults = await Promise.all(chunkPromises);\n\n // Maintain order\n chunkResults\n .sort((chunkA, chunkB) => chunkA.chunk.index - chunkB.chunk.index)\n .forEach(({ result }) => {\n chunkResult.push(result);\n });\n\n // Merge partial JSON objects produced from each chunk into a single object\n const merged = mergeDictionaries(\n chunkResult.map((chunk) => ({\n ...dictionaryToProcess,\n content: chunk,\n }))\n );\n\n // For per-locale files, merge the newly translated content with existing target content\n let finalContent = merged.content;\n if (typeof baseUnmergedDictionary.locale === 'string') {\n // Deep merge: existing content + newly translated content\n finalContent = deepMergeContent(\n targetLocaleDictionary.content ?? {},\n merged.content\n );\n }\n\n return [targetLocale, finalContent] as const;\n })\n );\n\n const translatedContent: Partial<Record<Locale, Dictionary['content']>> =\n Object.fromEntries(translatedContentResults);\n\n const baseDictionary = baseUnmergedDictionary.locale\n ? {\n ...baseUnmergedDictionary,\n key: baseUnmergedDictionary.key!,\n content: {},\n }\n : baseUnmergedDictionary;\n\n let dictionaryOutput: Dictionary = {\n ...getMultilingualDictionary(baseDictionary),\n locale: undefined, // Ensure the dictionary is multilingual\n ...metadata,\n };\n\n for (const targetLocale of task.targetLocales) {\n if (translatedContent[targetLocale]) {\n dictionaryOutput = insertContentInDictionary(\n dictionaryOutput,\n translatedContent[targetLocale],\n targetLocale\n );\n }\n }\n\n appLogger(\n `${task.dictionaryPreset} ${colorize('Translation completed successfully', ANSIColors.GREEN)} for ${colorizePath(basename(dictionaryOutput.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n if (\n baseUnmergedDictionary.locale &&\n (baseUnmergedDictionary.fill === true ||\n baseUnmergedDictionary.fill === undefined) &&\n baseUnmergedDictionary.location === 'local'\n ) {\n const dictionaryFilePath = baseUnmergedDictionary\n .filePath!.split('.')\n .slice(0, -1);\n\n const contentIndex = dictionaryFilePath[dictionaryFilePath.length - 1];\n\n return JSON.parse(\n JSON.stringify({\n ...task,\n dictionaryOutput: {\n ...dictionaryOutput,\n fill: undefined,\n filled: true,\n },\n }).replaceAll(\n new RegExp(`\\\\.${contentIndex}\\\\.[a-zA-Z0-9]+`, 'g'),\n `.filled.${contentIndex}.json`\n )\n );\n }\n\n return {\n ...task,\n dictionaryOutput,\n };\n },\n {\n maxRetry: GROUP_MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Error fill command:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n ),\n onMaxTryReached: ({ error }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Maximum number of retries reached:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n ),\n }\n )();\n\n return result as TranslateDictionaryResult;\n};\n"],"mappings":";;;;;;;;;;;AAkDA,MAAM,sBAAsB,eAC1B,CAAC,WAAW,eAAe,CAAC,WAAW,SAAS,CAAC,WAAW;AAE9D,MAAM,aAAa;AACnB,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,cAAc,MAAO;AAE3B,MAAM,uBAAuB;AAC7B,IAAI,kBAAkB;AAEtB,MAAa,sBAAsB,OACjC,MACA,eACA,YACuC;CACvC,MAAM,gDAAyB,cAAc;CAC7C,MAAM,sDAAkC,QAAW,cAAc;CAEjE,MAAM,EAAE,MAAM,WAAW,cAAc,UAAU,aAAa;EAC5D,MAAM;EACN,cAAc;EACd,GAAG;EACJ;CAED,MAAM,sBAAsB;AAC1B,oBAAkB;AAClB,W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,CAAC,mCAAY,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,MAAM,EAAEA,6BAAW,UAAU,CAAC,mDAA4B,UAAU,EAAE,CAAC,4CAAqB,SAAS,IAChP,EACE,OAAO,SACR,CACF;EACH,kBAAkB,EAAE,YAClB,UACE,GAAG,KAAK,iBAAiB,mCAAY,sCAAsCA,6BAAW,IAAI,CAAC,mCAAY,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,MAAM,EAAEA,6BAAW,UAAU,IACvL,EACE,OAAO,SACR,CACF;EACJ,CACF,EAAE"}
@@ -1,5 +1,6 @@
1
1
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
2
  const require_fill_formatFillData = require('./formatFillData.cjs');
3
+ const require_fill_getAvailableLocalesInDictionary = require('./getAvailableLocalesInDictionary.cjs');
3
4
  let __intlayer_chokidar = require("@intlayer/chokidar");
4
5
  let __intlayer_config = require("@intlayer/config");
5
6
  let node_path = require("node:path");
@@ -19,7 +20,14 @@ const writeFill = async (contentDeclarationFile, outputLocales, parentLocales, c
19
20
  appLogger(`Auto fill is disabled for '${(0, __intlayer_config.colorizeKey)(fullDictionary.key)}'`, { level: "info" });
20
21
  return;
21
22
  }
22
- const fillData = require_fill_formatFillData.formatFillData(fillOptions, (outputLocales ?? configuration.internationalization.locales).filter((locale) => !parentLocales?.includes(locale)), filePath, fullDictionary.key, configuration);
23
+ const requestedLocales = (outputLocales ?? configuration.internationalization.locales).filter((locale) => !parentLocales?.includes(locale));
24
+ const availableLocales = require_fill_getAvailableLocalesInDictionary.getAvailableLocalesInDictionary(contentDeclarationFile);
25
+ const localeList = requestedLocales.filter((locale) => availableLocales.includes(locale));
26
+ if (localeList.length === 0) {
27
+ appLogger(`No translations available for dictionary '${(0, __intlayer_config.colorizeKey)(fullDictionary.key)}'`, { level: "info" });
28
+ return;
29
+ }
30
+ const fillData = require_fill_formatFillData.formatFillData(fillOptions, localeList, filePath, fullDictionary.key, configuration);
23
31
  for await (const output of fillData) {
24
32
  if (!output.filePath) {
25
33
  appLogger(`No file path found for auto filled content declaration for '${(0, __intlayer_config.colorizeKey)(fullDictionary.key)}'`, { level: "error" });
@@ -1 +1 @@
1
- {"version":3,"file":"writeFill.cjs","names":["fillOptions: Fill | undefined","fillData: FillData[]","formatFillData"],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport {\n formatLocale,\n formatPath,\n writeContentDeclaration,\n} from '@intlayer/chokidar';\nimport { colorizeKey, getAppLogger } from '@intlayer/config';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary, Fill, IntlayerConfig, Locale } from '@intlayer/types';\nimport { type FillData, formatFillData } from './formatFillData';\n\nexport const writeFill = async (\n contentDeclarationFile: Dictionary,\n outputLocales: Locale[],\n parentLocales: Locale[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n const dictionaries = getDictionaries(configuration);\n\n const fullDictionary = dictionaries[contentDeclarationFile.key];\n\n const { filePath } = contentDeclarationFile;\n\n if (!filePath) {\n appLogger('No file path found for dictionary', {\n level: 'error',\n });\n return;\n }\n\n const fillOptions: Fill | undefined =\n contentDeclarationFile.fill ?? configuration.dictionary?.fill ?? true;\n\n if ((fillOptions as boolean) === false) {\n appLogger(\n `Auto fill is disabled for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const localeList: Locale[] = (\n outputLocales ?? configuration.internationalization.locales\n ).filter((locale) => !parentLocales?.includes(locale));\n\n const fillData: FillData[] = formatFillData(\n fillOptions as Fill,\n localeList,\n filePath,\n fullDictionary.key,\n configuration\n );\n\n for await (const output of fillData) {\n if (!output.filePath) {\n appLogger(\n `No file path found for auto filled content declaration for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n // biome-ignore lint/correctness/noUnusedVariables: Just filtering out the fill property\n const { fill, ...rest } = contentDeclarationFile;\n\n const relativeFilePath = relative(\n configuration.content.baseDir,\n output.filePath\n );\n\n // write file\n await writeContentDeclaration(\n {\n ...rest,\n filled: true,\n locale: output.isPerLocale ? output.localeList[0] : undefined,\n localId: `${contentDeclarationFile.key}::local::${relativeFilePath}`,\n filePath: relativeFilePath,\n },\n configuration,\n {\n localeList: output.localeList,\n }\n );\n\n if (output.isPerLocale) {\n const sourceLocale = output.localeList[0];\n\n appLogger(\n `Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(sourceLocale)}`,\n {\n level: 'info',\n }\n );\n } else {\n appLogger(\n `Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`,\n {\n level: 'info',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;AAWA,MAAa,YAAY,OACvB,wBACA,eACA,eACA,kBACG;CACH,MAAM,gDAAyB,cAAc;CAG7C,MAAM,oEAF+B,cAAc,CAEf,uBAAuB;CAE3D,MAAM,EAAE,aAAa;AAErB,KAAI,CAAC,UAAU;AACb,YAAU,qCAAqC,EAC7C,OAAO,SACR,CAAC;AACF;;CAGF,MAAMA,cACJ,uBAAuB,QAAQ,cAAc,YAAY,QAAQ;AAEnE,KAAK,gBAA4B,OAAO;AACtC,YACE,iEAA0C,eAAe,IAAI,CAAC,IAC9D,EACE,OAAO,QACR,CACF;AACD;;CAOF,MAAMC,WAAuBC,2CAC3B,cAJA,iBAAiB,cAAc,qBAAqB,SACpD,QAAQ,WAAW,CAAC,eAAe,SAAS,OAAO,CAAC,EAKpD,UACA,eAAe,KACf,cACD;AAED,YAAW,MAAM,UAAU,UAAU;AACnC,MAAI,CAAC,OAAO,UAAU;AACpB,aACE,kGAA2E,eAAe,IAAI,CAAC,IAC/F,EACE,OAAO,SACR,CACF;AACD;;EAIF,MAAM,EAAE,MAAM,GAAG,SAAS;EAE1B,MAAM,2CACJ,cAAc,QAAQ,SACtB,OAAO,SACR;AAGD,yDACE;GACE,GAAG;GACH,QAAQ;GACR,QAAQ,OAAO,cAAc,OAAO,WAAW,KAAK;GACpD,SAAS,GAAG,uBAAuB,IAAI,WAAW;GAClD,UAAU;GACX,EACD,eACA,EACE,YAAY,OAAO,YACpB,CACF;AAED,MAAI,OAAO,aAAa;GACtB,MAAM,eAAe,OAAO,WAAW;AAEvC,aACE,sFAA+D,eAAe,IAAI,CAAC,mDAA0B,OAAO,SAAS,CAAC,oDAA2B,aAAa,IACtK,EACE,OAAO,QACR,CACF;QAED,WACE,2EAAoD,eAAe,IAAI,CAAC,mDAA0B,OAAO,SAAS,IAClH,EACE,OAAO,QACR,CACF"}
1
+ {"version":3,"file":"writeFill.cjs","names":["fillOptions: Fill | undefined","requestedLocales: Locale[]","getAvailableLocalesInDictionary","fillData: FillData[]","formatFillData"],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport {\n formatLocale,\n formatPath,\n writeContentDeclaration,\n} from '@intlayer/chokidar';\nimport { colorizeKey, getAppLogger } from '@intlayer/config';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary, Fill, IntlayerConfig, Locale } from '@intlayer/types';\nimport { type FillData, formatFillData } from './formatFillData';\nimport { getAvailableLocalesInDictionary } from './getAvailableLocalesInDictionary';\n\nexport const writeFill = async (\n contentDeclarationFile: Dictionary,\n outputLocales: Locale[],\n parentLocales: Locale[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n const dictionaries = getDictionaries(configuration);\n\n const fullDictionary = dictionaries[contentDeclarationFile.key];\n\n const { filePath } = contentDeclarationFile;\n\n if (!filePath) {\n appLogger('No file path found for dictionary', {\n level: 'error',\n });\n return;\n }\n\n const fillOptions: Fill | undefined =\n contentDeclarationFile.fill ?? configuration.dictionary?.fill ?? true;\n\n if ((fillOptions as boolean) === false) {\n appLogger(\n `Auto fill is disabled for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const requestedLocales: Locale[] = (\n outputLocales ?? configuration.internationalization.locales\n ).filter((locale) => !parentLocales?.includes(locale));\n\n // Get locales that actually have translations in the content\n const availableLocales = getAvailableLocalesInDictionary(\n contentDeclarationFile\n );\n\n // Only write files for locales that have actual translations\n const localeList = requestedLocales.filter((locale) =>\n availableLocales.includes(locale)\n );\n\n if (localeList.length === 0) {\n appLogger(\n `No translations available for dictionary '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const fillData: FillData[] = formatFillData(\n fillOptions as Fill,\n localeList,\n filePath,\n fullDictionary.key,\n configuration\n );\n\n for await (const output of fillData) {\n if (!output.filePath) {\n appLogger(\n `No file path found for auto filled content declaration for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n // biome-ignore lint/correctness/noUnusedVariables: Just filtering out the fill property\n const { fill, ...rest } = contentDeclarationFile;\n\n const relativeFilePath = relative(\n configuration.content.baseDir,\n output.filePath\n );\n\n // write file\n await writeContentDeclaration(\n {\n ...rest,\n filled: true,\n locale: output.isPerLocale ? output.localeList[0] : undefined,\n localId: `${contentDeclarationFile.key}::local::${relativeFilePath}`,\n filePath: relativeFilePath,\n },\n configuration,\n {\n localeList: output.localeList,\n }\n );\n\n if (output.isPerLocale) {\n const sourceLocale = output.localeList[0];\n\n appLogger(\n `Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(sourceLocale)}`,\n {\n level: 'info',\n }\n );\n } else {\n appLogger(\n `Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`,\n {\n level: 'info',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAYA,MAAa,YAAY,OACvB,wBACA,eACA,eACA,kBACG;CACH,MAAM,gDAAyB,cAAc;CAG7C,MAAM,oEAF+B,cAAc,CAEf,uBAAuB;CAE3D,MAAM,EAAE,aAAa;AAErB,KAAI,CAAC,UAAU;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.ts
2
+ /**
3
+ * Deep merge two plain objects (for per-locale content).
4
+ * The second object's values take precedence over the first.
5
+ *
6
+ * @param target - The base object
7
+ * @param source - The object to merge in (takes precedence)
8
+ * @returns The merged object
9
+ */
10
+ const deepMergeContent = (target, source) => {
11
+ if (!target) return source;
12
+ if (!source) return target;
13
+ if (typeof target !== "object" || typeof source !== "object" || Array.isArray(target) || Array.isArray(source)) return source;
14
+ const result = { ...target };
15
+ for (const key in source) if (Object.hasOwn(source, key)) {
16
+ const sourceValue = source[key];
17
+ const targetValue = result[key];
18
+ if (typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue) && typeof targetValue === "object" && targetValue !== null && !Array.isArray(targetValue)) result[key] = deepMergeContent(targetValue, sourceValue);
19
+ else result[key] = sourceValue;
20
+ }
21
+ return result;
22
+ };
23
+
24
+ //#endregion
25
+ export { deepMergeContent };
26
+ //# sourceMappingURL=deepMergeContent.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deepMergeContent.mjs","names":["result: any"],"sources":["../../../src/fill/deepMergeContent.ts"],"sourcesContent":["/**\n * Deep merge two plain objects (for per-locale content).\n * The second object's values take precedence over the first.\n *\n * @param target - The base object\n * @param source - The object to merge in (takes precedence)\n * @returns The merged object\n */\nexport const deepMergeContent = <T = any>(target: T, source: T): T => {\n // Handle null/undefined\n if (!target) return source;\n if (!source) return target;\n\n // Handle non-objects (primitives, arrays)\n if (\n typeof target !== 'object' ||\n typeof source !== 'object' ||\n Array.isArray(target) ||\n Array.isArray(source)\n ) {\n return source;\n }\n\n // Merge objects\n const result: any = { ...target };\n\n for (const key in source) {\n if (Object.hasOwn(source, key)) {\n const sourceValue = (source as any)[key];\n const targetValue = result[key];\n\n if (\n typeof sourceValue === 'object' &&\n sourceValue !== null &&\n !Array.isArray(sourceValue) &&\n typeof targetValue === 'object' &&\n targetValue !== null &&\n !Array.isArray(targetValue)\n ) {\n // Recursively merge nested objects\n result[key] = deepMergeContent(targetValue, sourceValue);\n } else {\n // Overwrite with source value\n result[key] = sourceValue;\n }\n }\n }\n\n return result;\n};\n"],"mappings":";;;;;;;;;AAQA,MAAa,oBAA6B,QAAW,WAAiB;AAEpE,KAAI,CAAC,OAAQ,QAAO;AACpB,KAAI,CAAC,OAAQ,QAAO;AAGpB,KACE,OAAO,WAAW,YAClB,OAAO,WAAW,YAClB,MAAM,QAAQ,OAAO,IACrB,MAAM,QAAQ,OAAO,CAErB,QAAO;CAIT,MAAMA,SAAc,EAAE,GAAG,QAAQ;AAEjC,MAAK,MAAM,OAAO,OAChB,KAAI,OAAO,OAAO,QAAQ,IAAI,EAAE;EAC9B,MAAM,cAAe,OAAe;EACpC,MAAM,cAAc,OAAO;AAE3B,MACE,OAAO,gBAAgB,YACvB,gBAAgB,QAChB,CAAC,MAAM,QAAQ,YAAY,IAC3B,OAAO,gBAAgB,YACvB,gBAAgB,QAChB,CAAC,MAAM,QAAQ,YAAY,CAG3B,QAAO,OAAO,iBAAiB,aAAa,YAAY;MAGxD,QAAO,OAAO;;AAKpB,QAAO"}
@@ -56,7 +56,13 @@ const fill = async (options) => {
56
56
  });
57
57
  if (!translationTaskResult?.dictionaryOutput) return;
58
58
  const { dictionaryOutput, sourceLocale } = translationTaskResult;
59
- if (typeof dictionaryOutput.fill === "string" || typeof dictionaryOutput.fill === "object" || typeof dictionaryOutput.locale === "string" && dictionaryOutput.fill !== false) await writeFill(dictionaryOutput, outputLocales, [sourceLocale], configuration);
59
+ const hasDictionaryLevelFill = typeof dictionaryOutput.fill === "string" || typeof dictionaryOutput.fill === "object";
60
+ const isPerLocale = typeof dictionaryOutput.locale === "string";
61
+ const effectiveFill = hasDictionaryLevelFill ? dictionaryOutput.fill : isPerLocale ? configuration.dictionary?.fill ?? true : false;
62
+ if (typeof effectiveFill === "string" || typeof effectiveFill === "object") await writeFill({
63
+ ...dictionaryOutput,
64
+ fill: effectiveFill
65
+ }, outputLocales, [sourceLocale], configuration);
60
66
  else {
61
67
  await writeContentDeclaration(dictionaryOutput, configuration);
62
68
  if (dictionaryOutput.filePath) appLogger(`${task.dictionaryPreset} Content declaration written to ${formatPath(basename(dictionaryOutput.filePath))}`, { level: "info" });
@@ -1 +1 @@
1
- {"version":3,"file":"fill.mjs","names":["translationTasks: TranslationTask[]"],"sources":["../../../src/fill/fill.ts"],"sourcesContent":["import { basename, relative } from 'node:path';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n formatPath,\n getGlobalLimiter,\n getTaskLimiter,\n type ListGitFilesOptions,\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar';\nimport {\n ANSIColors,\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type { Locale } from '@intlayer/types';\nimport {\n ensureArray,\n type GetTargetDictionaryOptions,\n getTargetUnmergedDictionaries,\n} from '../getTargetDictionary';\nimport { setupAI } from '../utils/setupAI';\nimport {\n listTranslationsTasks,\n type TranslationTask,\n} from './listTranslationsTasks';\nimport { translateDictionary } from './translateDictionary';\nimport { writeFill } from './writeFill';\n\nconst NB_CONCURRENT_TRANSLATIONS = 7;\n\n// Arguments for the fill function\nexport type FillOptions = {\n sourceLocale?: Locale;\n outputLocales?: Locale | Locale[];\n mode?: 'complete' | 'review';\n gitOptions?: ListGitFilesOptions;\n aiOptions?: AIOptions; // Added aiOptions to be passed to translateJSON\n verbose?: boolean;\n nbConcurrentTranslations?: number;\n nbConcurrentTasks?: number; // NEW: number of tasks that may run at once\n build?: boolean;\n skipMetadata?: boolean;\n} & GetTargetDictionaryOptions;\n\n/**\n * Fill translations based on the provided options.\n */\nexport const fill = async (options?: FillOptions): Promise<void> => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n if (options?.build === true) {\n await prepareIntlayer(configuration, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(configuration);\n }\n\n const { defaultLocale, locales } = configuration.internationalization;\n const mode = options?.mode ?? 'complete';\n const baseLocale = options?.sourceLocale ?? defaultLocale;\n\n const outputLocales = options?.outputLocales\n ? ensureArray(options.outputLocales)\n : locales;\n\n const aiResult = await setupAI(configuration, options?.aiOptions);\n\n if (!aiResult?.hasAIAccess) return;\n\n const { aiClient, aiConfig } = aiResult;\n\n const targetUnmergedDictionaries =\n await getTargetUnmergedDictionaries(options);\n\n const affectedDictionaryKeys = new Set<string>();\n targetUnmergedDictionaries.forEach((dict) => {\n affectedDictionaryKeys.add(dict.key);\n });\n\n const keysToProcess = Array.from(affectedDictionaryKeys);\n\n appLogger([\n 'Affected dictionary keys for processing:',\n keysToProcess.length > 0\n ? keysToProcess.map((key) => colorizeKey(key)).join(', ')\n : colorize('No keys found', ANSIColors.YELLOW),\n ]);\n\n if (keysToProcess.length === 0) return;\n\n /**\n * List the translations tasks\n *\n * Create a list of per-locale dictionaries to translate\n *\n * In 'complete' mode, filter only the missing locales to translate\n */\n const translationTasks: TranslationTask[] = listTranslationsTasks(\n targetUnmergedDictionaries.map((dictionary) => dictionary.localId!),\n outputLocales,\n mode,\n baseLocale,\n configuration\n );\n\n // AI calls in flight at once (translateJSON + metadata audit)\n const nbConcurrentTranslations =\n options?.nbConcurrentTranslations ?? NB_CONCURRENT_TRANSLATIONS;\n const globalLimiter = getGlobalLimiter(nbConcurrentTranslations);\n\n // NEW: number of *tasks* that may run at once (start/prepare/log/write)\n const nbConcurrentTasks = Math.max(\n 1,\n Math.min(\n options?.nbConcurrentTasks ?? nbConcurrentTranslations,\n translationTasks.length\n )\n );\n\n const taskLimiter = getTaskLimiter(nbConcurrentTasks);\n\n const runners = translationTasks.map((task) =>\n taskLimiter(async () => {\n const relativePath = relative(\n configuration?.content?.baseDir ?? process.cwd(),\n task?.dictionaryFilePath ?? ''\n );\n\n // log AFTER acquiring a task slot\n appLogger(\n `${task.dictionaryPreset} Processing ${colorizePath(basename(relativePath))}`,\n { level: 'info' }\n );\n\n const translationTaskResult = await translateDictionary(\n task,\n configuration,\n {\n mode,\n aiOptions: options?.aiOptions,\n fillMetadata: !options?.skipMetadata,\n onHandle: globalLimiter, // <= AI calls go through here\n aiClient,\n aiConfig,\n }\n );\n\n if (!translationTaskResult?.dictionaryOutput) return;\n\n const { dictionaryOutput, sourceLocale } = translationTaskResult;\n\n const isFillOtherFile =\n typeof dictionaryOutput.fill === 'string' ||\n typeof dictionaryOutput.fill === 'object' ||\n (typeof dictionaryOutput.locale === 'string' &&\n dictionaryOutput.fill !== false);\n\n if (isFillOtherFile) {\n await writeFill(\n dictionaryOutput,\n outputLocales,\n [sourceLocale],\n configuration\n );\n } else {\n await writeContentDeclaration(dictionaryOutput, configuration);\n\n if (dictionaryOutput.filePath) {\n appLogger(\n `${task.dictionaryPreset} Content declaration written to ${formatPath(basename(dictionaryOutput.filePath))}`,\n { level: 'info' }\n );\n }\n }\n })\n );\n\n await Promise.all(runners);\n await (globalLimiter as any).onIdle();\n};\n"],"mappings":";;;;;;;;;;AAgCA,MAAM,6BAA6B;;;;AAmBnC,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,gBAAgB,iBAAiB,SAAS,cAAc;CAC9D,MAAM,YAAY,aAAa,cAAc;AAE7C,KAAI,SAAS,UAAU,KACrB,OAAM,gBAAgB,eAAe,EAAE,UAAU,MAAM,CAAC;UAC/C,OAAO,SAAS,UAAU,YACnC,OAAM,gBAAgB,cAAc;CAGtC,MAAM,EAAE,eAAe,YAAY,cAAc;CACjD,MAAM,OAAO,SAAS,QAAQ;CAC9B,MAAM,aAAa,SAAS,gBAAgB;CAE5C,MAAM,gBAAgB,SAAS,gBAC3B,YAAY,QAAQ,cAAc,GAClC;CAEJ,MAAM,WAAW,MAAM,QAAQ,eAAe,SAAS,UAAU;AAEjE,KAAI,CAAC,UAAU,YAAa;CAE5B,MAAM,EAAE,UAAU,aAAa;CAE/B,MAAM,6BACJ,MAAM,8BAA8B,QAAQ;CAE9C,MAAM,yCAAyB,IAAI,KAAa;AAChD,4BAA2B,SAAS,SAAS;AAC3C,yBAAuB,IAAI,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,CAClB;;GAGL,CACH;AAED,OAAM,QAAQ,IAAI,QAAQ;AAC1B,OAAO,cAAsB,QAAQ"}
1
+ {"version":3,"file":"fill.mjs","names":["translationTasks: TranslationTask[]"],"sources":["../../../src/fill/fill.ts"],"sourcesContent":["import { basename, relative } from 'node:path';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n formatPath,\n getGlobalLimiter,\n getTaskLimiter,\n type ListGitFilesOptions,\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar';\nimport {\n ANSIColors,\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type { Locale } from '@intlayer/types';\nimport {\n ensureArray,\n type GetTargetDictionaryOptions,\n getTargetUnmergedDictionaries,\n} from '../getTargetDictionary';\nimport { setupAI } from '../utils/setupAI';\nimport {\n listTranslationsTasks,\n type TranslationTask,\n} from './listTranslationsTasks';\nimport { translateDictionary } from './translateDictionary';\nimport { writeFill } from './writeFill';\n\nconst NB_CONCURRENT_TRANSLATIONS = 7;\n\n// Arguments for the fill function\nexport type FillOptions = {\n sourceLocale?: Locale;\n outputLocales?: Locale | Locale[];\n mode?: 'complete' | 'review';\n gitOptions?: ListGitFilesOptions;\n aiOptions?: AIOptions; // Added aiOptions to be passed to translateJSON\n verbose?: boolean;\n nbConcurrentTranslations?: number;\n nbConcurrentTasks?: number; // NEW: number of tasks that may run at once\n build?: boolean;\n skipMetadata?: boolean;\n} & GetTargetDictionaryOptions;\n\n/**\n * Fill translations based on the provided options.\n */\nexport const fill = async (options?: FillOptions): Promise<void> => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n if (options?.build === true) {\n await prepareIntlayer(configuration, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(configuration);\n }\n\n const { defaultLocale, locales } = configuration.internationalization;\n const mode = options?.mode ?? 'complete';\n const baseLocale = options?.sourceLocale ?? defaultLocale;\n\n const outputLocales = options?.outputLocales\n ? ensureArray(options.outputLocales)\n : locales;\n\n const aiResult = await setupAI(configuration, options?.aiOptions);\n\n if (!aiResult?.hasAIAccess) return;\n\n const { aiClient, aiConfig } = aiResult;\n\n const targetUnmergedDictionaries =\n await getTargetUnmergedDictionaries(options);\n\n const affectedDictionaryKeys = new Set<string>();\n targetUnmergedDictionaries.forEach((dict) => {\n affectedDictionaryKeys.add(dict.key);\n });\n\n const keysToProcess = Array.from(affectedDictionaryKeys);\n\n appLogger([\n 'Affected dictionary keys for processing:',\n keysToProcess.length > 0\n ? keysToProcess.map((key) => colorizeKey(key)).join(', ')\n : colorize('No keys found', ANSIColors.YELLOW),\n ]);\n\n if (keysToProcess.length === 0) return;\n\n /**\n * List the translations tasks\n *\n * Create a list of per-locale dictionaries to translate\n *\n * In 'complete' mode, filter only the missing locales to translate\n */\n const translationTasks: TranslationTask[] = listTranslationsTasks(\n targetUnmergedDictionaries.map((dictionary) => dictionary.localId!),\n outputLocales,\n mode,\n baseLocale,\n configuration\n );\n\n // AI calls in flight at once (translateJSON + metadata audit)\n const nbConcurrentTranslations =\n options?.nbConcurrentTranslations ?? NB_CONCURRENT_TRANSLATIONS;\n const globalLimiter = getGlobalLimiter(nbConcurrentTranslations);\n\n // NEW: number of *tasks* that may run at once (start/prepare/log/write)\n const nbConcurrentTasks = Math.max(\n 1,\n Math.min(\n options?.nbConcurrentTasks ?? nbConcurrentTranslations,\n translationTasks.length\n )\n );\n\n const taskLimiter = getTaskLimiter(nbConcurrentTasks);\n\n const runners = translationTasks.map((task) =>\n taskLimiter(async () => {\n const relativePath = relative(\n configuration?.content?.baseDir ?? process.cwd(),\n task?.dictionaryFilePath ?? ''\n );\n\n // log AFTER acquiring a task slot\n appLogger(\n `${task.dictionaryPreset} Processing ${colorizePath(basename(relativePath))}`,\n { level: 'info' }\n );\n\n const translationTaskResult = await translateDictionary(\n task,\n configuration,\n {\n mode,\n aiOptions: options?.aiOptions,\n fillMetadata: !options?.skipMetadata,\n onHandle: globalLimiter, // <= AI calls go through here\n aiClient,\n aiConfig,\n }\n );\n\n if (!translationTaskResult?.dictionaryOutput) return;\n\n const { dictionaryOutput, sourceLocale } = translationTaskResult;\n\n // Determine if we should write to separate files\n // - If dictionary has explicit fill setting (string or object), use it\n // - If dictionary is per-locale AND has no explicit fill=false, use global fill config\n // - If dictionary is multilingual (no locale property), always write to same file\n const hasDictionaryLevelFill =\n typeof dictionaryOutput.fill === 'string' ||\n typeof dictionaryOutput.fill === 'object';\n\n const isPerLocale = typeof dictionaryOutput.locale === 'string';\n\n const effectiveFill = hasDictionaryLevelFill\n ? dictionaryOutput.fill\n : isPerLocale\n ? (configuration.dictionary?.fill ?? true)\n : false; // Multilingual dictionaries don't use fill by default\n\n const isFillOtherFile =\n typeof effectiveFill === 'string' || typeof effectiveFill === 'object';\n\n if (isFillOtherFile) {\n await writeFill(\n {\n ...dictionaryOutput,\n // Ensure fill is set on the dictionary for writeFill to use\n fill: effectiveFill,\n },\n outputLocales,\n [sourceLocale],\n configuration\n );\n } else {\n await writeContentDeclaration(dictionaryOutput, configuration);\n\n if (dictionaryOutput.filePath) {\n appLogger(\n `${task.dictionaryPreset} Content declaration written to ${formatPath(basename(dictionaryOutput.filePath))}`,\n { level: 'info' }\n );\n }\n }\n })\n );\n\n await Promise.all(runners);\n await (globalLimiter as any).onIdle();\n};\n"],"mappings":";;;;;;;;;;AAgCA,MAAM,6BAA6B;;;;AAmBnC,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,gBAAgB,iBAAiB,SAAS,cAAc;CAC9D,MAAM,YAAY,aAAa,cAAc;AAE7C,KAAI,SAAS,UAAU,KACrB,OAAM,gBAAgB,eAAe,EAAE,UAAU,MAAM,CAAC;UAC/C,OAAO,SAAS,UAAU,YACnC,OAAM,gBAAgB,cAAc;CAGtC,MAAM,EAAE,eAAe,YAAY,cAAc;CACjD,MAAM,OAAO,SAAS,QAAQ;CAC9B,MAAM,aAAa,SAAS,gBAAgB;CAE5C,MAAM,g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B,SAAS,YACjC,OAAO,iBAAiB,SAAS;EAEnC,MAAM,cAAc,OAAO,iBAAiB,WAAW;EAEvD,MAAM,gBAAgB,yBAClB,iBAAiB,OACjB,cACG,cAAc,YAAY,QAAQ,OACnC;AAKN,MAFE,OAAO,kBAAkB,YAAY,OAAO,kBAAkB,SAG9D,OAAM,UACJ;GACE,GAAG;GAEH,MAAM;GACP,EACD,eACA,CAAC,aAAa,EACd,cACD;OACI;AACL,SAAM,wBAAwB,kBAAkB,cAAc;AAE9D,OAAI,iBAAiB,SACnB,WACE,GAAG,KAAK,iBAAiB,kCAAkC,WAAW,SAAS,iBAAiB,SAAS,CAAC,IAC1G,EAAE,OAAO,QAAQ,CAClB;;GAGL,CACH;AAED,OAAM,QAAQ,IAAI,QAAQ;AAC1B,OAAO,cAAsB,QAAQ"}
@@ -0,0 +1,25 @@
1
+ //#region src/fill/getAvailableLocalesInDictionary.ts
2
+ /**
3
+ * Recursively traverses dictionary content to find all locales that have actual translations.
4
+ * Returns a Set of locale strings that are present in the translation nodes.
5
+ */
6
+ const extractLocalesFromContent = (content, locales = /* @__PURE__ */ new Set()) => {
7
+ if (!content || typeof content !== "object") return locales;
8
+ if (content.nodeType === "translation" && content.translation) Object.keys(content.translation).forEach((locale) => {
9
+ locales.add(locale);
10
+ });
11
+ for (const value of Object.values(content)) if (value && typeof value === "object") extractLocalesFromContent(value, locales);
12
+ return locales;
13
+ };
14
+ /**
15
+ * Gets all locales that have actual translations in the dictionary content.
16
+ * Only returns locales that are present in at least one translation node.
17
+ */
18
+ const getAvailableLocalesInDictionary = (dictionary) => {
19
+ const localesSet = extractLocalesFromContent(dictionary.content);
20
+ return Array.from(localesSet);
21
+ };
22
+
23
+ //#endregion
24
+ export { getAvailableLocalesInDictionary };
25
+ //# sourceMappingURL=getAvailableLocalesInDictionary.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getAvailableLocalesInDictionary.mjs","names":[],"sources":["../../../src/fill/getAvailableLocalesInDictionary.ts"],"sourcesContent":["import type { Dictionary, Locale } from '@intlayer/types';\n\n/**\n * Recursively traverses dictionary content to find all locales that have actual translations.\n * Returns a Set of locale strings that are present in the translation nodes.\n */\nconst extractLocalesFromContent = (\n content: any,\n locales: Set<Locale> = new Set()\n): Set<Locale> => {\n if (!content || typeof content !== 'object') {\n return locales;\n }\n\n // Check if this is a translation node\n if (content.nodeType === 'translation' && content.translation) {\n // Add all locale keys from the translation map\n Object.keys(content.translation).forEach((locale) => {\n locales.add(locale as Locale);\n });\n }\n\n // Recursively check nested objects\n for (const value of Object.values(content)) {\n if (value && typeof value === 'object') {\n extractLocalesFromContent(value, locales);\n }\n }\n\n return locales;\n};\n\n/**\n * Gets all locales that have actual translations in the dictionary content.\n * Only returns locales that are present in at least one translation node.\n */\nexport const getAvailableLocalesInDictionary = (\n dictionary: Dictionary\n): Locale[] => {\n const localesSet = extractLocalesFromContent(dictionary.content);\n return Array.from(localesSet);\n};\n"],"mappings":";;;;;AAMA,MAAM,6BACJ,SACA,0BAAuB,IAAI,KAAK,KAChB;AAChB,KAAI,CAAC,WAAW,OAAO,YAAY,SACjC,QAAO;AAIT,KAAI,QAAQ,aAAa,iBAAiB,QAAQ,YAEhD,QAAO,KAAK,QAAQ,YAAY,CAAC,SAAS,WAAW;AACnD,UAAQ,IAAI,OAAiB;GAC7B;AAIJ,MAAK,MAAM,SAAS,OAAO,OAAO,QAAQ,CACxC,KAAI,SAAS,OAAO,UAAU,SAC5B,2BAA0B,OAAO,QAAQ;AAI7C,QAAO;;;;;;AAOT,MAAa,mCACX,eACa;CACb,MAAM,aAAa,0BAA0B,WAAW,QAAQ;AAChE,QAAO,MAAM,KAAK,WAAW"}
@@ -0,0 +1,49 @@
1
+ //#region src/fill/getFilterMissingContentPerLocale.ts
2
+ /**
3
+ * Recursively compares source content with target content and returns only the missing parts.
4
+ * For per-locale files where content is simple JSON (not translation nodes).
5
+ *
6
+ * @param sourceContent - The source content to check
7
+ * @param targetContent - The existing target content
8
+ * @returns Only the content that's missing in the target
9
+ */
10
+ const filterMissingContent = (sourceContent, targetContent) => {
11
+ if (targetContent === void 0 || targetContent === null) return sourceContent;
12
+ if (typeof sourceContent !== "object" || sourceContent === null) return;
13
+ if (Array.isArray(sourceContent)) {
14
+ if (!Array.isArray(targetContent)) return sourceContent;
15
+ const missingItems = sourceContent.map((item, index) => filterMissingContent(item, targetContent[index])).filter((item) => item !== void 0);
16
+ return missingItems.length > 0 ? missingItems : void 0;
17
+ }
18
+ const result = {};
19
+ let hasMissingContent = false;
20
+ for (const [key, value] of Object.entries(sourceContent)) {
21
+ const targetValue = targetContent?.[key];
22
+ const missingValue = filterMissingContent(value, targetValue);
23
+ if (missingValue !== void 0) {
24
+ result[key] = missingValue;
25
+ hasMissingContent = true;
26
+ }
27
+ }
28
+ return hasMissingContent ? result : void 0;
29
+ };
30
+ /**
31
+ * Filters a dictionary to only include content that's missing in the target dictionary.
32
+ * Used for per-locale content declarations in 'complete' mode.
33
+ *
34
+ * @param sourceDictionary - The source dictionary with content to translate
35
+ * @param targetDictionary - The existing target dictionary
36
+ * @returns A dictionary with only the missing content
37
+ */
38
+ const getFilterMissingContentPerLocale = (sourceDictionary, targetDictionary) => {
39
+ if (!targetDictionary || !targetDictionary.content) return sourceDictionary;
40
+ const missingContent = filterMissingContent(sourceDictionary.content, targetDictionary.content);
41
+ return {
42
+ ...sourceDictionary,
43
+ content: missingContent ?? {}
44
+ };
45
+ };
46
+
47
+ //#endregion
48
+ export { getFilterMissingContentPerLocale };
49
+ //# sourceMappingURL=getFilterMissingContentPerLocale.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getFilterMissingContentPerLocale.mjs","names":["result: any"],"sources":["../../../src/fill/getFilterMissingContentPerLocale.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types';\n\n/**\n * Recursively compares source content with target content and returns only the missing parts.\n * For per-locale files where content is simple JSON (not translation nodes).\n *\n * @param sourceContent - The source content to check\n * @param targetContent - The existing target content\n * @returns Only the content that's missing in the target\n */\nconst filterMissingContent = (sourceContent: any, targetContent: any): any => {\n // If target doesn't exist, all source content is missing\n if (targetContent === undefined || targetContent === null) {\n return sourceContent;\n }\n\n // Primitive values: if target exists (even if empty string), consider it translated\n if (typeof sourceContent !== 'object' || sourceContent === null) {\n return undefined;\n }\n\n // Handle arrays\n if (Array.isArray(sourceContent)) {\n if (!Array.isArray(targetContent)) {\n return sourceContent;\n }\n\n const missingItems = sourceContent\n .map((item, index) => filterMissingContent(item, targetContent[index]))\n .filter((item) => item !== undefined);\n\n return missingItems.length > 0 ? missingItems : undefined;\n }\n\n // Handle objects\n const result: any = {};\n let hasMissingContent = false;\n\n for (const [key, value] of Object.entries(sourceContent)) {\n const targetValue = targetContent?.[key];\n const missingValue = filterMissingContent(value, targetValue);\n\n if (missingValue !== undefined) {\n result[key] = missingValue;\n hasMissingContent = true;\n }\n }\n\n return hasMissingContent ? result : undefined;\n};\n\n/**\n * Filters a dictionary to only include content that's missing in the target dictionary.\n * Used for per-locale content declarations in 'complete' mode.\n *\n * @param sourceDictionary - The source dictionary with content to translate\n * @param targetDictionary - The existing target dictionary\n * @returns A dictionary with only the missing content\n */\nexport const getFilterMissingContentPerLocale = (\n sourceDictionary: Dictionary,\n targetDictionary: Dictionary | undefined\n): Dictionary => {\n if (!targetDictionary || !targetDictionary.content) {\n // If no target exists, all source content is missing\n return sourceDictionary;\n }\n\n const missingContent = filterMissingContent(\n sourceDictionary.content,\n targetDictionary.content\n );\n\n return {\n ...sourceDictionary,\n content: missingContent ?? {},\n };\n};\n"],"mappings":";;;;;;;;;AAUA,MAAM,wBAAwB,eAAoB,kBAA4B;AAE5E,KAAI,kBAAkB,UAAa,kBAAkB,KACnD,QAAO;AAIT,KAAI,OAAO,kBAAkB,YAAY,kBAAkB,KACzD;AAIF,KAAI,MAAM,QAAQ,cAAc,EAAE;AAChC,MAAI,CAAC,MAAM,QAAQ,cAAc,CAC/B,QAAO;EAGT,MAAM,eAAe,cAClB,KAAK,MAAM,UAAU,qBAAqB,MAAM,cAAc,OAAO,CAAC,CACtE,QAAQ,SAAS,SAAS,OAAU;AAEvC,SAAO,aAAa,SAAS,IAAI,eAAe;;CAIlD,MAAMA,SAAc,EAAE;CACtB,IAAI,oBAAoB;AAExB,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,EAAE;EACxD,MAAM,cAAc,gBAAgB;EACpC,MAAM,eAAe,qBAAqB,OAAO,YAAY;AAE7D,MAAI,iBAAiB,QAAW;AAC9B,UAAO,OAAO;AACd,uBAAoB;;;AAIxB,QAAO,oBAAoB,SAAS;;;;;;;;;;AAWtC,MAAa,oCACX,kBACA,qBACe;AACf,KAAI,CAAC,oBAAoB,CAAC,iBAAiB,QAEzC,QAAO;CAGT,MAAM,iBAAiB,qBACrB,iBAAiB,SACjB,iBAAiB,QAClB;AAED,QAAO;EACL,GAAG;EACH,SAAS,kBAAkB,EAAE;EAC9B"}
@@ -1,3 +1,5 @@
1
+ import { deepMergeContent } from "./deepMergeContent.mjs";
2
+ import { getFilterMissingContentPerLocale } from "./getFilterMissingContentPerLocale.mjs";
1
3
  import { getIntlayerAPIProxy } from "@intlayer/api";
2
4
  import { chunkJSON, formatLocale, reconstructFromSingleChunk, reduceObjectFormat, verifyIdenticObjectFormat } from "@intlayer/chokidar";
3
5
  import { ANSIColors, colon, colorize, colorizeNumber, colorizePath, getAppLogger, retryManager } from "@intlayer/config";
@@ -26,7 +28,8 @@ const translateDictionary = async (task, configuration, options) => {
26
28
  options?.onSuccess?.();
27
29
  };
28
30
  return await retryManager(async () => {
29
- const baseUnmergedDictionary = getUnmergedDictionaries(configuration)[task.dictionaryKey].find((dict) => dict.localId === task.dictionaryLocalId);
31
+ const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);
32
+ const baseUnmergedDictionary = unmergedDictionariesRecord[task.dictionaryKey].find((dict) => dict.localId === task.dictionaryLocalId);
30
33
  if (!baseUnmergedDictionary) {
31
34
  appLogger(`${task.dictionaryPreset}Dictionary not found in unmergedDictionariesRecord. Skipping.`, { level: "warn" });
32
35
  return {
@@ -61,15 +64,22 @@ const translateDictionary = async (task, configuration, options) => {
61
64
  *
62
65
  */
63
66
  let dictionaryToProcess = structuredClone(baseUnmergedDictionary);
64
- if (mode === "complete" && typeof baseUnmergedDictionary.locale !== "string") dictionaryToProcess = getFilterMissingTranslationsDictionary(dictionaryToProcess, targetLocale);
65
- dictionaryToProcess = getPerLocaleDictionary(dictionaryToProcess, task.sourceLocale);
66
67
  let targetLocaleDictionary;
67
- if (typeof baseUnmergedDictionary.locale === "string") targetLocaleDictionary = {
68
- key: baseUnmergedDictionary.key,
69
- content: {},
70
- filePath: baseUnmergedDictionary.filePath
71
- };
72
- else targetLocaleDictionary = getPerLocaleDictionary(baseUnmergedDictionary, targetLocale);
68
+ if (typeof baseUnmergedDictionary.locale === "string") {
69
+ const targetLocaleFilePath = baseUnmergedDictionary.filePath?.replace(new RegExp(`/${task.sourceLocale}/`, "g"), `/${targetLocale}/`);
70
+ const targetUnmergedDictionary = targetLocaleFilePath ? unmergedDictionariesRecord[task.dictionaryKey]?.find((dict) => dict.filePath === targetLocaleFilePath && dict.locale === targetLocale) : void 0;
71
+ targetLocaleDictionary = targetUnmergedDictionary ?? {
72
+ key: baseUnmergedDictionary.key,
73
+ content: {},
74
+ filePath: targetLocaleFilePath,
75
+ locale: targetLocale
76
+ };
77
+ if (mode === "complete") dictionaryToProcess = getFilterMissingContentPerLocale(dictionaryToProcess, targetUnmergedDictionary);
78
+ } else {
79
+ if (mode === "complete") dictionaryToProcess = getFilterMissingTranslationsDictionary(dictionaryToProcess, targetLocale);
80
+ dictionaryToProcess = getPerLocaleDictionary(dictionaryToProcess, task.sourceLocale);
81
+ targetLocaleDictionary = getPerLocaleDictionary(baseUnmergedDictionary, targetLocale);
82
+ }
73
83
  const localePreset = colon([
74
84
  colorize("[", ANSIColors.GREY_DARK),
75
85
  formatLocale(targetLocale),
@@ -97,6 +107,10 @@ const translateDictionary = async (task, configuration, options) => {
97
107
  const executeTranslation = async () => {
98
108
  return await retryManager(async () => {
99
109
  let translationResult;
110
+ console.dir({
111
+ chunkContent,
112
+ presetOutputContent
113
+ }, { depth: null });
100
114
  if (aiClient && aiConfig) translationResult = await aiClient.translateJSON({
101
115
  entryFileContent: chunkContent,
102
116
  presetOutputContent,
@@ -145,10 +159,13 @@ const translateDictionary = async (task, configuration, options) => {
145
159
  (await Promise.all(chunkPromises)).sort((chunkA, chunkB) => chunkA.chunk.index - chunkB.chunk.index).forEach(({ result }) => {
146
160
  chunkResult.push(result);
147
161
  });
148
- return [targetLocale, mergeDictionaries(chunkResult.map((chunk) => ({
162
+ const merged = mergeDictionaries(chunkResult.map((chunk) => ({
149
163
  ...dictionaryToProcess,
150
164
  content: chunk
151
- }))).content];
165
+ })));
166
+ let finalContent = merged.content;
167
+ if (typeof baseUnmergedDictionary.locale === "string") finalContent = deepMergeContent(targetLocaleDictionary.content ?? {}, merged.content);
168
+ return [targetLocale, finalContent];
152
169
  }));
153
170
  const translatedContent = Object.fromEntries(translatedContentResults);
154
171
  let dictionaryOutput = {
@@ -1 +1 @@
1
- {"version":3,"file":"translateDictionary.mjs","names":["baseUnmergedDictionary: Dictionary | undefined","metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined","targetLocaleDictionary: Dictionary","chunkedJsonContent: JsonChunk[]","chunkResult: JsonChunk[]","translationResult: any","chunkPreset","translatedContent: Partial<Record<Locale, Dictionary['content']>>","dictionaryOutput: Dictionary"],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport { type AIOptions, getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n chunkJSON,\n formatLocale,\n type JsonChunk,\n reconstructFromSingleChunk,\n reduceObjectFormat,\n verifyIdenticObjectFormat,\n} from '@intlayer/chokidar';\nimport {\n ANSIColors,\n colon,\n colorize,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n retryManager,\n} from '@intlayer/config';\nimport {\n getFilterMissingTranslationsDictionary,\n getMultilingualDictionary,\n getPerLocaleDictionary,\n insertContentInDictionary,\n mergeDictionaries,\n} from '@intlayer/core';\nimport type { Dictionary, IntlayerConfig, Locale } from '@intlayer/types';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport type { AIClient } from '../utils/setupAI';\nimport type { TranslationTask } from './listTranslationsTasks';\n\ntype TranslateDictionaryResult = TranslationTask & {\n dictionaryOutput: Dictionary | null;\n};\n\ntype TranslateDictionaryOptions = {\n mode: 'complete' | 'review';\n aiOptions?: AIOptions;\n fillMetadata?: boolean;\n onHandle?: ReturnType<typeof import('@intlayer/chokidar').getGlobalLimiter>;\n onSuccess?: () => void;\n onError?: (error: unknown) => void;\n getAbortError?: () => Error | null;\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n};\n\nconst hasMissingMetadata = (dictionary: Dictionary) =>\n !dictionary.description || !dictionary.title || !dictionary.tags;\n\nconst CHUNK_SIZE = 7000; // GPT-5 Mini safe input size\nconst GROUP_MAX_RETRY = 2;\nconst MAX_RETRY = 3;\nconst RETRY_DELAY = 1000 * 10; // 10 seconds\n\nconst MAX_FOLLOWING_ERRORS = 10; // 10 errors in a row, hard exit the process\nlet followingErrors = 0;\n\nexport const translateDictionary = async (\n task: TranslationTask,\n configuration: IntlayerConfig,\n options?: TranslateDictionaryOptions\n): Promise<TranslateDictionaryResult> => {\n const appLogger = getAppLogger(configuration);\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n const { mode, aiOptions, fillMetadata, aiClient, aiConfig } = {\n mode: 'complete',\n fillMetadata: true,\n ...options,\n } as const;\n\n const notifySuccess = () => {\n followingErrors = 0;\n options?.onSuccess?.();\n };\n\n const result = await retryManager(\n async () => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n\n const baseUnmergedDictionary: Dictionary | undefined =\n unmergedDictionariesRecord[task.dictionaryKey].find(\n (dict) => dict.localId === task.dictionaryLocalId\n );\n\n if (!baseUnmergedDictionary) {\n appLogger(\n `${task.dictionaryPreset}Dictionary not found in unmergedDictionariesRecord. Skipping.`,\n {\n level: 'warn',\n }\n );\n return { ...task, dictionaryOutput: null };\n }\n\n let metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined;\n\n if (\n fillMetadata &&\n (hasMissingMetadata(baseUnmergedDictionary) || mode === 'review')\n ) {\n const defaultLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n configuration.internationalization.defaultLocale\n );\n\n appLogger(\n `${task.dictionaryPreset} Filling missing metadata for ${colorizePath(basename(baseUnmergedDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const runAudit = async () => {\n if (aiClient && aiConfig) {\n const result = await aiClient.auditDictionaryMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiConfig,\n });\n\n return {\n data: result,\n };\n }\n\n return await intlayerAPI.ai.auditContentDeclarationMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiOptions,\n });\n };\n\n const metadataResult = options?.onHandle\n ? await options.onHandle(runAudit)\n : await runAudit();\n\n metadata = metadataResult.data?.fileContent;\n }\n\n const translatedContentResults = await Promise.all(\n task.targetLocales.map(async (targetLocale) => {\n /**\n * In complete mode, for large dictionaries, we want to filter all content that is already translated\n *\n * targetLocale: fr\n *\n * { test1: t({ ar: 'Hello', en: 'Hello', fr: 'Bonjour' } }) -> {}\n * { test2: t({ ar: 'Hello', en: 'Hello' }) } -> { test2: t({ ar: 'Hello', en: 'Hello' }) }\n *\n */\n // Reset to base dictionary for each locale to ensure we filter from the original\n let dictionaryToProcess = structuredClone(baseUnmergedDictionary);\n\n if (\n mode === 'complete' &&\n typeof baseUnmergedDictionary.locale !== 'string'\n ) {\n // Remove all nodes that don't have any content to translate\n dictionaryToProcess = getFilterMissingTranslationsDictionary(\n dictionaryToProcess,\n targetLocale\n );\n }\n\n dictionaryToProcess = getPerLocaleDictionary(\n dictionaryToProcess,\n task.sourceLocale\n );\n\n let targetLocaleDictionary: Dictionary;\n\n if (typeof baseUnmergedDictionary.locale === 'string') {\n targetLocaleDictionary = {\n key: baseUnmergedDictionary.key,\n content: {},\n filePath: baseUnmergedDictionary.filePath,\n };\n } else {\n targetLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n targetLocale\n );\n }\n\n const localePreset = colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n formatLocale(targetLocale),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 18 }\n );\n\n const createChunkPreset = (\n chunkIndex: number,\n totalChunks: number\n ) => {\n if (totalChunks <= 1) return '';\n return colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n colorizeNumber(chunkIndex + 1),\n colorize(`/${totalChunks}`, ANSIColors.GREY_DARK),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 5 }\n );\n };\n\n appLogger(\n `${task.dictionaryPreset}${localePreset} Preparing ${colorizePath(basename(targetLocaleDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const chunkedJsonContent: JsonChunk[] = chunkJSON(\n dictionaryToProcess.content,\n CHUNK_SIZE\n );\n\n const nbOfChunks = chunkedJsonContent.length;\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset} Split into ${colorizeNumber(nbOfChunks)} chunks for translation`,\n {\n level: 'info',\n }\n );\n }\n\n const chunkResult: JsonChunk[] = [];\n\n // Process chunks in parallel (globally throttled) to allow concurrent translation\n const chunkPromises = chunkedJsonContent.map((chunk) => {\n const chunkPreset = createChunkPreset(chunk.index, chunk.total);\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} Translating chunk`,\n {\n level: 'info',\n }\n );\n }\n\n // Reconstruct partial JSON content from this chunk's patches\n const chunkContent = reconstructFromSingleChunk(chunk);\n const presetOutputContent = reduceObjectFormat(\n targetLocaleDictionary.content,\n chunkContent\n ) as unknown as JSON;\n\n const executeTranslation = async () => {\n return await retryManager(\n async () => {\n let translationResult: any;\n\n if (aiClient && aiConfig) {\n translationResult = await aiClient.translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiConfig,\n });\n } else {\n translationResult = await intlayerAPI.ai\n .translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiOptions,\n })\n .then((result) => result.data);\n }\n\n if (!translationResult?.fileContent) {\n throw new Error('No content result');\n }\n\n const { isIdentic } = verifyIdenticObjectFormat(\n translationResult.fileContent,\n chunkContent\n );\n if (!isIdentic) {\n console.log(translationResult.fileContent);\n throw new Error(\n 'Translation result does not match expected format'\n );\n }\n\n notifySuccess();\n return translationResult.fileContent;\n },\n {\n maxRetry: MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) => {\n const chunkPreset = createChunkPreset(\n chunk.index,\n chunk.total\n );\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} ${colorize('Error filling:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n );\n\n followingErrors += 1;\n\n if (followingErrors >= MAX_FOLLOWING_ERRORS) {\n appLogger(`There is something wrong.`, {\n level: 'error',\n });\n process.exit(1); // 1 for error\n }\n },\n }\n )();\n };\n\n const wrapped = options?.onHandle\n ? options.onHandle(executeTranslation) // queued in global limiter\n : executeTranslation(); // no global limiter\n\n return wrapped.then((result) => ({ chunk, result }));\n });\n\n // Wait for all chunks for this locale in parallel (still capped by global limiter)\n const chunkResults = await Promise.all(chunkPromises);\n\n // Maintain order\n chunkResults\n .sort((chunkA, chunkB) => chunkA.chunk.index - chunkB.chunk.index)\n .forEach(({ result }) => {\n chunkResult.push(result);\n });\n\n // Merge partial JSON objects produced from each chunk into a single object\n const merged = mergeDictionaries(\n chunkResult.map((chunk) => ({\n ...dictionaryToProcess,\n content: chunk,\n }))\n );\n\n return [targetLocale, merged.content] as const;\n })\n );\n\n const translatedContent: Partial<Record<Locale, Dictionary['content']>> =\n Object.fromEntries(translatedContentResults);\n\n const baseDictionary = baseUnmergedDictionary.locale\n ? {\n ...baseUnmergedDictionary,\n key: baseUnmergedDictionary.key!,\n content: {},\n }\n : baseUnmergedDictionary;\n\n let dictionaryOutput: Dictionary = {\n ...getMultilingualDictionary(baseDictionary),\n locale: undefined, // Ensure the dictionary is multilingual\n ...metadata,\n };\n\n for (const targetLocale of task.targetLocales) {\n if (translatedContent[targetLocale]) {\n dictionaryOutput = insertContentInDictionary(\n dictionaryOutput,\n translatedContent[targetLocale],\n targetLocale\n );\n }\n }\n\n appLogger(\n `${task.dictionaryPreset} ${colorize('Translation completed successfully', ANSIColors.GREEN)} for ${colorizePath(basename(dictionaryOutput.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n if (\n baseUnmergedDictionary.locale &&\n (baseUnmergedDictionary.fill === true ||\n baseUnmergedDictionary.fill === undefined) &&\n baseUnmergedDictionary.location === 'local'\n ) {\n const dictionaryFilePath = baseUnmergedDictionary\n .filePath!.split('.')\n .slice(0, -1);\n\n const contentIndex = dictionaryFilePath[dictionaryFilePath.length - 1];\n\n return JSON.parse(\n JSON.stringify({\n ...task,\n dictionaryOutput: {\n ...dictionaryOutput,\n fill: undefined,\n filled: true,\n },\n }).replaceAll(\n new RegExp(`\\\\.${contentIndex}\\\\.[a-zA-Z0-9]+`, 'g'),\n `.filled.${contentIndex}.json`\n )\n );\n }\n\n return {\n ...task,\n dictionaryOutput,\n };\n },\n {\n maxRetry: GROUP_MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Error fill command:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n ),\n onMaxTryReached: ({ error }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Maximum number of retries reached:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n ),\n }\n )();\n\n return result as TranslateDictionaryResult;\n};\n"],"mappings":";;;;;;;;AAgDA,MAAM,sBAAsB,eAC1B,CAAC,WAAW,eAAe,CAAC,WAAW,SAAS,CAAC,WAAW;AAE9D,MAAM,aAAa;AACnB,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,cAAc,MAAO;AAE3B,MAAM,uBAAuB;AAC7B,IAAI,kBAAkB;AAEtB,MAAa,sBAAsB,OACjC,MACA,eACA,YACuC;CACvC,MAAM,YAAY,aAAa,cAAc;CAC7C,MAAM,cAAc,oBAAoB,QAAW,cAAc;CAEjE,MAAM,EAAE,MAAM,WAAW,cAAc,UAAU,aAAa;EAC5D,MAAM;EACN,cAAc;EACd,GAAG;EACJ;CAED,MAAM,sBAAsB;AAC1B,oBAAkB;AAClB,WAAS,aAAa;;AA0XxB,QAvXe,MAAM,aACnB,YAAY;EAGV,MAAMA,yBAF6B,wBAAwB,cAAc,CAG5C,KAAK,eAAe,MAC5C,SAAS,KAAK,YAAY,KAAK,kBACjC;AAEH,MAAI,CAAC,wBAAwB;AAC3B,aACE,GAAG,KAAK,iBAAiB,gEACzB,EACE,OAAO,QACR,CACF;AACD,UAAO;IAAE,GAAG;IAAM,kBAAkB;IAAM;;EAG5C,IAAIC;AAIJ,MACE,iBACC,mBAAmB,uBAAuB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AsC,WAAW,MAAM,CAAC,OAAO,aAAa,SAAS,iBAAiB,SAAU,CAAC,IACtJ,EACE,OAAO,QACR,CACF;AAED,MACE,uBAAuB,WACtB,uBAAuB,SAAS,QAC/B,uBAAuB,SAAS,WAClC,uBAAuB,aAAa,SACpC;GACA,MAAM,qBAAqB,uBACxB,SAAU,MAAM,IAAI,CACpB,MAAM,GAAG,GAAG;GAEf,MAAM,eAAe,mBAAmB,mBAAmB,SAAS;AAEpE,UAAO,KAAK,MACV,KAAK,UAAU;IACb,GAAG;IACH,kBAAkB;KAChB,GAAG;KACH,MAAM;KACN,QAAQ;KACT;IACF,CAAC,CAAC,WACD,IAAI,OAAO,MAAM,aAAa,kBAAkB,IAAI,EACpD,WAAW,aAAa,OACzB,CACF;;AAGH,SAAO;GACL,GAAG;GACH;GACD;IAEH;EACE,UAAU;EACV,OAAO;EACP,UAAU,EAAE,OAAO,SAAS,eAC1B,UACE,GAAG,KAAK,iBAAiB,GAAG,SAAS,uBAAuB,WAAW,IAAI,CAAC,GAAG,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,MAAM,EAAE,WAAW,UAAU,CAAC,aAAa,eAAe,UAAU,EAAE,CAAC,MAAM,eAAe,SAAS,IAChP,EACE,OAAO,SACR,CACF;EACH,kBAAkB,EAAE,YAClB,UACE,GAAG,KAAK,iBAAiB,GAAG,SAAS,sCAAsC,WAAW,IAAI,CAAC,GAAG,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,MAAM,EAAE,WAAW,UAAU,IACvL,EACE,OAAO,SACR,CACF;EACJ,CACF,EAAE"}
1
+ {"version":3,"file":"translateDictionary.mjs","names":["baseUnmergedDictionary: Dictionary | undefined","metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined","targetLocaleDictionary: Dictionary","chunkedJsonContent: JsonChunk[]","chunkResult: JsonChunk[]","translationResult: any","chunkPreset","translatedContent: Partial<Record<Locale, Dictionary['content']>>","dictionaryOutput: Dictionary"],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport { type AIOptions, getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n chunkJSON,\n formatLocale,\n type JsonChunk,\n reconstructFromSingleChunk,\n reduceObjectFormat,\n verifyIdenticObjectFormat,\n} from '@intlayer/chokidar';\nimport {\n ANSIColors,\n colon,\n colorize,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n retryManager,\n} from '@intlayer/config';\nimport {\n getFilterMissingTranslationsDictionary,\n getMultilingualDictionary,\n getPerLocaleDictionary,\n insertContentInDictionary,\n mergeDictionaries,\n} from '@intlayer/core';\nimport type { Dictionary, IntlayerConfig, Locale } from '@intlayer/types';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport type { AIClient } from '../utils/setupAI';\nimport { deepMergeContent } from './deepMergeContent';\nimport { getFilterMissingContentPerLocale } from './getFilterMissingContentPerLocale';\nimport type { TranslationTask } from './listTranslationsTasks';\n\ntype TranslateDictionaryResult = TranslationTask & {\n dictionaryOutput: Dictionary | null;\n};\n\ntype TranslateDictionaryOptions = {\n mode: 'complete' | 'review';\n aiOptions?: AIOptions;\n fillMetadata?: boolean;\n onHandle?: ReturnType<typeof import('@intlayer/chokidar').getGlobalLimiter>;\n onSuccess?: () => void;\n onError?: (error: unknown) => void;\n getAbortError?: () => Error | null;\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n};\n\nconst hasMissingMetadata = (dictionary: Dictionary) =>\n !dictionary.description || !dictionary.title || !dictionary.tags;\n\nconst CHUNK_SIZE = 7000; // GPT-5 Mini safe input size\nconst GROUP_MAX_RETRY = 2;\nconst MAX_RETRY = 3;\nconst RETRY_DELAY = 1000 * 10; // 10 seconds\n\nconst MAX_FOLLOWING_ERRORS = 10; // 10 errors in a row, hard exit the process\nlet followingErrors = 0;\n\nexport const translateDictionary = async (\n task: TranslationTask,\n configuration: IntlayerConfig,\n options?: TranslateDictionaryOptions\n): Promise<TranslateDictionaryResult> => {\n const appLogger = getAppLogger(configuration);\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n const { mode, aiOptions, fillMetadata, aiClient, aiConfig } = {\n mode: 'complete',\n fillMetadata: true,\n ...options,\n } as const;\n\n const notifySuccess = () => {\n followingErrors = 0;\n options?.onSuccess?.();\n };\n\n const result = await retryManager(\n async () => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n\n const baseUnmergedDictionary: Dictionary | undefined =\n unmergedDictionariesRecord[task.dictionaryKey].find(\n (dict) => dict.localId === task.dictionaryLocalId\n );\n\n if (!baseUnmergedDictionary) {\n appLogger(\n `${task.dictionaryPreset}Dictionary not found in unmergedDictionariesRecord. Skipping.`,\n {\n level: 'warn',\n }\n );\n return { ...task, dictionaryOutput: null };\n }\n\n let metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined;\n\n if (\n fillMetadata &&\n (hasMissingMetadata(baseUnmergedDictionary) || mode === 'review')\n ) {\n const defaultLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n configuration.internationalization.defaultLocale\n );\n\n appLogger(\n `${task.dictionaryPreset} Filling missing metadata for ${colorizePath(basename(baseUnmergedDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const runAudit = async () => {\n if (aiClient && aiConfig) {\n const result = await aiClient.auditDictionaryMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiConfig,\n });\n\n return {\n data: result,\n };\n }\n\n return await intlayerAPI.ai.auditContentDeclarationMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiOptions,\n });\n };\n\n const metadataResult = options?.onHandle\n ? await options.onHandle(runAudit)\n : await runAudit();\n\n metadata = metadataResult.data?.fileContent;\n }\n\n const translatedContentResults = await Promise.all(\n task.targetLocales.map(async (targetLocale) => {\n /**\n * In complete mode, for large dictionaries, we want to filter all content that is already translated\n *\n * targetLocale: fr\n *\n * { test1: t({ ar: 'Hello', en: 'Hello', fr: 'Bonjour' } }) -> {}\n * { test2: t({ ar: 'Hello', en: 'Hello' }) } -> { test2: t({ ar: 'Hello', en: 'Hello' }) }\n *\n */\n // Reset to base dictionary for each locale to ensure we filter from the original\n let dictionaryToProcess = structuredClone(baseUnmergedDictionary);\n\n let targetLocaleDictionary: Dictionary;\n\n if (typeof baseUnmergedDictionary.locale === 'string') {\n // For per-locale files, the content is already in simple JSON format (not translation nodes)\n // The base dictionary is already the source locale content\n\n // Load the existing target locale dictionary\n const targetLocaleFilePath =\n baseUnmergedDictionary.filePath?.replace(\n new RegExp(`/${task.sourceLocale}/`, 'g'),\n `/${targetLocale}/`\n );\n\n // Find the target locale dictionary in unmerged dictionaries\n const targetUnmergedDictionary = targetLocaleFilePath\n ? unmergedDictionariesRecord[task.dictionaryKey]?.find(\n (dict) =>\n dict.filePath === targetLocaleFilePath &&\n dict.locale === targetLocale\n )\n : undefined;\n\n targetLocaleDictionary = targetUnmergedDictionary ?? {\n key: baseUnmergedDictionary.key,\n content: {},\n filePath: targetLocaleFilePath,\n locale: targetLocale,\n };\n\n // In complete mode, filter out already translated content\n if (mode === 'complete') {\n dictionaryToProcess = getFilterMissingContentPerLocale(\n dictionaryToProcess,\n targetUnmergedDictionary\n );\n }\n } else {\n // For multilingual dictionaries\n if (mode === 'complete') {\n // Remove all nodes that don't have any content to translate\n dictionaryToProcess = getFilterMissingTranslationsDictionary(\n dictionaryToProcess,\n targetLocale\n );\n }\n\n dictionaryToProcess = getPerLocaleDictionary(\n dictionaryToProcess,\n task.sourceLocale\n );\n\n targetLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n targetLocale\n );\n }\n\n const localePreset = colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n formatLocale(targetLocale),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 18 }\n );\n\n const createChunkPreset = (\n chunkIndex: number,\n totalChunks: number\n ) => {\n if (totalChunks <= 1) return '';\n return colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n colorizeNumber(chunkIndex + 1),\n colorize(`/${totalChunks}`, ANSIColors.GREY_DARK),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 5 }\n );\n };\n\n appLogger(\n `${task.dictionaryPreset}${localePreset} Preparing ${colorizePath(basename(targetLocaleDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const chunkedJsonContent: JsonChunk[] = chunkJSON(\n dictionaryToProcess.content,\n CHUNK_SIZE\n );\n\n const nbOfChunks = chunkedJsonContent.length;\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset} Split into ${colorizeNumber(nbOfChunks)} chunks for translation`,\n {\n level: 'info',\n }\n );\n }\n\n const chunkResult: JsonChunk[] = [];\n\n // Process chunks in parallel (globally throttled) to allow concurrent translation\n const chunkPromises = chunkedJsonContent.map((chunk) => {\n const chunkPreset = createChunkPreset(chunk.index, chunk.total);\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} Translating chunk`,\n {\n level: 'info',\n }\n );\n }\n\n // Reconstruct partial JSON content from this chunk's patches\n const chunkContent = reconstructFromSingleChunk(chunk);\n const presetOutputContent = reduceObjectFormat(\n targetLocaleDictionary.content,\n chunkContent\n ) as unknown as JSON;\n\n const executeTranslation = async () => {\n return await retryManager(\n async () => {\n let translationResult: any;\n\n console.dir(\n { chunkContent, presetOutputContent },\n { depth: null }\n );\n\n if (aiClient && aiConfig) {\n translationResult = await aiClient.translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiConfig,\n });\n } else {\n translationResult = await intlayerAPI.ai\n .translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiOptions,\n })\n .then((result) => result.data);\n }\n\n if (!translationResult?.fileContent) {\n throw new Error('No content result');\n }\n\n const { isIdentic } = verifyIdenticObjectFormat(\n translationResult.fileContent,\n chunkContent\n );\n if (!isIdentic) {\n console.log(translationResult.fileContent);\n throw new Error(\n 'Translation result does not match expected format'\n );\n }\n\n notifySuccess();\n return translationResult.fileContent;\n },\n {\n maxRetry: MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) => {\n const chunkPreset = createChunkPreset(\n chunk.index,\n chunk.total\n );\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} ${colorize('Error filling:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n );\n\n followingErrors += 1;\n\n if (followingErrors >= MAX_FOLLOWING_ERRORS) {\n appLogger(`There is something wrong.`, {\n level: 'error',\n });\n process.exit(1); // 1 for error\n }\n },\n }\n )();\n };\n\n const wrapped = options?.onHandle\n ? options.onHandle(executeTranslation) // queued in global limiter\n : executeTranslation(); // no global limiter\n\n return wrapped.then((result) => ({ chunk, result }));\n });\n\n // Wait for all chunks for this locale in parallel (still capped by global limiter)\n const chunkResults = await Promise.all(chunkPromises);\n\n // Maintain order\n chunkResults\n .sort((chunkA, chunkB) => chunkA.chunk.index - chunkB.chunk.index)\n .forEach(({ result }) => {\n chunkResult.push(result);\n });\n\n // Merge partial JSON objects produced from each chunk into a single object\n const merged = mergeDictionaries(\n chunkResult.map((chunk) => ({\n ...dictionaryToProcess,\n content: chunk,\n }))\n );\n\n // For per-locale files, merge the newly translated content with existing target content\n let finalContent = merged.content;\n if (typeof baseUnmergedDictionary.locale === 'string') {\n // Deep merge: existing content + newly translated content\n finalContent = deepMergeContent(\n targetLocaleDictionary.content ?? {},\n merged.content\n );\n }\n\n return [targetLocale, finalContent] as const;\n })\n );\n\n const translatedContent: Partial<Record<Locale, Dictionary['content']>> =\n Object.fromEntries(translatedContentResults);\n\n const baseDictionary = baseUnmergedDictionary.locale\n ? {\n ...baseUnmergedDictionary,\n key: baseUnmergedDictionary.key!,\n content: {},\n }\n : baseUnmergedDictionary;\n\n let dictionaryOutput: Dictionary = {\n ...getMultilingualDictionary(baseDictionary),\n locale: undefined, // Ensure the dictionary is multilingual\n ...metadata,\n };\n\n for (const targetLocale of task.targetLocales) {\n if (translatedContent[targetLocale]) {\n dictionaryOutput = insertContentInDictionary(\n dictionaryOutput,\n translatedContent[targetLocale],\n targetLocale\n );\n }\n }\n\n appLogger(\n `${task.dictionaryPreset} ${colorize('Translation completed successfully', ANSIColors.GREEN)} for ${colorizePath(basename(dictionaryOutput.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n if (\n baseUnmergedDictionary.locale &&\n (baseUnmergedDictionary.fill === true ||\n baseUnmergedDictionary.fill === undefined) &&\n baseUnmergedDictionary.location === 'local'\n ) {\n const dictionaryFilePath = baseUnmergedDictionary\n .filePath!.split('.')\n .slice(0, -1);\n\n const contentIndex = dictionaryFilePath[dictionaryFilePath.length - 1];\n\n return JSON.parse(\n JSON.stringify({\n ...task,\n dictionaryOutput: {\n ...dictionaryOutput,\n fill: undefined,\n filled: true,\n },\n }).replaceAll(\n new RegExp(`\\\\.${contentIndex}\\\\.[a-zA-Z0-9]+`, 'g'),\n `.filled.${contentIndex}.json`\n )\n );\n }\n\n return {\n ...task,\n dictionaryOutput,\n };\n },\n {\n maxRetry: GROUP_MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Error fill command:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n ),\n onMaxTryReached: ({ error }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Maximum number of retries reached:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n ),\n }\n )();\n\n return result as TranslateDictionaryResult;\n};\n"],"mappings":";;;;;;;;;;AAkDA,MAAM,sBAAsB,eAC1B,CAAC,WAAW,eAAe,CAAC,WAAW,SAAS,CAAC,WAAW;AAE9D,MAAM,aAAa;AACnB,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,cAAc,MAAO;AAE3B,MAAM,uBAAuB;AAC7B,IAAI,kBAAkB;AAEtB,MAAa,sBAAsB,OACjC,MACA,eACA,YACuC;CACvC,MAAM,YAAY,aAAa,cAAc;CAC7C,MAAM,cAAc,oBAAoB,QAAW,cAAc;CAEjE,MAAM,EAAE,MAAM,WAAW,cAAc,UAAU,aAAa;EAC5D,MAAM;EACN,cAAc;EACd,GAAG;EACJ;CAED,MAAM,sBAAsB;AAC1B,oBAAkB;AAClB,WAAS,aAAa;;AAmaxB,QAhae,MAAM,aACnB,YAAY;EACV,MAAM,6BAA6B,wBAAwB,cAAc;EAEzE,MAAMA,yBACJ,2BAA2B,KAAK,eAAe,MAC5C,SAAS,KAAK,YAAY,KAAK,kBACjC;AAEH,MAAI,CAAC,wBAAwB;AAC3B,aACE,GAAG,KAAK,iBAAiB,gEACzB,EACE,OAAO,QACR,CACF;AACD,UAAO;IAAE,GAAG;IAAM,kBAAkB;IAAM;;EAG5C,IAAIC;AAIJ,MACE,iBACC,mBAAmB,uBAAuB,IAAI,SAAS,WACxD;GACA,MAAM,0BAA0B,uBAC9B,wBACA,cAAc,qBAAqB,cACpC;AAED,aACE,GAAG,KAAK,iBAAiB,gCAAgC,aAAa,SAAS,uBAAuB,SAAU,CAAC,IACjH,EACE,OAAO,QACR,CACF;GAED,MAAM,WAAW,YAAY;AAC3B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F;EACJ,CACF,EAAE"}
@@ -1,4 +1,5 @@
1
1
  import { formatFillData } from "./formatFillData.mjs";
2
+ import { getAvailableLocalesInDictionary } from "./getAvailableLocalesInDictionary.mjs";
2
3
  import { formatLocale, formatPath, writeContentDeclaration } from "@intlayer/chokidar";
3
4
  import { colorizeKey, getAppLogger } from "@intlayer/config";
4
5
  import { relative } from "node:path";
@@ -18,7 +19,14 @@ const writeFill = async (contentDeclarationFile, outputLocales, parentLocales, c
18
19
  appLogger(`Auto fill is disabled for '${colorizeKey(fullDictionary.key)}'`, { level: "info" });
19
20
  return;
20
21
  }
21
- const fillData = formatFillData(fillOptions, (outputLocales ?? configuration.internationalization.locales).filter((locale) => !parentLocales?.includes(locale)), filePath, fullDictionary.key, configuration);
22
+ const requestedLocales = (outputLocales ?? configuration.internationalization.locales).filter((locale) => !parentLocales?.includes(locale));
23
+ const availableLocales = getAvailableLocalesInDictionary(contentDeclarationFile);
24
+ const localeList = requestedLocales.filter((locale) => availableLocales.includes(locale));
25
+ if (localeList.length === 0) {
26
+ appLogger(`No translations available for dictionary '${colorizeKey(fullDictionary.key)}'`, { level: "info" });
27
+ return;
28
+ }
29
+ const fillData = formatFillData(fillOptions, localeList, filePath, fullDictionary.key, configuration);
22
30
  for await (const output of fillData) {
23
31
  if (!output.filePath) {
24
32
  appLogger(`No file path found for auto filled content declaration for '${colorizeKey(fullDictionary.key)}'`, { level: "error" });
@@ -1 +1 @@
1
- {"version":3,"file":"writeFill.mjs","names":["fillOptions: Fill | undefined","fillData: FillData[]"],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport {\n formatLocale,\n formatPath,\n writeContentDeclaration,\n} from '@intlayer/chokidar';\nimport { colorizeKey, getAppLogger } from '@intlayer/config';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary, Fill, IntlayerConfig, Locale } from '@intlayer/types';\nimport { type FillData, formatFillData } from './formatFillData';\n\nexport const writeFill = async (\n contentDeclarationFile: Dictionary,\n outputLocales: Locale[],\n parentLocales: Locale[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n const dictionaries = getDictionaries(configuration);\n\n const fullDictionary = dictionaries[contentDeclarationFile.key];\n\n const { filePath } = contentDeclarationFile;\n\n if (!filePath) {\n appLogger('No file path found for dictionary', {\n level: 'error',\n });\n return;\n }\n\n const fillOptions: Fill | undefined =\n contentDeclarationFile.fill ?? configuration.dictionary?.fill ?? true;\n\n if ((fillOptions as boolean) === false) {\n appLogger(\n `Auto fill is disabled for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const localeList: Locale[] = (\n outputLocales ?? configuration.internationalization.locales\n ).filter((locale) => !parentLocales?.includes(locale));\n\n const fillData: FillData[] = formatFillData(\n fillOptions as Fill,\n localeList,\n filePath,\n fullDictionary.key,\n configuration\n );\n\n for await (const output of fillData) {\n if (!output.filePath) {\n appLogger(\n `No file path found for auto filled content declaration for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n // biome-ignore lint/correctness/noUnusedVariables: Just filtering out the fill property\n const { fill, ...rest } = contentDeclarationFile;\n\n const relativeFilePath = relative(\n configuration.content.baseDir,\n output.filePath\n );\n\n // write file\n await writeContentDeclaration(\n {\n ...rest,\n filled: true,\n locale: output.isPerLocale ? output.localeList[0] : undefined,\n localId: `${contentDeclarationFile.key}::local::${relativeFilePath}`,\n filePath: relativeFilePath,\n },\n configuration,\n {\n localeList: output.localeList,\n }\n );\n\n if (output.isPerLocale) {\n const sourceLocale = output.localeList[0];\n\n appLogger(\n `Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(sourceLocale)}`,\n {\n level: 'info',\n }\n );\n } else {\n appLogger(\n `Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`,\n {\n level: 'info',\n }\n );\n }\n }\n};\n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","names":["fillOptions: Fill | undefined","requestedLocales: Locale[]","fillData: FillData[]"],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport {\n formatLocale,\n formatPath,\n writeContentDeclaration,\n} from '@intlayer/chokidar';\nimport { colorizeKey, getAppLogger } from '@intlayer/config';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary, Fill, IntlayerConfig, Locale } from '@intlayer/types';\nimport { type FillData, formatFillData } from './formatFillData';\nimport { getAvailableLocalesInDictionary } from './getAvailableLocalesInDictionary';\n\nexport const writeFill = async (\n contentDeclarationFile: Dictionary,\n outputLocales: Locale[],\n parentLocales: Locale[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n const dictionaries = getDictionaries(configuration);\n\n const fullDictionary = dictionaries[contentDeclarationFile.key];\n\n const { filePath } = contentDeclarationFile;\n\n if (!filePath) {\n appLogger('No file path found for dictionary', {\n level: 'error',\n });\n return;\n }\n\n const fillOptions: Fill | undefined =\n contentDeclarationFile.fill ?? configuration.dictionary?.fill ?? true;\n\n if ((fillOptions as boolean) === false) {\n appLogger(\n `Auto fill is disabled for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const requestedLocales: Locale[] = (\n outputLocales ?? configuration.internationalization.locales\n ).filter((locale) => !parentLocales?.includes(locale));\n\n // Get locales that actually have translations in the content\n const availableLocales = getAvailableLocalesInDictionary(\n contentDeclarationFile\n );\n\n // Only write files for locales that have actual translations\n const localeList = requestedLocales.filter((locale) =>\n availableLocales.includes(locale)\n );\n\n if (localeList.length === 0) {\n appLogger(\n `No translations available for dictionary '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const fillData: FillData[] = formatFillData(\n fillOptions as Fill,\n localeList,\n filePath,\n fullDictionary.key,\n configuration\n );\n\n for await (const output of fillData) {\n if (!output.filePath) {\n appLogger(\n `No file path found for auto filled content declaration for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n // biome-ignore lint/correctness/noUnusedVariables: Just filtering out the fill property\n const { fill, ...rest } = contentDeclarationFile;\n\n const relativeFilePath = relative(\n configuration.content.baseDir,\n output.filePath\n );\n\n // write file\n await writeContentDeclaration(\n {\n ...rest,\n filled: true,\n locale: output.isPerLocale ? output.localeList[0] : undefined,\n localId: `${contentDeclarationFile.key}::local::${relativeFilePath}`,\n filePath: relativeFilePath,\n },\n configuration,\n {\n localeList: output.localeList,\n }\n );\n\n if (output.isPerLocale) {\n const sourceLocale = output.localeList[0];\n\n appLogger(\n `Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(sourceLocale)}`,\n {\n level: 'info',\n }\n );\n } else {\n appLogger(\n `Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`,\n {\n level: 'info',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;AAYA,MAAa,YAAY,OACvB,wBACA,eACA,eACA,kBACG;CACH,MAAM,YAAY,aAAa,cAAc;CAG7C,MAAM,iBAFe,gBAAgB,cAAc,CAEf,uBAAuB;CAE3D,MAAM,EAAE,aAAa;AAErB,KAAI,CAAC,UAAU;AACb,YAAU,qCAAqC,EAC7C,OAAO,SACR,CAAC;AACF;;CAGF,MAAMA,cACJ,uBAAuB,QAAQ,cAAc,YAAY,QAAQ;AAEnE,KAAK,gBAA4B,OAAO;AACtC,YACE,8BAA8B,YAAY,eAAe,IAAI,CAAC,IAC9D,EACE,OAAO,QACR,CACF;AACD;;CAGF,MAAMC,oBACJ,iBAAiB,cAAc,qBAAqB,SACpD,QAAQ,WAAW,CAAC,eAAe,SAAS,OAAO,CAAC;CAGtD,MAAM,mBAAmB,gCACvB,uBACD;CAGD,MAAM,aAAa,iBAAiB,QAAQ,WAC1C,iBAAiB,SAAS,OAAO,CAClC;AAED,KAAI,WAAW,WAAW,GAAG;AAC3B,YACE,6CAA6C,YAAY,eAAe,IAAI,CAAC,IAC7E,EACE,OAAO,QACR,CACF;AACD;;CAGF,MAAMC,WAAuB,eAC3B,aACA,YACA,UACA,eAAe,KACf,cACD;AAED,YAAW,MAAM,UAAU,UAAU;AACnC,MAAI,CAAC,OAAO,UAAU;AACpB,aACE,+DAA+D,YAAY,eAAe,IAAI,CAAC,IAC/F,EACE,OAAO,SACR,CACF;AACD;;EAIF,MAAM,EAAE,MAAM,GAAG,SAAS;EAE1B,MAAM,mBAAmB,SACvB,cAAc,QAAQ,SACtB,OAAO,SACR;AAGD,QAAM,wBACJ;GACE,GAAG;GACH,QAAQ;GACR,QAAQ,OAAO,cAAc,OAAO,WAAW,KAAK;GACpD,SAAS,GAAG,uBAAuB,IAAI,WAAW;GAClD,UAAU;GACX,EACD,eACA,EACE,YAAY,OAAO,YACpB,CACF;AAED,MAAI,OAAO,aAAa;GACtB,MAAM,eAAe,OAAO,WAAW;AAEvC,aACE,mDAAmD,YAAY,eAAe,IAAI,CAAC,eAAe,WAAW,OAAO,SAAS,CAAC,cAAc,aAAa,aAAa,IACtK,EACE,OAAO,QACR,CACF;QAED,WACE,wCAAwC,YAAY,eAAe,IAAI,CAAC,eAAe,WAAW,OAAO,SAAS,IAClH,EACE,OAAO,QACR,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","names":[],"sources":["../../src/config.ts"],"sourcesContent":[],"mappings":";;;KAMK,aAAA;kBACa;AAHQ,CAAA;AAMb,cAAA,SAAuB,EAAA,CAAA,OAAa,CAAA,EAAb,aAAa,EAAA,GAAA,IAAA"}
1
+ {"version":3,"file":"config.d.ts","names":[],"sources":["../../src/config.ts"],"sourcesContent":[],"mappings":";;;KAMK,aAAA;kBACa;AAHQ,CAAA;AAMb,cAAA,SAAuB,EAAA,CAAA,OAAa,CAAb,EAAA,aAAa,EAAA,GAAA,IAAA"}
@@ -0,0 +1,13 @@
1
+ //#region src/fill/deepMergeContent.d.ts
2
+ /**
3
+ * Deep merge two plain objects (for per-locale content).
4
+ * The second object's values take precedence over the first.
5
+ *
6
+ * @param target - The base object
7
+ * @param source - The object to merge in (takes precedence)
8
+ * @returns The merged object
9
+ */
10
+ declare const deepMergeContent: <T = any>(target: T, source: T) => T;
11
+ //#endregion
12
+ export { deepMergeContent };
13
+ //# sourceMappingURL=deepMergeContent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deepMergeContent.d.ts","names":[],"sources":["../../../src/fill/deepMergeContent.ts"],"sourcesContent":[],"mappings":";;AAQA;;;;;;;cAAa,oCAAqC,WAAW,MAAI"}
@@ -1 +1 @@
1
- {"version":3,"file":"fill.d.ts","names":[],"sources":["../../../src/fill/fill.ts"],"sourcesContent":[],"mappings":";;;;;;KAmCY,WAAA;iBACK;EADL,aAAA,CAAW,EAEL,MAFK,GAEI,MAFJ,EAAA;EACN,IAAA,CAAA,EAAA,UAAA,GAAA,QAAA;EACC,UAAA,CAAA,EAEH,mBAFG;EAAS,SAAA,CAAA,EAGb,SAHa;EAEZ,OAAA,CAAA,EAAA,OAAA;EACD,wBAAA,CAAA,EAAA,MAAA;EAMV,iBAAA,CAAA,EAAA,MAAA;EAA0B,KAAA,CAAA,EAAA,OAAA;EAKjB,YAoIZ,CAAA,EAAA,OApIoC;IALjC;;;;cAKS,iBAAwB,gBAAc"}
1
+ {"version":3,"file":"fill.d.ts","names":[],"sources":["../../../src/fill/fill.ts"],"sourcesContent":[],"mappings":";;;;;;KAmCY,WAAA;iBACK;EADL,aAAA,CAAW,EAEL,MAFK,GAEI,MAFJ,EAAA;EACN,IAAA,CAAA,EAAA,UAAA,GAAA,QAAA;EACC,UAAA,CAAA,EAEH,mBAFG;EAAS,SAAA,CAAA,EAGb,SAHa;EAEZ,OAAA,CAAA,EAAA,OAAA;EACD,wBAAA,CAAA,EAAA,MAAA;EAMV,iBAAA,CAAA,EAAA,MAAA;EAA0B,KAAA,CAAA,EAAA,OAAA;EAKjB,YAqJZ,CAAA,EAAA,OArJoC;IALjC;;;;cAKS,iBAAwB,gBAAc"}
@@ -0,0 +1,12 @@
1
+ import { Dictionary, Locale } from "@intlayer/types";
2
+
3
+ //#region src/fill/getAvailableLocalesInDictionary.d.ts
4
+
5
+ /**
6
+ * Gets all locales that have actual translations in the dictionary content.
7
+ * Only returns locales that are present in at least one translation node.
8
+ */
9
+ declare const getAvailableLocalesInDictionary: (dictionary: Dictionary) => Locale[];
10
+ //#endregion
11
+ export { getAvailableLocalesInDictionary };
12
+ //# sourceMappingURL=getAvailableLocalesInDictionary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getAvailableLocalesInDictionary.d.ts","names":[],"sources":["../../../src/fill/getAvailableLocalesInDictionary.ts"],"sourcesContent":[],"mappings":";;;;;;AAoCA;;cAAa,8CACC,eACX"}
@@ -0,0 +1,16 @@
1
+ import { Dictionary } from "@intlayer/types";
2
+
3
+ //#region src/fill/getFilterMissingContentPerLocale.d.ts
4
+
5
+ /**
6
+ * Filters a dictionary to only include content that's missing in the target dictionary.
7
+ * Used for per-locale content declarations in 'complete' mode.
8
+ *
9
+ * @param sourceDictionary - The source dictionary with content to translate
10
+ * @param targetDictionary - The existing target dictionary
11
+ * @returns A dictionary with only the missing content
12
+ */
13
+ declare const getFilterMissingContentPerLocale: (sourceDictionary: Dictionary, targetDictionary: Dictionary | undefined) => Dictionary;
14
+ //#endregion
15
+ export { getFilterMissingContentPerLocale };
16
+ //# sourceMappingURL=getFilterMissingContentPerLocale.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getFilterMissingContentPerLocale.d.ts","names":[],"sources":["../../../src/fill/getFilterMissingContentPerLocale.ts"],"sourcesContent":[],"mappings":";;;;;;AA2DA;;;;;;cAAa,qDACO,8BACA,2BACjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"translateDictionary.d.ts","names":[],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":[],"mappings":";;;;;;;;KAgCK,yBAAA,GAA4B;o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CAEN,yBAFM,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"writeFill.d.ts","names":[],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":[],"mappings":";;;cAWa,oCACa,2BACT,yBACA,yBACA,mBAAc"}
1
+ {"version":3,"file":"writeFill.d.ts","names":[],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":[],"mappings":";;;cAYa,oCACa,2BACT,yBACA,yBACA,mBAAc"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/cli",
3
- "version": "7.3.5",
3
+ "version": "7.3.7",
4
4
  "private": false,
5
5
  "description": "Provides uniform command-line interface scripts for Intlayer, used in packages like intlayer-cli and intlayer.",
6
6
  "keywords": [
@@ -68,14 +68,14 @@
68
68
  },
69
69
  "dependencies": {
70
70
  "@clack/prompts": "^0.11.0",
71
- "@intlayer/api": "7.3.5",
72
- "@intlayer/chokidar": "7.3.5",
73
- "@intlayer/config": "7.3.5",
74
- "@intlayer/core": "7.3.5",
75
- "@intlayer/dictionaries-entry": "7.3.5",
76
- "@intlayer/remote-dictionaries-entry": "7.3.5",
77
- "@intlayer/types": "7.3.5",
78
- "@intlayer/unmerged-dictionaries-entry": "7.3.5",
71
+ "@intlayer/api": "7.3.7",
72
+ "@intlayer/chokidar": "7.3.7",
73
+ "@intlayer/config": "7.3.7",
74
+ "@intlayer/core": "7.3.7",
75
+ "@intlayer/dictionaries-entry": "7.3.7",
76
+ "@intlayer/remote-dictionaries-entry": "7.3.7",
77
+ "@intlayer/types": "7.3.7",
78
+ "@intlayer/unmerged-dictionaries-entry": "7.3.7",
79
79
  "commander": "14.0.1",
80
80
  "eventsource": "3.0.7",
81
81
  "fast-glob": "3.3.3"
@@ -91,7 +91,7 @@
91
91
  "vitest": "4.0.14"
92
92
  },
93
93
  "peerDependencies": {
94
- "@intlayer/ai": "7.3.5"
94
+ "@intlayer/ai": "7.3.7"
95
95
  },
96
96
  "peerDependenciesMeta": {
97
97
  "@intlayer/ai": {