@intlayer/cli 8.9.7 → 8.9.8
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.
- package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
- package/dist/cjs/auth/login.cjs +3 -1
- package/dist/cjs/auth/login.cjs.map +1 -1
- package/dist/cjs/auth/sessionToken.cjs.map +1 -1
- package/dist/cjs/build.cjs.map +1 -1
- package/dist/cjs/bundle.cjs.map +1 -1
- package/dist/cjs/ci.cjs.map +1 -1
- package/dist/cjs/cli.cjs.map +1 -1
- package/dist/cjs/config.cjs +1 -1
- package/dist/cjs/config.cjs.map +1 -1
- package/dist/cjs/editor.cjs.map +1 -1
- package/dist/cjs/extract.cjs.map +1 -1
- package/dist/cjs/fill/deepMergeContent.cjs.map +1 -1
- package/dist/cjs/fill/extractTranslatableContent.cjs.map +1 -1
- package/dist/cjs/fill/fill.cjs.map +1 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
- package/dist/cjs/fill/formatFillData.cjs.map +1 -1
- package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs.map +1 -1
- package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs.map +1 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
- package/dist/cjs/fill/translateDictionary.cjs +2 -2
- package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
- package/dist/cjs/fill/writeFill.cjs.map +1 -1
- package/dist/cjs/getTargetDictionary.cjs.map +1 -1
- package/dist/cjs/init.cjs.map +1 -1
- package/dist/cjs/initMCP.cjs.map +1 -1
- package/dist/cjs/initSkills.cjs.map +1 -1
- package/dist/cjs/listContentDeclaration.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/liveSync.cjs.map +1 -1
- package/dist/cjs/pull.cjs +3 -4
- package/dist/cjs/pull.cjs.map +1 -1
- package/dist/cjs/push/pullLog.cjs.map +1 -1
- package/dist/cjs/push/push.cjs +1 -2
- package/dist/cjs/push/push.cjs.map +1 -1
- package/dist/cjs/pushConfig.cjs +6 -4
- package/dist/cjs/pushConfig.cjs.map +1 -1
- package/dist/cjs/pushLog.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
- package/dist/cjs/searchDoc.cjs.map +1 -1
- package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
- package/dist/cjs/test/test.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
- package/dist/cjs/translateDoc/validation.cjs.map +1 -1
- package/dist/cjs/translation-alignment/alignBlocks.cjs.map +1 -1
- package/dist/cjs/translation-alignment/computeSimilarity.cjs.map +1 -1
- package/dist/cjs/translation-alignment/fingerprintBlock.cjs.map +1 -1
- package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs.map +1 -1
- package/dist/cjs/translation-alignment/normalizeBlock.cjs.map +1 -1
- package/dist/cjs/translation-alignment/pipeline.cjs.map +1 -1
- package/dist/cjs/translation-alignment/planActions.cjs.map +1 -1
- package/dist/cjs/translation-alignment/rebuildDocument.cjs.map +1 -1
- package/dist/cjs/translation-alignment/segmentDocument.cjs.map +1 -1
- package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
- package/dist/cjs/utils/checkAccess.cjs +6 -0
- package/dist/cjs/utils/checkAccess.cjs.map +1 -1
- package/dist/cjs/utils/checkConfigConsistency.cjs.map +1 -1
- package/dist/cjs/utils/checkFileModifiedRange.cjs.map +1 -1
- package/dist/cjs/utils/checkLastUpdateTime.cjs.map +1 -1
- package/dist/cjs/utils/chunkInference.cjs +2 -2
- package/dist/cjs/utils/chunkInference.cjs.map +1 -1
- package/dist/cjs/utils/fixChunkStartEndChars.cjs.map +1 -1
- package/dist/cjs/utils/formatTimeDiff.cjs.map +1 -1
- package/dist/cjs/utils/getIsFileUpdatedRecently.cjs.map +1 -1
- package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
- package/dist/cjs/utils/getParentPackageJSON.cjs.map +1 -1
- package/dist/cjs/utils/listSpecialChars.cjs.map +1 -1
- package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
- package/dist/cjs/utils/openBrowser.cjs.map +1 -1
- package/dist/cjs/utils/reorderParagraphs.cjs.map +1 -1
- package/dist/cjs/utils/setupAI.cjs.map +1 -1
- package/dist/cjs/watch.cjs.map +1 -1
- package/dist/esm/IntlayerEventListener.mjs.map +1 -1
- package/dist/esm/auth/login.mjs +3 -1
- package/dist/esm/auth/login.mjs.map +1 -1
- package/dist/esm/auth/sessionToken.mjs.map +1 -1
- package/dist/esm/build.mjs.map +1 -1
- package/dist/esm/bundle.mjs.map +1 -1
- package/dist/esm/ci.mjs.map +1 -1
- package/dist/esm/cli.mjs.map +1 -1
- package/dist/esm/config.mjs +2 -2
- package/dist/esm/config.mjs.map +1 -1
- package/dist/esm/editor.mjs.map +1 -1
- package/dist/esm/extract.mjs.map +1 -1
- package/dist/esm/fill/deepMergeContent.mjs.map +1 -1
- package/dist/esm/fill/extractTranslatableContent.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
- package/dist/esm/fill/formatFillData.mjs.map +1 -1
- package/dist/esm/fill/getAvailableLocalesInDictionary.mjs.map +1 -1
- package/dist/esm/fill/getFilterMissingContentPerLocale.mjs.map +1 -1
- package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -1
- package/dist/esm/fill/translateDictionary.mjs +2 -2
- package/dist/esm/fill/translateDictionary.mjs.map +1 -1
- package/dist/esm/fill/writeFill.mjs.map +1 -1
- package/dist/esm/getTargetDictionary.mjs.map +1 -1
- package/dist/esm/init.mjs.map +1 -1
- package/dist/esm/initMCP.mjs.map +1 -1
- package/dist/esm/initSkills.mjs.map +1 -1
- package/dist/esm/listContentDeclaration.mjs.map +1 -1
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/liveSync.mjs.map +1 -1
- package/dist/esm/pull.mjs +4 -5
- package/dist/esm/pull.mjs.map +1 -1
- package/dist/esm/push/pullLog.mjs.map +1 -1
- package/dist/esm/push/push.mjs +2 -3
- package/dist/esm/push/push.mjs.map +1 -1
- package/dist/esm/pushConfig.mjs +8 -6
- package/dist/esm/pushConfig.mjs.map +1 -1
- package/dist/esm/pushLog.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
- package/dist/esm/searchDoc.mjs.map +1 -1
- package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
- package/dist/esm/test/test.mjs.map +1 -1
- package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
- package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
- package/dist/esm/translateDoc/validation.mjs.map +1 -1
- package/dist/esm/translation-alignment/alignBlocks.mjs.map +1 -1
- package/dist/esm/translation-alignment/computeSimilarity.mjs.map +1 -1
- package/dist/esm/translation-alignment/fingerprintBlock.mjs.map +1 -1
- package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs.map +1 -1
- package/dist/esm/translation-alignment/normalizeBlock.mjs.map +1 -1
- package/dist/esm/translation-alignment/pipeline.mjs.map +1 -1
- package/dist/esm/translation-alignment/planActions.mjs.map +1 -1
- package/dist/esm/translation-alignment/rebuildDocument.mjs.map +1 -1
- package/dist/esm/translation-alignment/segmentDocument.mjs.map +1 -1
- package/dist/esm/utils/calculateChunks.mjs.map +1 -1
- package/dist/esm/utils/checkAccess.mjs +6 -1
- package/dist/esm/utils/checkAccess.mjs.map +1 -1
- package/dist/esm/utils/checkConfigConsistency.mjs.map +1 -1
- package/dist/esm/utils/checkFileModifiedRange.mjs.map +1 -1
- package/dist/esm/utils/checkLastUpdateTime.mjs.map +1 -1
- package/dist/esm/utils/chunkInference.mjs +2 -2
- package/dist/esm/utils/chunkInference.mjs.map +1 -1
- package/dist/esm/utils/fixChunkStartEndChars.mjs.map +1 -1
- package/dist/esm/utils/formatTimeDiff.mjs.map +1 -1
- package/dist/esm/utils/getIsFileUpdatedRecently.mjs.map +1 -1
- package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
- package/dist/esm/utils/getParentPackageJSON.mjs.map +1 -1
- package/dist/esm/utils/listSpecialChars.mjs.map +1 -1
- package/dist/esm/utils/mapChunksBetweenFiles.mjs.map +1 -1
- package/dist/esm/utils/openBrowser.mjs.map +1 -1
- package/dist/esm/utils/reorderParagraphs.mjs.map +1 -1
- package/dist/esm/utils/setupAI.mjs.map +1 -1
- package/dist/esm/watch.mjs.map +1 -1
- package/dist/types/IntlayerEventListener.d.ts.map +1 -1
- package/dist/types/auth/login.d.ts.map +1 -1
- package/dist/types/auth/sessionToken.d.ts +1 -1
- package/dist/types/auth/sessionToken.d.ts.map +1 -1
- package/dist/types/build.d.ts.map +1 -1
- package/dist/types/bundle.d.ts.map +1 -1
- package/dist/types/cli.d.ts.map +1 -1
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/editor.d.ts.map +1 -1
- package/dist/types/extract.d.ts.map +1 -1
- package/dist/types/fill/extractTranslatableContent.d.ts.map +1 -1
- package/dist/types/fill/fill.d.ts.map +1 -1
- package/dist/types/fill/formatFillData.d.ts.map +1 -1
- package/dist/types/fill/getAvailableLocalesInDictionary.d.ts.map +1 -1
- package/dist/types/fill/translateDictionary.d.ts +1 -2
- package/dist/types/fill/translateDictionary.d.ts.map +1 -1
- package/dist/types/index.d.ts +4 -4
- package/dist/types/init.d.ts.map +1 -1
- package/dist/types/initSkills.d.ts.map +1 -1
- package/dist/types/listContentDeclaration.d.ts.map +1 -1
- package/dist/types/listProjects.d.ts.map +1 -1
- package/dist/types/liveSync.d.ts.map +1 -1
- package/dist/types/pull.d.ts.map +1 -1
- package/dist/types/push/pullLog.d.ts.map +1 -1
- package/dist/types/push/push.d.ts.map +1 -1
- package/dist/types/pushConfig.d.ts.map +1 -1
- package/dist/types/pushLog.d.ts.map +1 -1
- package/dist/types/searchDoc.d.ts.map +1 -1
- package/dist/types/test/test.d.ts.map +1 -1
- package/dist/types/translateDoc/types.d.ts.map +1 -1
- package/dist/types/translateDoc/validation.d.ts.map +1 -1
- package/dist/types/translation-alignment/computeSimilarity.d.ts.map +1 -1
- package/dist/types/translation-alignment/normalizeBlock.d.ts.map +1 -1
- package/dist/types/translation-alignment/pipeline.d.ts.map +1 -1
- package/dist/types/translation-alignment/rebuildDocument.d.ts.map +1 -1
- package/dist/types/translation-alignment/segmentDocument.d.ts.map +1 -1
- package/dist/types/translation-alignment/types.d.ts.map +1 -1
- package/dist/types/utils/calculateChunks.d.ts.map +1 -1
- package/dist/types/utils/checkAccess.d.ts +3 -2
- package/dist/types/utils/checkAccess.d.ts.map +1 -1
- package/dist/types/utils/checkConfigConsistency.d.ts.map +1 -1
- package/dist/types/utils/checkFileModifiedRange.d.ts.map +1 -1
- package/dist/types/utils/checkLastUpdateTime.d.ts.map +1 -1
- package/dist/types/utils/chunkInference.d.ts.map +1 -1
- package/dist/types/utils/fixChunkStartEndChars.d.ts.map +1 -1
- package/dist/types/utils/formatTimeDiff.d.ts.map +1 -1
- package/dist/types/utils/getIsFileUpdatedRecently.d.ts.map +1 -1
- package/dist/types/utils/getOutputFilePath.d.ts.map +1 -1
- package/dist/types/utils/getParentPackageJSON.d.ts.map +1 -1
- package/dist/types/utils/listSpecialChars.d.ts.map +1 -1
- package/dist/types/utils/mapChunksBetweenFiles.d.ts.map +1 -1
- package/dist/types/utils/openBrowser.d.ts.map +1 -1
- package/dist/types/utils/reorderParagraphs.d.ts.map +1 -1
- package/dist/types/utils/setupAI.d.ts +1 -2
- package/dist/types/utils/setupAI.d.ts.map +1 -1
- package/dist/types/watch.d.ts.map +1 -1
- package/package.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fill.cjs","names":["ensureArray","setupAI","x","getTargetUnmergedDictionaries","ANSIColors","listTranslationsTasks","translateDictionary","writeFill"],"sources":["../../../src/fill/fill.ts"],"sourcesContent":["import { basename, join, relative } from 'node:path';\n\nimport type { AIOptions } from '@intlayer/api';\nimport {\n loadContentDeclarations,\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport {\n type ListGitFilesOptions,\n logConfigDetails,\n} from '@intlayer/chokidar/cli';\nimport {\n formatPath,\n getGlobalLimiter,\n getTaskLimiter,\n} from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { Fill } from '@intlayer/types/dictionary';\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 logConfigDetails(options?.configOptions);\n\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, isCustomAI } = aiResult;\n\n if (isCustomAI && aiClient && aiConfig) {\n const { hasAIAccess, error } = await aiClient.checkAISDKAccess(aiConfig);\n if (!hasAIAccess) {\n appLogger(`${x} ${error}`);\n return;\n }\n }\n\n const targetUnmergedDictionaries =\n await getTargetUnmergedDictionaries(options);\n\n // Load the original source content declaration files to recover function-type\n // `fill` values that are lost when dictionaries are JSON-serialised into\n // unmerged_dictionaries.cjs. Dictionary-level fill takes priority over the\n // config-level fill, but we can only know that by reading the source files.\n const uniqueSourcePaths = [\n ...new Set(\n targetUnmergedDictionaries\n .filter((unmergedDictionary) =>\n ['local', 'hybrid'].includes(unmergedDictionary.location!)\n )\n .map((unmergedDictionary) => unmergedDictionary.filePath)\n .filter(Boolean) as string[]\n ),\n ];\n const sourceDictionaries = await loadContentDeclarations(\n uniqueSourcePaths.map((sourcePath) =>\n join(configuration.system.baseDir, sourcePath)\n ),\n configuration,\n undefined,\n {\n logError: false,\n }\n );\n // Map relative filePath → original fill value from the source file\n const originalFillByPath = new Map<string, Fill | undefined>();\n\n for (const dictionary of sourceDictionaries) {\n if (dictionary.filePath) {\n originalFillByPath.set(\n dictionary.filePath,\n dictionary.fill as Fill | undefined\n );\n }\n }\n\n const affectedDictionaryKeys = new Set<string>();\n\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?.system?.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,\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, function, 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 //\n // NOTE: function-type fill values are lost during JSON serialisation of\n // unmerged_dictionaries.cjs. We recover them by checking the original\n // source file that was loaded above (originalFillByPath). Dictionary-level\n // fill always takes priority over config-level fill.\n const originalFill = originalFillByPath.get(\n dictionaryOutput.filePath ?? ''\n );\n\n // originalFill is undefined when the source file had no fill property; use\n // the (possibly JSON-preserved) dictionaryOutput.fill as a fallback so that\n // string/boolean fill values set directly on the dict still work.\n const dictFill: Fill | undefined =\n originalFill !== undefined ? originalFill : dictionaryOutput.fill;\n\n const hasDictionaryLevelFill =\n typeof dictFill === 'string' ||\n typeof dictFill === 'function' ||\n (typeof dictFill === 'object' && dictFill !== null);\n\n const isPerLocale = typeof dictionaryOutput.locale === 'string';\n\n const effectiveFill = hasDictionaryLevelFill\n ? dictFill\n : isPerLocale\n ? (configuration.dictionary?.fill ?? true)\n : false; // Multilingual dictionaries (no locale property) always write to same file unless explicitly set on the dictionary\n\n const isFillOtherFile =\n typeof effectiveFill === 'string' ||\n typeof effectiveFill === 'function' ||\n (typeof effectiveFill === 'object' && effectiveFill !== null);\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":";;;;;;;;;;;;;;;;;AAyCA,MAAM,6BAA6B;;;;AAmBnC,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,4DAAiC,SAAS,cAAc;CAC9D,6CAAiB,SAAS,cAAc;CAExC,MAAM,sDAAyB,cAAc;CAE7C,IAAI,SAAS,UAAU,MACrB,oDAAsB,eAAe,EAAE,UAAU,MAAM,CAAC;MACnD,IAAI,OAAO,SAAS,UAAU,aACnC,oDAAsB,cAAc;CAGtC,MAAM,EAAE,eAAe,YAAY,cAAc;CACjD,MAAM,OAAO,SAAS,QAAQ;CAC9B,MAAM,aAAa,SAAS,gBAAgB;CAE5C,MAAM,gBAAg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edDictionaries","ANSIColors","listTranslationsTasks","translateDictionary","writeFill"],"sources":["../../../src/fill/fill.ts"],"sourcesContent":["import { basename, join, relative } from 'node:path';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n loadContentDeclarations,\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport {\n type ListGitFilesOptions,\n logConfigDetails,\n} from '@intlayer/chokidar/cli';\nimport {\n formatPath,\n getGlobalLimiter,\n getTaskLimiter,\n} from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { Fill } from '@intlayer/types/dictionary';\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 logConfigDetails(options?.configOptions);\n\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, isCustomAI } = aiResult;\n\n if (isCustomAI && aiClient && aiConfig) {\n const { hasAIAccess, error } = await aiClient.checkAISDKAccess(aiConfig);\n if (!hasAIAccess) {\n appLogger(`${x} ${error}`);\n return;\n }\n }\n\n const targetUnmergedDictionaries =\n await getTargetUnmergedDictionaries(options);\n\n // Load the original source content declaration files to recover function-type\n // `fill` values that are lost when dictionaries are JSON-serialised into\n // unmerged_dictionaries.cjs. Dictionary-level fill takes priority over the\n // config-level fill, but we can only know that by reading the source files.\n const uniqueSourcePaths = [\n ...new Set(\n targetUnmergedDictionaries\n .filter((unmergedDictionary) =>\n ['local', 'hybrid'].includes(unmergedDictionary.location!)\n )\n .map((unmergedDictionary) => unmergedDictionary.filePath)\n .filter(Boolean) as string[]\n ),\n ];\n const sourceDictionaries = await loadContentDeclarations(\n uniqueSourcePaths.map((sourcePath) =>\n join(configuration.system.baseDir, sourcePath)\n ),\n configuration,\n undefined,\n {\n logError: false,\n }\n );\n // Map relative filePath → original fill value from the source file\n const originalFillByPath = new Map<string, Fill | undefined>();\n\n for (const dictionary of sourceDictionaries) {\n if (dictionary.filePath) {\n originalFillByPath.set(\n dictionary.filePath,\n dictionary.fill as Fill | undefined\n );\n }\n }\n\n const affectedDictionaryKeys = new Set<string>();\n\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?.system?.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,\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, function, 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 //\n // NOTE: function-type fill values are lost during JSON serialisation of\n // unmerged_dictionaries.cjs. We recover them by checking the original\n // source file that was loaded above (originalFillByPath). Dictionary-level\n // fill always takes priority over config-level fill.\n const originalFill = originalFillByPath.get(\n dictionaryOutput.filePath ?? ''\n );\n\n // originalFill is undefined when the source file had no fill property; use\n // the (possibly JSON-preserved) dictionaryOutput.fill as a fallback so that\n // string/boolean fill values set directly on the dict still work.\n const dictFill: Fill | undefined =\n originalFill !== undefined ? originalFill : dictionaryOutput.fill;\n\n const hasDictionaryLevelFill =\n typeof dictFill === 'string' ||\n typeof dictFill === 'function' ||\n (typeof dictFill === 'object' && dictFill !== null);\n\n const isPerLocale = typeof dictionaryOutput.locale === 'string';\n\n const effectiveFill = hasDictionaryLevelFill\n ? dictFill\n : isPerLocale\n ? (configuration.dictionary?.fill ?? true)\n : false; // Multilingual dictionaries (no locale property) always write to same file unless explicitly set on the dictionary\n\n const isFillOtherFile =\n typeof effectiveFill === 'string' ||\n typeof effectiveFill === 'function' ||\n (typeof effectiveFill === 'object' && effectiveFill !== null);\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":";;;;;;;;;;;;;;;;;AAwCA,MAAM,6BAA6B;;;;AAmBnC,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,4DAAiC,SAAS,aAAa;CAC7D,6CAAiB,SAAS,aAAa;CAEvC,MAAM,sDAAyB,aAAa;CAE5C,IAAI,SAAS,UAAU,MACrB,oDAAsB,eAAe,EAAE,UAAU,KAAK,CAAC;MAClD,IAAI,OAAO,SAAS,UAAU,aACnC,oDAAsB,aAAa;CAGrC,MAAM,EAAE,eAAe,YAAY,cAAc;CACjD,MAAM,OAAO,SAAS,QAAQ;CAC9B,MAAM,aAAa,SAAS,gBAAgB;CAE5C,MAAM,gBAAgB,SAAS,gBAC3BA,wCA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ledFilePath.cjs","names":["GREY_DARK"],"sources":["../../../src/fill/formatAutoFilledFilePath.ts"],"sourcesContent":["import { basename, dirname, isAbsolute, normalize, resolve } from 'node:path';\nimport { getFormatFromExtension } from '@intlayer/chokidar/utils';\nimport { GREY_DARK } from '@intlayer/config/colors';\nimport { colorize, colorizePath } from '@intlayer/config/logger';\nimport { parseFilePathPattern } from '@intlayer/config/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\n\nexport const formatAutoFilledFilePath = async (\n autoFillField: FilePathPattern,\n dictionaryKey: string,\n dictionaryFilePath: string,\n baseDir: string,\n configuration: IntlayerConfig,\n locale?: Locale\n): Promise<string> => {\n // Validate inputs\n if (!autoFillField) {\n throw new Error('autoFillField must be provided');\n }\n if (!dictionaryKey || typeof dictionaryKey !== 'string') {\n throw new Error('dictionaryKey must be a non-empty string');\n }\n if (!dictionaryFilePath || typeof dictionaryFilePath !== 'string') {\n throw new Error('dictionaryFilePath must be a non-empty string');\n }\n if (!baseDir || typeof baseDir !== 'string') {\n throw new Error('baseDir must be a non-empty string');\n }\n\n // Extract the original filename accurately\n const base = basename(dictionaryFilePath);\n\n const { fileExtensions } = configuration.content;\n const extensionMatch = fileExtensions.find((ext) => base.endsWith(ext));\n\n const originalFileName = extensionMatch\n ? base.slice(0, -extensionMatch.length)\n : base.split('.')[0];\n\n console.log({ extensionMatch });\n\n if (!extensionMatch) {\n throw new Error(\n `No extension found for file ${colorizePath(dictionaryFilePath)}. Valid extensions are: ${colorize(\n fileExtensions.join(', '),\n GREY_DARK\n )}`\n );\n }\n\n // Replace placeholders in autoFillField\n const result: string = await parseFilePathPattern(autoFillField, {\n key: dictionaryKey,\n fileName: originalFileName,\n locale,\n extension: extensionMatch,\n format: getFormatFromExtension(extensionMatch),\n });\n\n // Normalize the dictionary file path - if it's relative, make it absolute relative to baseDir\n const absoluteDictionaryPath = isAbsolute(dictionaryFilePath)\n ? dictionaryFilePath\n : resolve(baseDir, dictionaryFilePath);\n\n // Handle relative paths (starting with ./ or ../)\n if (result.startsWith('./') || result.startsWith('../')) {\n const fileDir = dirname(absoluteDictionaryPath);\n const resolvedPath = resolve(fileDir, result);\n\n return resolvedPath;\n }\n\n // Handle absolute paths\n if (isAbsolute(result)) {\n const normalizedResult = normalize(result);\n const normalizedBaseDir = normalize(baseDir);\n\n // Check if it's relative to baseDir (starts with /)\n // but not a system path (like /usr/local)\n if (\n result.startsWith('/') &&\n !normalizedResult.startsWith(normalizedBaseDir)\n ) {\n // Try to resolve it relative to baseDir first\n const relativeToBase = resolve(baseDir, result.substring(1));\n\n // If the path doesn't exist in common system directories, treat as relative to baseDir\n if (\n !result.startsWith('/usr/') &&\n !result.startsWith('/etc/') &&\n !result.startsWith('/var/') &&\n !result.startsWith('/home/') &&\n !result.startsWith('/Users/')\n ) {\n return relativeToBase;\n }\n }\n\n // It's a true system absolute path\n return normalizedResult;\n }\n\n // Default case: treat as relative to baseDir\n return normalize(result);\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,2BAA2B,OACtC,eACA,eACA,oBACA,SACA,eACA,WACoB;CAEpB,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,
|
|
1
|
+
{"version":3,"file":"formatAutoFilledFilePath.cjs","names":["GREY_DARK"],"sources":["../../../src/fill/formatAutoFilledFilePath.ts"],"sourcesContent":["import { basename, dirname, isAbsolute, normalize, resolve } from 'node:path';\nimport { getFormatFromExtension } from '@intlayer/chokidar/utils';\nimport { GREY_DARK } from '@intlayer/config/colors';\nimport { colorize, colorizePath } from '@intlayer/config/logger';\nimport { parseFilePathPattern } from '@intlayer/config/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\n\nexport const formatAutoFilledFilePath = async (\n autoFillField: FilePathPattern,\n dictionaryKey: string,\n dictionaryFilePath: string,\n baseDir: string,\n configuration: IntlayerConfig,\n locale?: Locale\n): Promise<string> => {\n // Validate inputs\n if (!autoFillField) {\n throw new Error('autoFillField must be provided');\n }\n if (!dictionaryKey || typeof dictionaryKey !== 'string') {\n throw new Error('dictionaryKey must be a non-empty string');\n }\n if (!dictionaryFilePath || typeof dictionaryFilePath !== 'string') {\n throw new Error('dictionaryFilePath must be a non-empty string');\n }\n if (!baseDir || typeof baseDir !== 'string') {\n throw new Error('baseDir must be a non-empty string');\n }\n\n // Extract the original filename accurately\n const base = basename(dictionaryFilePath);\n\n const { fileExtensions } = configuration.content;\n const extensionMatch = fileExtensions.find((ext) => base.endsWith(ext));\n\n const originalFileName = extensionMatch\n ? base.slice(0, -extensionMatch.length)\n : base.split('.')[0];\n\n console.log({ extensionMatch });\n\n if (!extensionMatch) {\n throw new Error(\n `No extension found for file ${colorizePath(dictionaryFilePath)}. Valid extensions are: ${colorize(\n fileExtensions.join(', '),\n GREY_DARK\n )}`\n );\n }\n\n // Replace placeholders in autoFillField\n const result: string = await parseFilePathPattern(autoFillField, {\n key: dictionaryKey,\n fileName: originalFileName,\n locale,\n extension: extensionMatch,\n format: getFormatFromExtension(extensionMatch),\n });\n\n // Normalize the dictionary file path - if it's relative, make it absolute relative to baseDir\n const absoluteDictionaryPath = isAbsolute(dictionaryFilePath)\n ? dictionaryFilePath\n : resolve(baseDir, dictionaryFilePath);\n\n // Handle relative paths (starting with ./ or ../)\n if (result.startsWith('./') || result.startsWith('../')) {\n const fileDir = dirname(absoluteDictionaryPath);\n const resolvedPath = resolve(fileDir, result);\n\n return resolvedPath;\n }\n\n // Handle absolute paths\n if (isAbsolute(result)) {\n const normalizedResult = normalize(result);\n const normalizedBaseDir = normalize(baseDir);\n\n // Check if it's relative to baseDir (starts with /)\n // but not a system path (like /usr/local)\n if (\n result.startsWith('/') &&\n !normalizedResult.startsWith(normalizedBaseDir)\n ) {\n // Try to resolve it relative to baseDir first\n const relativeToBase = resolve(baseDir, result.substring(1));\n\n // If the path doesn't exist in common system directories, treat as relative to baseDir\n if (\n !result.startsWith('/usr/') &&\n !result.startsWith('/etc/') &&\n !result.startsWith('/var/') &&\n !result.startsWith('/home/') &&\n !result.startsWith('/Users/')\n ) {\n return relativeToBase;\n }\n }\n\n // It's a true system absolute path\n return normalizedResult;\n }\n\n // Default case: treat as relative to baseDir\n return normalize(result);\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,2BAA2B,OACtC,eACA,eACA,oBACA,SACA,eACA,WACoB;CAEpB,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,gCAAgC;CAElD,IAAI,CAAC,iBAAiB,OAAO,kBAAkB,UAC7C,MAAM,IAAI,MAAM,0CAA0C;CAE5D,IAAI,CAAC,sBAAsB,OAAO,uBAAuB,UACvD,MAAM,IAAI,MAAM,+CAA+C;CAEjE,IAAI,CAAC,WAAW,OAAO,YAAY,UACjC,MAAM,IAAI,MAAM,oCAAoC;CAItD,MAAM,+BAAgB,kBAAkB;CAExC,MAAM,EAAE,mBAAmB,cAAc;CACzC,MAAM,iBAAiB,eAAe,MAAM,QAAQ,KAAK,SAAS,GAAG,CAAC;CAEtE,MAAM,mBAAmB,iBACrB,KAAK,MAAM,GAAG,CAAC,eAAe,MAAM,IACpC,KAAK,MAAM,GAAG,EAAE;CAEpB,QAAQ,IAAI,EAAE,eAAe,CAAC;CAE9B,IAAI,CAAC,gBACH,MAAM,IAAI,MACR,yEAA4C,kBAAkB,EAAE,gEAC9D,eAAe,KAAK,IAAI,GACxBA,iCACF,GACF;CAIF,MAAM,SAAiB,uDAA2B,eAAe;EAC/D,KAAK;EACL,UAAU;EACV;EACA,WAAW;EACX,6DAA+B,cAAc;CAC/C,CAAC;CAGD,MAAM,mDAAoC,kBAAkB,IACxD,4CACQ,SAAS,kBAAkB;CAGvC,IAAI,OAAO,WAAW,IAAI,KAAK,OAAO,WAAW,KAAK,GAIpD,qDAHwB,sBACW,GAAG,MAEpB;CAIpB,8BAAe,MAAM,GAAG;EACtB,MAAM,4CAA6B,MAAM;EACzC,MAAM,6CAA8B,OAAO;EAI3C,IACE,OAAO,WAAW,GAAG,KACrB,CAAC,iBAAiB,WAAW,iBAAiB,GAC9C;GAEA,MAAM,wCAAyB,SAAS,OAAO,UAAU,CAAC,CAAC;GAG3D,IACE,CAAC,OAAO,WAAW,OAAO,KAC1B,CAAC,OAAO,WAAW,OAAO,KAC1B,CAAC,OAAO,WAAW,OAAO,KAC1B,CAAC,OAAO,WAAW,QAAQ,KAC3B,CAAC,OAAO,WAAW,SAAS,GAE5B,OAAO;EAEX;EAGA,OAAO;CACT;CAGA,gCAAiB,MAAM;AACzB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatFillData.cjs","names":["resolveOutputPattern","getPatternForLocale"],"sources":["../../../src/fill/formatFillData.ts"],"sourcesContent":["import { basename, dirname, extname, relative } from 'node:path';\nimport { getFormatFromExtension } from '@intlayer/chokidar/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { DictionaryKey, Fill } from '@intlayer/types/dictionary';\nimport type { FilePathPatternContext } from '@intlayer/types/filePathPattern';\nimport {\n getPatternForLocale,\n resolveOutputPattern,\n} from '../utils/getOutputFilePath';\n\nexport type FillData = {\n localeList: Locale[];\n filePath: string;\n isPerLocale: boolean;\n};\n\n/** Merge FillData entries that resolve to the same file path. */\nconst groupByFilePath = (entries: FillData[]): FillData[] =>\n entries.reduce((acc, curr) => {\n const existing = acc.find((item) => item.filePath === curr.filePath);\n if (existing) {\n for (const loc of curr.localeList) {\n if (!existing.localeList.includes(loc)) existing.localeList.push(loc);\n }\n // Multiple locales sharing one path → multilingual file\n existing.isPerLocale = false;\n } else {\n acc.push(curr);\n }\n return acc;\n }, [] as FillData[]);\n\nexport const formatFillData = async (\n fillField: Fill,\n localeList: Locale[],\n filePath: string,\n dictionaryKey: DictionaryKey,\n configuration: IntlayerConfig\n): Promise<FillData[]> => {\n if (!fillField || typeof fillField === 'boolean') return [];\n\n const { baseDir } = configuration.system;\n const { defaultLocale, locales } = configuration.internationalization;\n\n const extension = extname(filePath);\n const base = basename(filePath);\n\n const { fileExtensions } = configuration.content;\n const extensionMatch = fileExtensions.find((ext) => base.endsWith(ext));\n\n let cleanComponentFileName = extensionMatch\n ? base.slice(0, -extensionMatch.length)\n : base.split('.')[0];\n\n // Strip source locale if present\n const sourceLocaleMatch = locales.find((loc) =>\n cleanComponentFileName.endsWith(`.${loc}`)\n );\n if (sourceLocaleMatch) {\n cleanComponentFileName = cleanComponentFileName.slice(\n 0,\n -(sourceLocaleMatch.length + 1)\n );\n }\n\n const uncapitalizedName =\n cleanComponentFileName.charAt(0).toLowerCase() +\n cleanComponentFileName.slice(1);\n const componentFormat = getFormatFromExtension(extension);\n\n const getContext = (\n locale: Locale,\n patternString?: string\n ): FilePathPatternContext => {\n let format: FilePathPatternContext['format'] = 'json';\n if (patternString) {\n const extFormat = getFormatFromExtension(extname(patternString) as any);\n if (extFormat) format = extFormat as any;\n }\n return {\n key: dictionaryKey,\n componentDirPath: relative(baseDir, dirname(filePath)),\n componentFileName: cleanComponentFileName,\n fileName: uncapitalizedName,\n componentFormat:\n componentFormat as FilePathPatternContext['componentFormat'],\n componentExtension:\n extension as FilePathPatternContext['componentExtension'],\n format,\n locale,\n extension:\n configuration.content.fileExtensions.find((ext) =>\n ext.endsWith(extension)\n ) ?? configuration.content.fileExtensions[0],\n };\n };\n\n /**\n * Evaluate a scalar Fill pattern (string or function) for a list of locales.\n *\n * - Uses a dummy locale probe to detect whether the pattern varies per locale.\n * - `forcePerLocale` overrides the probe for object-fill entries where each\n * locale always maps to its own dedicated file regardless of whether the\n * path itself contains the locale string.\n */\n const processPattern = async (\n pattern: Fill,\n locales: Locale[],\n forcePerLocale = false\n ): Promise<FillData[]> => {\n const dummyLocale = '###########locale###########' as Locale;\n const patternString = typeof pattern === 'string' ? pattern : undefined;\n\n const dummyPath = await resolveOutputPattern(\n pattern,\n dummyLocale,\n getContext(dummyLocale, patternString),\n filePath,\n baseDir\n );\n const isPatternPerLocale =\n forcePerLocale ||\n (typeof dummyPath === 'string' && dummyPath.includes(dummyLocale));\n\n if (isPatternPerLocale) {\n const resolvedPaths: FillData[] = [];\n for (const locale of locales) {\n const absolutePath = await resolveOutputPattern(\n pattern,\n locale,\n getContext(locale, patternString),\n filePath,\n baseDir\n );\n if (absolutePath !== false) {\n resolvedPaths.push({\n filePath: absolutePath,\n localeList: [locale],\n isPerLocale: true,\n });\n }\n }\n return groupByFilePath(resolvedPaths);\n }\n\n // Single multilingual path — resolve using the default locale for context\n const absolutePath = await resolveOutputPattern(\n pattern,\n defaultLocale as Locale,\n getContext(defaultLocale as Locale, patternString),\n filePath,\n baseDir\n );\n if (absolutePath === false) return [];\n return [\n { filePath: absolutePath, localeList: locales, isPerLocale: false },\n ];\n };\n\n // Object fill: each locale key maps to its own pattern.\n // Object fill entries are always per-locale in intent (each locale → its own file).\n if (typeof fillField === 'object' && fillField !== null) {\n const results: FillData[] = [];\n for (const locale of localeList) {\n const pattern = getPatternForLocale(fillField, locale);\n if (pattern) {\n const res = await processPattern(pattern, [locale], true);\n results.push(...res);\n }\n }\n return groupByFilePath(results);\n }\n\n // Scalar string or function pattern\n return processPattern(fillField, localeList);\n};\n"],"mappings":";;;;;;;;AAkBA,MAAM,mBAAmB,YACvB,QAAQ,QAAQ,KAAK,SAAS;CAC5B,MAAM,WAAW,IAAI,MAAM,SAAS,KAAK,aAAa,KAAK,
|
|
1
|
+
{"version":3,"file":"formatFillData.cjs","names":["resolveOutputPattern","getPatternForLocale"],"sources":["../../../src/fill/formatFillData.ts"],"sourcesContent":["import { basename, dirname, extname, relative } from 'node:path';\nimport { getFormatFromExtension } from '@intlayer/chokidar/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { DictionaryKey, Fill } from '@intlayer/types/dictionary';\nimport type { FilePathPatternContext } from '@intlayer/types/filePathPattern';\nimport {\n getPatternForLocale,\n resolveOutputPattern,\n} from '../utils/getOutputFilePath';\n\nexport type FillData = {\n localeList: Locale[];\n filePath: string;\n isPerLocale: boolean;\n};\n\n/** Merge FillData entries that resolve to the same file path. */\nconst groupByFilePath = (entries: FillData[]): FillData[] =>\n entries.reduce((acc, curr) => {\n const existing = acc.find((item) => item.filePath === curr.filePath);\n if (existing) {\n for (const loc of curr.localeList) {\n if (!existing.localeList.includes(loc)) existing.localeList.push(loc);\n }\n // Multiple locales sharing one path → multilingual file\n existing.isPerLocale = false;\n } else {\n acc.push(curr);\n }\n return acc;\n }, [] as FillData[]);\n\nexport const formatFillData = async (\n fillField: Fill,\n localeList: Locale[],\n filePath: string,\n dictionaryKey: DictionaryKey,\n configuration: IntlayerConfig\n): Promise<FillData[]> => {\n if (!fillField || typeof fillField === 'boolean') return [];\n\n const { baseDir } = configuration.system;\n const { defaultLocale, locales } = configuration.internationalization;\n\n const extension = extname(filePath);\n const base = basename(filePath);\n\n const { fileExtensions } = configuration.content;\n const extensionMatch = fileExtensions.find((ext) => base.endsWith(ext));\n\n let cleanComponentFileName = extensionMatch\n ? base.slice(0, -extensionMatch.length)\n : base.split('.')[0];\n\n // Strip source locale if present\n const sourceLocaleMatch = locales.find((loc) =>\n cleanComponentFileName.endsWith(`.${loc}`)\n );\n if (sourceLocaleMatch) {\n cleanComponentFileName = cleanComponentFileName.slice(\n 0,\n -(sourceLocaleMatch.length + 1)\n );\n }\n\n const uncapitalizedName =\n cleanComponentFileName.charAt(0).toLowerCase() +\n cleanComponentFileName.slice(1);\n const componentFormat = getFormatFromExtension(extension);\n\n const getContext = (\n locale: Locale,\n patternString?: string\n ): FilePathPatternContext => {\n let format: FilePathPatternContext['format'] = 'json';\n if (patternString) {\n const extFormat = getFormatFromExtension(extname(patternString) as any);\n if (extFormat) format = extFormat as any;\n }\n return {\n key: dictionaryKey,\n componentDirPath: relative(baseDir, dirname(filePath)),\n componentFileName: cleanComponentFileName,\n fileName: uncapitalizedName,\n componentFormat:\n componentFormat as FilePathPatternContext['componentFormat'],\n componentExtension:\n extension as FilePathPatternContext['componentExtension'],\n format,\n locale,\n extension:\n configuration.content.fileExtensions.find((ext) =>\n ext.endsWith(extension)\n ) ?? configuration.content.fileExtensions[0],\n };\n };\n\n /**\n * Evaluate a scalar Fill pattern (string or function) for a list of locales.\n *\n * - Uses a dummy locale probe to detect whether the pattern varies per locale.\n * - `forcePerLocale` overrides the probe for object-fill entries where each\n * locale always maps to its own dedicated file regardless of whether the\n * path itself contains the locale string.\n */\n const processPattern = async (\n pattern: Fill,\n locales: Locale[],\n forcePerLocale = false\n ): Promise<FillData[]> => {\n const dummyLocale = '###########locale###########' as Locale;\n const patternString = typeof pattern === 'string' ? pattern : undefined;\n\n const dummyPath = await resolveOutputPattern(\n pattern,\n dummyLocale,\n getContext(dummyLocale, patternString),\n filePath,\n baseDir\n );\n const isPatternPerLocale =\n forcePerLocale ||\n (typeof dummyPath === 'string' && dummyPath.includes(dummyLocale));\n\n if (isPatternPerLocale) {\n const resolvedPaths: FillData[] = [];\n for (const locale of locales) {\n const absolutePath = await resolveOutputPattern(\n pattern,\n locale,\n getContext(locale, patternString),\n filePath,\n baseDir\n );\n if (absolutePath !== false) {\n resolvedPaths.push({\n filePath: absolutePath,\n localeList: [locale],\n isPerLocale: true,\n });\n }\n }\n return groupByFilePath(resolvedPaths);\n }\n\n // Single multilingual path — resolve using the default locale for context\n const absolutePath = await resolveOutputPattern(\n pattern,\n defaultLocale as Locale,\n getContext(defaultLocale as Locale, patternString),\n filePath,\n baseDir\n );\n if (absolutePath === false) return [];\n return [\n { filePath: absolutePath, localeList: locales, isPerLocale: false },\n ];\n };\n\n // Object fill: each locale key maps to its own pattern.\n // Object fill entries are always per-locale in intent (each locale → its own file).\n if (typeof fillField === 'object' && fillField !== null) {\n const results: FillData[] = [];\n for (const locale of localeList) {\n const pattern = getPatternForLocale(fillField, locale);\n if (pattern) {\n const res = await processPattern(pattern, [locale], true);\n results.push(...res);\n }\n }\n return groupByFilePath(results);\n }\n\n // Scalar string or function pattern\n return processPattern(fillField, localeList);\n};\n"],"mappings":";;;;;;;;AAkBA,MAAM,mBAAmB,YACvB,QAAQ,QAAQ,KAAK,SAAS;CAC5B,MAAM,WAAW,IAAI,MAAM,SAAS,KAAK,aAAa,KAAK,QAAQ;CACnE,IAAI,UAAU;EACZ,KAAK,MAAM,OAAO,KAAK,YACrB,IAAI,CAAC,SAAS,WAAW,SAAS,GAAG,GAAG,SAAS,WAAW,KAAK,GAAG;EAGtE,SAAS,cAAc;CACzB,OACE,IAAI,KAAK,IAAI;CAEf,OAAO;AACT,GAAG,CAAC,CAAe;AAErB,MAAa,iBAAiB,OAC5B,WACA,YACA,UACA,eACA,kBACwB;CACxB,IAAI,CAAC,aAAa,OAAO,cAAc,WAAW,OAAO,CAAC;CAE1D,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,eAAe,YAAY,cAAc;CAEjD,MAAM,mCAAoB,QAAQ;CAClC,MAAM,+BAAgB,QAAQ;CAE9B,MAAM,EAAE,mBAAmB,cAAc;CACzC,MAAM,iBAAiB,eAAe,MAAM,QAAQ,KAAK,SAAS,GAAG,CAAC;CAEtE,IAAI,yBAAyB,iBACzB,KAAK,MAAM,GAAG,CAAC,eAAe,MAAM,IACpC,KAAK,MAAM,GAAG,EAAE;CAGpB,MAAM,oBAAoB,QAAQ,MAAM,QACtC,uBAAuB,SAAS,IAAI,KAAK,CAC3C;CACA,IAAI,mBACF,yBAAyB,uBAAuB,MAC9C,GACA,EAAE,kBAAkB,SAAS,EAC/B;CAGF,MAAM,oBACJ,uBAAuB,OAAO,CAAC,EAAE,YAAY,IAC7C,uBAAuB,MAAM,CAAC;CAChC,MAAM,uEAAyC,SAAS;CAExD,MAAM,cACJ,QACA,kBAC2B;EAC3B,IAAI,SAA2C;EAC/C,IAAI,eAAe;GACjB,MAAM,wFAA2C,aAAa,CAAQ;GACtE,IAAI,WAAW,SAAS;EAC1B;EACA,OAAO;GAC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7C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getAvailableLocalesInDictionary.cjs","names":[],"sources":["../../../src/fill/getAvailableLocalesInDictionary.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"getAvailableLocalesInDictionary.cjs","names":[],"sources":["../../../src/fill/getAvailableLocalesInDictionary.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { Dictionary } from '@intlayer/types/dictionary';\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":";;;;;;;AAOA,MAAM,6BACJ,SACA,0BAAuB,IAAI,IAAI,MACf;CAChB,IAAI,CAAC,WAAW,OAAO,YAAY,UACjC,OAAO;CAIT,IAAI,QAAQ,aAAa,iBAAiB,QAAQ,aAEhD,OAAO,KAAK,QAAQ,WAAW,EAAE,SAAS,WAAW;EACnD,QAAQ,IAAI,MAAgB;CAC9B,CAAC;CAIH,KAAK,MAAM,SAAS,OAAO,OAAO,OAAO,GACvC,IAAI,SAAS,OAAO,UAAU,UAC5B,0BAA0B,OAAO,OAAO;CAI5C,OAAO;AACT;;;;;AAMA,MAAa,mCACX,eACa;CACb,MAAM,aAAa,0BAA0B,WAAW,OAAO;CAC/D,OAAO,MAAM,KAAK,UAAU;AAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getFilterMissingContentPerLocale.cjs","names":[],"sources":["../../../src/fill/getFilterMissingContentPerLocale.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\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 // Source is null - only missing if target doesn't already have null\n if (sourceContent === null) {\n return targetContent === null ? undefined : null;\n }\n\n // If target doesn't exist or is null, 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') {\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;CAE5E,IAAI,kBAAkB,MACpB,OAAO,kBAAkB,OAAO,SAAY;CAI9C,IAAI,kBAAkB,UAAa,kBAAkB,MACnD,OAAO;CAIT,IAAI,OAAO,kBAAkB,UAC3B;CAIF,IAAI,MAAM,QAAQ,
|
|
1
|
+
{"version":3,"file":"getFilterMissingContentPerLocale.cjs","names":[],"sources":["../../../src/fill/getFilterMissingContentPerLocale.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\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 // Source is null - only missing if target doesn't already have null\n if (sourceContent === null) {\n return targetContent === null ? undefined : null;\n }\n\n // If target doesn't exist or is null, 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') {\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;CAE5E,IAAI,kBAAkB,MACpB,OAAO,kBAAkB,OAAO,SAAY;CAI9C,IAAI,kBAAkB,UAAa,kBAAkB,MACnD,OAAO;CAIT,IAAI,OAAO,kBAAkB,UAC3B;CAIF,IAAI,MAAM,QAAQ,aAAa,GAAG;EAChC,IAAI,CAAC,MAAM,QAAQ,aAAa,GAC9B,OAAO;EAGT,MAAM,eAAe,cAClB,KAAK,MAAM,UAAU,qBAAqB,MAAM,cAAc,MAAM,CAAC,EACrE,QAAQ,SAAS,SAAS,MAAS;EAEtC,OAAO,aAAa,SAAS,IAAI,eAAe;CAClD;CAGA,MAAM,SAAc,CAAC;CACrB,IAAI,oBAAoB;CAExB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,aAAa,GAAG;EACxD,MAAM,cAAc,gBAAgB;EACpC,MAAM,eAAe,qBAAqB,OAAO,WAAW;EAE5D,IAAI,iBAAiB,QAAW;GAC9B,OAAO,OAAO;GACd,oBAAoB;EACtB;CACF;CAEA,OAAO,oBAAoB,SAAS;AACtC;;;;;;;;;AAUA,MAAa,oCACX,kBACA,qBACe;CACf,IAAI,CAAC,oBAAoB,CAAC,iBAAiB,SAEzC,OAAO;CAGT,MAAM,iBAAiB,qBACrB,iBAAiB,SACjB,iBAAiB,OACnB;CAEA,OAAO;EACL,GAAG;EACH,SAAS,kBAAkB,CAAC;CAC9B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listTranslationsTasks.cjs","names":["listMissingTranslationsWithConfig","ANSIColors"],"sources":["../../../src/fill/listTranslationsTasks.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { formatLocale } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getFilterTranslationsOnlyDictionary } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, LocalDictionaryId } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { listMissingTranslationsWithConfig } from '../test';\n\nexport type TranslationTask = {\n dictionaryKey: string;\n dictionaryLocalId: LocalDictionaryId;\n sourceLocale: Locale;\n targetLocales: Locale[];\n dictionaryPreset: string;\n dictionaryFilePath: string;\n};\n\nexport const listTranslationsTasks = (\n localIds: LocalDictionaryId[],\n outputLocales: Locale[],\n mode: 'complete' | 'review',\n baseLocale: Locale,\n configuration: IntlayerConfig\n): TranslationTask[] => {\n const appLogger = getAppLogger(configuration);\n\n const mergedDictionariesRecord = getDictionaries(configuration);\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n\n const allFlatDictionaries = Object.values(unmergedDictionariesRecord).flat();\n const dictionariesToProcess = allFlatDictionaries.filter((dictionary) =>\n localIds.includes(dictionary.localId!)\n );\n\n const { missingTranslations } =\n listMissingTranslationsWithConfig(configuration);\n\n const maxKeyLength = Math.max(\n ...dictionariesToProcess.map((dictionary) => dictionary.key.length)\n );\n\n const translationTasks: TranslationTask[] = [];\n\n for (const targetUnmergedDictionary of dictionariesToProcess) {\n const dictionaryPreset = colon(\n [\n ' - ',\n colorize('[', ANSIColors.GREY_DARK),\n colorizeKey(targetUnmergedDictionary.key),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: maxKeyLength + 6 }\n );\n\n const dictionaryKey = targetUnmergedDictionary.key;\n const dictionaryLocalId = targetUnmergedDictionary.localId!;\n const mainDictionaryToProcess: Dictionary =\n mergedDictionariesRecord[dictionaryKey];\n const dictionaryFilled = targetUnmergedDictionary.filled ?? false;\n\n if (dictionaryFilled === true) {\n continue;\n }\n\n const dictionaryFill =\n targetUnmergedDictionary.fill ?? configuration.dictionary?.fill ?? false;\n\n if (dictionaryFill === false) continue;\n\n const sourceLocale: Locale = (targetUnmergedDictionary.locale ??\n baseLocale) as Locale;\n\n if (!mainDictionaryToProcess) {\n appLogger(\n `${dictionaryPreset} Dictionary not found in dictionariesRecord. Skipping.`,\n {\n level: 'warn',\n }\n );\n continue;\n }\n\n if (!targetUnmergedDictionary.filePath) {\n appLogger(`${dictionaryPreset} Dictionary has no file path. Skipping.`, {\n level: 'warn',\n });\n continue;\n }\n\n const sourceLocaleContent = getFilterTranslationsOnlyDictionary(\n mainDictionaryToProcess,\n sourceLocale\n );\n\n if (\n Object.keys(sourceLocaleContent as Record<string, unknown>).length === 0\n ) {\n appLogger(\n `${dictionaryPreset} No content found for dictionary in source locale ${formatLocale(sourceLocale)}. Skipping translation for this dictionary.`,\n {\n level: 'warn',\n }\n );\n continue;\n }\n\n /**\n * In 'complete' mode, filter only the missing locales to translate\n *\n * Skip the dictionary if there are no missing locales to translate\n */\n let outputLocalesList: Locale[] = outputLocales as Locale[];\n\n if (mode === 'complete') {\n outputLocalesList =\n missingTranslations\n .find(\n (missingTranslation) => missingTranslation.key === dictionaryKey\n )\n ?.locales.filter((locale) => outputLocales.includes(locale)) ?? [];\n }\n\n if (outputLocalesList.length === 0) {\n appLogger(\n `${dictionaryPreset} ${colorize('No locales to fill, Skipping', ANSIColors.GREY_DARK)} ${colorizePath(basename(targetUnmergedDictionary.filePath))}`,\n {\n level: 'warn',\n }\n );\n continue;\n }\n\n translationTasks.push({\n dictionaryKey,\n dictionaryLocalId,\n sourceLocale,\n targetLocales: outputLocalesList,\n dictionaryPreset,\n dictionaryFilePath: targetUnmergedDictionary.filePath,\n });\n }\n\n // Return the list of tasks to execute\n return translationTasks;\n};\n"],"mappings":";;;;;;;;;;;;;AA2BA,MAAa,yBACX,UACA,eACA,MACA,YACA,kBACsB;CACtB,MAAM,sDAAyB,
|
|
1
|
+
{"version":3,"file":"listTranslationsTasks.cjs","names":["listMissingTranslationsWithConfig","ANSIColors"],"sources":["../../../src/fill/listTranslationsTasks.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { formatLocale } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getFilterTranslationsOnlyDictionary } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, LocalDictionaryId } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { listMissingTranslationsWithConfig } from '../test';\n\nexport type TranslationTask = {\n dictionaryKey: string;\n dictionaryLocalId: LocalDictionaryId;\n sourceLocale: Locale;\n targetLocales: Locale[];\n dictionaryPreset: string;\n dictionaryFilePath: string;\n};\n\nexport const listTranslationsTasks = (\n localIds: LocalDictionaryId[],\n outputLocales: Locale[],\n mode: 'complete' | 'review',\n baseLocale: Locale,\n configuration: IntlayerConfig\n): TranslationTask[] => {\n const appLogger = getAppLogger(configuration);\n\n const mergedDictionariesRecord = getDictionaries(configuration);\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n\n const allFlatDictionaries = Object.values(unmergedDictionariesRecord).flat();\n const dictionariesToProcess = allFlatDictionaries.filter((dictionary) =>\n localIds.includes(dictionary.localId!)\n );\n\n const { missingTranslations } =\n listMissingTranslationsWithConfig(configuration);\n\n const maxKeyLength = Math.max(\n ...dictionariesToProcess.map((dictionary) => dictionary.key.length)\n );\n\n const translationTasks: TranslationTask[] = [];\n\n for (const targetUnmergedDictionary of dictionariesToProcess) {\n const dictionaryPreset = colon(\n [\n ' - ',\n colorize('[', ANSIColors.GREY_DARK),\n colorizeKey(targetUnmergedDictionary.key),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: maxKeyLength + 6 }\n );\n\n const dictionaryKey = targetUnmergedDictionary.key;\n const dictionaryLocalId = targetUnmergedDictionary.localId!;\n const mainDictionaryToProcess: Dictionary =\n mergedDictionariesRecord[dictionaryKey];\n const dictionaryFilled = targetUnmergedDictionary.filled ?? false;\n\n if (dictionaryFilled === true) {\n continue;\n }\n\n const dictionaryFill =\n targetUnmergedDictionary.fill ?? configuration.dictionary?.fill ?? false;\n\n if (dictionaryFill === false) continue;\n\n const sourceLocale: Locale = (targetUnmergedDictionary.locale ??\n baseLocale) as Locale;\n\n if (!mainDictionaryToProcess) {\n appLogger(\n `${dictionaryPreset} Dictionary not found in dictionariesRecord. Skipping.`,\n {\n level: 'warn',\n }\n );\n continue;\n }\n\n if (!targetUnmergedDictionary.filePath) {\n appLogger(`${dictionaryPreset} Dictionary has no file path. Skipping.`, {\n level: 'warn',\n });\n continue;\n }\n\n const sourceLocaleContent = getFilterTranslationsOnlyDictionary(\n mainDictionaryToProcess,\n sourceLocale\n );\n\n if (\n Object.keys(sourceLocaleContent as Record<string, unknown>).length === 0\n ) {\n appLogger(\n `${dictionaryPreset} No content found for dictionary in source locale ${formatLocale(sourceLocale)}. Skipping translation for this dictionary.`,\n {\n level: 'warn',\n }\n );\n continue;\n }\n\n /**\n * In 'complete' mode, filter only the missing locales to translate\n *\n * Skip the dictionary if there are no missing locales to translate\n */\n let outputLocalesList: Locale[] = outputLocales as Locale[];\n\n if (mode === 'complete') {\n outputLocalesList =\n missingTranslations\n .find(\n (missingTranslation) => missingTranslation.key === dictionaryKey\n )\n ?.locales.filter((locale) => outputLocales.includes(locale)) ?? [];\n }\n\n if (outputLocalesList.length === 0) {\n appLogger(\n `${dictionaryPreset} ${colorize('No locales to fill, Skipping', ANSIColors.GREY_DARK)} ${colorizePath(basename(targetUnmergedDictionary.filePath))}`,\n {\n level: 'warn',\n }\n );\n continue;\n }\n\n translationTasks.push({\n dictionaryKey,\n dictionaryLocalId,\n sourceLocale,\n targetLocales: outputLocalesList,\n dictionaryPreset,\n dictionaryFilePath: targetUnmergedDictionary.filePath,\n });\n }\n\n // Return the list of tasks to execute\n return translationTasks;\n};\n"],"mappings":";;;;;;;;;;;;;AA2BA,MAAa,yBACX,UACA,eACA,MACA,YACA,kBACsB;CACtB,MAAM,sDAAyB,aAAa;CAE5C,MAAM,6EAA2C,aAAa;CAC9D,MAAM,gGAAqD,aAAa;CAGxE,MAAM,wBADsB,OAAO,OAAO,0BAA0B,EAAE,KACtB,EAAE,QAAQ,eACxD,SAAS,SAAS,WAAW,OAAQ,CACvC;CAEA,MAAM,EAAE,wBACNA,uEAAkC,aAAa;CAEjD,MAAM,eAAe,KAAK,IACxB,GAAG,sBAAsB,KAAK,eAAe,WAAW,IAAI,MAAM,CACpE;CAEA,MAAM,mBAAsC,CAAC;CAE7C,KAAK,MAAM,4BAA4B,uBAAuB;EAC5D,MAAM,sDACJ;GACE;yCACS,KAAKC,wBAAW,SAAS;4CACtB,yBAAyB,GAAG;yCAC/B,KAAKA,wBAAW,SAAS;EACpC,EAAE,KAAK,EAAE,GACT,EAAE,SAAS,eAAe,EAAE,CAC9B;EAEA,MAAM,gBAAgB,yBAAyB;EAC/C,MAAM,oBAAoB,yBAAyB;EACnD,MAAM,0BACJ,yBAAyB;EAG3B,KAFyB,yBAAyB,UAAU,WAEnC,MACvB;EAMF,KAFE,yBAAyB,QAAQ,cAAc,YAAY,QAAQ,WAE9C,OAAO;EAE9B,MAAM,eAAwB,yBAAyB,UACrD;EAEF,IAAI,CAAC,yBAAyB;GAC5B,UACE,GAAG,iBAAiB,yDACpB,EACE,OAAO,OACT,CACF;GACA;EACF;EAEA,IAAI,CAAC,yBAAyB,UAAU;GACtC,UAAU,GAAG,iBAAiB,0CAA0C,EACtE,OAAO,OACT,CAAC;GACD;EACF;EAEA,MAAM,sFACJ,yBACA,YACF;EAEA,IACE,OAAO,KAAK,mBAA8C,EAAE,WAAW,GACvE;GACA,UACE,GAAG,iBAAiB,+FAAiE,YAAY,EAAE,8CACnG,EACE,OAAO,OACT,CACF;GACA;EACF;;;;;;EAOA,IAAI,oBAA8B;EAElC,IAAI,SAAS,YACX,oBACE,oBACG,MACE,uBAAuB,mBAAmB,QAAQ,aACrD,GACE,QAAQ,QAAQ,WAAW,cAAc,SAAS,MAAM,CAAC,KAAK,CAAC;EAGvE,IAAI,kBAAkB,WAAW,GAAG;GAClC,UACE,GAAG,iBAAiB,yCAAY,gCAAgCA,wBAAW,SAAS,EAAE,qEAAyB,yBAAyB,QAAQ,CAAC,KACjJ,EACE,OAAO,OACT,CACF;GACA;EACF;EAEA,iBAAiB,KAAK;GACpB;GACA;GACA;GACA,eAAe;GACf;GACA,oBAAoB,yBAAyB;EAC/C,CAAC;CACH;CAGA,OAAO;AACT"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
const require_utils_checkAccess = require('../utils/checkAccess.cjs');
|
|
3
4
|
const require_fill_deepMergeContent = require('./deepMergeContent.cjs');
|
|
4
5
|
const require_fill_extractTranslatableContent = require('./extractTranslatableContent.cjs');
|
|
5
6
|
let node_path = require("node:path");
|
|
@@ -9,7 +10,6 @@ _intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
|
9
10
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
10
11
|
let _intlayer_unmerged_dictionaries_entry = require("@intlayer/unmerged-dictionaries-entry");
|
|
11
12
|
let _intlayer_core_plugins = require("@intlayer/core/plugins");
|
|
12
|
-
let _intlayer_api = require("@intlayer/api");
|
|
13
13
|
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
14
14
|
|
|
15
15
|
//#region src/fill/translateDictionary.ts
|
|
@@ -40,7 +40,7 @@ const MAX_FOLLOWING_ERRORS = 10;
|
|
|
40
40
|
let followingErrors = 0;
|
|
41
41
|
const translateDictionary = async (task, configuration, options) => {
|
|
42
42
|
const appLogger = (0, _intlayer_config_logger.getAppLogger)(configuration);
|
|
43
|
-
const intlayerAPI =
|
|
43
|
+
const intlayerAPI = await require_utils_checkAccess.getAuthenticatedAPI(configuration);
|
|
44
44
|
const { mode, aiOptions, fillMetadata, aiClient, aiConfig } = {
|
|
45
45
|
mode: "complete",
|
|
46
46
|
fillMetadata: true,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translateDictionary.cjs","names":["ANSIColors","extractTranslatableContent","reinsertTranslatedContent","deepMergeContent"],"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 excludeObjectFormat,\n formatLocale,\n type JsonChunk,\n mergeChunks,\n reconstructFromSingleChunk,\n verifyIdenticObjectFormat,\n} from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport {\n getFilterMissingTranslationsDictionary,\n getMultilingualDictionary,\n getPerLocaleDictionary,\n insertContentInDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport type { AIClient } from '../utils/setupAI';\nimport { deepMergeContent } from './deepMergeContent';\nimport {\n extractTranslatableContent,\n reinsertTranslatedContent,\n} from './extractTranslatableContent';\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<\n typeof import('@intlayer/chokidar/utils').getGlobalLimiter\n >;\n onSuccess?: () => void;\n onError?: (error: unknown) => void;\n getAbortError?: () => Error | null;\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n};\n\nconst createChunkPreset = (chunkIndex: number, totalChunks: number) => {\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\nconst hasMissingMetadata = (dictionary: Dictionary) =>\n !dictionary.description || !dictionary.title || !dictionary.tags;\n\nconst serializeError = (error: unknown): string => {\n if (error instanceof Error) {\n return error.cause\n ? `${error.message} (cause: ${String(error.cause)})`\n : error.message;\n }\n if (typeof error === 'string') return error;\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n};\n\nconst CHUNK_SIZE = 4000;\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 // Look up the target locale dictionary by its locale property.\n // This handles both directory-based paths (/en/file.json → /es/file.json)\n // AND filename-based paths (messages_ICU/en.json → messages_ICU/es.json).\n // Plugins like syncJSON set `dict.locale` correctly, so matching by locale\n // is the only reliable strategy — path string-replacement fails when the\n // locale appears in the filename rather than a directory segment.\n const targetUnmergedDictionary = unmergedDictionariesRecord[\n task.dictionaryKey\n ]?.find(\n (dict) =>\n dict.locale === targetLocale &&\n dict.filePath !== baseUnmergedDictionary.filePath\n );\n\n // Derive the target file path for the fallback (when the file doesn't exist yet).\n // Try directory-style first (/en/ → /es/), then filename-style (en.json → es.json).\n const sourceFilePath = baseUnmergedDictionary.filePath ?? '';\n const derivedTargetFilePath = sourceFilePath.includes(\n `/${task.sourceLocale}/`\n )\n ? sourceFilePath.replace(\n new RegExp(`/${task.sourceLocale}/`, 'g'),\n `/${targetLocale}/`\n )\n : sourceFilePath.replace(\n new RegExp(`(^|/)${task.sourceLocale}(\\\\.[^/]+)$`),\n `$1${targetLocale}$2`\n );\n\n targetLocaleDictionary = targetUnmergedDictionary ?? {\n key: baseUnmergedDictionary.key,\n content: {},\n filePath: derivedTargetFilePath || undefined,\n locale: targetLocale,\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 // Filter to only untranslated fields, preserving explicit null values as\n // default-locale fallback markers. Applied after both paths converge so\n // the same logic covers per-locale and multilingual dictionaries.\n if (mode === 'complete') {\n dictionaryToProcess = {\n ...dictionaryToProcess,\n content:\n excludeObjectFormat(\n dictionaryToProcess.content,\n targetLocaleDictionary.content\n ) ?? {},\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 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 as unknown as Record<string, any>,\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(async (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 const reconstructedChunk = reconstructFromSingleChunk(chunk);\n const {\n extractedContent: chunkExtractedContent,\n translatableDictionary: chunkTranslatableDictionary,\n } = extractTranslatableContent(reconstructedChunk);\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:\n chunkTranslatableDictionary as unknown as JSON,\n presetOutputContent: chunkTranslatableDictionary,\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:\n chunkTranslatableDictionary as unknown as JSON,\n presetOutputContent: chunkTranslatableDictionary,\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, error } = verifyIdenticObjectFormat(\n translationResult.fileContent,\n chunkTranslatableDictionary\n );\n\n if (!isIdentic) {\n throw new Error(\n `Translation result does not match expected format: ${error}`\n );\n }\n\n notifySuccess();\n return reinsertTranslatedContent(\n reconstructedChunk,\n chunkExtractedContent,\n translationResult.fileContent as Record<number, string>\n );\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(serializeError(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 translated chunk contents back into a single content object\n const reinsertedContent = mergeChunks(chunkResult);\n\n const merged = {\n ...dictionaryToProcess,\n content: reinsertedContent,\n };\n\n // Merge newly translated content (including explicit null fallbacks) back\n // into the existing target locale content. Applies to both per-locale and\n // multilingual paths so the target always retains previously translated\n // fields and receives null markers where the source has no translation.\n const finalContent = deepMergeContent(\n targetLocaleDictionary.content ?? {},\n merged.content\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 // The dict-level `fill` value may have been lost during JSON serialisation\n // (functions can't be serialised to JSON). Fall back to the config-level\n // fill so that an explicit fill in intlayer.config.ts is honoured.\n const effectiveFillForCheck =\n baseUnmergedDictionary.fill ?? configuration.dictionary?.fill;\n\n if (\n baseUnmergedDictionary.locale &&\n (effectiveFillForCheck === true ||\n effectiveFillForCheck === 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:', ANSIColors.RED)} ${colorize(serializeError(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(serializeError(error), ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n ),\n }\n )();\n\n return result as TranslateDictionaryResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAyDA,MAAM,qBAAqB,YAAoB,gBAAwB;CACrE,IAAI,eAAe,GAAG,OAAO;CAC7B,0CACE;wCACW,KAAKA,wBAAW,UAAU;8CACpB,aAAa,EAAE;wCACrB,IAAI,eAAeA,wBAAW,UAAU;wCACxC,KAAKA,wBAAW,UAAU;EACpC,CAAC,KAAK,GAAG,EACV,EAAE,SAAS,GAAG,CACf;;AAGH,MAAM,sBAAsB,eAC1B,CAAC,WAAW,eAAe,CAAC,WAAW,SAAS,CAAC,WAAW;AAE9D,MAAM,kBAAkB,UAA2B;CACjD,IAAI,iBAAiB,OACnB,OAAO,MAAM,QACT,GAAG,MAAM,QAAQ,WAAW,OAAO,MAAM,MAAM,CAAC,KAChD,MAAM;CAEZ,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI;EACF,OAAO,KAAK,UAAU,MAAM;SACtB;EACN,OAAO,OAAO,MAAM;;;AAIxB,MAAM,aAAa;AACnB,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,cAAc,MAAO;AAE3B,MAAM,u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EACE,UAAU;EACV,OAAO;EACP,UAAU,EAAE,OAAO,SAAS,eAC1B,UACE,GAAG,KAAK,iBAAiB,yCAAY,UAAUA,wBAAW,IAAI,CAAC,yCAAY,eAAe,MAAM,EAAEA,wBAAW,UAAU,CAAC,yDAA4B,UAAU,EAAE,CAAC,kDAAqB,SAAS,IAC/L,EACE,OAAO,SACR,CACF;EACH,kBAAkB,EAAE,YAClB,UACE,GAAG,KAAK,iBAAiB,yCAAY,sCAAsCA,wBAAW,IAAI,CAAC,yCAAY,eAAe,MAAM,EAAEA,wBAAW,UAAU,IACnJ,EACE,OAAO,SACR,CACF;EACJ,CACF,EAAE"}
|
|
1
|
+
{"version":3,"file":"translateDictionary.cjs","names":["ANSIColors","getAuthenticatedAPI","extractTranslatableContent","reinsertTranslatedContent","deepMergeContent"],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n chunkJSON,\n excludeObjectFormat,\n formatLocale,\n type JsonChunk,\n mergeChunks,\n reconstructFromSingleChunk,\n verifyIdenticObjectFormat,\n} from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport {\n getFilterMissingTranslationsDictionary,\n getMultilingualDictionary,\n getPerLocaleDictionary,\n insertContentInDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { getAuthenticatedAPI } from '../utils/checkAccess';\nimport type { AIClient } from '../utils/setupAI';\nimport { deepMergeContent } from './deepMergeContent';\nimport {\n extractTranslatableContent,\n reinsertTranslatedContent,\n} from './extractTranslatableContent';\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<\n typeof import('@intlayer/chokidar/utils').getGlobalLimiter\n >;\n onSuccess?: () => void;\n onError?: (error: unknown) => void;\n getAbortError?: () => Error | null;\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n};\n\nconst createChunkPreset = (chunkIndex: number, totalChunks: number) => {\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\nconst hasMissingMetadata = (dictionary: Dictionary) =>\n !dictionary.description || !dictionary.title || !dictionary.tags;\n\nconst serializeError = (error: unknown): string => {\n if (error instanceof Error) {\n return error.cause\n ? `${error.message} (cause: ${String(error.cause)})`\n : error.message;\n }\n if (typeof error === 'string') return error;\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n};\n\nconst CHUNK_SIZE = 4000;\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 = await getAuthenticatedAPI(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 // Look up the target locale dictionary by its locale property.\n // This handles both directory-based paths (/en/file.json → /es/file.json)\n // AND filename-based paths (messages_ICU/en.json → messages_ICU/es.json).\n // Plugins like syncJSON set `dict.locale` correctly, so matching by locale\n // is the only reliable strategy — path string-replacement fails when the\n // locale appears in the filename rather than a directory segment.\n const targetUnmergedDictionary = unmergedDictionariesRecord[\n task.dictionaryKey\n ]?.find(\n (dict) =>\n dict.locale === targetLocale &&\n dict.filePath !== baseUnmergedDictionary.filePath\n );\n\n // Derive the target file path for the fallback (when the file doesn't exist yet).\n // Try directory-style first (/en/ → /es/), then filename-style (en.json → es.json).\n const sourceFilePath = baseUnmergedDictionary.filePath ?? '';\n const derivedTargetFilePath = sourceFilePath.includes(\n `/${task.sourceLocale}/`\n )\n ? sourceFilePath.replace(\n new RegExp(`/${task.sourceLocale}/`, 'g'),\n `/${targetLocale}/`\n )\n : sourceFilePath.replace(\n new RegExp(`(^|/)${task.sourceLocale}(\\\\.[^/]+)$`),\n `$1${targetLocale}$2`\n );\n\n targetLocaleDictionary = targetUnmergedDictionary ?? {\n key: baseUnmergedDictionary.key,\n content: {},\n filePath: derivedTargetFilePath || undefined,\n locale: targetLocale,\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 // Filter to only untranslated fields, preserving explicit null values as\n // default-locale fallback markers. Applied after both paths converge so\n // the same logic covers per-locale and multilingual dictionaries.\n if (mode === 'complete') {\n dictionaryToProcess = {\n ...dictionaryToProcess,\n content:\n excludeObjectFormat(\n dictionaryToProcess.content,\n targetLocaleDictionary.content\n ) ?? {},\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 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 as unknown as Record<string, any>,\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(async (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 const reconstructedChunk = reconstructFromSingleChunk(chunk);\n const {\n extractedContent: chunkExtractedContent,\n translatableDictionary: chunkTranslatableDictionary,\n } = extractTranslatableContent(reconstructedChunk);\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:\n chunkTranslatableDictionary as unknown as JSON,\n presetOutputContent: chunkTranslatableDictionary,\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:\n chunkTranslatableDictionary as unknown as JSON,\n presetOutputContent: chunkTranslatableDictionary,\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, error } = verifyIdenticObjectFormat(\n translationResult.fileContent,\n chunkTranslatableDictionary\n );\n\n if (!isIdentic) {\n throw new Error(\n `Translation result does not match expected format: ${error}`\n );\n }\n\n notifySuccess();\n return reinsertTranslatedContent(\n reconstructedChunk,\n chunkExtractedContent,\n translationResult.fileContent as Record<number, string>\n );\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(serializeError(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 translated chunk contents back into a single content object\n const reinsertedContent = mergeChunks(chunkResult);\n\n const merged = {\n ...dictionaryToProcess,\n content: reinsertedContent,\n };\n\n // Merge newly translated content (including explicit null fallbacks) back\n // into the existing target locale content. Applies to both per-locale and\n // multilingual paths so the target always retains previously translated\n // fields and receives null markers where the source has no translation.\n const finalContent = deepMergeContent(\n targetLocaleDictionary.content ?? {},\n merged.content\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 // The dict-level `fill` value may have been lost during JSON serialisation\n // (functions can't be serialised to JSON). Fall back to the config-level\n // fill so that an explicit fill in intlayer.config.ts is honoured.\n const effectiveFillForCheck =\n baseUnmergedDictionary.fill ?? configuration.dictionary?.fill;\n\n if (\n baseUnmergedDictionary.locale &&\n (effectiveFillForCheck === true ||\n effectiveFillForCheck === 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:', ANSIColors.RED)} ${colorize(serializeError(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(serializeError(error), ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n ),\n }\n )();\n\n return result as TranslateDictionaryResult;\n};\n"],"mappings":";;;;;;;;;;;;;;;AA0DA,MAAM,qBAAqB,YAAoB,gBAAwB;CACrE,IAAI,eAAe,GAAG,OAAO;CAC7B,0CACE;wCACW,KAAKA,wBAAW,SAAS;8CACnB,aAAa,CAAC;wCACpB,IAAI,eAAeA,wBAAW,SAAS;wCACvC,KAAKA,wBAAW,SAAS;CACpC,EAAE,KAAK,EAAE,GACT,EAAE,SAAS,EAAE,CACf;AACF;AAEA,MAAM,sBAAsB,eAC1B,CAAC,WAAW,eAAe,CAAC,WAAW,SAAS,CAAC,WAAW;AAE9D,MAAM,kBAAkB,UAA2B;CACjD,IAAI,iBAAiB,OACnB,OAAO,MAAM,QACT,GAAG,MAAM,QAAQ,WAAW,OAAO,MAAM,KAAK,EAAE,KAChD,MAAM;CAEZ,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;AAEA,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,sDAAyB,aAAa;CAC5C,MAAM,cAAc,MAAMC,8CAAoB,aAAa;CAE3D,MAAM,EAAE,MA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AK,iBAAiB,yCAAY,UAAUA,wBAAW,GAAG,EAAE,yCAAY,eAAe,KAAK,GAAGA,wBAAW,SAAS,EAAE,yDAA4B,UAAU,CAAC,EAAE,kDAAqB,QAAQ,KAC9L,EACE,OAAO,QACT,CACF;EACF,kBAAkB,EAAE,YAClB,UACE,GAAG,KAAK,iBAAiB,yCAAY,sCAAsCA,wBAAW,GAAG,EAAE,yCAAY,eAAe,KAAK,GAAGA,wBAAW,SAAS,KAClJ,EACE,OAAO,QACT,CACF;CACJ,CACF,EAAE;AAGJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeFill.cjs","names":["getAvailableLocalesInDictionary","formatFillData"],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { writeContentDeclaration } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, Fill } from '@intlayer/types/dictionary';\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[] = await 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 const { fill, ...rest } = contentDeclarationFile;\n\n await writeContentDeclaration(\n {\n ...rest,\n filled: true,\n locale: output.isPerLocale ? output.localeList[0] : undefined,\n localId: `${contentDeclarationFile.key}::local::${output.filePath}`,\n filePath: resolve(configuration.system.baseDir, output.filePath), // Use absolute path for vscode extension\n },\n configuration,\n {\n // Per-locale files: write only the specific locale.\n // Multilingual files (string/function fill, single output): include all\n // output locales (including source) so the file is complete.\n localeList: output.isPerLocale\n ? output.localeList\n : (outputLocales ?? configuration.internationalization.locales),\n }\n );\n\n if (output.isPerLocale) {\n appLogger(\n `Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(output.localeList[0])}`,\n { level: 'info' }\n );\n } else {\n appLogger(\n `Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`,\n { level: 'info' }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,YAAY,OACvB,wBACA,eACA,eACA,kBACG;CACH,MAAM,sDAAyB,
|
|
1
|
+
{"version":3,"file":"writeFill.cjs","names":["getAvailableLocalesInDictionary","formatFillData"],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { writeContentDeclaration } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, Fill } from '@intlayer/types/dictionary';\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[] = await 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 const { fill, ...rest } = contentDeclarationFile;\n\n await writeContentDeclaration(\n {\n ...rest,\n filled: true,\n locale: output.isPerLocale ? output.localeList[0] : undefined,\n localId: `${contentDeclarationFile.key}::local::${output.filePath}`,\n filePath: resolve(configuration.system.baseDir, output.filePath), // Use absolute path for vscode extension\n },\n configuration,\n {\n // Per-locale files: write only the specific locale.\n // Multilingual files (string/function fill, single output): include all\n // output locales (including source) so the file is complete.\n localeList: output.isPerLocale\n ? output.localeList\n : (outputLocales ?? configuration.internationalization.locales),\n }\n );\n\n if (output.isPerLocale) {\n appLogger(\n `Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(output.localeList[0])}`,\n { level: 'info' }\n );\n } else {\n appLogger(\n `Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`,\n { level: 'info' }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,YAAY,OACvB,wBACA,eACA,eACA,kBACG;CACH,MAAM,sDAAyB,aAAa;CAG5C,MAAM,mEAF+B,aAEH,EAAE,uBAAuB;CAE3D,MAAM,EAAE,aAAa;CAErB,IAAI,CAAC,UAAU;EACb,UAAU,qCAAqC,EAC7C,OAAO,QACT,CAAC;EACD;CACF;CAEA,MAAM,cACJ,uBAAuB,QAAQ,cAAc,YAAY,QAAQ;CAEnE,IAAK,gBAA4B,OAAO;EACtC,UACE,uEAA0C,eAAe,GAAG,EAAE,IAC9D,EACE,OAAO,OACT,CACF;EACA;CACF;CAEA,MAAM,oBACJ,iBAAiB,cAAc,qBAAqB,SACpD,QAAQ,WAAW,CAAC,eAAe,SAAS,MAAM,CAAC;CAGrD,MAAM,mBAAmBA,6EACvB,sBACF;CAGA,MAAM,aAAa,iBAAiB,QAAQ,WAC1C,iBAAiB,SAAS,MAAM,CAClC;CAEA,IAAI,WAAW,WAAW,GAAG;EAC3B,UACE,sFAAyD,eAAe,GAAG,EAAE,IAC7E,EACE,OAAO,OACT,CACF;EACA;CACF;CAEA,MAAM,WAAuB,MAAMC,2CACjC,aACA,YACA,UACA,eAAe,KACf,aACF;CAEA,WAAW,MAAM,UAAU,UAAU;EACnC,IAAI,CAAC,OAAO,UAAU;GACpB,UACE,wGAA2E,eAAe,GAAG,EAAE,IAC/F,EACE,OAAO,QACT,CACF;GACA;EACF;EAEA,MAAM,EAAE,MAAM,GAAG,SAAS;EAE1B,4DACE;GACE,GAAG;GACH,QAAQ;GACR,QAAQ,OAAO,cAAc,OAAO,WAAW,KAAK;GACpD,SAAS,GAAG,uBAAuB,IAAI,WAAW,OAAO;GACzD,iCAAkB,cAAc,OAAO,SAAS,OAAO,QAAQ;EACjE,GACA,eACA,EAIE,YAAY,OAAO,cACf,OAAO,aACN,iBAAiB,cAAc,qBAAqB,QAC3D,CACF;EAEA,IAAI,OAAO,aACT,UACE,4FAA+D,eAAe,GAAG,EAAE,wDAA0B,OAAO,QAAQ,EAAE,yDAA2B,OAAO,WAAW,EAAE,KAC7K,EAAE,OAAO,OAAO,CAClB;OAEA,UACE,iFAAoD,eAAe,GAAG,EAAE,wDAA0B,OAAO,QAAQ,KACjH,EAAE,OAAO,OAAO,CAClB;CAEJ;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTargetDictionary.cjs","names":[],"sources":["../../src/getTargetDictionary.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport { type ListGitFilesOptions, listGitFiles } from '@intlayer/chokidar/cli';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\nexport const ensureArray = <T>(value: T | T[]): T[] => [value].flat() as T[];\n\n// Arguments for the fill function\nexport type GetTargetDictionaryOptions = {\n file?: string | string[];\n keys?: string | string[];\n excludedKeys?: string | string[];\n filter?: (entry: Dictionary) => boolean; // DictionaryEntry needs to be defined\n pathFilter?: string | string[];\n gitOptions?: ListGitFilesOptions;\n configOptions?: GetConfigurationOptions;\n};\n\nexport const getTargetUnmergedDictionaries = async (\n options?: GetTargetDictionaryOptions\n): Promise<Dictionary[]> => {\n const configuration = getConfiguration(options?.configOptions);\n\n const { baseDir } = configuration.system;\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n let result = Object.values(unmergedDictionariesRecord).flat();\n\n // 1. if filePath not defined, list all content declaration files based on unmerged dictionaries list\n if (typeof options?.file !== 'undefined') {\n const fileArray = ensureArray(options?.file);\n const relativeFilePaths = fileArray.map((file) =>\n file.startsWith('/') ? relative(baseDir, file) : join('./', file)\n );\n\n result = result.filter(\n (dict) =>\n dict.filePath &&\n // Check for absolute path\n relativeFilePaths.includes(dict.filePath)\n );\n }\n\n if (typeof options?.keys !== 'undefined') {\n result = result.filter((dict) =>\n ensureArray(options?.keys)?.includes(dict.key)\n );\n }\n\n if (typeof options?.excludedKeys !== 'undefined') {\n result = result.filter(\n (dict) => !ensureArray(options?.excludedKeys)?.includes(dict.key)\n );\n }\n\n if (typeof options?.pathFilter !== 'undefined') {\n result = result.filter((dict) =>\n ensureArray(options?.pathFilter)?.includes(dict.filePath ?? '')\n );\n }\n\n if (typeof options?.filter !== 'undefined') {\n result = result.filter(options?.filter);\n }\n\n const gitOptions = options?.gitOptions;\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n\n if (gitChangedFiles) {\n // Convert dictionary file paths to be relative to git root for comparison\n\n // Filter dictionaries based on git changed files\n result = result.filter((dict) => {\n if (!dict.filePath) return false;\n\n return gitChangedFiles.some((gitFile) => dict.filePath === gitFile);\n });\n }\n }\n\n return result;\n};\n"],"mappings":";;;;;;;;AASA,MAAa,eAAkB,UAAwB,CAAC,
|
|
1
|
+
{"version":3,"file":"getTargetDictionary.cjs","names":[],"sources":["../../src/getTargetDictionary.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport { type ListGitFilesOptions, listGitFiles } from '@intlayer/chokidar/cli';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\nexport const ensureArray = <T>(value: T | T[]): T[] => [value].flat() as T[];\n\n// Arguments for the fill function\nexport type GetTargetDictionaryOptions = {\n file?: string | string[];\n keys?: string | string[];\n excludedKeys?: string | string[];\n filter?: (entry: Dictionary) => boolean; // DictionaryEntry needs to be defined\n pathFilter?: string | string[];\n gitOptions?: ListGitFilesOptions;\n configOptions?: GetConfigurationOptions;\n};\n\nexport const getTargetUnmergedDictionaries = async (\n options?: GetTargetDictionaryOptions\n): Promise<Dictionary[]> => {\n const configuration = getConfiguration(options?.configOptions);\n\n const { baseDir } = configuration.system;\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n let result = Object.values(unmergedDictionariesRecord).flat();\n\n // 1. if filePath not defined, list all content declaration files based on unmerged dictionaries list\n if (typeof options?.file !== 'undefined') {\n const fileArray = ensureArray(options?.file);\n const relativeFilePaths = fileArray.map((file) =>\n file.startsWith('/') ? relative(baseDir, file) : join('./', file)\n );\n\n result = result.filter(\n (dict) =>\n dict.filePath &&\n // Check for absolute path\n relativeFilePaths.includes(dict.filePath)\n );\n }\n\n if (typeof options?.keys !== 'undefined') {\n result = result.filter((dict) =>\n ensureArray(options?.keys)?.includes(dict.key)\n );\n }\n\n if (typeof options?.excludedKeys !== 'undefined') {\n result = result.filter(\n (dict) => !ensureArray(options?.excludedKeys)?.includes(dict.key)\n );\n }\n\n if (typeof options?.pathFilter !== 'undefined') {\n result = result.filter((dict) =>\n ensureArray(options?.pathFilter)?.includes(dict.filePath ?? '')\n );\n }\n\n if (typeof options?.filter !== 'undefined') {\n result = result.filter(options?.filter);\n }\n\n const gitOptions = options?.gitOptions;\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n\n if (gitChangedFiles) {\n // Convert dictionary file paths to be relative to git root for comparison\n\n // Filter dictionaries based on git changed files\n result = result.filter((dict) => {\n if (!dict.filePath) return false;\n\n return gitChangedFiles.some((gitFile) => dict.filePath === gitFile);\n });\n }\n }\n\n return result;\n};\n"],"mappings":";;;;;;;;AASA,MAAa,eAAkB,UAAwB,CAAC,KAAK,EAAE,KAAK;AAapE,MAAa,gCAAgC,OAC3C,YAC0B;CAC1B,MAAM,4DAAiC,SAAS,aAAa;CAE7D,MAAM,EAAE,YAAY,cAAc;CAElC,MAAM,gGAAqD,aAAa;CACxE,IAAI,SAAS,OAAO,OAAO,0BAA0B,EAAE,KAAK;CAG5D,IAAI,OAAO,SAAS,SAAS,aAAa;EAExC,MAAM,oBADY,YAAY,SAAS,IACL,EAAE,KAAK,SACvC,KAAK,WAAW,GAAG,4BAAa,SAAS,IAAI,wBAAS,MAAM,IAAI,CAClE;EAEA,SAAS,OAAO,QACb,SACC,KAAK,YAEL,kBAAkB,SAAS,KAAK,QAAQ,CAC5C;CACF;CAEA,IAAI,OAAO,SAAS,SAAS,aAC3B,SAAS,OAAO,QAAQ,SACtB,YAAY,SAAS,IAAI,GAAG,SAAS,KAAK,GAAG,CAC/C;CAGF,IAAI,OAAO,SAAS,iBAAiB,aACnC,SAAS,OAAO,QACb,SAAS,CAAC,YAAY,SAAS,YAAY,GAAG,SAAS,KAAK,GAAG,CAClE;CAGF,IAAI,OAAO,SAAS,eAAe,aACjC,SAAS,OAAO,QAAQ,SACtB,YAAY,SAAS,UAAU,GAAG,SAAS,KAAK,YAAY,EAAE,CAChE;CAGF,IAAI,OAAO,SAAS,WAAW,aAC7B,SAAS,OAAO,OAAO,SAAS,MAAM;CAGxC,MAAM,aAAa,SAAS;CAC5B,IAAI,YAAY;EACd,MAAM,kBAAkB,+CAAmB,UAAU;EAErD,IAAI,iBAIF,SAAS,OAAO,QAAQ,SAAS;GAC/B,IAAI,CAAC,KAAK,UAAU,OAAO;GAE3B,OAAO,gBAAgB,MAAM,YAAY,KAAK,aAAa,OAAO;EACpE,CAAC;CAEL;CAEA,OAAO;AACT"}
|
package/dist/cjs/init.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.cjs","names":[],"sources":["../../src/init.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { type InitOptions, initIntlayer } from '@intlayer/chokidar/cli';\n\nexport const findProjectRoot = (startDir: string) => {\n let currentDir = startDir;\n\n while (currentDir !== resolve(currentDir, '..')) {\n if (existsSync(join(currentDir, 'package.json'))) {\n return currentDir;\n }\n currentDir = resolve(currentDir, '..');\n }\n\n // If no package.json is found, return the start directory.\n // The initIntlayer function will handle the missing package.json error.\n return startDir;\n};\n\nexport const init = async (projectRoot?: string, options?: InitOptions) => {\n const root = projectRoot\n ? findProjectRoot(resolve(projectRoot))\n : findProjectRoot(process.cwd());\n\n await initIntlayer(root, options);\n};\n"],"mappings":";;;;;;;AAIA,MAAa,mBAAmB,aAAqB;CACnD,IAAI,aAAa;CAEjB,OAAO,sCAAuB,YAAY,
|
|
1
|
+
{"version":3,"file":"init.cjs","names":[],"sources":["../../src/init.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { type InitOptions, initIntlayer } from '@intlayer/chokidar/cli';\n\nexport const findProjectRoot = (startDir: string) => {\n let currentDir = startDir;\n\n while (currentDir !== resolve(currentDir, '..')) {\n if (existsSync(join(currentDir, 'package.json'))) {\n return currentDir;\n }\n currentDir = resolve(currentDir, '..');\n }\n\n // If no package.json is found, return the start directory.\n // The initIntlayer function will handle the missing package.json error.\n return startDir;\n};\n\nexport const init = async (projectRoot?: string, options?: InitOptions) => {\n const root = projectRoot\n ? findProjectRoot(resolve(projectRoot))\n : findProjectRoot(process.cwd());\n\n await initIntlayer(root, options);\n};\n"],"mappings":";;;;;;;AAIA,MAAa,mBAAmB,aAAqB;CACnD,IAAI,aAAa;CAEjB,OAAO,sCAAuB,YAAY,IAAI,GAAG;EAC/C,gDAAoB,YAAY,cAAc,CAAC,GAC7C,OAAO;EAET,oCAAqB,YAAY,IAAI;CACvC;CAIA,OAAO;AACT;AAEA,MAAa,OAAO,OAAO,aAAsB,YAA0B;CAKzE,+CAJa,cACT,uCAAwB,WAAW,CAAC,IACpC,gBAAgB,QAAQ,IAAI,CAAC,GAER,OAAO;AAClC"}
|
package/dist/cjs/initMCP.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initMCP.cjs","names":["findProjectRoot","getDetectedPlatform","PLATFORMS","PLATFORM_OPTIONS","p"],"sources":["../../src/initMCP.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n installMCP,\n type MCPTransport,\n PLATFORMS,\n} from '@intlayer/chokidar/cli';\nimport enquirer from 'enquirer';\nimport { findProjectRoot } from './init';\nimport { getDetectedPlatform, PLATFORM_OPTIONS } from './initSkills';\n\nexport const initMCP = async (projectRoot?: string) => {\n const root = findProjectRoot(\n projectRoot ? resolve(projectRoot) : process.cwd()\n );\n\n p.intro('Initializing Intlayer MCP Server');\n\n const detectedPlatform = getDetectedPlatform();\n\n let platform: any;\n try {\n const response = await enquirer.prompt<{ platforms: any }>({\n type: 'autocomplete',\n name: 'platforms',\n message: 'Which platform are you using? (Type to search)',\n multiple: false,\n initial: detectedPlatform\n ? PLATFORMS.indexOf(detectedPlatform)\n : undefined,\n choices: PLATFORM_OPTIONS.map((opt) => ({\n name: opt.value,\n message: opt.label,\n hint: opt.hint,\n })),\n });\n platform = response.platforms;\n } catch {\n p.cancel('Operation cancelled.');\n return;\n }\n\n if (!platform) {\n p.cancel('Operation cancelled. No platform selected.');\n return;\n }\n\n const transport = (await p.select({\n message: 'Which transport method do you want to use?',\n options: [\n {\n value: 'stdio',\n label: 'Local server (stdio)',\n hint: 'Recommended. Integrates all features including CLI tools.',\n },\n {\n value: 'sse',\n label: 'Remote server (SSE)',\n hint: 'Hosted by Intlayer. Documentation only.',\n },\n ],\n })) as MCPTransport;\n\n if (p.isCancel(transport) || !transport) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const s = p.spinner();\n s.start('Configuring MCP Server...');\n\n try {\n const result = await installMCP(root, platform, transport);\n\n s.stop('MCP Server configured successfully');\n\n p.note(result, 'Success');\n } catch (error) {\n s.stop('Failed to configure MCP Server');\n p.log.error(error instanceof Error ? error.message : String(error));\n }\n\n p.outro('Intlayer MCP Server initialization complete');\n};\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,UAAU,OAAO,gBAAyB;CACrD,MAAM,OAAOA,6BACX,qCAAsB,
|
|
1
|
+
{"version":3,"file":"initMCP.cjs","names":["findProjectRoot","getDetectedPlatform","PLATFORMS","PLATFORM_OPTIONS","p"],"sources":["../../src/initMCP.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n installMCP,\n type MCPTransport,\n PLATFORMS,\n} from '@intlayer/chokidar/cli';\nimport enquirer from 'enquirer';\nimport { findProjectRoot } from './init';\nimport { getDetectedPlatform, PLATFORM_OPTIONS } from './initSkills';\n\nexport const initMCP = async (projectRoot?: string) => {\n const root = findProjectRoot(\n projectRoot ? resolve(projectRoot) : process.cwd()\n );\n\n p.intro('Initializing Intlayer MCP Server');\n\n const detectedPlatform = getDetectedPlatform();\n\n let platform: any;\n try {\n const response = await enquirer.prompt<{ platforms: any }>({\n type: 'autocomplete',\n name: 'platforms',\n message: 'Which platform are you using? (Type to search)',\n multiple: false,\n initial: detectedPlatform\n ? PLATFORMS.indexOf(detectedPlatform)\n : undefined,\n choices: PLATFORM_OPTIONS.map((opt) => ({\n name: opt.value,\n message: opt.label,\n hint: opt.hint,\n })),\n });\n platform = response.platforms;\n } catch {\n p.cancel('Operation cancelled.');\n return;\n }\n\n if (!platform) {\n p.cancel('Operation cancelled. No platform selected.');\n return;\n }\n\n const transport = (await p.select({\n message: 'Which transport method do you want to use?',\n options: [\n {\n value: 'stdio',\n label: 'Local server (stdio)',\n hint: 'Recommended. Integrates all features including CLI tools.',\n },\n {\n value: 'sse',\n label: 'Remote server (SSE)',\n hint: 'Hosted by Intlayer. Documentation only.',\n },\n ],\n })) as MCPTransport;\n\n if (p.isCancel(transport) || !transport) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const s = p.spinner();\n s.start('Configuring MCP Server...');\n\n try {\n const result = await installMCP(root, platform, transport);\n\n s.stop('MCP Server configured successfully');\n\n p.note(result, 'Success');\n } catch (error) {\n s.stop('Failed to configure MCP Server');\n p.log.error(error instanceof Error ? error.message : String(error));\n }\n\n p.outro('Intlayer MCP Server initialization complete');\n};\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,UAAU,OAAO,gBAAyB;CACrD,MAAM,OAAOA,6BACX,qCAAsB,WAAW,IAAI,QAAQ,IAAI,CACnD;CAEA,eAAE,MAAM,kCAAkC;CAE1C,MAAM,mBAAmBC,uCAAoB;CAE7C,IAAI;CACJ,IAAI;EAeF,YAAW,MAdY,iBAAS,OAA2B;GACzD,MAAM;GACN,MAAM;GACN,SAAS;GACT,UAAU;GACV,SAAS,mBACLC,iCAAU,QAAQ,gBAAgB,IAClC;GACJ,SAASC,oCAAiB,KAAK,SAAS;IACtC,MAAM,IAAI;IACV,SAAS,IAAI;IACb,MAAM,IAAI;GACZ,EAAE;EACJ,CAAC,GACmB;CACtB,QAAQ;EACN,eAAE,OAAO,sBAAsB;EAC/B;CACF;CAEA,IAAI,CAAC,UAAU;EACb,eAAE,OAAO,4CAA4C;EACrD;CACF;CAEA,MAAM,YAAa,MAAMC,eAAE,OAAO;EAChC,SAAS;EACT,SAAS,CACP;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR,GACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR,CACF;CACF,CAAC;CAED,IAAIA,eAAE,SAAS,SAAS,KAAK,CAAC,WAAW;EACvC,eAAE,OAAO,sBAAsB;EAC/B;CACF;CAEA,MAAM,IAAIA,eAAE,QAAQ;CACpB,EAAE,MAAM,2BAA2B;CAEnC,IAAI;EACF,MAAM,SAAS,6CAAiB,MAAM,UAAU,SAAS;EAEzD,EAAE,KAAK,oCAAoC;EAE3C,eAAE,KAAK,QAAQ,SAAS;CAC1B,SAAS,OAAO;EACd,EAAE,KAAK,gCAAgC;EACvC,eAAE,IAAI,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CACpE;CAEA,eAAE,MAAM,6CAA6C;AACvD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initSkills.cjs","names":["PLATFORMS","PLATFORMS_METADATA","findProjectRoot","p","SKILLS","SKILLS_METADATA"],"sources":["../../src/initSkills.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n getInitialSkills,\n installSkills,\n PLATFORMS,\n PLATFORMS_METADATA,\n type Platform,\n SKILLS,\n SKILLS_METADATA,\n} from '@intlayer/chokidar/cli';\nimport enquirer from 'enquirer';\nimport { findProjectRoot } from './init';\n\nconst PLATFORM_CHECKS: Array<{ check: () => boolean; platform: Platform }> =\n PLATFORMS.filter((platform) => PLATFORMS_METADATA[platform].check).map(\n (platform) => ({\n check: PLATFORMS_METADATA[platform].check ?? (() => false),\n platform,\n })\n );\n\nexport const PLATFORM_OPTIONS: Array<{\n value: Platform;\n label: string;\n hint: string;\n}> = PLATFORMS.map((platform) => ({\n value: platform,\n label: PLATFORMS_METADATA[platform].label,\n hint: `(${PLATFORMS_METADATA[platform].dir})`,\n}));\n\nexport const getDetectedPlatform = (): Platform | undefined =>\n PLATFORM_CHECKS.find(({ check }) => check())?.platform;\n\nconst getDependencies = (root: string): Record<string, string> => {\n try {\n const packageJsonPath = join(root, 'package.json');\n if (!existsSync(packageJsonPath)) return {};\n\n const { dependencies = {}, devDependencies = {} } = JSON.parse(\n readFileSync(packageJsonPath, 'utf-8')\n );\n return { ...dependencies, ...devDependencies };\n } catch {\n return {};\n }\n};\n\nexport const initSkills = async (projectRoot?: string) => {\n const root = findProjectRoot(\n projectRoot ? resolve(projectRoot) : process.cwd()\n );\n\n p.intro('Initializing Intlayer skills');\n\n const detectedPlatform = getDetectedPlatform();\n\n let platform: Platform;\n try {\n const response = await enquirer.prompt<{ platforms: Platform }>({\n type: 'autocomplete',\n name: 'platforms',\n message: 'Which platforms are you using? (Type to search)',\n multiple: false,\n initial: detectedPlatform\n ? PLATFORMS.indexOf(detectedPlatform)\n : undefined,\n choices: PLATFORM_OPTIONS.map((opt) => ({\n name: opt.value,\n message: opt.label,\n hint: opt.hint,\n })),\n });\n platform = response.platforms;\n } catch {\n p.cancel('Operation cancelled.');\n return;\n }\n\n if (!platform) {\n p.log.warn('No platform selected. Nothing to install.');\n return;\n }\n\n const dependencies = getDependencies(root);\n const initialValues = getInitialSkills(dependencies);\n\n const selectedSkills = await p.multiselect({\n message: 'Select the documentation skills to provide to your AI:',\n initialValues,\n options: SKILLS.map((skill) => ({\n value: skill,\n label: skill,\n hint: SKILLS_METADATA[skill],\n })),\n required: false,\n });\n\n if (\n p.isCancel(selectedSkills) ||\n !selectedSkills ||\n (selectedSkills as string[]).length === 0\n ) {\n p.cancel('Operation cancelled. No skills selected.');\n return;\n }\n\n const s = p.spinner();\n s.start('Installing skills...');\n\n try {\n const result = await installSkills(root, platform, selectedSkills);\n\n s.stop('Skills installed successfully');\n\n p.note(result, 'Success');\n } catch (error) {\n s.stop('Failed to install skills');\n p.log.error(error instanceof Error ? error.message : String(error));\n }\n\n p.outro('Intlayer skills initialization complete');\n};\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,kBACJA,iCAAU,QAAQ,aAAaC,0CAAmB,UAAU,
|
|
1
|
+
{"version":3,"file":"initSkills.cjs","names":["PLATFORMS","PLATFORMS_METADATA","findProjectRoot","p","SKILLS","SKILLS_METADATA"],"sources":["../../src/initSkills.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n getInitialSkills,\n installSkills,\n PLATFORMS,\n PLATFORMS_METADATA,\n type Platform,\n SKILLS,\n SKILLS_METADATA,\n} from '@intlayer/chokidar/cli';\nimport enquirer from 'enquirer';\nimport { findProjectRoot } from './init';\n\nconst PLATFORM_CHECKS: Array<{ check: () => boolean; platform: Platform }> =\n PLATFORMS.filter((platform) => PLATFORMS_METADATA[platform].check).map(\n (platform) => ({\n check: PLATFORMS_METADATA[platform].check ?? (() => false),\n platform,\n })\n );\n\nexport const PLATFORM_OPTIONS: Array<{\n value: Platform;\n label: string;\n hint: string;\n}> = PLATFORMS.map((platform) => ({\n value: platform,\n label: PLATFORMS_METADATA[platform].label,\n hint: `(${PLATFORMS_METADATA[platform].dir})`,\n}));\n\nexport const getDetectedPlatform = (): Platform | undefined =>\n PLATFORM_CHECKS.find(({ check }) => check())?.platform;\n\nconst getDependencies = (root: string): Record<string, string> => {\n try {\n const packageJsonPath = join(root, 'package.json');\n if (!existsSync(packageJsonPath)) return {};\n\n const { dependencies = {}, devDependencies = {} } = JSON.parse(\n readFileSync(packageJsonPath, 'utf-8')\n );\n return { ...dependencies, ...devDependencies };\n } catch {\n return {};\n }\n};\n\nexport const initSkills = async (projectRoot?: string) => {\n const root = findProjectRoot(\n projectRoot ? resolve(projectRoot) : process.cwd()\n );\n\n p.intro('Initializing Intlayer skills');\n\n const detectedPlatform = getDetectedPlatform();\n\n let platform: Platform;\n try {\n const response = await enquirer.prompt<{ platforms: Platform }>({\n type: 'autocomplete',\n name: 'platforms',\n message: 'Which platforms are you using? (Type to search)',\n multiple: false,\n initial: detectedPlatform\n ? PLATFORMS.indexOf(detectedPlatform)\n : undefined,\n choices: PLATFORM_OPTIONS.map((opt) => ({\n name: opt.value,\n message: opt.label,\n hint: opt.hint,\n })),\n });\n platform = response.platforms;\n } catch {\n p.cancel('Operation cancelled.');\n return;\n }\n\n if (!platform) {\n p.log.warn('No platform selected. Nothing to install.');\n return;\n }\n\n const dependencies = getDependencies(root);\n const initialValues = getInitialSkills(dependencies);\n\n const selectedSkills = await p.multiselect({\n message: 'Select the documentation skills to provide to your AI:',\n initialValues,\n options: SKILLS.map((skill) => ({\n value: skill,\n label: skill,\n hint: SKILLS_METADATA[skill],\n })),\n required: false,\n });\n\n if (\n p.isCancel(selectedSkills) ||\n !selectedSkills ||\n (selectedSkills as string[]).length === 0\n ) {\n p.cancel('Operation cancelled. No skills selected.');\n return;\n }\n\n const s = p.spinner();\n s.start('Installing skills...');\n\n try {\n const result = await installSkills(root, platform, selectedSkills);\n\n s.stop('Skills installed successfully');\n\n p.note(result, 'Success');\n } catch (error) {\n s.stop('Failed to install skills');\n p.log.error(error instanceof Error ? error.message : String(error));\n }\n\n p.outro('Intlayer skills initialization complete');\n};\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,kBACJA,iCAAU,QAAQ,aAAaC,0CAAmB,UAAU,KAAK,EAAE,KAChE,cAAc;CACb,OAAOA,0CAAmB,UAAU,gBAAgB;CACpD;AACF,EACF;AAEF,MAAa,mBAIRD,iCAAU,KAAK,cAAc;CAChC,OAAO;CACP,OAAOC,0CAAmB,UAAU;CACpC,MAAM,IAAIA,0CAAmB,UAAU,IAAI;AAC7C,EAAE;AAEF,MAAa,4BACX,gBAAgB,MAAM,EAAE,YAAY,MAAM,CAAC,GAAG;AAEhD,MAAM,mBAAmB,SAAyC;CAChE,IAAI;EACF,MAAM,sCAAuB,MAAM,cAAc;EACjD,IAAI,yBAAY,eAAe,GAAG,OAAO,CAAC;EAE1C,MAAM,EAAE,eAAe,CAAC,GAAG,kBAAkB,CAAC,MAAM,KAAK,gCAC1C,iBAAiB,OAAO,CACvC;EACA,OAAO;GAAE,GAAG;GAAc,GAAG;EAAgB;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;AACF;AAEA,MAAa,aAAa,OAAO,gBAA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ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/cli';\nimport { formatPath } from '@intlayer/chokidar/utils';\nimport {\n colon,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\ntype ListContentDeclarationOptions = {\n configOptions?: GetConfigurationOptions;\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listContentDeclarationRows = async (\n options?: ListContentDeclarationOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n\n await prepareIntlayer(config);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n\n const rows = Object.values(unmergedDictionariesRecord)\n .flat()\n .map((dictionary) => ({\n key: dictionary.key ?? '',\n path: options?.absolute\n ? (dictionary.filePath ?? 'Remote')\n : relative(config.system.baseDir, dictionary.filePath ?? 'Remote'),\n }));\n return rows;\n};\n\nexport const listContentDeclaration = async (\n options?: ListContentDeclarationOptions\n) => {\n const rows = await listContentDeclarationRows(options);\n\n if (options?.json) {\n console.log(JSON.stringify(rows));\n return;\n }\n\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n const lines = rows.map((row) =>\n [\n colon(` - ${colorizeKey(row.key)}`, {\n colSize: rows.map((row) => row.key.length),\n maxSize: 60,\n }),\n ' - ',\n formatPath(row.path),\n ].join('')\n );\n\n appLogger(`Content declaration files:`);\n\n lines.forEach((line) => {\n appLogger(line, {\n level: 'info',\n });\n });\n\n appLogger(`Total content declaration files: ${colorizeNumber(rows.length)}`);\n};\n"],"mappings":";;;;;;;;;;AAqBA,MAAa,6BAA6B,OACxC,YACG;CACH,MAAM,qDAA0B,SAAS,
|
|
1
|
+
{"version":3,"file":"listContentDeclaration.cjs","names":[],"sources":["../../src/listContentDeclaration.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { prepareIntlayer } from '@intlayer/chokidar/cli';\nimport { formatPath } from '@intlayer/chokidar/utils';\nimport {\n colon,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\ntype ListContentDeclarationOptions = {\n configOptions?: GetConfigurationOptions;\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listContentDeclarationRows = async (\n options?: ListContentDeclarationOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n\n await prepareIntlayer(config);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n\n const rows = Object.values(unmergedDictionariesRecord)\n .flat()\n .map((dictionary) => ({\n key: dictionary.key ?? '',\n path: options?.absolute\n ? (dictionary.filePath ?? 'Remote')\n : relative(config.system.baseDir, dictionary.filePath ?? 'Remote'),\n }));\n return rows;\n};\n\nexport const listContentDeclaration = async (\n options?: ListContentDeclarationOptions\n) => {\n const rows = await listContentDeclarationRows(options);\n\n if (options?.json) {\n console.log(JSON.stringify(rows));\n return;\n }\n\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n const lines = rows.map((row) =>\n [\n colon(` - ${colorizeKey(row.key)}`, {\n colSize: rows.map((row) => row.key.length),\n maxSize: 60,\n }),\n ' - ',\n formatPath(row.path),\n ].join('')\n );\n\n appLogger(`Content declaration files:`);\n\n lines.forEach((line) => {\n appLogger(line, {\n level: 'info',\n });\n });\n\n appLogger(`Total content declaration files: ${colorizeNumber(rows.length)}`);\n};\n"],"mappings":";;;;;;;;;;AAqBA,MAAa,6BAA6B,OACxC,YACG;CACH,MAAM,qDAA0B,SAAS,aAAa;CAEtD,kDAAsB,MAAM;CAE5B,MAAM,gGAAqD,MAAM;CAUjE,OARa,OAAO,OAAO,0BAA0B,EAClD,KAAK,EACL,KAAK,gBAAgB;EACpB,KAAK,WAAW,OAAO;EACvB,MAAM,SAAS,WACV,WAAW,YAAY,mCACf,OAAO,OAAO,SAAS,WAAW,YAAY,QAAQ;CACrE,EACQ;AACZ;AAEA,MAAa,yBAAyB,OACpC,YACG;CACH,MAAM,OAAO,MAAM,2BAA2B,OAAO;CAErD,IAAI,SAAS,MAAM;EACjB,QAAQ,IAAI,KAAK,UAAU,IAAI,CAAC;EAChC;CACF;CAGA,MAAM,kGAD0B,SAAS,aACL,CAAC;CAErC,MAAM,QAAQ,KAAK,KAAK,QACtB;qCACQ,+CAAkB,IAAI,GAAG,KAAK;GAClC,SAAS,KAAK,KAAK,QAAQ,IAAI,IAAI,MAAM;GACzC,SAAS;EACX,CAAC;EACD;2CACW,IAAI,IAAI;CACrB,EAAE,KAAK,EAAE,CACX;CAEA,UAAU,4BAA4B;CAEtC,MAAM,SAAS,SAAS;EACtB,UAAU,MAAM,EACd,OAAO,OACT,CAAC;CACH,CAAC;CAED,UAAU,gFAAmD,KAAK,MAAM,GAAG;AAC7E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listProjects.cjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { type ListProjectsOptions, listProjects } from '@intlayer/chokidar/cli';\n\nexport type ListProjectsCommandOptions = ListProjectsOptions & {\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listProjectsCommand = async (\n options?: ListProjectsCommandOptions\n) => {\n const { searchDir, projectsPath } = await listProjects(options);\n\n const projectsRelativePath = projectsPath\n .map((projectPath) =>\n options?.absolute ? projectPath : relative(searchDir, projectPath)\n )\n .map((projectPath) => (projectPath === '' ? '.' : projectPath));\n\n if (options?.json) {\n console.dir(projectsRelativePath, { depth: null, arrayLimit: null });\n return;\n }\n\n if (projectsPath.length === 0) {\n console.log('No Intlayer projects found.');\n return;\n }\n\n console.log(`Found ${projectsPath.length} Intlayer project(s):\\n`);\n projectsPath.forEach((project) => {\n console.log(` - ${project}`);\n });\n};\n"],"mappings":";;;;;;AAQA,MAAa,sBAAsB,OACjC,YACG;CACH,MAAM,EAAE,WAAW,iBAAiB,+CAAmB,
|
|
1
|
+
{"version":3,"file":"listProjects.cjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { type ListProjectsOptions, listProjects } from '@intlayer/chokidar/cli';\n\nexport type ListProjectsCommandOptions = ListProjectsOptions & {\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listProjectsCommand = async (\n options?: ListProjectsCommandOptions\n) => {\n const { searchDir, projectsPath } = await listProjects(options);\n\n const projectsRelativePath = projectsPath\n .map((projectPath) =>\n options?.absolute ? projectPath : relative(searchDir, projectPath)\n )\n .map((projectPath) => (projectPath === '' ? '.' : projectPath));\n\n if (options?.json) {\n console.dir(projectsRelativePath, { depth: null, arrayLimit: null });\n return;\n }\n\n if (projectsPath.length === 0) {\n console.log('No Intlayer projects found.');\n return;\n }\n\n console.log(`Found ${projectsPath.length} Intlayer project(s):\\n`);\n projectsPath.forEach((project) => {\n console.log(` - ${project}`);\n });\n};\n"],"mappings":";;;;;;AAQA,MAAa,sBAAsB,OACjC,YACG;CACH,MAAM,EAAE,WAAW,iBAAiB,+CAAmB,OAAO;CAE9D,MAAM,uBAAuB,aAC1B,KAAK,gBACJ,SAAS,WAAW,sCAAuB,WAAW,WAAW,CACnE,EACC,KAAK,gBAAiB,gBAAgB,KAAK,MAAM,WAAY;CAEhE,IAAI,SAAS,MAAM;EACjB,QAAQ,IAAI,sBAAsB;GAAE,OAAO;GAAM,YAAY;EAAK,CAAC;EACnE;CACF;CAEA,IAAI,aAAa,WAAW,GAAG;EAC7B,QAAQ,IAAI,6BAA6B;EACzC;CACF;CAEA,QAAQ,IAAI,SAAS,aAAa,OAAO,wBAAwB;CACjE,aAAa,SAAS,YAAY;EAChC,QAAQ,IAAI,OAAO,SAAS;CAC9B,CAAC;AACH"}
|