@intlayer/cli 9.6.0 → 9.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
- package/dist/cjs/auth/login.cjs +11 -0
- package/dist/cjs/auth/login.cjs.map +1 -1
- package/dist/cjs/auth/setupRepository.cjs +95 -0
- package/dist/cjs/auth/setupRepository.cjs.map +1 -0
- package/dist/cjs/cli.cjs +12 -6
- package/dist/cjs/cli.cjs.map +1 -1
- package/dist/cjs/editor.cjs +61 -32
- package/dist/cjs/editor.cjs.map +1 -1
- package/dist/cjs/fill/fill.cjs.map +1 -1
- package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
- package/dist/cjs/index.cjs +14 -0
- package/dist/cjs/init.cjs +165 -11
- package/dist/cjs/init.cjs.map +1 -1
- package/dist/cjs/liveSync.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/utils/checkAccess.cjs.map +1 -1
- package/dist/cjs/utils/detectGitRepository.cjs +87 -0
- package/dist/cjs/utils/detectGitRepository.cjs.map +1 -0
- package/dist/esm/IntlayerEventListener.mjs.map +1 -1
- package/dist/esm/auth/login.mjs +11 -0
- package/dist/esm/auth/login.mjs.map +1 -1
- package/dist/esm/auth/setupRepository.mjs +90 -0
- package/dist/esm/auth/setupRepository.mjs.map +1 -0
- package/dist/esm/cli.mjs +12 -6
- package/dist/esm/cli.mjs.map +1 -1
- package/dist/esm/editor.mjs +62 -34
- package/dist/esm/editor.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/translateDictionary.mjs.map +1 -1
- package/dist/esm/index.mjs +7 -3
- package/dist/esm/init.mjs +163 -13
- package/dist/esm/init.mjs.map +1 -1
- package/dist/esm/liveSync.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/utils/checkAccess.mjs.map +1 -1
- package/dist/esm/utils/detectGitRepository.mjs +85 -0
- package/dist/esm/utils/detectGitRepository.mjs.map +1 -0
- package/dist/types/IntlayerEventListener.d.ts +1 -1
- package/dist/types/IntlayerEventListener.d.ts.map +1 -1
- package/dist/types/auth/login.d.ts +5 -0
- package/dist/types/auth/login.d.ts.map +1 -1
- package/dist/types/auth/setupRepository.d.ts +25 -0
- package/dist/types/auth/setupRepository.d.ts.map +1 -0
- package/dist/types/editor.d.ts +10 -0
- package/dist/types/editor.d.ts.map +1 -1
- package/dist/types/fill/fill.d.ts +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 +7 -3
- package/dist/types/init.d.ts +19 -2
- package/dist/types/init.d.ts.map +1 -1
- package/dist/types/liveSync.d.ts.map +1 -1
- package/dist/types/reviewDoc/reviewDoc.d.ts +1 -1
- package/dist/types/reviewDoc/reviewDoc.d.ts.map +1 -1
- package/dist/types/reviewDoc/reviewDocBlockAware.d.ts +1 -2
- package/dist/types/reviewDoc/reviewDocBlockAware.d.ts.map +1 -1
- package/dist/types/translateDoc/types.d.ts +1 -1
- package/dist/types/utils/checkAccess.d.ts +2 -1
- package/dist/types/utils/checkAccess.d.ts.map +1 -1
- package/dist/types/utils/detectGitRepository.d.ts +34 -0
- package/dist/types/utils/detectGitRepository.d.ts.map +1 -0
- package/dist/types/utils/selectCmsEnvironment.d.ts +1 -1
- package/package.json +11 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translateDictionary.cjs","names":["colon","colorize","ANSIColors","colorizeNumber","getAppLogger","getAuthenticatedAPI","retryManager","getUnmergedDictionaries","getPerLocaleDictionary","colorizePath","basename","getFilterMissingTranslationsDictionary","excludeObjectFormat","formatLocale","chunkJSON","reconstructFromSingleChunk","extractTranslatableContent","verifyIdenticObjectFormat","reinsertTranslatedContent","mergeChunks","deepMergeContent","getMultilingualDictionary","insertContentInDictionary"],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport type { AIOptions } from '@intlayer/api';\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 { getUnmergedDictionaries } from '@intlayer/dictionaries-entry/unmerged';\nimport {\n chunkJSON,\n excludeObjectFormat,\n formatLocale,\n type JsonChunk,\n mergeChunks,\n reconstructFromSingleChunk,\n verifyIdenticObjectFormat,\n} from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\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/engine/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,YAA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G,EAAE,OAAGD,kCAAS,eAAe,KAAK,GAAGC,wBAAW,SAAS,EAAE,iBAAaC,wCAAe,UAAU,CAAC,EAAE,UAAMA,wCAAe,QAAQ,KAC9L,EACE,OAAO,QACT,CACF;EACF,kBAAkB,EAAE,YAClB,UACE,GAAG,KAAK,iBAAiB,OAAGF,kCAAS,sCAAsCC,wBAAW,GAAG,EAAE,OAAGD,kCAAS,eAAe,KAAK,GAAGC,wBAAW,SAAS,KAClJ,EACE,OAAO,QACT,CACF;CACJ,CACF,CAAC,CAAC;AAGJ"}
|
|
1
|
+
{"version":3,"file":"translateDictionary.cjs","names":["colon","colorize","ANSIColors","colorizeNumber","getAppLogger","getAuthenticatedAPI","retryManager","getUnmergedDictionaries","getPerLocaleDictionary","colorizePath","basename","getFilterMissingTranslationsDictionary","excludeObjectFormat","formatLocale","chunkJSON","reconstructFromSingleChunk","extractTranslatableContent","verifyIdenticObjectFormat","reinsertTranslatedContent","mergeChunks","deepMergeContent","getMultilingualDictionary","insertContentInDictionary"],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport type { AIConfig, AIOptions } from '@intlayer/ai';\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 { getUnmergedDictionaries } from '@intlayer/dictionaries-entry/unmerged';\nimport {\n chunkJSON,\n excludeObjectFormat,\n formatLocale,\n type JsonChunk,\n mergeChunks,\n reconstructFromSingleChunk,\n verifyIdenticObjectFormat,\n} from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\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/engine/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: chunkTranslatableDictionary,\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,WAAOA,+BACL;MACEC,kCAAS,KAAKC,wBAAW,SAAS;MAClCC,wCAAe,aAAa,CAAC;MAC7BF,kCAAS,IAAI,eAAeC,wBAAW,SAAS;MAChDD,kCAAS,KAAKC,wBAAW,SAAS;CACpC,CAAC,CAAC,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;AAEpB,MAAM,uBAAuB;AAC7B,IAAI,kBAAkB;A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B,QACzB,0BAA0B,WAC5B,uBAAuB,aAAa,SACpC;GACA,MAAM,qBAAqB,uBACxB,SAAU,MAAM,GAAG,CAAC,CACpB,MAAM,GAAG,EAAE;GAEd,MAAM,eAAe,mBAAmB,mBAAmB,SAAS;GAEpE,OAAO,KAAK,MACV,KAAK,UAAU;IACb,GAAG;IACH,kBAAkB;KAChB,GAAG;KACH,MAAM;KACN,QAAQ;IACV;GACF,CAAC,CAAC,CAAC,WACD,IAAI,OAAO,MAAM,aAAa,kBAAkB,GAAG,GACnD,WAAW,aAAa,MAC1B,CACF;EACF;EAEA,OAAO;GACL,GAAG;GACH;EACF;CACF,GACA;EACE,UAAU;EACV,OAAO;EACP,UAAU,EAAE,OAAO,SAAS,eAC1B,UACE,GAAG,KAAK,iBAAiB,OAAGT,kCAAS,UAAUC,wBAAW,GAAG,EAAE,OAAGD,kCAAS,eAAe,KAAK,GAAGC,wBAAW,SAAS,EAAE,iBAAaC,wCAAe,UAAU,CAAC,EAAE,UAAMA,wCAAe,QAAQ,KAC9L,EACE,OAAO,QACT,CACF;EACF,kBAAkB,EAAE,YAClB,UACE,GAAG,KAAK,iBAAiB,OAAGF,kCAAS,sCAAsCC,wBAAW,GAAG,EAAE,OAAGD,kCAAS,eAAe,KAAK,GAAGC,wBAAW,SAAS,KAClJ,EACE,OAAO,QACT,CACF;CACJ,CACF,CAAC,CAAC;AAGJ"}
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_auth_sessionToken = require('./auth/sessionToken.cjs');
|
|
3
|
+
const require_auth_login = require('./auth/login.cjs');
|
|
2
4
|
const require_initChromeExtension = require('./initChromeExtension.cjs');
|
|
3
5
|
const require_initInfra = require('./initInfra.cjs');
|
|
4
6
|
const require_initSkills = require('./initSkills.cjs');
|
|
@@ -10,10 +12,12 @@ const require_scan = require('./scan.cjs');
|
|
|
10
12
|
const require_cli = require('./cli.cjs');
|
|
11
13
|
const require_extract = require('./extract.cjs');
|
|
12
14
|
const require_bundle = require('./bundle.cjs');
|
|
15
|
+
const require_utils_checkConfigConsistency = require('./utils/checkConfigConsistency.cjs');
|
|
13
16
|
const require_utils_checkAccess = require('./utils/checkAccess.cjs');
|
|
14
17
|
const require_test_listMissingTranslations = require('./test/listMissingTranslations.cjs');
|
|
15
18
|
const require_test_test = require('./test/test.cjs');
|
|
16
19
|
const require_fill_fill = require('./fill/fill.cjs');
|
|
20
|
+
const require_IntlayerEventListener = require('./IntlayerEventListener.cjs');
|
|
17
21
|
const require_listContentDeclaration = require('./listContentDeclaration.cjs');
|
|
18
22
|
const require_liveSync = require('./liveSync.cjs');
|
|
19
23
|
const require_pull = require('./pull.cjs');
|
|
@@ -25,6 +29,7 @@ const require_translateDoc_translateDoc = require('./translateDoc/translateDoc.c
|
|
|
25
29
|
|
|
26
30
|
exports.BROWSER_EXTENSION_OPTIONS = require_initChromeExtension.BROWSER_EXTENSION_OPTIONS;
|
|
27
31
|
exports.CHROME_EXTENSION_URL = require_initChromeExtension.CHROME_EXTENSION_URL;
|
|
32
|
+
exports.CONTENT_LAYOUT_CHOICES = require_init.CONTENT_LAYOUT_CHOICES;
|
|
28
33
|
exports.DEFAULT_INIT_STEPS = require_init.DEFAULT_INIT_STEPS;
|
|
29
34
|
exports.ESLINT_CONFIG_FILES = require_init.ESLINT_CONFIG_FILES;
|
|
30
35
|
exports.EXTENSION_BROWSERS = require_initChromeExtension.EXTENSION_BROWSERS;
|
|
@@ -34,6 +39,7 @@ exports.INIT_STEP_COMMANDS = require_init.INIT_STEP_COMMANDS;
|
|
|
34
39
|
exports.INIT_STEP_GROUPS = require_init.INIT_STEP_GROUPS;
|
|
35
40
|
exports.INSTALL_SCRIPT_URL = require_initInfra.INSTALL_SCRIPT_URL;
|
|
36
41
|
exports.INSTALL_SCRIPT_URL_WINDOWS = require_initInfra.INSTALL_SCRIPT_URL_WINDOWS;
|
|
42
|
+
exports.IntlayerEventListener = require_IntlayerEventListener.IntlayerEventListener;
|
|
37
43
|
exports.LOCALE_ROUTING_CHOICES = require_init.LOCALE_ROUTING_CHOICES;
|
|
38
44
|
exports.MOZILLA_EXTENSION_URL = require_initChromeExtension.MOZILLA_EXTENSION_URL;
|
|
39
45
|
exports.OPT_IN_INIT_STEPS = require_init.OPT_IN_INIT_STEPS;
|
|
@@ -41,19 +47,24 @@ exports.PLATFORM_OPTIONS = require_initSkills.PLATFORM_OPTIONS;
|
|
|
41
47
|
exports.build = require_build.build;
|
|
42
48
|
exports.bundle = require_bundle.bundle;
|
|
43
49
|
exports.checkCMSAuth = require_utils_checkAccess.checkCMSAuth;
|
|
50
|
+
exports.checkConfigConsistency = require_utils_checkConfigConsistency.checkConfigConsistency;
|
|
51
|
+
exports.clearCliSessionToken = require_auth_sessionToken.clearCliSessionToken;
|
|
44
52
|
exports.dirname = require_cli.dirname;
|
|
45
53
|
exports.extract = require_extract.extract;
|
|
46
54
|
exports.fill = require_fill_fill.fill;
|
|
47
55
|
exports.findProjectRoot = require_init.findProjectRoot;
|
|
48
56
|
exports.getAuthenticatedAPI = require_utils_checkAccess.getAuthenticatedAPI;
|
|
57
|
+
exports.getContentInitOptions = require_init.getContentInitOptions;
|
|
49
58
|
exports.getInitOptionsForSteps = require_init.getInitOptionsForSteps;
|
|
50
59
|
exports.getInitialInitSteps = require_init.getInitialInitSteps;
|
|
51
60
|
exports.getProjectDependencies = require_init.getProjectDependencies;
|
|
61
|
+
exports.getRemoteEditorRunners = require_editor.getRemoteEditorRunners;
|
|
52
62
|
exports.getRoutingInitOptions = require_init.getRoutingInitOptions;
|
|
53
63
|
exports.init = require_init.init;
|
|
54
64
|
exports.initChromeExtension = require_initChromeExtension.initChromeExtension;
|
|
55
65
|
exports.initCms = require_init.initCms;
|
|
56
66
|
exports.initInfra = require_initInfra.initInfra;
|
|
67
|
+
exports.initRepository = require_init.initRepository;
|
|
57
68
|
exports.initSkills = require_initSkills.initSkills;
|
|
58
69
|
exports.initSteps = require_init.initSteps;
|
|
59
70
|
exports.isEslintInstalled = require_init.isEslintInstalled;
|
|
@@ -63,6 +74,8 @@ exports.listMissingTranslations = require_test_listMissingTranslations.listMissi
|
|
|
63
74
|
exports.listMissingTranslationsWithConfig = require_test_listMissingTranslations.listMissingTranslationsWithConfig;
|
|
64
75
|
exports.listProjectsCommand = require_listProjects.listProjectsCommand;
|
|
65
76
|
exports.liveSync = require_liveSync.liveSync;
|
|
77
|
+
exports.login = require_auth_login.login;
|
|
78
|
+
exports.parseContentLayoutChoice = require_init.parseContentLayoutChoice;
|
|
66
79
|
exports.parseExtensionBrowsers = require_initChromeExtension.parseExtensionBrowsers;
|
|
67
80
|
exports.parseInfraMode = require_initInfra.parseInfraMode;
|
|
68
81
|
exports.parseLocaleRoutingChoice = require_init.parseLocaleRoutingChoice;
|
|
@@ -72,6 +85,7 @@ exports.promptPlatform = require_initSkills.promptPlatform;
|
|
|
72
85
|
exports.pull = require_pull.pull;
|
|
73
86
|
exports.push = require_push_push.push;
|
|
74
87
|
exports.pushConfig = require_pushConfig.pushConfig;
|
|
88
|
+
exports.readCliSessionToken = require_auth_sessionToken.readCliSessionToken;
|
|
75
89
|
exports.resolvePlatformWithoutPrompt = require_initSkills.resolvePlatformWithoutPrompt;
|
|
76
90
|
exports.resolveProjectRoot = require_init.resolveProjectRoot;
|
|
77
91
|
exports.reviewDoc = require_reviewDoc_reviewDoc.reviewDoc;
|
package/dist/cjs/init.cjs
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_auth_login = require('./auth/login.cjs');
|
|
3
|
+
const require_auth_setupRepository = require('./auth/setupRepository.cjs');
|
|
3
4
|
const require_loadPrompts = require('./loadPrompts.cjs');
|
|
4
5
|
const require_utils_isInteractiveTerminal = require('./utils/isInteractiveTerminal.cjs');
|
|
5
6
|
const require_utils_parseChoice = require('./utils/parseChoice.cjs');
|
|
6
7
|
const require_initChromeExtension = require('./initChromeExtension.cjs');
|
|
7
8
|
const require_initInfra = require('./initInfra.cjs');
|
|
8
9
|
const require_initSkills = require('./initSkills.cjs');
|
|
10
|
+
const require_utils_detectGitRepository = require('./utils/detectGitRepository.cjs');
|
|
9
11
|
const require_initMCP = require('./initMCP.cjs');
|
|
10
12
|
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
11
13
|
let node_fs = require("node:fs");
|
|
@@ -41,7 +43,7 @@ const DEFAULT_INIT_STEPS = ["packages", "projectSetup"];
|
|
|
41
43
|
*/
|
|
42
44
|
const INIT_STEP_COMMANDS = {
|
|
43
45
|
packages: "intlayer init packages",
|
|
44
|
-
projectSetup: "intlayer init project [--routing <routing>]",
|
|
46
|
+
projectSetup: "intlayer init project [--routing <routing>] [--content <layout>] [--content-format <format>] [--message-format <format>]",
|
|
45
47
|
githubActions: "intlayer init github-actions",
|
|
46
48
|
vscodeExtension: "intlayer init vscode-extension",
|
|
47
49
|
eslint: "intlayer init eslint",
|
|
@@ -50,6 +52,7 @@ const INIT_STEP_COMMANDS = {
|
|
|
50
52
|
mcp: "intlayer init mcp [--platform <platform>] [--transport <stdio|sse>]",
|
|
51
53
|
lsp: "intlayer init lsp",
|
|
52
54
|
cms: "intlayer init cms",
|
|
55
|
+
repository: "intlayer init repository",
|
|
53
56
|
infra: "intlayer init infra --mode <desktop|docker|compose>"
|
|
54
57
|
};
|
|
55
58
|
/**
|
|
@@ -88,6 +91,18 @@ const initCms = async (projectRoot) => {
|
|
|
88
91
|
onCredentials: (credentials) => (0, _intlayer_engine_cli.setupCmsCredentials)(root, credentials)
|
|
89
92
|
});
|
|
90
93
|
};
|
|
94
|
+
/**
|
|
95
|
+
* Connects the git repository of the project to its CMS project (and sets
|
|
96
|
+
* its build settings) in the browser, pre-filled with the `origin` remote.
|
|
97
|
+
*/
|
|
98
|
+
const initRepository = async (projectRoot) => {
|
|
99
|
+
const root = resolveProjectRoot(projectRoot);
|
|
100
|
+
const p = await require_loadPrompts.loadPrompts();
|
|
101
|
+
const detectedRepository = require_utils_detectGitRepository.detectGitRepository(root);
|
|
102
|
+
p.log.info(detectedRepository ? `Detected repository: ${detectedRepository.provider} ${detectedRepository.owner}/${detectedRepository.repository}` : "No supported git remote detected: pick the repository in the browser.");
|
|
103
|
+
p.log.info("Opening your browser to connect the repository...");
|
|
104
|
+
await require_auth_setupRepository.setupRepository({ detectedRepository });
|
|
105
|
+
};
|
|
91
106
|
/** Explains why `--interactive` cannot run, and what to run instead. */
|
|
92
107
|
const getNoTerminalMessage = () => [
|
|
93
108
|
"`intlayer init --interactive` needs a terminal to answer its prompts (none is attached, e.g. when run by an AI agent or in CI).",
|
|
@@ -148,15 +163,23 @@ const INIT_STEP_GROUPS = {
|
|
|
148
163
|
hint: "go-to-definition from keys to .content files"
|
|
149
164
|
}
|
|
150
165
|
],
|
|
151
|
-
CMS: [
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
166
|
+
CMS: [
|
|
167
|
+
{
|
|
168
|
+
value: "cms",
|
|
169
|
+
label: "CMS",
|
|
170
|
+
hint: "log in through your browser, then store the credentials in your .env"
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
value: "repository",
|
|
174
|
+
label: "Git repository",
|
|
175
|
+
hint: "connect the git repository to the CMS project and set its build settings (GitHub, GitLab, Bitbucket, Codeberg, Gitee)"
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
value: "infra",
|
|
179
|
+
label: "Infrastructure (desktop app / self-hosting)",
|
|
180
|
+
hint: "install the desktop app, or self-host with Docker (all-in-one or Compose)"
|
|
181
|
+
}
|
|
182
|
+
]
|
|
160
183
|
};
|
|
161
184
|
/** Locale routing strategies offered by the interactive init flow. */
|
|
162
185
|
const ROUTING_OPTIONS = [
|
|
@@ -198,6 +221,83 @@ const getRoutingInitOptions = (choice) => choice === "none" ? {
|
|
|
198
221
|
routingMode: choice,
|
|
199
222
|
enableProxy: true
|
|
200
223
|
};
|
|
224
|
+
/** Content declaration layouts offered by the interactive init flow. */
|
|
225
|
+
const CONTENT_LAYOUT_OPTIONS = [
|
|
226
|
+
{
|
|
227
|
+
value: "multilingual",
|
|
228
|
+
label: "Multilingual content declaration",
|
|
229
|
+
hint: "/**/{fileName}.content.{ts,json} — every locale in one file"
|
|
230
|
+
},
|
|
231
|
+
{
|
|
232
|
+
value: "per-locale",
|
|
233
|
+
label: "Per-locale content declaration",
|
|
234
|
+
hint: "/**/{fileName}.{locale}.content.{ts,json}"
|
|
235
|
+
},
|
|
236
|
+
{
|
|
237
|
+
value: "centralized",
|
|
238
|
+
label: "Centralized",
|
|
239
|
+
hint: "/locales/{locale}.{json,po}"
|
|
240
|
+
},
|
|
241
|
+
{
|
|
242
|
+
value: "namespaces",
|
|
243
|
+
label: "Namespaces",
|
|
244
|
+
hint: "/locales/{locale}/{namespace}.{json,po}"
|
|
245
|
+
}
|
|
246
|
+
];
|
|
247
|
+
/** Labels of the content formats offered by the interactive init flow. */
|
|
248
|
+
const CONTENT_FORMAT_LABELS = {
|
|
249
|
+
ts: "TypeScript (.ts)",
|
|
250
|
+
json: "JSON (.json)",
|
|
251
|
+
po: "Gettext (.po)"
|
|
252
|
+
};
|
|
253
|
+
/** Labels of the JSON catalog message formats, in display order. */
|
|
254
|
+
const CATALOG_MESSAGE_FORMAT_OPTIONS = {
|
|
255
|
+
icu: {
|
|
256
|
+
label: "ICU",
|
|
257
|
+
hint: "{count, plural, one {# item} other {# items}}"
|
|
258
|
+
},
|
|
259
|
+
i18next: {
|
|
260
|
+
label: "i18next",
|
|
261
|
+
hint: "{{count}} item, key_one / key_other"
|
|
262
|
+
},
|
|
263
|
+
"vue-i18n": {
|
|
264
|
+
label: "vue-i18n",
|
|
265
|
+
hint: "{count} item | {count} items"
|
|
266
|
+
},
|
|
267
|
+
intlayer: {
|
|
268
|
+
label: "Intlayer",
|
|
269
|
+
hint: "Intlayer dictionary content"
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
/** Content layouts accepted by `--content`. */
|
|
273
|
+
const CONTENT_LAYOUT_CHOICES = CONTENT_LAYOUT_OPTIONS.map((option) => option.value);
|
|
274
|
+
/** Validates a `--content` value, throwing on an unknown layout. */
|
|
275
|
+
const parseContentLayoutChoice = (value) => require_utils_parseChoice.parseChoice(value, CONTENT_LAYOUT_CHOICES, "--content");
|
|
276
|
+
/** Whether a layout + format pair produces a JSON catalog (sync plugin). */
|
|
277
|
+
const isJsonCatalog = (layout, format) => (layout === "centralized" || layout === "namespaces") && format === "json";
|
|
278
|
+
/**
|
|
279
|
+
* Validates `--content` / `--content-format` / `--message-format` and maps
|
|
280
|
+
* them to the init options. The format must be one the layout accepts, and the
|
|
281
|
+
* message format only applies to JSON catalogs.
|
|
282
|
+
*/
|
|
283
|
+
const getContentInitOptions = (layoutValue, formatValue, messageFormatValue) => {
|
|
284
|
+
if (!layoutValue) {
|
|
285
|
+
if (formatValue || messageFormatValue) throw new Error("--content-format and --message-format require --content.");
|
|
286
|
+
return {};
|
|
287
|
+
}
|
|
288
|
+
const contentLayout = parseContentLayoutChoice(layoutValue);
|
|
289
|
+
const contentFormat = formatValue ? require_utils_parseChoice.parseChoice(formatValue, _intlayer_engine_cli.CONTENT_FORMATS_BY_LAYOUT[contentLayout], "--content-format") : void 0;
|
|
290
|
+
if (!messageFormatValue) return {
|
|
291
|
+
contentLayout,
|
|
292
|
+
contentFormat
|
|
293
|
+
};
|
|
294
|
+
if (!isJsonCatalog(contentLayout, contentFormat ?? "json")) throw new Error("--message-format only applies to JSON catalogs (--content centralized | namespaces with json).");
|
|
295
|
+
return {
|
|
296
|
+
contentLayout,
|
|
297
|
+
contentFormat,
|
|
298
|
+
contentMessageFormat: require_utils_parseChoice.parseChoice(messageFormatValue, _intlayer_engine_cli.CATALOG_MESSAGE_FORMATS, "--message-format")
|
|
299
|
+
};
|
|
300
|
+
};
|
|
201
301
|
/** Known ESLint and oxlint configuration file names. */
|
|
202
302
|
const ESLINT_CONFIG_FILES = [
|
|
203
303
|
"eslint.config.js",
|
|
@@ -289,10 +389,59 @@ const runInteractiveInit = async (root, baseOptions) => {
|
|
|
289
389
|
}
|
|
290
390
|
routingOptions = getRoutingInitOptions(selectedRouting);
|
|
291
391
|
}
|
|
392
|
+
let contentOptions = {};
|
|
393
|
+
if (steps.includes("projectSetup") && baseOptions?.contentLayout === void 0 && !hasCompatLib) {
|
|
394
|
+
const contentLayout = await p.select({
|
|
395
|
+
message: "How do you want to declare your content?",
|
|
396
|
+
options: CONTENT_LAYOUT_OPTIONS,
|
|
397
|
+
initialValue: "multilingual"
|
|
398
|
+
});
|
|
399
|
+
if (p.isCancel(contentLayout)) {
|
|
400
|
+
p.cancel("Operation cancelled.");
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const acceptedFormats = _intlayer_engine_cli.CONTENT_FORMATS_BY_LAYOUT[contentLayout];
|
|
404
|
+
const hasTypeScript = (0, node_fs.existsSync)((0, node_path.join)(root, "tsconfig.json"));
|
|
405
|
+
const contentFormat = await p.select({
|
|
406
|
+
message: "Which format for your content?",
|
|
407
|
+
options: acceptedFormats.map((format) => ({
|
|
408
|
+
value: format,
|
|
409
|
+
label: CONTENT_FORMAT_LABELS[format]
|
|
410
|
+
})),
|
|
411
|
+
initialValue: acceptedFormats.includes("ts") && !hasTypeScript ? "json" : acceptedFormats[0]
|
|
412
|
+
});
|
|
413
|
+
if (p.isCancel(contentFormat)) {
|
|
414
|
+
p.cancel("Operation cancelled.");
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
contentOptions = {
|
|
418
|
+
contentLayout,
|
|
419
|
+
contentFormat
|
|
420
|
+
};
|
|
421
|
+
if (isJsonCatalog(contentLayout, contentFormat)) {
|
|
422
|
+
const contentMessageFormat = await p.select({
|
|
423
|
+
message: "Which message format do your JSON catalogs use?",
|
|
424
|
+
options: _intlayer_engine_cli.CATALOG_MESSAGE_FORMATS.map((messageFormat) => ({
|
|
425
|
+
value: messageFormat,
|
|
426
|
+
...CATALOG_MESSAGE_FORMAT_OPTIONS[messageFormat]
|
|
427
|
+
})),
|
|
428
|
+
initialValue: _intlayer_engine_cli.CATALOG_MESSAGE_FORMATS[0]
|
|
429
|
+
});
|
|
430
|
+
if (p.isCancel(contentMessageFormat)) {
|
|
431
|
+
p.cancel("Operation cancelled.");
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
contentOptions = {
|
|
435
|
+
...contentOptions,
|
|
436
|
+
contentMessageFormat
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
}
|
|
292
440
|
const options = {
|
|
293
441
|
...getInitOptionsForSteps(steps, {
|
|
294
442
|
...baseOptions,
|
|
295
|
-
...routingOptions
|
|
443
|
+
...routingOptions,
|
|
444
|
+
...contentOptions
|
|
296
445
|
}),
|
|
297
446
|
skipFinalMessage: true
|
|
298
447
|
};
|
|
@@ -302,6 +451,7 @@ const runInteractiveInit = async (root, baseOptions) => {
|
|
|
302
451
|
if (steps.includes("infra")) await require_initInfra.initInfra();
|
|
303
452
|
if (steps.includes("chromeExtension")) await require_initChromeExtension.initChromeExtension();
|
|
304
453
|
if (steps.includes("cms")) await initCms(root);
|
|
454
|
+
if (steps.includes("repository")) await initRepository(root);
|
|
305
455
|
p.outro("Intlayer initialization complete");
|
|
306
456
|
if (guideUrl) (0, _intlayer_engine_cli.logInitSuccessMessage)(guideUrl);
|
|
307
457
|
};
|
|
@@ -324,6 +474,7 @@ const init = async (projectRoot, options, interactive) => {
|
|
|
324
474
|
};
|
|
325
475
|
|
|
326
476
|
//#endregion
|
|
477
|
+
exports.CONTENT_LAYOUT_CHOICES = CONTENT_LAYOUT_CHOICES;
|
|
327
478
|
exports.DEFAULT_INIT_STEPS = DEFAULT_INIT_STEPS;
|
|
328
479
|
exports.ESLINT_CONFIG_FILES = ESLINT_CONFIG_FILES;
|
|
329
480
|
exports.INIT_STEP_COMMANDS = INIT_STEP_COMMANDS;
|
|
@@ -331,14 +482,17 @@ exports.INIT_STEP_GROUPS = INIT_STEP_GROUPS;
|
|
|
331
482
|
exports.LOCALE_ROUTING_CHOICES = LOCALE_ROUTING_CHOICES;
|
|
332
483
|
exports.OPT_IN_INIT_STEPS = OPT_IN_INIT_STEPS;
|
|
333
484
|
exports.findProjectRoot = findProjectRoot;
|
|
485
|
+
exports.getContentInitOptions = getContentInitOptions;
|
|
334
486
|
exports.getInitOptionsForSteps = getInitOptionsForSteps;
|
|
335
487
|
exports.getInitialInitSteps = getInitialInitSteps;
|
|
336
488
|
exports.getProjectDependencies = getProjectDependencies;
|
|
337
489
|
exports.getRoutingInitOptions = getRoutingInitOptions;
|
|
338
490
|
exports.init = init;
|
|
339
491
|
exports.initCms = initCms;
|
|
492
|
+
exports.initRepository = initRepository;
|
|
340
493
|
exports.initSteps = initSteps;
|
|
341
494
|
exports.isEslintInstalled = isEslintInstalled;
|
|
495
|
+
exports.parseContentLayoutChoice = parseContentLayoutChoice;
|
|
342
496
|
exports.parseLocaleRoutingChoice = parseLocaleRoutingChoice;
|
|
343
497
|
exports.resolveProjectRoot = resolveProjectRoot;
|
|
344
498
|
//# sourceMappingURL=init.cjs.map
|
package/dist/cjs/init.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.cjs","names":["resolve","existsSync","join","initIntlayer","loadPrompts","login","setupCmsCredentials","parseChoice","hasLintTooling","readFileSync","detectCompatI18nLibraries","hasUrlRoutingFramework","initSkills","initMCP","initInfra","initChromeExtension","isInteractiveTerminal"],"sources":["../../src/init.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport {\n detectCompatI18nLibraries,\n hasLintTooling,\n hasUrlRoutingFramework,\n type InitOptions,\n initIntlayer,\n logInitSuccessMessage,\n type RoutingMode,\n setupCmsCredentials,\n} from '@intlayer/engine/cli';\nimport { login } from './auth/login';\nimport { initChromeExtension } from './initChromeExtension';\nimport { initInfra } from './initInfra';\nimport { initMCP } from './initMCP';\nimport { initSkills } from './initSkills';\nimport { loadPrompts } from './loadPrompts';\nimport { isInteractiveTerminal } from './utils/isInteractiveTerminal';\nimport { parseChoice } from './utils/parseChoice';\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\n/** Resolves the project root from `--project-root`, else the working directory. */\nexport const resolveProjectRoot = (projectRoot?: string): string =>\n findProjectRoot(projectRoot ? resolve(projectRoot) : process.cwd());\n\n/** Individually selectable setup steps exposed by the interactive init flow. */\nexport type InitStep =\n | 'packages'\n | 'githubActions'\n | 'projectSetup'\n | 'vscodeExtension'\n | 'lsp'\n | 'eslint'\n | 'skills'\n | 'mcp'\n | 'infra'\n | 'cms'\n | 'chromeExtension';\n\n/** A checkbox entry of the interactive init flow. */\nexport type InitStepOption = {\n value: InitStep;\n label: string;\n hint: string;\n};\n\n/**\n * Steps shown but not pre-selected. The infrastructure installer touches the\n * machine (downloads an app, pulls Docker images) and browser extensions open external URLs\n * rather than modifying the project, so they must be an explicit choice.\n */\nexport const OPT_IN_INIT_STEPS: InitStep[] = ['infra', 'chromeExtension'];\n\n/**\n * Steps run by `intlayer init` without `--interactive`: install the packages\n * and set up the framework. Every other step has its own command\n * ({@link INIT_STEP_COMMANDS}), so nothing outside the app code is touched\n * unless asked for.\n */\nexport const DEFAULT_INIT_STEPS: InitStep[] = ['packages', 'projectSetup'];\n\n/**\n * Command running each interactive step on its own, without prompts when every\n * value is passed as a flag. Printed when `--interactive` has no terminal.\n */\nexport const INIT_STEP_COMMANDS: Record<InitStep, string> = {\n packages: 'intlayer init packages',\n projectSetup: 'intlayer init project [--routing <routing>]',\n githubActions: 'intlayer init github-actions',\n vscodeExtension: 'intlayer init vscode-extension',\n eslint: 'intlayer init eslint',\n chromeExtension: 'intlayer init extension [--browser <chrome|firefox>]',\n skills: 'intlayer init skills [--platform <platform>] [--skills <skills...>]',\n mcp: 'intlayer init mcp [--platform <platform>] [--transport <stdio|sse>]',\n lsp: 'intlayer init lsp',\n cms: 'intlayer init cms',\n infra: 'intlayer init infra --mode <desktop|docker|compose>',\n};\n\n/**\n * Maps setup steps to the {@link initIntlayer} options: every step handled by\n * `initIntlayer` that is not listed is skipped. Explicit `--no-*` flags in\n * `baseOptions` still win over a listed step.\n */\nexport const getInitOptionsForSteps = (\n steps: InitStep[],\n baseOptions?: InitOptions\n): InitOptions => ({\n ...baseOptions,\n noInstallPackages:\n baseOptions?.noInstallPackages || !steps.includes('packages'),\n // The `.gitignore` entry is tied to project setup.\n noGitignore: baseOptions?.noGitignore || !steps.includes('projectSetup'),\n noGithubActions:\n baseOptions?.noGithubActions || !steps.includes('githubActions'),\n noFrameworkSetup:\n baseOptions?.noFrameworkSetup || !steps.includes('projectSetup'),\n noVscodeExtension:\n baseOptions?.noVscodeExtension || !steps.includes('vscodeExtension'),\n noLsp: baseOptions?.noLsp || !steps.includes('lsp'),\n noEslint: baseOptions?.noEslint || !steps.includes('eslint'),\n // The documentation link only matters once the project itself is set up.\n skipFinalMessage:\n baseOptions?.skipFinalMessage || !steps.includes('projectSetup'),\n});\n\n/**\n * Runs the given {@link initIntlayer} steps only (packages, project setup, CI,\n * VS Code extension, LSP, lint rules). Backs `intlayer init` and its\n * single-step subcommands.\n */\nexport const initSteps = async (\n projectRoot: string | undefined,\n steps: InitStep[],\n options?: InitOptions\n): Promise<void> => {\n await initIntlayer(\n resolveProjectRoot(projectRoot),\n getInitOptionsForSteps(steps, options)\n );\n};\n\n/**\n * Logs in to the Intlayer CMS through the browser, then stores the access-key\n * credentials in `.env` and enables the editor in the config file.\n */\nexport const initCms = async (projectRoot?: string): Promise<void> => {\n const root = resolveProjectRoot(projectRoot);\n const p = await loadPrompts();\n\n p.log.info('Opening your browser to log in to the Intlayer CMS...');\n // `exitAfter: false` keeps the process alive so the flow can finish; the\n // credentials are persisted to `.env` and the editor enabled in the config.\n await login({\n exitAfter: false,\n onCredentials: (credentials) => setupCmsCredentials(root, credentials),\n });\n};\n\n/** Explains why `--interactive` cannot run, and what to run instead. */\nconst getNoTerminalMessage = (): string =>\n [\n '`intlayer init --interactive` needs a terminal to answer its prompts (none is attached, e.g. when run by an AI agent or in CI).',\n 'Run the steps directly instead:',\n ' intlayer init (installs the packages and sets up the framework)',\n ...Object.values(INIT_STEP_COMMANDS).map((command) => ` ${command}`),\n ].join('\\n');\n\n/** Grouped checkbox entries of the interactive init flow, in display order. */\nexport const INIT_STEP_GROUPS: Record<string, InitStepOption[]> = {\n Codebase: [\n {\n value: 'packages',\n label: 'Install & upgrade packages',\n hint: 'install missing Intlayer dependencies and upgrade outdated ones',\n },\n {\n value: 'projectSetup',\n label: 'Project setup',\n hint: 'intlayer config, tsconfig, bundler plugin, middleware/proxy and providers in layout/page',\n },\n {\n value: 'githubActions',\n label: 'CI/CD (GitHub Actions)',\n hint: 'scaffold the fill and test workflows that run on every pull request (covers every project in a monorepo)',\n },\n ],\n DevTools: [\n {\n value: 'vscodeExtension',\n label: 'VS Code extension',\n hint: 'recommend the Intlayer extension',\n },\n {\n value: 'eslint',\n label: 'Lint rules (ESLint / oxlint)',\n hint: 'flag hardcoded text and dynamic calls the compiler cannot optimize',\n },\n {\n value: 'chromeExtension',\n label: 'Chrome extension',\n hint: 'for audit, debug and analysis purpose',\n },\n ],\n 'Coding assistant': [\n {\n value: 'skills',\n label: 'AI skills',\n hint: 'install the Intlayer documentation as agent skills',\n },\n {\n value: 'mcp',\n label: 'MCP server',\n hint: 'configure the Intlayer MCP server',\n },\n {\n value: 'lsp',\n label: 'Editor LSP',\n hint: 'go-to-definition from keys to .content files',\n },\n ],\n CMS: [\n {\n value: 'cms',\n label: 'CMS',\n hint: 'log in through your browser, then store the credentials in your .env',\n },\n {\n value: 'infra',\n label: 'Infrastructure (desktop app / self-hosting)',\n hint: 'install the desktop app, or self-host with Docker (all-in-one or Compose)',\n },\n ],\n};\n\n/**\n * Locale routing choice: a `routing.mode` served through the locale proxy, or\n * `none` to leave routing to the app (`no-prefix` with the proxy disabled).\n */\nexport type LocaleRoutingChoice = RoutingMode | 'none';\n\n/** Locale routing strategies offered by the interactive init flow. */\nconst ROUTING_OPTIONS: Array<{\n value: LocaleRoutingChoice;\n label: string;\n hint: string;\n}> = [\n {\n value: 'prefix-no-default',\n label: 'Prefix all except the default locale',\n hint: '/about, /fr/about (default)',\n },\n {\n value: 'prefix-all',\n label: 'Prefix all locales',\n hint: '/en/about, /fr/about',\n },\n {\n value: 'no-prefix',\n label: 'No locale in the URL',\n hint: '/about',\n },\n {\n value: 'search-params',\n label: 'Use a search parameter',\n hint: '/about?locale=fr',\n },\n {\n value: 'none',\n label: 'No locale routing',\n hint: 'no proxy, no locale route segment — handle the locale yourself',\n },\n];\n\n/** Locale routing choices accepted by `--routing`. */\nexport const LOCALE_ROUTING_CHOICES = ROUTING_OPTIONS.map(\n (option) => option.value\n);\n\n/** Validates a `--routing` value, throwing on an unknown choice. */\nexport const parseLocaleRoutingChoice = (value: string): LocaleRoutingChoice =>\n parseChoice(value, LOCALE_ROUTING_CHOICES, '--routing');\n\n/** Maps a routing choice to the init options it sets. */\nexport const getRoutingInitOptions = (\n choice: LocaleRoutingChoice\n): Pick<InitOptions, 'routingMode' | 'enableProxy'> =>\n choice === 'none'\n ? { routingMode: 'no-prefix', enableProxy: false }\n : { routingMode: choice, enableProxy: true };\n\n/** Known ESLint and oxlint configuration file names. */\nexport const ESLINT_CONFIG_FILES = [\n 'eslint.config.js',\n 'eslint.config.mjs',\n 'eslint.config.cjs',\n 'eslint.config.ts',\n 'eslint.config.mts',\n 'eslint.config.cts',\n '.eslintrc.js',\n '.eslintrc.cjs',\n '.eslintrc.yaml',\n '.eslintrc.yml',\n '.eslintrc.json',\n '.eslintrc',\n '.oxlintrc.json',\n];\n\n/**\n * Checks whether ESLint or a compatible linter (oxlint) is installed or\n * configured in the project.\n */\nexport const isEslintInstalled = (\n dependencies: Record<string, string>,\n root?: string\n): boolean => {\n if (hasLintTooling(dependencies)) return true;\n if (dependencies.eslint || dependencies.oxlint) return true;\n\n if (root) {\n return ESLINT_CONFIG_FILES.some((file) => existsSync(join(root, file)));\n }\n\n return false;\n};\n\n/**\n * Computes the initial setup steps selected by default in the interactive prompt.\n * Steps like infrastructure and browser extension require opt-in, while\n * eslint is preselected only if installed on the project.\n */\nexport const getInitialInitSteps = (\n dependencies: Record<string, string>,\n root?: string\n): InitStep[] => {\n const isEslintPresent = isEslintInstalled(dependencies, root);\n\n return Object.values(INIT_STEP_GROUPS)\n .flat()\n .map((option) => option.value)\n .filter((step) => {\n if (OPT_IN_INIT_STEPS.includes(step)) return false;\n if (step === 'eslint' && !isEslintPresent) return false;\n return true;\n });\n};\n\n/** Reads the merged dependencies of the project at `root`. */\nexport const getProjectDependencies = (\n root: string\n): Record<string, string> => {\n try {\n const packageJsonPath = join(root, 'package.json');\n if (!existsSync(packageJsonPath)) return {};\n const { dependencies = {}, devDependencies = {} } = JSON.parse(\n readFileSync(packageJsonPath, 'utf-8')\n );\n return { ...dependencies, ...devDependencies };\n } catch {\n return {};\n }\n};\n\n/**\n * Runs `init` in interactive mode: prompts the user with a checkbox of setup\n * steps, then forwards the selection to {@link initIntlayer} (packages, GitHub\n * Actions, VS Code extension, LSP) and runs the dedicated skills/MCP installers\n * for the steps that own their own prompts. The `.gitignore` entry is not\n * offered as a checkbox — it is always added (unless `--no-gitignore` is set).\n */\nconst runInteractiveInit = async (\n root: string,\n baseOptions?: InitOptions\n): Promise<void> => {\n const p = await loadPrompts();\n\n p.intro('Initialize Intlayer');\n\n const projectDependencies = getProjectDependencies(root);\n\n const selected = await p.groupMultiselect<InitStep>({\n message: 'Select what you want to set up:',\n options: INIT_STEP_GROUPS,\n initialValues: getInitialInitSteps(projectDependencies, root),\n required: false,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const steps = selected as InitStep[];\n\n // Compat i18n library detection — never asked, always derived from the\n // installed packages. `detectMissingIntlayerPackages` reads the very same\n // dependency map to schedule the compat adapter, the sync plugin and the\n // catalog template, so a project without any of those packages is simply set\n // up on Intlayer alone.\n const detectedCompatLibraries =\n detectCompatI18nLibraries(projectDependencies);\n const hasCompatLib = detectedCompatLibraries.length > 0;\n\n if (hasCompatLib) {\n p.log.info(\n `Detected existing i18n ${detectedCompatLibraries.length > 1 ? 'libraries' : 'library'}: ${detectedCompatLibraries.join(', ')} — the matching Intlayer compat adapter and catalog sync will be set up.`\n );\n }\n\n // Locale routing → `routing.mode` + `routing.enableProxy` in the config, and\n // the route segment the framework scaffolding creates. Only asked for web\n // frontends; projects without URL routing (backend, React Native / Expo) keep\n // only `routing.storage` in a freshly created config. Skipped for compat\n // i18n libraries, which keep their own routing.\n let routingOptions: Pick<InitOptions, 'routingMode' | 'enableProxy'> = {};\n\n if (\n steps.includes('projectSetup') &&\n baseOptions?.routingMode === undefined &&\n !hasCompatLib &&\n hasUrlRoutingFramework(projectDependencies)\n ) {\n const selectedRouting = await p.select<LocaleRoutingChoice>({\n message: 'How should the locale appear in your URLs?',\n options: ROUTING_OPTIONS,\n initialValue: 'prefix-no-default',\n });\n\n if (p.isCancel(selectedRouting)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n routingOptions = getRoutingInitOptions(selectedRouting);\n }\n\n const options: InitOptions = {\n ...getInitOptionsForSteps(steps, { ...baseOptions, ...routingOptions }),\n skipFinalMessage: true,\n };\n\n const { guideUrl } = await initIntlayer(root, options);\n\n // Skills ask for the platform after the skill selection; MCP reuses it.\n const skillsPlatform = steps.includes('skills')\n ? await initSkills(root)\n : undefined;\n\n if (steps.includes('mcp')) {\n await initMCP(root, { platform: skillsPlatform });\n }\n\n // Delegated to the hosted install script, which owns its own menu.\n if (steps.includes('infra')) {\n await initInfra();\n }\n\n if (steps.includes('chromeExtension')) {\n await initChromeExtension();\n }\n\n // CMS / visual editor runs last: the browser login persists the access-key\n // credentials to `.env` and enables the editor in the config file. Kept last\n // so the browser flow does not interrupt setup.\n if (steps.includes('cms')) {\n await initCms(root);\n }\n\n p.outro('Intlayer initialization complete');\n\n if (guideUrl) {\n logInitSuccessMessage(guideUrl);\n }\n};\n\n/**\n * `intlayer init`: installs the packages and sets up the framework, or, with\n * `interactive`, lets the user pick every setup step. `--interactive` needs a\n * terminal; without one it fails and lists the single-step commands instead.\n */\nexport const init = async (\n projectRoot?: string,\n options?: InitOptions,\n interactive?: boolean\n) => {\n if (!interactive) {\n await initSteps(projectRoot, DEFAULT_INIT_STEPS, options);\n return;\n }\n\n if (!isInteractiveTerminal()) {\n const p = await loadPrompts();\n\n p.log.error(getNoTerminalMessage());\n process.exitCode = 1;\n return;\n }\n\n await runInteractiveInit(resolveProjectRoot(projectRoot), options);\n};\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAa,mBAAmB,aAAqB;CACnD,IAAI,aAAa;CAEjB,OAAO,mBAAeA,mBAAQ,YAAY,IAAI,GAAG;EAC/C,QAAIC,wBAAWC,gBAAK,YAAY,cAAc,CAAC,GAC7C,OAAO;EAET,iBAAaF,mBAAQ,YAAY,IAAI;CACvC;CAIA,OAAO;AACT;;AAGA,MAAa,sBAAsB,gBACjC,gBAAgB,kBAAcA,mBAAQ,WAAW,IAAI,QAAQ,IAAI,CAAC;;;;;;AA4BpE,MAAa,oBAAgC,CAAC,SAAS,iBAAiB;;;;;;;AAQxE,MAAa,qBAAiC,CAAC,YAAY,cAAc;;;;;AAMzE,MAAa,qBAA+C;CAC1D,UAAU;CACV,cAAc;CACd,eAAe;CACf,iBAAiB;CACjB,QAAQ;CACR,iBAAiB;CACjB,QAAQ;CACR,KAAK;CACL,KAAK;CACL,KAAK;CACL,OAAO;AACT;;;;;;AAOA,MAAa,0BACX,OACA,iBACiB;CACjB,GAAG;CACH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,uBAAuB,OAAO;GAAE,GAAG;GAAa,GAAG;EAAe,CAAC;EACtE,kBAAkB;CACpB;CAEA,MAAM,EAAE,aAAa,UAAMR,mCAAa,MAAM,OAAO;CAGrD,MAAM,iBAAiB,MAAM,SAAS,QAAQ,IAC1C,MAAMS,8BAAW,IAAI,IACrB;CAEJ,IAAI,MAAM,SAAS,KAAK,GACtB,MAAMC,wBAAQ,MAAM,EAAE,UAAU,eAAe,CAAC;CAIlD,IAAI,MAAM,SAAS,OAAO,GACxB,MAAMC,4BAAU;CAGlB,IAAI,MAAM,SAAS,iBAAiB,GAClC,MAAMC,gDAAoB;CAM5B,IAAI,MAAM,SAAS,KAAK,GACtB,MAAM,QAAQ,IAAI;CAGpB,EAAE,MAAM,kCAAkC;CAE1C,IAAI,UACF,gDAAsB,QAAQ;AAElC;;;;;;AAOA,MAAa,OAAO,OAClB,aACA,SACA,gBACG;CACH,IAAI,CAAC,aAAa;EAChB,MAAM,UAAU,aAAa,oBAAoB,OAAO;EACxD;CACF;CAEA,IAAI,CAACC,0DAAsB,GAAG;EAG5B,OAFgBZ,gCAAY,EAE3B,CAAC,IAAI,MAAM,qBAAqB,CAAC;EAClC,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,mBAAmB,mBAAmB,WAAW,GAAG,OAAO;AACnE"}
|
|
1
|
+
{"version":3,"file":"init.cjs","names":["resolve","existsSync","join","initIntlayer","loadPrompts","login","setupCmsCredentials","detectGitRepository","setupRepository","parseChoice","CONTENT_FORMATS_BY_LAYOUT","CATALOG_MESSAGE_FORMATS","hasLintTooling","readFileSync","detectCompatI18nLibraries","hasUrlRoutingFramework","initSkills","initMCP","initInfra","initChromeExtension","isInteractiveTerminal"],"sources":["../../src/init.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport {\n CATALOG_MESSAGE_FORMATS,\n type CatalogMessageFormat,\n CONTENT_FORMATS_BY_LAYOUT,\n type ContentFormat,\n type ContentLayout,\n detectCompatI18nLibraries,\n hasLintTooling,\n hasUrlRoutingFramework,\n type InitOptions,\n initIntlayer,\n logInitSuccessMessage,\n type RoutingMode,\n setupCmsCredentials,\n} from '@intlayer/engine/cli';\nimport { login } from './auth/login';\nimport { setupRepository } from './auth/setupRepository';\nimport { initChromeExtension } from './initChromeExtension';\nimport { initInfra } from './initInfra';\nimport { initMCP } from './initMCP';\nimport { initSkills } from './initSkills';\nimport { loadPrompts } from './loadPrompts';\nimport { detectGitRepository } from './utils/detectGitRepository';\nimport { isInteractiveTerminal } from './utils/isInteractiveTerminal';\nimport { parseChoice } from './utils/parseChoice';\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\n/** Resolves the project root from `--project-root`, else the working directory. */\nexport const resolveProjectRoot = (projectRoot?: string): string =>\n findProjectRoot(projectRoot ? resolve(projectRoot) : process.cwd());\n\n/** Individually selectable setup steps exposed by the interactive init flow. */\nexport type InitStep =\n | 'packages'\n | 'githubActions'\n | 'projectSetup'\n | 'vscodeExtension'\n | 'lsp'\n | 'eslint'\n | 'skills'\n | 'mcp'\n | 'infra'\n | 'cms'\n | 'repository'\n | 'chromeExtension';\n\n/** A checkbox entry of the interactive init flow. */\nexport type InitStepOption = {\n value: InitStep;\n label: string;\n hint: string;\n};\n\n/**\n * Steps shown but not pre-selected. The infrastructure installer touches the\n * machine (downloads an app, pulls Docker images) and browser extensions open external URLs\n * rather than modifying the project, so they must be an explicit choice.\n */\nexport const OPT_IN_INIT_STEPS: InitStep[] = ['infra', 'chromeExtension'];\n\n/**\n * Steps run by `intlayer init` without `--interactive`: install the packages\n * and set up the framework. Every other step has its own command\n * ({@link INIT_STEP_COMMANDS}), so nothing outside the app code is touched\n * unless asked for.\n */\nexport const DEFAULT_INIT_STEPS: InitStep[] = ['packages', 'projectSetup'];\n\n/**\n * Command running each interactive step on its own, without prompts when every\n * value is passed as a flag. Printed when `--interactive` has no terminal.\n */\nexport const INIT_STEP_COMMANDS: Record<InitStep, string> = {\n packages: 'intlayer init packages',\n projectSetup:\n 'intlayer init project [--routing <routing>] [--content <layout>] [--content-format <format>] [--message-format <format>]',\n githubActions: 'intlayer init github-actions',\n vscodeExtension: 'intlayer init vscode-extension',\n eslint: 'intlayer init eslint',\n chromeExtension: 'intlayer init extension [--browser <chrome|firefox>]',\n skills: 'intlayer init skills [--platform <platform>] [--skills <skills...>]',\n mcp: 'intlayer init mcp [--platform <platform>] [--transport <stdio|sse>]',\n lsp: 'intlayer init lsp',\n cms: 'intlayer init cms',\n repository: 'intlayer init repository',\n infra: 'intlayer init infra --mode <desktop|docker|compose>',\n};\n\n/**\n * Maps setup steps to the {@link initIntlayer} options: every step handled by\n * `initIntlayer` that is not listed is skipped. Explicit `--no-*` flags in\n * `baseOptions` still win over a listed step.\n */\nexport const getInitOptionsForSteps = (\n steps: InitStep[],\n baseOptions?: InitOptions\n): InitOptions => ({\n ...baseOptions,\n noInstallPackages:\n baseOptions?.noInstallPackages || !steps.includes('packages'),\n // The `.gitignore` entry is tied to project setup.\n noGitignore: baseOptions?.noGitignore || !steps.includes('projectSetup'),\n noGithubActions:\n baseOptions?.noGithubActions || !steps.includes('githubActions'),\n noFrameworkSetup:\n baseOptions?.noFrameworkSetup || !steps.includes('projectSetup'),\n noVscodeExtension:\n baseOptions?.noVscodeExtension || !steps.includes('vscodeExtension'),\n noLsp: baseOptions?.noLsp || !steps.includes('lsp'),\n noEslint: baseOptions?.noEslint || !steps.includes('eslint'),\n // The documentation link only matters once the project itself is set up.\n skipFinalMessage:\n baseOptions?.skipFinalMessage || !steps.includes('projectSetup'),\n});\n\n/**\n * Runs the given {@link initIntlayer} steps only (packages, project setup, CI,\n * VS Code extension, LSP, lint rules). Backs `intlayer init` and its\n * single-step subcommands.\n */\nexport const initSteps = async (\n projectRoot: string | undefined,\n steps: InitStep[],\n options?: InitOptions\n): Promise<void> => {\n await initIntlayer(\n resolveProjectRoot(projectRoot),\n getInitOptionsForSteps(steps, options)\n );\n};\n\n/**\n * Logs in to the Intlayer CMS through the browser, then stores the access-key\n * credentials in `.env` and enables the editor in the config file.\n */\nexport const initCms = async (projectRoot?: string): Promise<void> => {\n const root = resolveProjectRoot(projectRoot);\n const p = await loadPrompts();\n\n p.log.info('Opening your browser to log in to the Intlayer CMS...');\n // `exitAfter: false` keeps the process alive so the flow can finish; the\n // credentials are persisted to `.env` and the editor enabled in the config.\n await login({\n exitAfter: false,\n onCredentials: (credentials) => setupCmsCredentials(root, credentials),\n });\n};\n\n/**\n * Connects the git repository of the project to its CMS project (and sets\n * its build settings) in the browser, pre-filled with the `origin` remote.\n */\nexport const initRepository = async (projectRoot?: string): Promise<void> => {\n const root = resolveProjectRoot(projectRoot);\n const p = await loadPrompts();\n const detectedRepository = detectGitRepository(root);\n\n p.log.info(\n detectedRepository\n ? `Detected repository: ${detectedRepository.provider} ${detectedRepository.owner}/${detectedRepository.repository}`\n : 'No supported git remote detected: pick the repository in the browser.'\n );\n p.log.info('Opening your browser to connect the repository...');\n\n await setupRepository({ detectedRepository });\n};\n\n/** Explains why `--interactive` cannot run, and what to run instead. */\nconst getNoTerminalMessage = (): string =>\n [\n '`intlayer init --interactive` needs a terminal to answer its prompts (none is attached, e.g. when run by an AI agent or in CI).',\n 'Run the steps directly instead:',\n ' intlayer init (installs the packages and sets up the framework)',\n ...Object.values(INIT_STEP_COMMANDS).map((command) => ` ${command}`),\n ].join('\\n');\n\n/** Grouped checkbox entries of the interactive init flow, in display order. */\nexport const INIT_STEP_GROUPS: Record<string, InitStepOption[]> = {\n Codebase: [\n {\n value: 'packages',\n label: 'Install & upgrade packages',\n hint: 'install missing Intlayer dependencies and upgrade outdated ones',\n },\n {\n value: 'projectSetup',\n label: 'Project setup',\n hint: 'intlayer config, tsconfig, bundler plugin, middleware/proxy and providers in layout/page',\n },\n {\n value: 'githubActions',\n label: 'CI/CD (GitHub Actions)',\n hint: 'scaffold the fill and test workflows that run on every pull request (covers every project in a monorepo)',\n },\n ],\n DevTools: [\n {\n value: 'vscodeExtension',\n label: 'VS Code extension',\n hint: 'recommend the Intlayer extension',\n },\n {\n value: 'eslint',\n label: 'Lint rules (ESLint / oxlint)',\n hint: 'flag hardcoded text and dynamic calls the compiler cannot optimize',\n },\n {\n value: 'chromeExtension',\n label: 'Chrome extension',\n hint: 'for audit, debug and analysis purpose',\n },\n ],\n 'Coding assistant': [\n {\n value: 'skills',\n label: 'AI skills',\n hint: 'install the Intlayer documentation as agent skills',\n },\n {\n value: 'mcp',\n label: 'MCP server',\n hint: 'configure the Intlayer MCP server',\n },\n {\n value: 'lsp',\n label: 'Editor LSP',\n hint: 'go-to-definition from keys to .content files',\n },\n ],\n CMS: [\n {\n value: 'cms',\n label: 'CMS',\n hint: 'log in through your browser, then store the credentials in your .env',\n },\n {\n value: 'repository',\n label: 'Git repository',\n hint: 'connect the git repository to the CMS project and set its build settings (GitHub, GitLab, Bitbucket, Codeberg, Gitee)',\n },\n {\n value: 'infra',\n label: 'Infrastructure (desktop app / self-hosting)',\n hint: 'install the desktop app, or self-host with Docker (all-in-one or Compose)',\n },\n ],\n};\n\n/**\n * Locale routing choice: a `routing.mode` served through the locale proxy, or\n * `none` to leave routing to the app (`no-prefix` with the proxy disabled).\n */\nexport type LocaleRoutingChoice = RoutingMode | 'none';\n\n/** Locale routing strategies offered by the interactive init flow. */\nconst ROUTING_OPTIONS: Array<{\n value: LocaleRoutingChoice;\n label: string;\n hint: string;\n}> = [\n {\n value: 'prefix-no-default',\n label: 'Prefix all except the default locale',\n hint: '/about, /fr/about (default)',\n },\n {\n value: 'prefix-all',\n label: 'Prefix all locales',\n hint: '/en/about, /fr/about',\n },\n {\n value: 'no-prefix',\n label: 'No locale in the URL',\n hint: '/about',\n },\n {\n value: 'search-params',\n label: 'Use a search parameter',\n hint: '/about?locale=fr',\n },\n {\n value: 'none',\n label: 'No locale routing',\n hint: 'no proxy, no locale route segment — handle the locale yourself',\n },\n];\n\n/** Locale routing choices accepted by `--routing`. */\nexport const LOCALE_ROUTING_CHOICES = ROUTING_OPTIONS.map(\n (option) => option.value\n);\n\n/** Validates a `--routing` value, throwing on an unknown choice. */\nexport const parseLocaleRoutingChoice = (value: string): LocaleRoutingChoice =>\n parseChoice(value, LOCALE_ROUTING_CHOICES, '--routing');\n\n/** Maps a routing choice to the init options it sets. */\nexport const getRoutingInitOptions = (\n choice: LocaleRoutingChoice\n): Pick<InitOptions, 'routingMode' | 'enableProxy'> =>\n choice === 'none'\n ? { routingMode: 'no-prefix', enableProxy: false }\n : { routingMode: choice, enableProxy: true };\n\n/** Content declaration layouts offered by the interactive init flow. */\nconst CONTENT_LAYOUT_OPTIONS: Array<{\n value: ContentLayout;\n label: string;\n hint: string;\n}> = [\n {\n value: 'multilingual',\n label: 'Multilingual content declaration',\n hint: '/**/{fileName}.content.{ts,json} — every locale in one file',\n },\n {\n value: 'per-locale',\n label: 'Per-locale content declaration',\n hint: '/**/{fileName}.{locale}.content.{ts,json}',\n },\n {\n value: 'centralized',\n label: 'Centralized',\n hint: '/locales/{locale}.{json,po}',\n },\n {\n value: 'namespaces',\n label: 'Namespaces',\n hint: '/locales/{locale}/{namespace}.{json,po}',\n },\n];\n\n/** Labels of the content formats offered by the interactive init flow. */\nconst CONTENT_FORMAT_LABELS: Record<ContentFormat, string> = {\n ts: 'TypeScript (.ts)',\n json: 'JSON (.json)',\n po: 'Gettext (.po)',\n};\n\n/** Labels of the JSON catalog message formats, in display order. */\nconst CATALOG_MESSAGE_FORMAT_OPTIONS: Record<\n CatalogMessageFormat,\n { label: string; hint: string }\n> = {\n icu: { label: 'ICU', hint: '{count, plural, one {# item} other {# items}}' },\n i18next: { label: 'i18next', hint: '{{count}} item, key_one / key_other' },\n 'vue-i18n': { label: 'vue-i18n', hint: '{count} item | {count} items' },\n intlayer: { label: 'Intlayer', hint: 'Intlayer dictionary content' },\n};\n\n/** Content layouts accepted by `--content`. */\nexport const CONTENT_LAYOUT_CHOICES = CONTENT_LAYOUT_OPTIONS.map(\n (option) => option.value\n);\n\n/** Validates a `--content` value, throwing on an unknown layout. */\nexport const parseContentLayoutChoice = (value: string): ContentLayout =>\n parseChoice(value, CONTENT_LAYOUT_CHOICES, '--content');\n\n/** Init options set by the content layout questions / flags. */\ntype ContentInitOptions = Pick<\n InitOptions,\n 'contentLayout' | 'contentFormat' | 'contentMessageFormat'\n>;\n\n/** Whether a layout + format pair produces a JSON catalog (sync plugin). */\nconst isJsonCatalog = (layout: ContentLayout, format: ContentFormat): boolean =>\n (layout === 'centralized' || layout === 'namespaces') && format === 'json';\n\n/**\n * Validates `--content` / `--content-format` / `--message-format` and maps\n * them to the init options. The format must be one the layout accepts, and the\n * message format only applies to JSON catalogs.\n */\nexport const getContentInitOptions = (\n layoutValue?: string,\n formatValue?: string,\n messageFormatValue?: string\n): ContentInitOptions => {\n if (!layoutValue) {\n if (formatValue || messageFormatValue) {\n throw new Error(\n '--content-format and --message-format require --content.'\n );\n }\n return {};\n }\n\n const contentLayout = parseContentLayoutChoice(layoutValue);\n const contentFormat = formatValue\n ? parseChoice(\n formatValue,\n CONTENT_FORMATS_BY_LAYOUT[contentLayout],\n '--content-format'\n )\n : undefined;\n\n if (!messageFormatValue) return { contentLayout, contentFormat };\n\n // Catalog layouts default to JSON.\n if (!isJsonCatalog(contentLayout, contentFormat ?? 'json')) {\n throw new Error(\n '--message-format only applies to JSON catalogs (--content centralized | namespaces with json).'\n );\n }\n\n return {\n contentLayout,\n contentFormat,\n contentMessageFormat: parseChoice(\n messageFormatValue,\n CATALOG_MESSAGE_FORMATS,\n '--message-format'\n ),\n };\n};\n\n/** Known ESLint and oxlint configuration file names. */\nexport const ESLINT_CONFIG_FILES = [\n 'eslint.config.js',\n 'eslint.config.mjs',\n 'eslint.config.cjs',\n 'eslint.config.ts',\n 'eslint.config.mts',\n 'eslint.config.cts',\n '.eslintrc.js',\n '.eslintrc.cjs',\n '.eslintrc.yaml',\n '.eslintrc.yml',\n '.eslintrc.json',\n '.eslintrc',\n '.oxlintrc.json',\n];\n\n/**\n * Checks whether ESLint or a compatible linter (oxlint) is installed or\n * configured in the project.\n */\nexport const isEslintInstalled = (\n dependencies: Record<string, string>,\n root?: string\n): boolean => {\n if (hasLintTooling(dependencies)) return true;\n if (dependencies.eslint || dependencies.oxlint) return true;\n\n if (root) {\n return ESLINT_CONFIG_FILES.some((file) => existsSync(join(root, file)));\n }\n\n return false;\n};\n\n/**\n * Computes the initial setup steps selected by default in the interactive prompt.\n * Steps like infrastructure and browser extension require opt-in, while\n * eslint is preselected only if installed on the project.\n */\nexport const getInitialInitSteps = (\n dependencies: Record<string, string>,\n root?: string\n): InitStep[] => {\n const isEslintPresent = isEslintInstalled(dependencies, root);\n\n return Object.values(INIT_STEP_GROUPS)\n .flat()\n .map((option) => option.value)\n .filter((step) => {\n if (OPT_IN_INIT_STEPS.includes(step)) return false;\n if (step === 'eslint' && !isEslintPresent) return false;\n return true;\n });\n};\n\n/** Reads the merged dependencies of the project at `root`. */\nexport const getProjectDependencies = (\n root: string\n): Record<string, string> => {\n try {\n const packageJsonPath = join(root, 'package.json');\n if (!existsSync(packageJsonPath)) return {};\n const { dependencies = {}, devDependencies = {} } = JSON.parse(\n readFileSync(packageJsonPath, 'utf-8')\n );\n return { ...dependencies, ...devDependencies };\n } catch {\n return {};\n }\n};\n\n/**\n * Runs `init` in interactive mode: prompts the user with a checkbox of setup\n * steps, then forwards the selection to {@link initIntlayer} (packages, GitHub\n * Actions, VS Code extension, LSP) and runs the dedicated skills/MCP installers\n * for the steps that own their own prompts. The `.gitignore` entry is not\n * offered as a checkbox — it is always added (unless `--no-gitignore` is set).\n */\nconst runInteractiveInit = async (\n root: string,\n baseOptions?: InitOptions\n): Promise<void> => {\n const p = await loadPrompts();\n\n p.intro('Initialize Intlayer');\n\n const projectDependencies = getProjectDependencies(root);\n\n const selected = await p.groupMultiselect<InitStep>({\n message: 'Select what you want to set up:',\n options: INIT_STEP_GROUPS,\n initialValues: getInitialInitSteps(projectDependencies, root),\n required: false,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const steps = selected as InitStep[];\n\n // Compat i18n library detection — never asked, always derived from the\n // installed packages. `detectMissingIntlayerPackages` reads the very same\n // dependency map to schedule the compat adapter, the sync plugin and the\n // catalog template, so a project without any of those packages is simply set\n // up on Intlayer alone.\n const detectedCompatLibraries =\n detectCompatI18nLibraries(projectDependencies);\n const hasCompatLib = detectedCompatLibraries.length > 0;\n\n if (hasCompatLib) {\n p.log.info(\n `Detected existing i18n ${detectedCompatLibraries.length > 1 ? 'libraries' : 'library'}: ${detectedCompatLibraries.join(', ')} — the matching Intlayer compat adapter and catalog sync will be set up.`\n );\n }\n\n // Locale routing → `routing.mode` + `routing.enableProxy` in the config, and\n // the route segment the framework scaffolding creates. Only asked for web\n // frontends; projects without URL routing (backend, React Native / Expo) keep\n // only `routing.storage` in a freshly created config. Skipped for compat\n // i18n libraries, which keep their own routing.\n let routingOptions: Pick<InitOptions, 'routingMode' | 'enableProxy'> = {};\n\n if (\n steps.includes('projectSetup') &&\n baseOptions?.routingMode === undefined &&\n !hasCompatLib &&\n hasUrlRoutingFramework(projectDependencies)\n ) {\n const selectedRouting = await p.select<LocaleRoutingChoice>({\n message: 'How should the locale appear in your URLs?',\n options: ROUTING_OPTIONS,\n initialValue: 'prefix-no-default',\n });\n\n if (p.isCancel(selectedRouting)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n routingOptions = getRoutingInitOptions(selectedRouting);\n }\n\n // Content layout → `compiler.output` (+ `dictionary.locale`) for `.content`\n // files, or the syncJSON / syncPO plugin for catalogs. Skipped for compat\n // i18n libraries, which keep their own catalogs.\n let contentOptions: ContentInitOptions = {};\n\n if (\n steps.includes('projectSetup') &&\n baseOptions?.contentLayout === undefined &&\n !hasCompatLib\n ) {\n const contentLayout = await p.select<ContentLayout>({\n message: 'How do you want to declare your content?',\n options: CONTENT_LAYOUT_OPTIONS,\n initialValue: 'multilingual',\n });\n\n if (p.isCancel(contentLayout)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const acceptedFormats = CONTENT_FORMATS_BY_LAYOUT[contentLayout];\n const hasTypeScript = existsSync(join(root, 'tsconfig.json'));\n\n const contentFormat = await p.select<ContentFormat>({\n message: 'Which format for your content?',\n options: acceptedFormats.map((format) => ({\n value: format,\n label: CONTENT_FORMAT_LABELS[format],\n })),\n initialValue:\n acceptedFormats.includes('ts') && !hasTypeScript\n ? 'json'\n : acceptedFormats[0],\n });\n\n if (p.isCancel(contentFormat)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n contentOptions = { contentLayout, contentFormat };\n\n // JSON catalogs carry a message syntax (plurals, interpolation…).\n if (isJsonCatalog(contentLayout, contentFormat)) {\n const contentMessageFormat = await p.select<CatalogMessageFormat>({\n message: 'Which message format do your JSON catalogs use?',\n options: CATALOG_MESSAGE_FORMATS.map((messageFormat) => ({\n value: messageFormat,\n ...CATALOG_MESSAGE_FORMAT_OPTIONS[messageFormat],\n })),\n initialValue: CATALOG_MESSAGE_FORMATS[0],\n });\n\n if (p.isCancel(contentMessageFormat)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n contentOptions = { ...contentOptions, contentMessageFormat };\n }\n }\n\n const options: InitOptions = {\n ...getInitOptionsForSteps(steps, {\n ...baseOptions,\n ...routingOptions,\n ...contentOptions,\n }),\n skipFinalMessage: true,\n };\n\n const { guideUrl } = await initIntlayer(root, options);\n\n // Skills ask for the platform after the skill selection; MCP reuses it.\n const skillsPlatform = steps.includes('skills')\n ? await initSkills(root)\n : undefined;\n\n if (steps.includes('mcp')) {\n await initMCP(root, { platform: skillsPlatform });\n }\n\n // Delegated to the hosted install script, which owns its own menu.\n if (steps.includes('infra')) {\n await initInfra();\n }\n\n if (steps.includes('chromeExtension')) {\n await initChromeExtension();\n }\n\n // CMS / visual editor runs last: the browser login persists the access-key\n // credentials to `.env` and enables the editor in the config file. Kept last\n // so the browser flow does not interrupt setup.\n if (steps.includes('cms')) {\n await initCms(root);\n }\n\n // After the CMS login, so the browser is already signed in\n if (steps.includes('repository')) {\n await initRepository(root);\n }\n\n p.outro('Intlayer initialization complete');\n\n if (guideUrl) {\n logInitSuccessMessage(guideUrl);\n }\n};\n\n/**\n * `intlayer init`: installs the packages and sets up the framework, or, with\n * `interactive`, lets the user pick every setup step. `--interactive` needs a\n * terminal; without one it fails and lists the single-step commands instead.\n */\nexport const init = async (\n projectRoot?: string,\n options?: InitOptions,\n interactive?: boolean\n) => {\n if (!interactive) {\n await initSteps(projectRoot, DEFAULT_INIT_STEPS, options);\n return;\n }\n\n if (!isInteractiveTerminal()) {\n const p = await loadPrompts();\n\n p.log.error(getNoTerminalMessage());\n process.exitCode = 1;\n return;\n }\n\n await runInteractiveInit(resolveProjectRoot(projectRoot), options);\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAa,mBAAmB,aAAqB;CACnD,IAAI,aAAa;CAEjB,OAAO,mBAAeA,mBAAQ,YAAY,IAAI,GAAG;EAC/C,QAAIC,wBAAWC,gBAAK,YAAY,cAAc,CAAC,GAC7C,OAAO;EAET,iBAAaF,mBAAQ,YAAY,IAAI;CACvC;CAIA,OAAO;AACT;;AAGA,MAAa,sBAAsB,gBACjC,gBAAgB,kBAAcA,mBAAQ,WAAW,IAAI,QAAQ,IAAI,CAAC;;;;;;AA6BpE,MAAa,oBAAgC,CAAC,SAAS,iBAAiB;;;;;;;AAQxE,MAAa,qBAAiC,CAAC,YAAY,cAAc;;;;;AAMzE,MAAa,qBAA+C;CAC1D,UAAU;CACV,cACE;CACF,eAAe;CACf,iBAAiB;CACjB,QAAQ;CACR,iBAAiB;CACjB,QAAQ;CACR,KAAK;CACL,KAAK;CACL,KAAK;CACL,YAAY;CACZ,OAAO;AACT;;;;;;AAOA,MAAa,0BACX,O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Gb,MAAa,mBAAqD;CAChE,UAAU;EACR;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;CACA,UAAU;EACR;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;CACA,oBAAoB;EAClB;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;CACA,KAAK;EACH;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;AACF;;AASA,MAAM,kBAID;CACH;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;AACF;;AAGA,MAAa,yBAAyB,gBAAgB,KACnD,WAAW,OAAO,KACrB;;AAGA,MAAa,4BAA4B,UACvCC,sCAAY,OAAO,wBAAwB,WAAW;;AAGxD,MAAa,yBACX,WAEA,WAAW,SACP;CAAE,aAAa;CAAa,aAAa;AAAM,IAC/C;CAAE,aAAa;CAAQ,aAAa;AAAK;;AAG/C,MAAM,yBAID;CACH;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CAC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