@intlayer/cli 8.2.4 → 8.3.0-canary.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 +1 -1
- package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
- package/dist/cjs/_virtual/_utils_asset.cjs +1 -1
- package/dist/cjs/auth/login.cjs +2 -2
- package/dist/cjs/auth/login.cjs.map +1 -1
- package/dist/cjs/build.cjs +1 -1
- package/dist/cjs/ci.cjs +1 -1
- package/dist/cjs/cli.cjs +1 -1
- package/dist/cjs/cli.cjs.map +1 -1
- package/dist/cjs/config.cjs +1 -1
- package/dist/cjs/editor.cjs +1 -1
- package/dist/cjs/extract.cjs +1 -1
- package/dist/cjs/extract.cjs.map +1 -1
- package/dist/cjs/fill/fill.cjs +1 -1
- package/dist/cjs/fill/fill.cjs.map +1 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs +1 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
- package/dist/cjs/fill/formatFillData.cjs +1 -1
- package/dist/cjs/fill/formatFillData.cjs.map +1 -1
- package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs.map +1 -1
- package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs.map +1 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs +1 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
- package/dist/cjs/fill/translateDictionary.cjs +1 -1
- package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
- package/dist/cjs/fill/writeFill.cjs +1 -1
- package/dist/cjs/fill/writeFill.cjs.map +1 -1
- package/dist/cjs/getTargetDictionary.cjs +1 -1
- package/dist/cjs/getTargetDictionary.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/init.cjs +1 -1
- package/dist/cjs/initMCP.cjs +1 -1
- package/dist/cjs/initSkills.cjs +1 -1
- package/dist/cjs/listContentDeclaration.cjs +1 -1
- package/dist/cjs/listContentDeclaration.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs +1 -1
- package/dist/cjs/liveSync.cjs +4 -4
- package/dist/cjs/liveSync.cjs.map +1 -1
- package/dist/cjs/pull.cjs +1 -1
- package/dist/cjs/pull.cjs.map +1 -1
- package/dist/cjs/push/push.cjs +1 -1
- package/dist/cjs/push/push.cjs.map +1 -1
- package/dist/cjs/pushConfig.cjs +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
- package/dist/cjs/searchDoc.cjs +1 -1
- package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
- package/dist/cjs/test/test.cjs +1 -1
- package/dist/cjs/translateDoc/translateDoc.cjs +1 -1
- package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateFile.cjs +2 -2
- package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
- package/dist/cjs/utils/checkAccess.cjs +1 -1
- package/dist/cjs/utils/checkAccess.cjs.map +1 -1
- package/dist/cjs/utils/chunkInference.cjs.map +1 -1
- package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
- package/dist/cjs/utils/getParentPackageJSON.cjs +1 -1
- package/dist/cjs/utils/setupAI.cjs.map +1 -1
- package/dist/cjs/watch.cjs +1 -1
- package/dist/esm/IntlayerEventListener.mjs +1 -1
- package/dist/esm/IntlayerEventListener.mjs.map +1 -1
- package/dist/esm/_virtual/_utils_asset.mjs +1 -1
- package/dist/esm/auth/login.mjs +2 -2
- package/dist/esm/build.mjs +1 -1
- package/dist/esm/ci.mjs +1 -1
- package/dist/esm/cli.mjs +1 -1
- package/dist/esm/cli.mjs.map +1 -1
- package/dist/esm/config.mjs +1 -1
- package/dist/esm/editor.mjs +1 -1
- package/dist/esm/extract.mjs +1 -1
- package/dist/esm/extract.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs +1 -1
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
- package/dist/esm/fill/formatFillData.mjs +1 -1
- package/dist/esm/fill/formatFillData.mjs.map +1 -1
- package/dist/esm/fill/getAvailableLocalesInDictionary.mjs.map +1 -1
- package/dist/esm/fill/getFilterMissingContentPerLocale.mjs.map +1 -1
- package/dist/esm/fill/listTranslationsTasks.mjs +1 -1
- package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -1
- package/dist/esm/fill/translateDictionary.mjs +1 -1
- package/dist/esm/fill/translateDictionary.mjs.map +1 -1
- package/dist/esm/fill/writeFill.mjs +1 -1
- package/dist/esm/fill/writeFill.mjs.map +1 -1
- package/dist/esm/getTargetDictionary.mjs +1 -1
- package/dist/esm/getTargetDictionary.mjs.map +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/init.mjs +1 -1
- package/dist/esm/initMCP.mjs +1 -1
- package/dist/esm/initSkills.mjs +1 -1
- package/dist/esm/listContentDeclaration.mjs +1 -1
- package/dist/esm/listContentDeclaration.mjs.map +1 -1
- package/dist/esm/listProjects.mjs +1 -1
- package/dist/esm/liveSync.mjs +3 -3
- package/dist/esm/liveSync.mjs.map +1 -1
- package/dist/esm/pull.mjs +1 -1
- package/dist/esm/pull.mjs.map +1 -1
- package/dist/esm/push/push.mjs +1 -1
- package/dist/esm/push/push.mjs.map +1 -1
- package/dist/esm/pushConfig.mjs +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
- package/dist/esm/searchDoc.mjs +1 -1
- package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
- package/dist/esm/test/test.mjs +1 -1
- package/dist/esm/translateDoc/translateDoc.mjs +1 -1
- package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
- package/dist/esm/translateDoc/translateFile.mjs +2 -2
- package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
- package/dist/esm/utils/checkAccess.mjs +1 -1
- package/dist/esm/utils/checkAccess.mjs.map +1 -1
- package/dist/esm/utils/chunkInference.mjs.map +1 -1
- package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
- package/dist/esm/utils/getParentPackageJSON.mjs +1 -1
- package/dist/esm/utils/setupAI.mjs.map +1 -1
- package/dist/esm/watch.mjs +1 -1
- package/dist/types/IntlayerEventListener.d.ts +1 -1
- package/dist/types/extract.d.ts +2 -1
- package/dist/types/extract.d.ts.map +1 -1
- package/dist/types/fill/fill.d.ts +1 -1
- package/dist/types/fill/formatAutoFilledFilePath.d.ts +3 -2
- package/dist/types/fill/formatAutoFilledFilePath.d.ts.map +1 -1
- package/dist/types/fill/formatFillData.d.ts +5 -3
- package/dist/types/fill/formatFillData.d.ts.map +1 -1
- package/dist/types/fill/getAvailableLocalesInDictionary.d.ts +2 -1
- package/dist/types/fill/getAvailableLocalesInDictionary.d.ts.map +1 -1
- package/dist/types/fill/getFilterMissingContentPerLocale.d.ts +1 -1
- package/dist/types/fill/listTranslationsTasks.d.ts +3 -1
- package/dist/types/fill/listTranslationsTasks.d.ts.map +1 -1
- package/dist/types/fill/translateDictionary.d.ts +2 -1
- package/dist/types/fill/translateDictionary.d.ts.map +1 -1
- package/dist/types/fill/writeFill.d.ts +3 -1
- package/dist/types/fill/writeFill.d.ts.map +1 -1
- package/dist/types/getTargetDictionary.d.ts +1 -1
- package/dist/types/reviewDoc/reviewDoc.d.ts +1 -1
- package/dist/types/reviewDoc/reviewDocBlockAware.d.ts +1 -1
- package/dist/types/reviewDoc/reviewDocBlockAware.d.ts.map +1 -1
- package/dist/types/test/listMissingTranslations.d.ts +2 -1
- package/dist/types/test/listMissingTranslations.d.ts.map +1 -1
- package/dist/types/translateDoc/types.d.ts +2 -1
- package/dist/types/translateDoc/types.d.ts.map +1 -1
- package/dist/types/utils/checkAccess.d.ts +1 -1
- package/dist/types/utils/chunkInference.d.ts +1 -1
- package/dist/types/utils/getOutputFilePath.d.ts +1 -1
- package/dist/types/utils/setupAI.d.ts +1 -1
- package/package.json +23 -23
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../_virtual/_utils_asset.cjs`),t=require(`./validation.cjs`),n=require(`../utils/chunkInference.cjs`),r=require(`../utils/fixChunkStartEndChars.cjs`),i=require(`../utils/calculateChunks.cjs`);let a=require(
|
|
2
|
-
`)},{role:`user`,content:`>>> TARGET CHUNK START <<<\n${m}\n>>> TARGET CHUNK END <<<`}],v,g,b,x),a=t.sanitizeChunk(e?.fileContent,m);if(a=r.fixChunkStartEndChars(a,m),!t.validateTranslation(m,a,o))throw Error(`Validation failed for chunk ${i+1}/${O}`);return{content:a,tokens:e.tokenUsed}})(),E=(d.performance.now()-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../_virtual/_utils_asset.cjs`),t=require(`./validation.cjs`),n=require(`../utils/chunkInference.cjs`),r=require(`../utils/fixChunkStartEndChars.cjs`),i=require(`../utils/calculateChunks.cjs`);let a=require(`node:fs`),o=require(`node:fs/promises`),s=require(`node:path`),c=require(`@intlayer/config/logger`),l=require(`@intlayer/chokidar/utils`),u=require(`@intlayer/config/utils`),d=require(`node:perf_hooks`);const f=async({baseFilePath:f,outputFilePath:p,locale:m,baseLocale:h,configuration:g,errorState:_,aiOptions:v,customInstructions:y,aiClient:b,aiConfig:x,flushStrategy:S=`incremental`,onChunkReceive:C,limit:w})=>{if(_.shouldStop)return null;let T=(0,c.getAppLogger)(g,{config:{prefix:``}}),E=d.performance.now();try{let D=i.chunkText(await(0,o.readFile)(f,`utf-8`)),O=D.length,k=`${(0,c.colon)(`${c.ANSIColors.GREY_DARK}[${(0,l.formatPath)(f)}${c.ANSIColors.GREY_DARK}] `,{colSize:40})}${c.ANSIColors.RESET}`,A=`${(0,c.colon)(`${c.ANSIColors.GREY_DARK}[${(0,l.formatPath)(f)}${c.ANSIColors.GREY_DARK}][${(0,l.formatLocale)(m)}${c.ANSIColors.GREY_DARK}] `,{colSize:40})}${c.ANSIColors.RESET}`;T(`${k}Split into ${(0,c.colorizeNumber)(O)} chunks. Queuing...`);let j=e.readAsset(`./prompts/TRANSLATE_PROMPT.md`,`utf-8`).replaceAll(`{{localeName}}`,`${(0,l.formatLocale)(m,!1)}`).replaceAll(`{{baseLocaleName}}`,`${(0,l.formatLocale)(h,!1)}`).replace(`{{applicationContext}}`,v?.applicationContext??`-`).replace(`{{customInstructions}}`,y??`-`),M=Array(O).fill(``),N=w??(e=>e()),P=D.map((e,i)=>N(async()=>{if(_.shouldStop)return null;let o=(0,c.getAppLogger)(g,{config:{prefix:`${A} ${c.ANSIColors.GREY_DARK}[${i+1}/${O}] ${c.ANSIColors.RESET}`}}),l=d.performance.now(),f=i===0,m=e.content,h=()=>">>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\n```\n"+(D[i-1]?.content??``)+"\n```\n>>> END PREVIOUS CONTEXT <<<",y=()=>">>> CONTEXT: NEXT CONTENT <<<\n```\n"+(D[i+1]?.content??``)+"\n```\n>>> END NEXT CONTEXT <<<";o(`Process started`);let{content:w,tokens:T}=await(0,u.retryManager)(async()=>{let e=await n.chunkInference([{role:`system`,content:j},...D[i+1]?[{role:`system`,content:y()}]:[],...f?[]:[{role:`system`,content:h()}],{role:`system`,content:[`You are translating TARGET CHUNK (${i+1}/${O}).`,`Translate ONLY the target chunk. Preserve frontmatter/code exactly.`].join(`
|
|
2
|
+
`)},{role:`user`,content:`>>> TARGET CHUNK START <<<\n${m}\n>>> TARGET CHUNK END <<<`}],v,g,b,x),a=t.sanitizeChunk(e?.fileContent,m);if(a=r.fixChunkStartEndChars(a,m),!t.validateTranslation(m,a,o))throw Error(`Validation failed for chunk ${i+1}/${O}`);return{content:a,tokens:e.tokenUsed}})(),E=(d.performance.now()-l).toFixed(0);if(M[i]=w,C&&C(w,i,O),S===`incremental`&&M.slice(0,i+1).every(e=>e&&e!==``)){let e=0;for(;e<O&&M[e]&&M[e]!==``;)e++;let t=M.slice(0,e).join(``);(0,a.mkdirSync)((0,s.dirname)(p),{recursive:!0}),(0,a.writeFileSync)(p,t)}o([`${(0,c.colorizeNumber)(T)} tokens used `,`${c.ANSIColors.GREY_DARK}in ${(0,c.colorizeNumber)(E)}ms${c.ANSIColors.RESET}`].join(``))}));await Promise.all(P);let F=M.join(``);(S===`end`||S===`incremental`)&&((0,a.mkdirSync)((0,s.dirname)(p),{recursive:!0}),(0,a.writeFileSync)(p,F));let I=((d.performance.now()-E)/1e3).toFixed(2),L=(0,s.relative)(g.system.baseDir,p);return T(`${(0,c.colorize)(`✔`,c.ANSIColors.GREEN)} File ${(0,l.formatPath)(L)} completed in ${(0,c.colorizeNumber)(I)}s.`),F}catch(e){_.count++;let t=e?.message??JSON.stringify(e);return T(`${(0,c.colorize)(`✖`,c.ANSIColors.RED)} Error: ${t}`),_.count>=_.maxErrors&&(_.shouldStop=!0),null}};exports.translateFile=f;
|
|
3
3
|
//# sourceMappingURL=translateFile.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translateFile.cjs","names":["performance","chunkText","ANSIColors","readAsset","chunkInference","sanitizeChunk","fixChunkStartEndChars","validateTranslation"],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport { chunkText } from '../utils/calculateChunks';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { TranslateFileOptions } from './types';\nimport { sanitizeChunk, validateTranslation } from './validation';\n\nexport const translateFile = async ({\n baseFilePath,\n outputFilePath,\n locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy = 'incremental',\n onChunkReceive,\n limit, // The Global Limiter\n}: TranslateFileOptions): Promise<string | null> => {\n if (errorState.shouldStop) return null;\n\n const appLogger = getAppLogger(configuration, { config: { prefix: '' } });\n const fileStartTime = performance.now();\n\n try {\n const fileContent = await readFile(baseFilePath, 'utf-8');\n const chunks = chunkText(fileContent);\n const totalChunks = chunks.length;\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = `${colon(filePrefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = `${colon(prefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n\n appLogger(\n `${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`\n );\n\n const basePrompt = readAsset('./prompts/TRANSLATE_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const translatedParts: string[] = new Array(totalChunks).fill('');\n\n // Fallback if no limiter is provided (runs immediately)\n const runTask = limit ?? ((fn) => fn());\n\n // MAP CHUNKS TO GLOBAL TASKS\n // This pushes ALL chunks for this file into the Global Queue immediately.\n // They will execute whenever the global concurrency slots open up.\n const tasks = chunks.map((chunk, i) =>\n runTask(async () => {\n if (errorState.shouldStop) return null;\n\n const chunkLogger = getAppLogger(configuration, {\n config: {\n prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}`,\n },\n });\n\n const chunkStartTime = performance.now();\n const isFirstChunk = i === 0;\n const fileToTranslateCurrentChunk = chunk.content;\n\n // Context Preparation\n const getPrevChunkPrompt = () =>\n `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i - 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END PREVIOUS CONTEXT <<<`;\n\n const getBaseChunkContextPrompt = () =>\n `>>> CONTEXT: NEXT CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i + 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END NEXT CONTEXT <<<`;\n\n chunkLogger('Process started');\n\n const chunkTranslation = retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n ...(chunks[i + 1]\n ? [\n {\n role: 'system',\n content: getBaseChunkContextPrompt(),\n } as const,\n ]\n : []),\n ...(isFirstChunk\n ? []\n : [{ role: 'system', content: getPrevChunkPrompt() } as const]),\n {\n role: 'system',\n content: [\n `You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`,\n `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`,\n ].join('\\n'),\n },\n {\n role: 'user',\n content: `>>> TARGET CHUNK START <<<\\n${fileToTranslateCurrentChunk}\\n>>> TARGET CHUNK END <<<`,\n },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n fileToTranslateCurrentChunk\n );\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n fileToTranslateCurrentChunk\n );\n\n const isValid = validateTranslation(\n fileToTranslateCurrentChunk,\n processedChunk,\n chunkLogger\n );\n\n if (!isValid) {\n // Throwing an error here signals retryManager to try again\n throw new Error(\n `Validation failed for chunk ${i + 1}/${totalChunks}`\n );\n }\n\n return { content: processedChunk, tokens: result.tokenUsed };\n });\n\n const { content: translatedChunk, tokens } = await chunkTranslation();\n const chunkEndTime = performance.now();\n const chunkDuration = (chunkEndTime - chunkStartTime).toFixed(0);\n\n // Store Result\n translatedParts[i] = translatedChunk;\n\n if (onChunkReceive) {\n onChunkReceive(translatedChunk, i, totalChunks);\n }\n\n // Incremental Flush Strategy\n if (flushStrategy === 'incremental') {\n const isContiguous = translatedParts\n .slice(0, i + 1)\n .every((p) => p && p !== '');\n\n if (isContiguous) {\n let endIdx = 0;\n while (\n endIdx < totalChunks &&\n translatedParts[endIdx] &&\n translatedParts[endIdx] !== ''\n ) {\n endIdx++;\n }\n const currentContent = translatedParts.slice(0, endIdx).join('');\n // Write asynchronously/sync is fine here as node handles file locks reasonably well for single process\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, currentContent);\n }\n }\n\n chunkLogger(\n [\n `${colorizeNumber(tokens)} tokens used `,\n `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`,\n ].join('')\n );\n })\n );\n\n // Wait for all chunks for this specific file/locale to finish\n await Promise.all(tasks);\n\n // Final Flush\n const fullContent = translatedParts.join('');\n if (flushStrategy === 'end' || flushStrategy === 'incremental') {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, fullContent);\n }\n\n const fileEndTime = performance.now();\n const totalDuration = ((fileEndTime - fileStartTime) / 1000).toFixed(2);\n const relativePath = relative(\n configuration.content.baseDir,\n outputFilePath\n );\n\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`\n );\n\n return fullContent;\n } catch (error: any) {\n errorState.count++;\n const errorMessage = error?.message ?? JSON.stringify(error);\n appLogger(`${colorize('✖', ANSIColors.RED)} Error: ${errorMessage}`);\n if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;\n return null;\n }\n};\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"translateFile.cjs","names":["performance","chunkText","ANSIColors","readAsset","chunkInference","sanitizeChunk","fixChunkStartEndChars","validateTranslation"],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport { chunkText } from '../utils/calculateChunks';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { TranslateFileOptions } from './types';\nimport { sanitizeChunk, validateTranslation } from './validation';\n\nexport const translateFile = async ({\n baseFilePath,\n outputFilePath,\n locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy = 'incremental',\n onChunkReceive,\n limit, // The Global Limiter\n}: TranslateFileOptions): Promise<string | null> => {\n if (errorState.shouldStop) return null;\n\n const appLogger = getAppLogger(configuration, { config: { prefix: '' } });\n const fileStartTime = performance.now();\n\n try {\n const fileContent = await readFile(baseFilePath, 'utf-8');\n const chunks = chunkText(fileContent);\n const totalChunks = chunks.length;\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = `${colon(filePrefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = `${colon(prefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n\n appLogger(\n `${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`\n );\n\n const basePrompt = readAsset('./prompts/TRANSLATE_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const translatedParts: string[] = new Array(totalChunks).fill('');\n\n // Fallback if no limiter is provided (runs immediately)\n const runTask = limit ?? ((fn) => fn());\n\n // MAP CHUNKS TO GLOBAL TASKS\n // This pushes ALL chunks for this file into the Global Queue immediately.\n // They will execute whenever the global concurrency slots open up.\n const tasks = chunks.map((chunk, i) =>\n runTask(async () => {\n if (errorState.shouldStop) return null;\n\n const chunkLogger = getAppLogger(configuration, {\n config: {\n prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}`,\n },\n });\n\n const chunkStartTime = performance.now();\n const isFirstChunk = i === 0;\n const fileToTranslateCurrentChunk = chunk.content;\n\n // Context Preparation\n const getPrevChunkPrompt = () =>\n `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i - 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END PREVIOUS CONTEXT <<<`;\n\n const getBaseChunkContextPrompt = () =>\n `>>> CONTEXT: NEXT CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i + 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END NEXT CONTEXT <<<`;\n\n chunkLogger('Process started');\n\n const chunkTranslation = retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n ...(chunks[i + 1]\n ? [\n {\n role: 'system',\n content: getBaseChunkContextPrompt(),\n } as const,\n ]\n : []),\n ...(isFirstChunk\n ? []\n : [{ role: 'system', content: getPrevChunkPrompt() } as const]),\n {\n role: 'system',\n content: [\n `You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`,\n `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`,\n ].join('\\n'),\n },\n {\n role: 'user',\n content: `>>> TARGET CHUNK START <<<\\n${fileToTranslateCurrentChunk}\\n>>> TARGET CHUNK END <<<`,\n },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n fileToTranslateCurrentChunk\n );\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n fileToTranslateCurrentChunk\n );\n\n const isValid = validateTranslation(\n fileToTranslateCurrentChunk,\n processedChunk,\n chunkLogger\n );\n\n if (!isValid) {\n // Throwing an error here signals retryManager to try again\n throw new Error(\n `Validation failed for chunk ${i + 1}/${totalChunks}`\n );\n }\n\n return { content: processedChunk, tokens: result.tokenUsed };\n });\n\n const { content: translatedChunk, tokens } = await chunkTranslation();\n const chunkEndTime = performance.now();\n const chunkDuration = (chunkEndTime - chunkStartTime).toFixed(0);\n\n // Store Result\n translatedParts[i] = translatedChunk;\n\n if (onChunkReceive) {\n onChunkReceive(translatedChunk, i, totalChunks);\n }\n\n // Incremental Flush Strategy\n if (flushStrategy === 'incremental') {\n const isContiguous = translatedParts\n .slice(0, i + 1)\n .every((p) => p && p !== '');\n\n if (isContiguous) {\n let endIdx = 0;\n while (\n endIdx < totalChunks &&\n translatedParts[endIdx] &&\n translatedParts[endIdx] !== ''\n ) {\n endIdx++;\n }\n const currentContent = translatedParts.slice(0, endIdx).join('');\n // Write asynchronously/sync is fine here as node handles file locks reasonably well for single process\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, currentContent);\n }\n }\n\n chunkLogger(\n [\n `${colorizeNumber(tokens)} tokens used `,\n `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`,\n ].join('')\n );\n })\n );\n\n // Wait for all chunks for this specific file/locale to finish\n await Promise.all(tasks);\n\n // Final Flush\n const fullContent = translatedParts.join('');\n if (flushStrategy === 'end' || flushStrategy === 'incremental') {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, fullContent);\n }\n\n const fileEndTime = performance.now();\n const totalDuration = ((fileEndTime - fileStartTime) / 1000).toFixed(2);\n const relativePath = relative(configuration.system.baseDir, outputFilePath);\n\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`\n );\n\n return fullContent;\n } catch (error: any) {\n errorState.count++;\n const errorMessage = error?.message ?? JSON.stringify(error);\n appLogger(`${colorize('✖', ANSIColors.RED)} Error: ${errorMessage}`);\n if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;\n return null;\n }\n};\n"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./checkConfigConsistency.cjs`);let t=require(`@intlayer/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./checkConfigConsistency.cjs`);let t=require(`@intlayer/config/logger`),n=require(`@intlayer/api`),r=require(`@intlayer/config/utils`);const i=async(i,a=!0)=>{let o=(0,t.getAppLogger)(i);if(!(i.editor.clientId&&i.editor.clientSecret))return o([`CMS auth not provided. You can either retreive the CMS access key on`,(0,t.colorize)(`https://intlayer.org/dahboard`,t.ANSIColors.GREY),(0,t.colorize)(`(see doc:`,t.ANSIColors.GREY_DARK),(0,t.colorize)(`https://intlayer.org/doc/concept/cms`,t.ANSIColors.GREY),(0,t.colorize)(`)`,t.ANSIColors.GREY_DARK),`.`],{level:`error`}),!1;let s=(0,n.getIntlayerAPIProxy)(void 0,i);try{let n=(await s.oAuth.getOAuth2AccessToken()).data?.project;if(!n)return o(`Project not found`),!0;if(n.configuration&&a)try{let t=n.configuration;if(t.ai&&`apiKeyConfigured`in t.ai){let{apiKeyConfigured:e,...n}=t.ai;t={...t,ai:n}}e.checkConfigConsistency(t,i)}catch{o([`Remote configuration is not up to date. The project configuration does not match the local configuration.`,`You can push the configuration by running`,(0,t.colorize)(`npx intlayer configuration push`,t.ANSIColors.CYAN),(0,t.colorize)(`(see doc:`,t.ANSIColors.GREY_DARK),(0,t.colorize)(`https://intlayer.org/doc/concept/cli/push`,t.ANSIColors.GREY),(0,t.colorize)(`)`,t.ANSIColors.GREY_DARK),`.`],{level:`warn`})}}catch(e){return o((0,r.extractErrorMessage)(e),{level:`error`}),!1}return!0},a=async(e,n,r=!0)=>{let a=(0,t.getAppLogger)(e),o=!!(e.editor.clientId&&e.editor.clientSecret),s=e.ai?.provider===`ollama`||n?.provider===`ollama`;return e.ai?.apiKey||n?.apiKey||s?!0:o?await i(e,r):(a([`AI options or API key not provided. You can either retreive the CMS access key on`,(0,t.colorize)(`https://intlayer.org/dahboard`,t.ANSIColors.GREY),(0,t.colorize)(`(see doc:`,t.ANSIColors.GREY_DARK),(0,t.colorize)(`https://intlayer.org/doc/concept/cms`,t.ANSIColors.GREY),(0,t.colorize)(`)`,t.ANSIColors.GREY_DARK),`. Alternatively, you can add your own OpenAI API key in the settings`,(0,t.colorize)(`(see doc:`,t.ANSIColors.GREY_DARK),(0,t.colorize)(`https://intlayer.org/doc/concept/configuration`,t.ANSIColors.GREY),(0,t.colorize)(`)`,t.ANSIColors.GREY_DARK),`.`],{level:`error`}),!1)};exports.checkAIAccess=a,exports.checkCMSAuth=i;
|
|
2
2
|
//# sourceMappingURL=checkAccess.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkAccess.cjs","names":["ANSIColors"],"sources":["../../../src/utils/checkAccess.ts"],"sourcesContent":["import type { AIOptions } from '@intlayer/api';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport { ANSIColors, colorize, getAppLogger } from '@intlayer/config/logger';\nimport { extractErrorMessage } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { checkConfigConsistency } from './checkConfigConsistency';\n\nexport const checkCMSAuth = async (\n configuration: IntlayerConfig,\n shouldCheckConfigConsistency: boolean = true\n): Promise<boolean> => {\n const appLogger = getAppLogger(configuration);\n\n const hasCMSAuth =\n configuration.editor.clientId && configuration.editor.clientSecret;\n if (!hasCMSAuth) {\n appLogger(\n [\n 'CMS auth not provided. You can either retreive the CMS access key on',\n colorize('https://intlayer.org/dahboard', ANSIColors.GREY),\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize('https://intlayer.org/doc/concept/cms', ANSIColors.GREY),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n {\n level: 'error',\n }\n );\n\n return false;\n }\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n try {\n const result = await intlayerAPI.oAuth.getOAuth2AccessToken();\n\n const project = result.data?.project;\n\n if (!project) {\n appLogger('Project not found');\n\n return true;\n }\n\n if (project.configuration && shouldCheckConfigConsistency) {\n try {\n let remoteConfigToCheck = project.configuration;\n\n // Remove server-side computed flags (apiKeyConfigured)\n // We use destructuring + spread to avoid the 'delete' operator (performance)\n if (\n remoteConfigToCheck.ai &&\n 'apiKeyConfigured' in remoteConfigToCheck.ai\n ) {\n const { apiKeyConfigured, ...restAi } = remoteConfigToCheck.ai as any;\n\n remoteConfigToCheck = {\n ...remoteConfigToCheck,\n ai: restAi,\n };\n }\n\n // Recursively check if project.configuration (subset) matches configuration (superset)\n checkConfigConsistency(remoteConfigToCheck, configuration);\n } catch {\n appLogger(\n [\n 'Remote configuration is not up to date. The project configuration does not match the local configuration.',\n 'You can push the configuration by running',\n colorize('npx intlayer configuration push', ANSIColors.CYAN),\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize(\n 'https://intlayer.org/doc/concept/cli/push',\n ANSIColors.GREY\n ),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n {\n level: 'warn',\n }\n );\n }\n }\n } catch (error) {\n const message = extractErrorMessage(error);\n\n appLogger(message, {\n level: 'error',\n });\n return false;\n }\n\n return true;\n};\n\nexport const checkAIAccess = async (\n configuration: IntlayerConfig,\n aiOptions?: AIOptions,\n shouldCheckConfigConsistency: boolean = true\n): Promise<boolean> => {\n const appLogger = getAppLogger(configuration);\n\n const hasCMSAuth = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n const isOllama =\n configuration.ai?.provider === 'ollama' || aiOptions?.provider === 'ollama';\n const hasHisOwnAIAPIKey = Boolean(\n configuration.ai?.apiKey || aiOptions?.apiKey\n );\n\n if (hasHisOwnAIAPIKey || isOllama) {\n return true;\n }\n\n // User need to provide either his own AI API key or the CMS auth\n if (!hasCMSAuth) {\n appLogger(\n [\n 'AI options or API key not provided. You can either retreive the CMS access key on',\n colorize('https://intlayer.org/dahboard', ANSIColors.GREY),\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize('https://intlayer.org/doc/concept/cms', ANSIColors.GREY),\n colorize(')', ANSIColors.GREY_DARK),\n '. Alternatively, you can add your own OpenAI API key in the settings',\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize(\n 'https://intlayer.org/doc/concept/configuration',\n ANSIColors.GREY\n ),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n {\n level: 'error',\n }\n );\n\n return false;\n }\n\n // If the user do not have his own AI API key, we need to check the CMS auth\n return await checkCMSAuth(configuration, shouldCheckConfigConsistency);\n};\n"],"mappings":"wQAOA,MAAa,EAAe,MAC1B,EACA,EAAwC,KACnB,CACrB,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAI7C,GAAI,EADF,EAAc,OAAO,UAAY,EAAc,OAAO,cAgBtD,OAdA,EACE,CACE,sFACS,gCAAiCA,EAAAA,WAAW,KAAK,gBACjD,YAAaA,EAAAA,WAAW,UAAU,gBAClC,uCAAwCA,EAAAA,WAAW,KAAK,gBACxD,IAAKA,EAAAA,WAAW,UAAU,CACnC,IACD,CACD,CACE,MAAO,QACR,CACF,CAEM,GAET,IAAM,GAAA,EAAA,EAAA,qBAAkC,IAAA,GAAW,EAAc,CAEjE,GAAI,CAGF,IAAM,GAFS,MAAM,EAAY,MAAM,sBAAsB,EAEtC,MAAM,QAE7B,GAAI,CAAC,EAGH,OAFA,EAAU,oBAAoB,CAEvB,GAGT,GAAI,EAAQ,eAAiB,EAC3B,GAAI,CACF,IAAI,EAAsB,EAAQ,cAIlC,GACE,EAAoB,IACpB,qBAAsB,EAAoB,GAC1C,CACA,GAAM,CAAE,mBAAkB,GAAG,GAAW,EAAoB,GAE5D,EAAsB,CACpB,GAAG,EACH,GAAI,EACL,CAIH,EAAA,uBAAuB,EAAqB,EAAc,MACpD,CACN,EACE,CACE,4GACA,2DACS,kCAAmCA,EAAAA,WAAW,KAAK,gBACnD,YAAaA,EAAAA,WAAW,UAAU,gBAEzC,4CACAA,EAAAA,WAAW,KACZ,gBACQ,IAAKA,EAAAA,WAAW,UAAU,CACnC,IACD,CACD,CACE,MAAO,OACR,CACF,QAGE,EAAO,CAMd,OAHA,GAAA,EAAA,EAAA,qBAFoC,EAAM,CAEvB,CACjB,MAAO,QACR,CAAC,CACK,GAGT,MAAO,IAGI,EAAgB,MAC3B,EACA,EACA,EAAwC,KACnB,CACrB,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,EAAa,GACjB,EAAc,OAAO,UAAY,EAAc,OAAO,cAElD,EACJ,EAAc,IAAI,WAAa,UAAY,GAAW,WAAa,SAoCrE,OAlCE,EAAc,IAAI,QAAU,GAAW,QAGhB,EAChB,GAIJ,EA0BE,MAAM,EAAa,EAAe,EAA6B,EAzBpE,EACE,CACE,mGACS,gCAAiCA,EAAAA,WAAW,KAAK,gBACjD,YAAaA,EAAAA,WAAW,UAAU,gBAClC,uCAAwCA,EAAAA,WAAW,KAAK,gBACxD,IAAKA,EAAAA,WAAW,UAAU,CACnC,sFACS,YAAaA,EAAAA,WAAW,UAAU,gBAEzC,iDACAA,EAAAA,WAAW,KACZ,gBACQ,IAAKA,EAAAA,WAAW,UAAU,CACnC,IACD,CACD,CACE,MAAO,QACR,CACF,CAEM"}
|
|
1
|
+
{"version":3,"file":"checkAccess.cjs","names":["ANSIColors"],"sources":["../../../src/utils/checkAccess.ts"],"sourcesContent":["import type { AIOptions } from '@intlayer/api';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport { ANSIColors, colorize, getAppLogger } from '@intlayer/config/logger';\nimport { extractErrorMessage } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { checkConfigConsistency } from './checkConfigConsistency';\n\nexport const checkCMSAuth = async (\n configuration: IntlayerConfig,\n shouldCheckConfigConsistency: boolean = true\n): Promise<boolean> => {\n const appLogger = getAppLogger(configuration);\n\n const hasCMSAuth =\n configuration.editor.clientId && configuration.editor.clientSecret;\n if (!hasCMSAuth) {\n appLogger(\n [\n 'CMS auth not provided. You can either retreive the CMS access key on',\n colorize('https://intlayer.org/dahboard', ANSIColors.GREY),\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize('https://intlayer.org/doc/concept/cms', ANSIColors.GREY),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n {\n level: 'error',\n }\n );\n\n return false;\n }\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n try {\n const result = await intlayerAPI.oAuth.getOAuth2AccessToken();\n\n const project = result.data?.project;\n\n if (!project) {\n appLogger('Project not found');\n\n return true;\n }\n\n if (project.configuration && shouldCheckConfigConsistency) {\n try {\n let remoteConfigToCheck = project.configuration;\n\n // Remove server-side computed flags (apiKeyConfigured)\n // We use destructuring + spread to avoid the 'delete' operator (performance)\n if (\n remoteConfigToCheck.ai &&\n 'apiKeyConfigured' in remoteConfigToCheck.ai\n ) {\n const { apiKeyConfigured, ...restAi } = remoteConfigToCheck.ai as any;\n\n remoteConfigToCheck = {\n ...remoteConfigToCheck,\n ai: restAi,\n };\n }\n\n // Recursively check if project.configuration (subset) matches configuration (superset)\n checkConfigConsistency(remoteConfigToCheck, configuration);\n } catch {\n appLogger(\n [\n 'Remote configuration is not up to date. The project configuration does not match the local configuration.',\n 'You can push the configuration by running',\n colorize('npx intlayer configuration push', ANSIColors.CYAN),\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize(\n 'https://intlayer.org/doc/concept/cli/push',\n ANSIColors.GREY\n ),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n {\n level: 'warn',\n }\n );\n }\n }\n } catch (error) {\n const message = extractErrorMessage(error);\n\n appLogger(message, {\n level: 'error',\n });\n return false;\n }\n\n return true;\n};\n\nexport const checkAIAccess = async (\n configuration: IntlayerConfig,\n aiOptions?: AIOptions,\n shouldCheckConfigConsistency: boolean = true\n): Promise<boolean> => {\n const appLogger = getAppLogger(configuration);\n\n const hasCMSAuth = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n const isOllama =\n configuration.ai?.provider === 'ollama' || aiOptions?.provider === 'ollama';\n const hasHisOwnAIAPIKey = Boolean(\n configuration.ai?.apiKey || aiOptions?.apiKey\n );\n\n if (hasHisOwnAIAPIKey || isOllama) {\n return true;\n }\n\n // User need to provide either his own AI API key or the CMS auth\n if (!hasCMSAuth) {\n appLogger(\n [\n 'AI options or API key not provided. You can either retreive the CMS access key on',\n colorize('https://intlayer.org/dahboard', ANSIColors.GREY),\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize('https://intlayer.org/doc/concept/cms', ANSIColors.GREY),\n colorize(')', ANSIColors.GREY_DARK),\n '. Alternatively, you can add your own OpenAI API key in the settings',\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize(\n 'https://intlayer.org/doc/concept/configuration',\n ANSIColors.GREY\n ),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n {\n level: 'error',\n }\n );\n\n return false;\n }\n\n // If the user do not have his own AI API key, we need to check the CMS auth\n return await checkCMSAuth(configuration, shouldCheckConfigConsistency);\n};\n"],"mappings":"wQAOA,MAAa,EAAe,MAC1B,EACA,EAAwC,KACnB,CACrB,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAI7C,GAAI,EADF,EAAc,OAAO,UAAY,EAAc,OAAO,cAgBtD,OAdA,EACE,CACE,sFACS,gCAAiCA,EAAAA,WAAW,KAAK,gBACjD,YAAaA,EAAAA,WAAW,UAAU,gBAClC,uCAAwCA,EAAAA,WAAW,KAAK,gBACxD,IAAKA,EAAAA,WAAW,UAAU,CACnC,IACD,CACD,CACE,MAAO,QACR,CACF,CAEM,GAET,IAAM,GAAA,EAAA,EAAA,qBAAkC,IAAA,GAAW,EAAc,CAEjE,GAAI,CAGF,IAAM,GAFS,MAAM,EAAY,MAAM,sBAAsB,EAEtC,MAAM,QAE7B,GAAI,CAAC,EAGH,OAFA,EAAU,oBAAoB,CAEvB,GAGT,GAAI,EAAQ,eAAiB,EAC3B,GAAI,CACF,IAAI,EAAsB,EAAQ,cAIlC,GACE,EAAoB,IACpB,qBAAsB,EAAoB,GAC1C,CACA,GAAM,CAAE,mBAAkB,GAAG,GAAW,EAAoB,GAE5D,EAAsB,CACpB,GAAG,EACH,GAAI,EACL,CAIH,EAAA,uBAAuB,EAAqB,EAAc,MACpD,CACN,EACE,CACE,4GACA,2DACS,kCAAmCA,EAAAA,WAAW,KAAK,gBACnD,YAAaA,EAAAA,WAAW,UAAU,gBAEzC,4CACAA,EAAAA,WAAW,KACZ,gBACQ,IAAKA,EAAAA,WAAW,UAAU,CACnC,IACD,CACD,CACE,MAAO,OACR,CACF,QAGE,EAAO,CAMd,OAHA,GAAA,EAAA,EAAA,qBAFoC,EAAM,CAEvB,CACjB,MAAO,QACR,CAAC,CACK,GAGT,MAAO,IAGI,EAAgB,MAC3B,EACA,EACA,EAAwC,KACnB,CACrB,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,EAAa,GACjB,EAAc,OAAO,UAAY,EAAc,OAAO,cAElD,EACJ,EAAc,IAAI,WAAa,UAAY,GAAW,WAAa,SAoCrE,OAlCE,EAAc,IAAI,QAAU,GAAW,QAGhB,EAChB,GAIJ,EA0BE,MAAM,EAAa,EAAe,EAA6B,EAzBpE,EACE,CACE,mGACS,gCAAiCA,EAAAA,WAAW,KAAK,gBACjD,YAAaA,EAAAA,WAAW,UAAU,gBAClC,uCAAwCA,EAAAA,WAAW,KAAK,gBACxD,IAAKA,EAAAA,WAAW,UAAU,CACnC,sFACS,YAAaA,EAAAA,WAAW,UAAU,gBAEzC,iDACAA,EAAAA,WAAW,KACZ,gBACQ,IAAKA,EAAAA,WAAW,UAAU,CACnC,IACD,CACD,CACE,MAAO,QACR,CACF,CAEM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunkInference.cjs","names":[],"sources":["../../../src/utils/chunkInference.ts"],"sourcesContent":["import type { AIConfig, AIOptions } from '@intlayer/ai';\nimport { getIntlayerAPIProxy, type Messages } from '@intlayer/api';\nimport { retryManager } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport type { AIClient } from './setupAI';\n\ntype ChunkInferenceResult = {\n fileContent: string;\n tokenUsed: number;\n};\n\n/**\n * Translates a single chunk via the OpenAI API.\n * Includes retry logic if the call fails.\n */\nexport const chunkInference = async (\n messages: Messages,\n aiOptions?: AIOptions,\n configuration?: IntlayerConfig,\n aiClient?: AIClient,\n aiConfig?: AIConfig\n): Promise<ChunkInferenceResult> => {\n let lastResult: ChunkInferenceResult;\n\n await retryManager(async () => {\n if (aiClient && aiConfig) {\n const response = await aiClient.customQuery({\n aiConfig,\n messages,\n });\n\n if (!response) {\n throw new Error('No response from AI API');\n }\n\n const { fileContent, tokenUsed } = response;\n\n lastResult = {\n fileContent: processContent(fileContent),\n tokenUsed,\n };\n\n return;\n }\n\n const api = getIntlayerAPIProxy(undefined, configuration);\n\n const response = await api.ai.customQuery({\n aiOptions,\n messages,\n });\n\n if (!response.data) {\n throw new Error('No response from AI API');\n }\n\n const { fileContent, tokenUsed } = response.data;\n\n lastResult = {\n fileContent: processContent(fileContent),\n tokenUsed,\n };\n })();\n\n return lastResult!;\n};\n\nconst processContent = (content: string) => {\n return content\n .replaceAll('///chunksStart///', '')\n .replaceAll('///chunkStart///', '')\n .replaceAll('///chunksEnd///', '')\n .replaceAll('///chunkEnd///', '')\n .replaceAll('///chunksStart///', '')\n .replaceAll('chunkStart///', '')\n .replaceAll('chunksEnd///', '')\n .replaceAll('chunkEnd///', '')\n .replaceAll('///chunksStart', '')\n .replaceAll('///chunkStart', '')\n .replaceAll('///chunksEnd', '')\n .replaceAll('///chunkEnd', '')\n .replaceAll('chunksStart', '')\n .replaceAll('chunkStart', '')\n .replaceAll('chunksEnd', '')\n .replaceAll('chunkEnd', '');\n};\n"],"mappings":"mLAeA,MAAa,EAAiB,MAC5B,EACA,EACA,EACA,EACA,IACkC,CAClC,IAAI,EA0CJ,OAxCA,MAAA,EAAA,EAAA,cAAmB,SAAY,CAC7B,GAAI,GAAY,EAAU,CACxB,IAAM,EAAW,MAAM,EAAS,YAAY,CAC1C,WACA,WACD,CAAC,CAEF,GAAI,CAAC,EACH,MAAU,MAAM,0BAA0B,CAG5C,GAAM,CAAE,cAAa,aAAc,EAEnC,EAAa,CACX,YAAa,EAAe,EAAY,CACxC,YACD,CAED,OAKF,IAAM,EAAW,MAAA,EAAA,EAAA,qBAFe,IAAA,GAAW,EAAc,CAE9B,GAAG,YAAY,CACxC,YACA,WACD,CAAC,CAEF,GAAI,CAAC,EAAS,KACZ,MAAU,MAAM,0BAA0B,CAG5C,GAAM,CAAE,cAAa,aAAc,EAAS,KAE5C,EAAa,CACX,YAAa,EAAe,EAAY,CACxC,YACD,EACD,EAAE,CAEG,GAGH,EAAkB,GACf,EACJ,WAAW,oBAAqB,GAAG,CACnC,WAAW,mBAAoB,GAAG,CAClC,WAAW,kBAAmB,GAAG,CACjC,WAAW,iBAAkB,GAAG,CAChC,WAAW,oBAAqB,GAAG,CACnC,WAAW,gBAAiB,GAAG,CAC/B,WAAW,eAAgB,GAAG,CAC9B,WAAW,cAAe,GAAG,CAC7B,WAAW,iBAAkB,GAAG,CAChC,WAAW,gBAAiB,GAAG,CAC/B,WAAW,eAAgB,GAAG,CAC9B,WAAW,cAAe,GAAG,CAC7B,WAAW,cAAe,GAAG,CAC7B,WAAW,aAAc,GAAG,CAC5B,WAAW,YAAa,GAAG,CAC3B,WAAW,WAAY,GAAG"}
|
|
1
|
+
{"version":3,"file":"chunkInference.cjs","names":[],"sources":["../../../src/utils/chunkInference.ts"],"sourcesContent":["import type { AIConfig, AIOptions } from '@intlayer/ai';\nimport { getIntlayerAPIProxy, type Messages } from '@intlayer/api';\nimport { retryManager } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { AIClient } from './setupAI';\n\ntype ChunkInferenceResult = {\n fileContent: string;\n tokenUsed: number;\n};\n\n/**\n * Translates a single chunk via the OpenAI API.\n * Includes retry logic if the call fails.\n */\nexport const chunkInference = async (\n messages: Messages,\n aiOptions?: AIOptions,\n configuration?: IntlayerConfig,\n aiClient?: AIClient,\n aiConfig?: AIConfig\n): Promise<ChunkInferenceResult> => {\n let lastResult: ChunkInferenceResult;\n\n await retryManager(async () => {\n if (aiClient && aiConfig) {\n const response = await aiClient.customQuery({\n aiConfig,\n messages,\n });\n\n if (!response) {\n throw new Error('No response from AI API');\n }\n\n const { fileContent, tokenUsed } = response;\n\n lastResult = {\n fileContent: processContent(fileContent),\n tokenUsed,\n };\n\n return;\n }\n\n const api = getIntlayerAPIProxy(undefined, configuration);\n\n const response = await api.ai.customQuery({\n aiOptions,\n messages,\n });\n\n if (!response.data) {\n throw new Error('No response from AI API');\n }\n\n const { fileContent, tokenUsed } = response.data;\n\n lastResult = {\n fileContent: processContent(fileContent),\n tokenUsed,\n };\n })();\n\n return lastResult!;\n};\n\nconst processContent = (content: string) => {\n return content\n .replaceAll('///chunksStart///', '')\n .replaceAll('///chunkStart///', '')\n .replaceAll('///chunksEnd///', '')\n .replaceAll('///chunkEnd///', '')\n .replaceAll('///chunksStart///', '')\n .replaceAll('chunkStart///', '')\n .replaceAll('chunksEnd///', '')\n .replaceAll('chunkEnd///', '')\n .replaceAll('///chunksStart', '')\n .replaceAll('///chunkStart', '')\n .replaceAll('///chunksEnd', '')\n .replaceAll('///chunkEnd', '')\n .replaceAll('chunksStart', '')\n .replaceAll('chunkStart', '')\n .replaceAll('chunksEnd', '')\n .replaceAll('chunkEnd', '');\n};\n"],"mappings":"mLAeA,MAAa,EAAiB,MAC5B,EACA,EACA,EACA,EACA,IACkC,CAClC,IAAI,EA0CJ,OAxCA,MAAA,EAAA,EAAA,cAAmB,SAAY,CAC7B,GAAI,GAAY,EAAU,CACxB,IAAM,EAAW,MAAM,EAAS,YAAY,CAC1C,WACA,WACD,CAAC,CAEF,GAAI,CAAC,EACH,MAAU,MAAM,0BAA0B,CAG5C,GAAM,CAAE,cAAa,aAAc,EAEnC,EAAa,CACX,YAAa,EAAe,EAAY,CACxC,YACD,CAED,OAKF,IAAM,EAAW,MAAA,EAAA,EAAA,qBAFe,IAAA,GAAW,EAAc,CAE9B,GAAG,YAAY,CACxC,YACA,WACD,CAAC,CAEF,GAAI,CAAC,EAAS,KACZ,MAAU,MAAM,0BAA0B,CAG5C,GAAM,CAAE,cAAa,aAAc,EAAS,KAE5C,EAAa,CACX,YAAa,EAAe,EAAY,CACxC,YACD,EACD,EAAE,CAEG,GAGH,EAAkB,GACf,EACJ,WAAW,oBAAqB,GAAG,CACnC,WAAW,mBAAoB,GAAG,CAClC,WAAW,kBAAmB,GAAG,CACjC,WAAW,iBAAkB,GAAG,CAChC,WAAW,oBAAqB,GAAG,CACnC,WAAW,gBAAiB,GAAG,CAC/B,WAAW,eAAgB,GAAG,CAC9B,WAAW,cAAe,GAAG,CAC7B,WAAW,iBAAkB,GAAG,CAChC,WAAW,gBAAiB,GAAG,CAC/B,WAAW,eAAgB,GAAG,CAC9B,WAAW,cAAe,GAAG,CAC7B,WAAW,cAAe,GAAG,CAC7B,WAAW,aAAc,GAAG,CAC5B,WAAW,YAAa,GAAG,CAC3B,WAAW,WAAY,GAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getOutputFilePath.cjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types';\n\n/**\n * Get the output file path by replacing the base locale with the target locale\n *\n * This function handles two types of replacements:\n * 1. Actual locale values (e.g., `/en/` → `/fr/`)\n * 2. Template placeholders (e.g., `{{baseLocale}}` → `{{locale}}`, `{{baseLocaleName}}` → `{{localeName}}`)\n *\n * Replacement patterns:\n * - `/baseLocale/` → `/locale/`\n * - `\\baseLocale\\` → `\\locale\\`\n * - `_baseLocale.` → `_locale.`\n * - `baseLocale_` → `locale_`\n * - `.baseLocaleName.` → `.localeName.`\n * - `{{baseLocale}}` → `{{locale}}`\n * - `{{baseLocaleName}}` → `{{localeName}}`\n *\n * If no patterns match, appends `.locale` to the file extension.\n *\n * @param filePath - The input file path\n * @param locale - The target locale\n * @param baseLocale - The base locale to replace\n * @returns The output file path with locale replacements\n */\nexport const getOutputFilePath = (\n filePath: string,\n locale: LocalesValues,\n baseLocale: LocalesValues\n): string => {\n if (!filePath || !locale || !baseLocale) {\n throw new Error('filePath, locale, and baseLocale are required');\n }\n\n let outputFilePath = filePath;\n\n // Define replacement patterns with global flag to replace all occurrences\n const replacements = [\n // Template placeholders (processed first)\n {\n pattern: /\\{\\{baseLocale\\}\\}/g,\n replacement: '{{locale}}',\n },\n {\n pattern: /\\{\\{baseLocaleName\\}\\}/g,\n replacement: '{{localeName}}',\n },\n\n // Path separators (most specific first)\n {\n // Unix path separators\n pattern: new RegExp(`/${baseLocale}/`, 'g'),\n replacement: `/${locale}/`,\n },\n {\n // Windows path separators\n pattern: new RegExp(`\\\\\\\\${baseLocale}\\\\\\\\`, 'g'),\n replacement: `\\\\${locale}\\\\`,\n },\n\n // File naming patterns\n {\n // file_en.md → file_fr.md\n pattern: new RegExp(`_${baseLocale}\\\\.`, 'g'),\n replacement: `_${locale}.`,\n },\n {\n // /file_en.md → /file_fr.md\n pattern: new RegExp(`/${baseLocale}_`, 'g'),\n replacement: `/${locale}_`,\n },\n {\n // Start of filename pattern en_guide.md → fr_guide.md (or after path separator)\n pattern: new RegExp(`(^|[\\\\/])${baseLocale}_`, 'g'),\n replacement: `$1${locale}_`,\n },\n {\n // Dot delimited pattern guide.en.md → guide.fr.md\n pattern: new RegExp(`\\\\.${baseLocale}\\\\.`, 'g'),\n replacement: `.${locale}.`,\n },\n ];\n\n // Apply all replacements\n for (const { pattern, replacement } of replacements) {\n outputFilePath = outputFilePath.replace(pattern, replacement);\n }\n\n // If no changes were made, append locale as extension\n if (outputFilePath === filePath) {\n const lastDotIndex = filePath.lastIndexOf('.');\n if (lastDotIndex > 0) {\n // Insert locale before the file extension\n return `${filePath.slice(0, lastDotIndex)}.${locale}${filePath.slice(lastDotIndex)}`;\n } else {\n // No extension found, just append\n return `${filePath}.${locale}`;\n }\n }\n\n return outputFilePath;\n};\n"],"mappings":"mEAyBA,MAAa,GACX,EACA,EACA,IACW,CACX,GAAI,CAAC,GAAY,CAAC,GAAU,CAAC,EAC3B,MAAU,MAAM,gDAAgD,CAGlE,IAAI,EAAiB,EAGf,EAAe,CAEnB,CACE,QAAS,sBACT,YAAa,aACd,CACD,CACE,QAAS,0BACT,YAAa,iBACd,CAGD,CAEE,QAAa,OAAO,IAAI,EAAW,GAAI,IAAI,CAC3C,YAAa,IAAI,EAAO,GACzB,CACD,CAEE,QAAa,OAAO,OAAO,EAAW,MAAO,IAAI,CACjD,YAAa,KAAK,EAAO,IAC1B,CAGD,CAEE,QAAa,OAAO,IAAI,EAAW,KAAM,IAAI,CAC7C,YAAa,IAAI,EAAO,GACzB,CACD,CAEE,QAAa,OAAO,IAAI,EAAW,GAAI,IAAI,CAC3C,YAAa,IAAI,EAAO,GACzB,CACD,CAEE,QAAa,OAAO,YAAY,EAAW,GAAI,IAAI,CACnD,YAAa,KAAK,EAAO,GAC1B,CACD,CAEE,QAAa,OAAO,MAAM,EAAW,KAAM,IAAI,CAC/C,YAAa,IAAI,EAAO,GACzB,CACF,CAGD,IAAK,GAAM,CAAE,UAAS,iBAAiB,EACrC,EAAiB,EAAe,QAAQ,EAAS,EAAY,CAI/D,GAAI,IAAmB,EAAU,CAC/B,IAAM,EAAe,EAAS,YAAY,IAAI,CAM5C,OALE,EAAe,EAEV,GAAG,EAAS,MAAM,EAAG,EAAa,CAAC,GAAG,IAAS,EAAS,MAAM,EAAa,GAG3E,GAAG,EAAS,GAAG,IAI1B,OAAO"}
|
|
1
|
+
{"version":3,"file":"getOutputFilePath.cjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Get the output file path by replacing the base locale with the target locale\n *\n * This function handles two types of replacements:\n * 1. Actual locale values (e.g., `/en/` → `/fr/`)\n * 2. Template placeholders (e.g., `{{baseLocale}}` → `{{locale}}`, `{{baseLocaleName}}` → `{{localeName}}`)\n *\n * Replacement patterns:\n * - `/baseLocale/` → `/locale/`\n * - `\\baseLocale\\` → `\\locale\\`\n * - `_baseLocale.` → `_locale.`\n * - `baseLocale_` → `locale_`\n * - `.baseLocaleName.` → `.localeName.`\n * - `{{baseLocale}}` → `{{locale}}`\n * - `{{baseLocaleName}}` → `{{localeName}}`\n *\n * If no patterns match, appends `.locale` to the file extension.\n *\n * @param filePath - The input file path\n * @param locale - The target locale\n * @param baseLocale - The base locale to replace\n * @returns The output file path with locale replacements\n */\nexport const getOutputFilePath = (\n filePath: string,\n locale: LocalesValues,\n baseLocale: LocalesValues\n): string => {\n if (!filePath || !locale || !baseLocale) {\n throw new Error('filePath, locale, and baseLocale are required');\n }\n\n let outputFilePath = filePath;\n\n // Define replacement patterns with global flag to replace all occurrences\n const replacements = [\n // Template placeholders (processed first)\n {\n pattern: /\\{\\{baseLocale\\}\\}/g,\n replacement: '{{locale}}',\n },\n {\n pattern: /\\{\\{baseLocaleName\\}\\}/g,\n replacement: '{{localeName}}',\n },\n\n // Path separators (most specific first)\n {\n // Unix path separators\n pattern: new RegExp(`/${baseLocale}/`, 'g'),\n replacement: `/${locale}/`,\n },\n {\n // Windows path separators\n pattern: new RegExp(`\\\\\\\\${baseLocale}\\\\\\\\`, 'g'),\n replacement: `\\\\${locale}\\\\`,\n },\n\n // File naming patterns\n {\n // file_en.md → file_fr.md\n pattern: new RegExp(`_${baseLocale}\\\\.`, 'g'),\n replacement: `_${locale}.`,\n },\n {\n // /file_en.md → /file_fr.md\n pattern: new RegExp(`/${baseLocale}_`, 'g'),\n replacement: `/${locale}_`,\n },\n {\n // Start of filename pattern en_guide.md → fr_guide.md (or after path separator)\n pattern: new RegExp(`(^|[\\\\/])${baseLocale}_`, 'g'),\n replacement: `$1${locale}_`,\n },\n {\n // Dot delimited pattern guide.en.md → guide.fr.md\n pattern: new RegExp(`\\\\.${baseLocale}\\\\.`, 'g'),\n replacement: `.${locale}.`,\n },\n ];\n\n // Apply all replacements\n for (const { pattern, replacement } of replacements) {\n outputFilePath = outputFilePath.replace(pattern, replacement);\n }\n\n // If no changes were made, append locale as extension\n if (outputFilePath === filePath) {\n const lastDotIndex = filePath.lastIndexOf('.');\n if (lastDotIndex > 0) {\n // Insert locale before the file extension\n return `${filePath.slice(0, lastDotIndex)}.${locale}${filePath.slice(lastDotIndex)}`;\n } else {\n // No extension found, just append\n return `${filePath}.${locale}`;\n }\n }\n\n return outputFilePath;\n};\n"],"mappings":"mEAyBA,MAAa,GACX,EACA,EACA,IACW,CACX,GAAI,CAAC,GAAY,CAAC,GAAU,CAAC,EAC3B,MAAU,MAAM,gDAAgD,CAGlE,IAAI,EAAiB,EAGf,EAAe,CAEnB,CACE,QAAS,sBACT,YAAa,aACd,CACD,CACE,QAAS,0BACT,YAAa,iBACd,CAGD,CAEE,QAAa,OAAO,IAAI,EAAW,GAAI,IAAI,CAC3C,YAAa,IAAI,EAAO,GACzB,CACD,CAEE,QAAa,OAAO,OAAO,EAAW,MAAO,IAAI,CACjD,YAAa,KAAK,EAAO,IAC1B,CAGD,CAEE,QAAa,OAAO,IAAI,EAAW,KAAM,IAAI,CAC7C,YAAa,IAAI,EAAO,GACzB,CACD,CAEE,QAAa,OAAO,IAAI,EAAW,GAAI,IAAI,CAC3C,YAAa,IAAI,EAAO,GACzB,CACD,CAEE,QAAa,OAAO,YAAY,EAAW,GAAI,IAAI,CACnD,YAAa,KAAK,EAAO,GAC1B,CACD,CAEE,QAAa,OAAO,MAAM,EAAW,KAAM,IAAI,CAC/C,YAAa,IAAI,EAAO,GACzB,CACF,CAGD,IAAK,GAAM,CAAE,UAAS,iBAAiB,EACrC,EAAiB,EAAe,QAAQ,EAAS,EAAY,CAI/D,GAAI,IAAmB,EAAU,CAC/B,IAAM,EAAe,EAAS,YAAY,IAAI,CAM5C,OALE,EAAe,EAEV,GAAG,EAAS,MAAM,EAAG,EAAa,CAAC,GAAG,IAAS,EAAS,MAAM,EAAa,GAG3E,GAAG,EAAS,GAAG,IAI1B,OAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`node:
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`node:fs`),t=require(`node:path`);const n=n=>{let r=n;for(;r!==(0,t.dirname)(r);){let n=(0,t.resolve)(r,`package.json`);if((0,e.existsSync)(n))return JSON.parse((0,e.readFileSync)(n,`utf8`));r=(0,t.dirname)(r)}let i=(0,t.resolve)(r,`package.json`);if((0,e.existsSync)(i))return JSON.parse((0,e.readFileSync)(i,`utf8`));throw Error(`No package.json found in any parent directory of ${n}`)};exports.getParentPackageJSON=n;
|
|
2
2
|
//# sourceMappingURL=getParentPackageJSON.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setupAI.cjs","names":["ANSIColors","checkAIAccess"],"sources":["../../../src/utils/setupAI.ts"],"sourcesContent":["import type { AIConfig, AIOptions } from '@intlayer/ai';\nimport {\n ANSIColors,\n colorize,\n getAppLogger,\n type logger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { checkAIAccess } from './checkAccess';\n\nexport type AIClient = typeof import('@intlayer/ai');\n\ntype SetupAIResult = {\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n isCustomAI: boolean;\n hasAIAccess: boolean;\n};\n\n// Disable warnings from the AI SDK\nglobalThis.AI_SDK_LOG_WARNINGS = false;\n\nconst logAIConfig = (aiOptions: AIOptions, appLogger: typeof logger) => {\n appLogger([\n colorize('Provider:', ANSIColors.GREY_DARK),\n colorize(aiOptions?.provider ?? '(default)', ANSIColors.BLUE),\n colorize('- Model:', ANSIColors.GREY_DARK),\n colorize(aiOptions?.model ?? '(default)', ANSIColors.BLUE),\n colorize('- API Key:', ANSIColors.GREY_DARK),\n colorize(aiOptions?.apiKey ? '✓' : '(not set)', ANSIColors.BLUE),\n ]);\n};\n\n/**\n * Checks if the @intlayer/ai package is available and configured when an API key is provided.\n * If API key is present but package is missing, logs a warning.\n * Also checks if the user has access to AI (either via local key or CMS auth).\n */\nexport const setupAI = async (\n configuration: IntlayerConfig,\n aiOptions?: AIOptions\n): Promise<SetupAIResult | undefined> => {\n const appLogger = getAppLogger(configuration);\n\n const isLocalAI =\n aiOptions?.apiKey ||\n aiOptions?.provider === 'ollama' ||\n configuration.ai?.apiKey ||\n configuration.ai?.provider === 'ollama';\n\n if (isLocalAI) {\n // Try to import the AI package for local AI usage\n let aiClient: AIClient | undefined;\n\n try {\n aiClient = await import('@intlayer/ai');\n } catch {\n // Package not installed - log warning and fall back to backend\n appLogger(\n [\n colorize('Using your API key, you can install the', ANSIColors.GREY),\n colorize('@intlayer/ai', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to run the process locally, with no dependency on the Intlayer server',\n ANSIColors.GREY\n ),\n ],\n {\n level: 'warn',\n }\n );\n\n // Fall back to backend API check\n const hasAIAccess = await checkAIAccess(configuration, aiOptions);\n logAIConfig(aiOptions ?? {}, appLogger);\n return {\n isCustomAI: false,\n hasAIAccess,\n };\n }\n\n // Package found - now configure it (errors here should propagate, not fall back)\n appLogger([\n colorize('@intlayer/ai', ANSIColors.GREY_LIGHT),\n colorize('found - Run process locally', ANSIColors.GREY_DARK),\n ]);\n\n const aiConfig = await aiClient.getAIConfig({\n userOptions: aiOptions,\n accessType: ['public'],\n });\n\n logAIConfig(aiOptions ?? {}, appLogger);\n\n return {\n aiClient,\n aiConfig,\n isCustomAI: true,\n hasAIAccess: true, // Local AI always has access\n };\n }\n\n // No local AI configured - use backend API\n const hasAIAccess = await checkAIAccess(configuration, aiOptions);\n logAIConfig(aiOptions ?? {}, appLogger);\n\n return {\n isCustomAI: false,\n hasAIAccess,\n };\n};\n"],"mappings":"8LAoBA,WAAW,oBAAsB,GAEjC,MAAM,GAAe,EAAsB,IAA6B,CACtE,EAAU,gBACC,YAAaA,EAAAA,WAAW,UAAU,gBAClC,GAAW,UAAY,YAAaA,EAAAA,WAAW,KAAK,gBACpD,WAAYA,EAAAA,WAAW,UAAU,gBACjC,GAAW,OAAS,YAAaA,EAAAA,WAAW,KAAK,gBACjD,aAAcA,EAAAA,WAAW,UAAU,gBACnC,GAAW,OAAS,IAAM,YAAaA,EAAAA,WAAW,KAAK,CACjE,CAAC,EAQS,EAAU,MACrB,EACA,IACuC,CACvC,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAQ7C,GALE,GAAW,QACX,GAAW,WAAa,UACxB,EAAc,IAAI,QAClB,EAAc,IAAI,WAAa,SAElB,CAEb,IAAI,EAEJ,GAAI,CACF,EAAW,MAAM,OAAO,qBAClB,CAEN,EACE,gBACW,0CAA2CA,EAAAA,WAAW,KAAK,gBAC3D,eAAgBA,EAAAA,WAAW,WAAW,gBAE7C,gFACAA,EAAAA,WAAW,KACZ,CACF,CACD,CACE,MAAO,OACR,CACF,CAGD,IAAM,EAAc,MAAMC,EAAAA,cAAc,EAAe,EAAU,CAEjE,OADA,EAAY,GAAa,EAAE,CAAE,EAAU,CAChC,CACL,WAAY,GACZ,cACD,CAIH,EAAU,EAAA,EAAA,EAAA,UACC,eAAgBD,EAAAA,WAAW,WAAW,EAAA,EAAA,EAAA,UACtC,8BAA+BA,EAAAA,WAAW,UAAU,CAC9D,CAAC,CAEF,IAAM,EAAW,MAAM,EAAS,YAAY,CAC1C,YAAa,EACb,WAAY,CAAC,SAAS,CACvB,CAAC,CAIF,OAFA,EAAY,GAAa,EAAE,CAAE,EAAU,CAEhC,CACL,WACA,WACA,WAAY,GACZ,YAAa,GACd,CAIH,IAAM,EAAc,MAAMC,EAAAA,cAAc,EAAe,EAAU,CAGjE,OAFA,EAAY,GAAa,EAAE,CAAE,EAAU,CAEhC,CACL,WAAY,GACZ,cACD"}
|
|
1
|
+
{"version":3,"file":"setupAI.cjs","names":["ANSIColors","checkAIAccess"],"sources":["../../../src/utils/setupAI.ts"],"sourcesContent":["import type { AIConfig, AIOptions } from '@intlayer/ai';\nimport {\n ANSIColors,\n colorize,\n getAppLogger,\n type logger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { checkAIAccess } from './checkAccess';\n\nexport type AIClient = typeof import('@intlayer/ai');\n\ntype SetupAIResult = {\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n isCustomAI: boolean;\n hasAIAccess: boolean;\n};\n\n// Disable warnings from the AI SDK\nglobalThis.AI_SDK_LOG_WARNINGS = false;\n\nconst logAIConfig = (aiOptions: AIOptions, appLogger: typeof logger) => {\n appLogger([\n colorize('Provider:', ANSIColors.GREY_DARK),\n colorize(aiOptions?.provider ?? '(default)', ANSIColors.BLUE),\n colorize('- Model:', ANSIColors.GREY_DARK),\n colorize(aiOptions?.model ?? '(default)', ANSIColors.BLUE),\n colorize('- API Key:', ANSIColors.GREY_DARK),\n colorize(aiOptions?.apiKey ? '✓' : '(not set)', ANSIColors.BLUE),\n ]);\n};\n\n/**\n * Checks if the @intlayer/ai package is available and configured when an API key is provided.\n * If API key is present but package is missing, logs a warning.\n * Also checks if the user has access to AI (either via local key or CMS auth).\n */\nexport const setupAI = async (\n configuration: IntlayerConfig,\n aiOptions?: AIOptions\n): Promise<SetupAIResult | undefined> => {\n const appLogger = getAppLogger(configuration);\n\n const isLocalAI =\n aiOptions?.apiKey ||\n aiOptions?.provider === 'ollama' ||\n configuration.ai?.apiKey ||\n configuration.ai?.provider === 'ollama';\n\n if (isLocalAI) {\n // Try to import the AI package for local AI usage\n let aiClient: AIClient | undefined;\n\n try {\n aiClient = await import('@intlayer/ai');\n } catch {\n // Package not installed - log warning and fall back to backend\n appLogger(\n [\n colorize('Using your API key, you can install the', ANSIColors.GREY),\n colorize('@intlayer/ai', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to run the process locally, with no dependency on the Intlayer server',\n ANSIColors.GREY\n ),\n ],\n {\n level: 'warn',\n }\n );\n\n // Fall back to backend API check\n const hasAIAccess = await checkAIAccess(configuration, aiOptions);\n logAIConfig(aiOptions ?? {}, appLogger);\n return {\n isCustomAI: false,\n hasAIAccess,\n };\n }\n\n // Package found - now configure it (errors here should propagate, not fall back)\n appLogger([\n colorize('@intlayer/ai', ANSIColors.GREY_LIGHT),\n colorize('found - Run process locally', ANSIColors.GREY_DARK),\n ]);\n\n const aiConfig = await aiClient.getAIConfig({\n userOptions: aiOptions,\n accessType: ['public'],\n });\n\n logAIConfig(aiOptions ?? {}, appLogger);\n\n return {\n aiClient,\n aiConfig,\n isCustomAI: true,\n hasAIAccess: true, // Local AI always has access\n };\n }\n\n // No local AI configured - use backend API\n const hasAIAccess = await checkAIAccess(configuration, aiOptions);\n logAIConfig(aiOptions ?? {}, appLogger);\n\n return {\n isCustomAI: false,\n hasAIAccess,\n };\n};\n"],"mappings":"8LAoBA,WAAW,oBAAsB,GAEjC,MAAM,GAAe,EAAsB,IAA6B,CACtE,EAAU,gBACC,YAAaA,EAAAA,WAAW,UAAU,gBAClC,GAAW,UAAY,YAAaA,EAAAA,WAAW,KAAK,gBACpD,WAAYA,EAAAA,WAAW,UAAU,gBACjC,GAAW,OAAS,YAAaA,EAAAA,WAAW,KAAK,gBACjD,aAAcA,EAAAA,WAAW,UAAU,gBACnC,GAAW,OAAS,IAAM,YAAaA,EAAAA,WAAW,KAAK,CACjE,CAAC,EAQS,EAAU,MACrB,EACA,IACuC,CACvC,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAQ7C,GALE,GAAW,QACX,GAAW,WAAa,UACxB,EAAc,IAAI,QAClB,EAAc,IAAI,WAAa,SAElB,CAEb,IAAI,EAEJ,GAAI,CACF,EAAW,MAAM,OAAO,qBAClB,CAEN,EACE,gBACW,0CAA2CA,EAAAA,WAAW,KAAK,gBAC3D,eAAgBA,EAAAA,WAAW,WAAW,gBAE7C,gFACAA,EAAAA,WAAW,KACZ,CACF,CACD,CACE,MAAO,OACR,CACF,CAGD,IAAM,EAAc,MAAMC,EAAAA,cAAc,EAAe,EAAU,CAEjE,OADA,EAAY,GAAa,EAAE,CAAE,EAAU,CAChC,CACL,WAAY,GACZ,cACD,CAIH,EAAU,EAAA,EAAA,EAAA,UACC,eAAgBD,EAAAA,WAAW,WAAW,EAAA,EAAA,EAAA,UACtC,8BAA+BA,EAAAA,WAAW,UAAU,CAC9D,CAAC,CAEF,IAAM,EAAW,MAAM,EAAS,YAAY,CAC1C,YAAa,EACb,WAAY,CAAC,SAAS,CACvB,CAAC,CAIF,OAFA,EAAY,GAAa,EAAE,CAAE,EAAU,CAEhC,CACL,WACA,WACA,WAAY,GACZ,YAAa,GACd,CAIH,IAAM,EAAc,MAAMC,EAAAA,cAAc,EAAe,EAAU,CAGjE,OAFA,EAAY,GAAa,EAAE,CAAE,EAAU,CAEhC,CACL,WAAY,GACZ,cACD"}
|
package/dist/cjs/watch.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`@intlayer/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`@intlayer/chokidar/cli`),t=require(`@intlayer/config/logger`),n=require(`@intlayer/config/node`),r=require(`@intlayer/chokidar/utils`),i=require(`@intlayer/chokidar/watcher`);const a=async a=>{let o=(0,n.getConfiguration)(a?.configOptions);(0,e.logConfigDetails)(a?.configOptions);let s=(0,t.getAppLogger)(o),c;a?.with&&(c=(0,r.runParallel)(a.with),c.result.catch(()=>{process.exit(1)}));let l=(0,i.watch)({persistent:!0,skipPrepare:a?.skipPrepare??!1}),u=async()=>{process.off(`SIGINT`,u),process.off(`SIGTERM`,u),s(`Stopping Intlayer watcher...`);try{await l.close(),c&&`child`in c&&c.child?.kill(`SIGTERM`)}catch(e){console.error(`Error during shutdown:`,e)}finally{process.exit(0)}};process.on(`SIGINT`,u),process.on(`SIGTERM`,u)};exports.watchContentDeclaration=a;
|
|
2
2
|
//# sourceMappingURL=watch.cjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{getAppLogger as e}from"@intlayer/config/logger";import{getIntlayerAPIProxy as t}from"@intlayer/api";import n from"@intlayer/config/built";import{EventSource as r}from"eventsource";var i=class{appLogger=e(n);eventSource=null;reconnectAttempts=0;maxReconnectAttempts=5;reconnectDelay=1e3;isManuallyDisconnected=!1;reconnectTimeout=null;onDictionaryAdded;onDictionaryChange;onDictionaryDeleted;onConnectionOpen;onConnectionError;constructor(t=n){this.intlayerConfig=t,this.appLogger=e(this.intlayerConfig)}async initialize(){this.isManuallyDisconnected=!1,await this.connect()}async connect(){try{let e=this.intlayerConfig.editor.backendURL,n=await t(void 0,this.intlayerConfig).oAuth.getOAuth2AccessToken();if(!n)throw Error(`Failed to retrieve access token`);let i=`${e}/api/event-listener`;this.eventSource&&this.eventSource.close(),this.eventSource=new r(i,{fetch:(e,t)=>fetch(e,{...t,headers:{...t?.headers??{},Authorization:`Bearer ${n.data?.accessToken}`}})}),this.eventSource.onopen=()=>{this.reconnectAttempts=0,this.reconnectDelay=1e3,this.onConnectionOpen?.()},this.eventSource.onmessage=e=>this.handleMessage(e),this.eventSource.onerror=e=>this.handleError(e)}catch{this.appLogger(`Failed to establish EventSource connection:`,{level:`error`}),this.scheduleReconnect()}}cleanup(){this.isManuallyDisconnected=!0,this.reconnectTimeout&&=(clearTimeout(this.reconnectTimeout),null),this.eventSource&&=(this.eventSource.close(),null)}scheduleReconnect(){if(this.isManuallyDisconnected||this.reconnectAttempts>=this.maxReconnectAttempts){this.reconnectAttempts>=this.maxReconnectAttempts&&this.appLogger([`Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`],{level:`error`});return}this.reconnectAttempts++;let e=this.reconnectDelay*2**(this.reconnectAttempts-1);this.appLogger(`Scheduling reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${e}ms`),this.reconnectTimeout=setTimeout(async()=>{this.isManuallyDisconnected||await this.connect()},e)}async handleMessage(e){try{let{data:t}=e,n=JSON.parse(t);for(let e of n)switch(e.object){case`DICTIONARY`:switch(e.status){case`ADDED`:await this.onDictionaryAdded?.(e.data);break;case`UPDATED`:await this.onDictionaryChange?.(e.data);break;case`DELETED`:await this.onDictionaryDeleted?.(e.data);break;default:this.appLogger([`Unhandled dictionary status:`,e.status],{level:`error`});break}break;default:this.appLogger([`Unknown object type:`,e.object],{level:`error`});break}}catch(e){this.appLogger([`Error processing dictionary update:`,e],{level:`error`})}}handleError(e){let t=e;this.appLogger([`EventSource error:`,{type:t.type,message:t.message,code:t.code,readyState:this.eventSource?.readyState,url:this.eventSource?.url}],{level:`error`}),this.onConnectionError?.(e),t.type===`error`&&(t.message?.includes(`terminated`)||t.message?.includes(`closed`)||this.eventSource?.readyState===r.CLOSED)&&!this.isManuallyDisconnected?(this.appLogger(`Connection was terminated by server, attempting to reconnect...`),this.scheduleReconnect()):this.cleanup()}};export{i as IntlayerEventListener};
|
|
2
2
|
//# sourceMappingURL=IntlayerEventListener.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IntlayerEventListener.mjs","names":[],"sources":["../../src/IntlayerEventListener.ts"],"sourcesContent":["import { getIntlayerAPIProxy } from '@intlayer/api';\n// @ts-ignore: @intlayer/backend is not built yet\nimport type { DictionaryAPI, MessageEventData } from '@intlayer/backend';\nimport configuration from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { EventSource } from 'eventsource';\n\nexport type IntlayerMessageEvent = MessageEvent;\n\n/**\n * IntlayerEventListener class to listen for dictionary changes via SSE (Server-Sent Events).\n *\n * Usage example:\n *\n * import { buildIntlayerDictionary } from './transpiler/declaration_file_to_dictionary/intlayer_dictionary';\n * import { IntlayerEventListener } from '@intlayer/api';\n *\n * export const checkDictionaryChanges = async () => {\n * // Instantiate the listener\n * const eventListener = new IntlayerEventListener();\n *\n * // Set up your callbacks\n * eventListener.onDictionaryChange = async (dictionary) => {\n * await buildIntlayerDictionary(dictionary);\n * };\n *\n * // Initialize the listener\n * await eventListener.initialize();\n *\n * // Optionally, clean up later when you’re done\n * // eventListener.cleanup();\n * };\n */\nexport class IntlayerEventListener {\n private appLogger = getAppLogger(configuration);\n\n private eventSource: EventSource | null = null;\n private reconnectAttempts = 0;\n private maxReconnectAttempts = 5;\n private reconnectDelay = 1000; // Start with 1 second\n private isManuallyDisconnected = false;\n private reconnectTimeout: NodeJS.Timeout | null = null;\n\n /**\n * Callback triggered when a Dictionary is ADDED.\n */\n public onDictionaryAdded?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when a Dictionary is UPDATED.\n */\n public onDictionaryChange?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when a Dictionary is DELETED.\n */\n public onDictionaryDeleted?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when connection is established or re-established.\n */\n public onConnectionOpen?: () => any;\n\n /**\n * Callback triggered when connection encounters an error.\n */\n public onConnectionError?: (error: Event) => any;\n\n constructor(private intlayerConfig: IntlayerConfig = configuration) {\n this.appLogger = getAppLogger(this.intlayerConfig);\n }\n\n /**\n * Initializes the EventSource connection using the given intlayerConfig\n * (or the default config if none was provided).\n */\n public async initialize(): Promise<void> {\n this.isManuallyDisconnected = false;\n await this.connect();\n }\n\n /**\n * Establishes the EventSource connection with automatic reconnection support.\n */\n private async connect(): Promise<void> {\n try {\n const backendURL = this.intlayerConfig.editor.backendURL;\n\n // Retrieve the access token via proxy\n const accessToken = await getIntlayerAPIProxy(\n undefined,\n this.intlayerConfig\n ).oAuth.getOAuth2AccessToken();\n\n if (!accessToken) {\n throw new Error('Failed to retrieve access token');\n }\n\n const API_ROUTE = `${backendURL}/api/event-listener`;\n\n // Close existing connection if any\n if (this.eventSource) {\n this.eventSource.close();\n }\n\n this.eventSource = new EventSource(API_ROUTE, {\n fetch: (input, init) =>\n fetch(input, {\n ...init,\n headers: {\n ...(init?.headers ?? {}),\n Authorization: `Bearer ${accessToken.data?.accessToken}`,\n },\n }),\n });\n\n this.eventSource.onopen = () => {\n this.reconnectAttempts = 0;\n this.reconnectDelay = 1000; // Reset delay\n this.onConnectionOpen?.();\n };\n\n this.eventSource.onmessage = (event) => this.handleMessage(event);\n this.eventSource.onerror = (event) => this.handleError(event);\n } catch (_error) {\n this.appLogger('Failed to establish EventSource connection:', {\n level: 'error',\n });\n this.scheduleReconnect();\n }\n }\n\n /**\n * Cleans up (closes) the EventSource connection.\n */\n public cleanup(): void {\n this.isManuallyDisconnected = true;\n\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n }\n\n /**\n * Schedules a reconnection attempt with exponential backoff.\n */\n private scheduleReconnect(): void {\n if (\n this.isManuallyDisconnected ||\n this.reconnectAttempts >= this.maxReconnectAttempts\n ) {\n if (this.reconnectAttempts >= this.maxReconnectAttempts) {\n this.appLogger(\n [\n `Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`,\n ],\n {\n level: 'error',\n }\n );\n }\n return;\n }\n\n this.reconnectAttempts++;\n const delay = this.reconnectDelay * 2 ** (this.reconnectAttempts - 1); // Exponential backoff\n\n this.appLogger(\n `Scheduling reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`\n );\n\n this.reconnectTimeout = setTimeout(async () => {\n if (!this.isManuallyDisconnected) {\n await this.connect();\n }\n }, delay);\n }\n\n /**\n * Handles incoming SSE messages, parses the event data,\n * and invokes the appropriate callback.\n */\n private async handleMessage(event: IntlayerMessageEvent): Promise<void> {\n try {\n const { data } = event;\n\n const dataJSON: MessageEventData[] = JSON.parse(data);\n\n for (const dataEl of dataJSON) {\n switch (dataEl.object) {\n case 'DICTIONARY':\n switch (dataEl.status) {\n case 'ADDED':\n await this.onDictionaryAdded?.(dataEl.data);\n break;\n case 'UPDATED':\n await this.onDictionaryChange?.(dataEl.data);\n break;\n case 'DELETED':\n await this.onDictionaryDeleted?.(dataEl.data);\n break;\n default:\n this.appLogger(\n ['Unhandled dictionary status:', dataEl.status],\n {\n level: 'error',\n }\n );\n break;\n }\n break;\n default:\n this.appLogger(['Unknown object type:', dataEl.object], {\n level: 'error',\n });\n break;\n }\n }\n } catch (error) {\n this.appLogger(['Error processing dictionary update:', error], {\n level: 'error',\n });\n }\n }\n\n /**\n * Handles any SSE errors and attempts reconnection if appropriate.\n */\n private handleError(event: Event): void {\n const errorEvent = event as any;\n\n // Log detailed error information\n this.appLogger(\n [\n 'EventSource error:',\n {\n type: errorEvent.type,\n message: errorEvent.message,\n code: errorEvent.code,\n readyState: this.eventSource?.readyState,\n url: this.eventSource?.url,\n },\n ],\n {\n level: 'error',\n }\n );\n\n // Notify error callback\n this.onConnectionError?.(event);\n\n // Check if this is a connection close error\n const isConnectionClosed =\n errorEvent.type === 'error' &&\n (errorEvent.message?.includes('terminated') ||\n errorEvent.message?.includes('closed') ||\n this.eventSource?.readyState === EventSource.CLOSED);\n\n if (isConnectionClosed && !this.isManuallyDisconnected) {\n this.appLogger(\n 'Connection was terminated by server, attempting to reconnect...'\n );\n this.scheduleReconnect();\n } else {\n // For other types of errors, close the connection\n this.cleanup();\n }\n }\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"IntlayerEventListener.mjs","names":[],"sources":["../../src/IntlayerEventListener.ts"],"sourcesContent":["import { getIntlayerAPIProxy } from '@intlayer/api';\n// @ts-ignore: @intlayer/backend is not built yet\nimport type { DictionaryAPI, MessageEventData } from '@intlayer/backend';\nimport configuration from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { EventSource } from 'eventsource';\n\nexport type IntlayerMessageEvent = MessageEvent;\n\n/**\n * IntlayerEventListener class to listen for dictionary changes via SSE (Server-Sent Events).\n *\n * Usage example:\n *\n * import { buildIntlayerDictionary } from './transpiler/declaration_file_to_dictionary/intlayer_dictionary';\n * import { IntlayerEventListener } from '@intlayer/api';\n *\n * export const checkDictionaryChanges = async () => {\n * // Instantiate the listener\n * const eventListener = new IntlayerEventListener();\n *\n * // Set up your callbacks\n * eventListener.onDictionaryChange = async (dictionary) => {\n * await buildIntlayerDictionary(dictionary);\n * };\n *\n * // Initialize the listener\n * await eventListener.initialize();\n *\n * // Optionally, clean up later when you’re done\n * // eventListener.cleanup();\n * };\n */\nexport class IntlayerEventListener {\n private appLogger = getAppLogger(configuration);\n\n private eventSource: EventSource | null = null;\n private reconnectAttempts = 0;\n private maxReconnectAttempts = 5;\n private reconnectDelay = 1000; // Start with 1 second\n private isManuallyDisconnected = false;\n private reconnectTimeout: NodeJS.Timeout | null = null;\n\n /**\n * Callback triggered when a Dictionary is ADDED.\n */\n public onDictionaryAdded?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when a Dictionary is UPDATED.\n */\n public onDictionaryChange?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when a Dictionary is DELETED.\n */\n public onDictionaryDeleted?: (dictionary: DictionaryAPI) => any;\n\n /**\n * Callback triggered when connection is established or re-established.\n */\n public onConnectionOpen?: () => any;\n\n /**\n * Callback triggered when connection encounters an error.\n */\n public onConnectionError?: (error: Event) => any;\n\n constructor(private intlayerConfig: IntlayerConfig = configuration) {\n this.appLogger = getAppLogger(this.intlayerConfig);\n }\n\n /**\n * Initializes the EventSource connection using the given intlayerConfig\n * (or the default config if none was provided).\n */\n public async initialize(): Promise<void> {\n this.isManuallyDisconnected = false;\n await this.connect();\n }\n\n /**\n * Establishes the EventSource connection with automatic reconnection support.\n */\n private async connect(): Promise<void> {\n try {\n const backendURL = this.intlayerConfig.editor.backendURL;\n\n // Retrieve the access token via proxy\n const accessToken = await getIntlayerAPIProxy(\n undefined,\n this.intlayerConfig\n ).oAuth.getOAuth2AccessToken();\n\n if (!accessToken) {\n throw new Error('Failed to retrieve access token');\n }\n\n const API_ROUTE = `${backendURL}/api/event-listener`;\n\n // Close existing connection if any\n if (this.eventSource) {\n this.eventSource.close();\n }\n\n this.eventSource = new EventSource(API_ROUTE, {\n fetch: (input, init) =>\n fetch(input, {\n ...init,\n headers: {\n ...(init?.headers ?? {}),\n Authorization: `Bearer ${accessToken.data?.accessToken}`,\n },\n }),\n });\n\n this.eventSource.onopen = () => {\n this.reconnectAttempts = 0;\n this.reconnectDelay = 1000; // Reset delay\n this.onConnectionOpen?.();\n };\n\n this.eventSource.onmessage = (event) => this.handleMessage(event);\n this.eventSource.onerror = (event) => this.handleError(event);\n } catch (_error) {\n this.appLogger('Failed to establish EventSource connection:', {\n level: 'error',\n });\n this.scheduleReconnect();\n }\n }\n\n /**\n * Cleans up (closes) the EventSource connection.\n */\n public cleanup(): void {\n this.isManuallyDisconnected = true;\n\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n }\n\n /**\n * Schedules a reconnection attempt with exponential backoff.\n */\n private scheduleReconnect(): void {\n if (\n this.isManuallyDisconnected ||\n this.reconnectAttempts >= this.maxReconnectAttempts\n ) {\n if (this.reconnectAttempts >= this.maxReconnectAttempts) {\n this.appLogger(\n [\n `Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`,\n ],\n {\n level: 'error',\n }\n );\n }\n return;\n }\n\n this.reconnectAttempts++;\n const delay = this.reconnectDelay * 2 ** (this.reconnectAttempts - 1); // Exponential backoff\n\n this.appLogger(\n `Scheduling reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`\n );\n\n this.reconnectTimeout = setTimeout(async () => {\n if (!this.isManuallyDisconnected) {\n await this.connect();\n }\n }, delay);\n }\n\n /**\n * Handles incoming SSE messages, parses the event data,\n * and invokes the appropriate callback.\n */\n private async handleMessage(event: IntlayerMessageEvent): Promise<void> {\n try {\n const { data } = event;\n\n const dataJSON: MessageEventData[] = JSON.parse(data);\n\n for (const dataEl of dataJSON) {\n switch (dataEl.object) {\n case 'DICTIONARY':\n switch (dataEl.status) {\n case 'ADDED':\n await this.onDictionaryAdded?.(dataEl.data);\n break;\n case 'UPDATED':\n await this.onDictionaryChange?.(dataEl.data);\n break;\n case 'DELETED':\n await this.onDictionaryDeleted?.(dataEl.data);\n break;\n default:\n this.appLogger(\n ['Unhandled dictionary status:', dataEl.status],\n {\n level: 'error',\n }\n );\n break;\n }\n break;\n default:\n this.appLogger(['Unknown object type:', dataEl.object], {\n level: 'error',\n });\n break;\n }\n }\n } catch (error) {\n this.appLogger(['Error processing dictionary update:', error], {\n level: 'error',\n });\n }\n }\n\n /**\n * Handles any SSE errors and attempts reconnection if appropriate.\n */\n private handleError(event: Event): void {\n const errorEvent = event as any;\n\n // Log detailed error information\n this.appLogger(\n [\n 'EventSource error:',\n {\n type: errorEvent.type,\n message: errorEvent.message,\n code: errorEvent.code,\n readyState: this.eventSource?.readyState,\n url: this.eventSource?.url,\n },\n ],\n {\n level: 'error',\n }\n );\n\n // Notify error callback\n this.onConnectionError?.(event);\n\n // Check if this is a connection close error\n const isConnectionClosed =\n errorEvent.type === 'error' &&\n (errorEvent.message?.includes('terminated') ||\n errorEvent.message?.includes('closed') ||\n this.eventSource?.readyState === EventSource.CLOSED);\n\n if (isConnectionClosed && !this.isManuallyDisconnected) {\n this.appLogger(\n 'Connection was terminated by server, attempting to reconnect...'\n );\n this.scheduleReconnect();\n } else {\n // For other types of errors, close the connection\n this.cleanup();\n }\n }\n}\n"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{existsSync as e,readFileSync as t}from"node:fs";import{basename as n,dirname as r,join as i,relative as a,resolve as o,sep as s}from"node:path";import{fileURLToPath as c}from"node:url";const l=()=>{try{return r(c(import.meta.url))}catch{return typeof __dirname<`u`?__dirname:process.cwd()}},u=e=>{let t=e;for(let e=0;e<12;e++){if(n(t)===`dist`)return t;let e=o(t,`..`);if(e===t)break;t=e}return null},d=e=>{if(!e)return null;try{if(e.startsWith(`file://`))return c(e)}catch{}return e},f=()=>{let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error();Error.captureStackTrace(e,f);let t=e.stack||[],n=e=>e.includes(`${s}_virtual${s}`)||e.includes(`/_virtual/`);for(let e of t){let t=d(typeof e.getFileName==`function`?e.getFileName():null);if(t&&!(t.includes(`node:internal`)||t.includes(`${s}internal${s}modules${s}`))&&!n(t))return r(t)}for(let e of t){let t=d(typeof e.getFileName==`function`?e.getFileName():null);if(t)return r(t)}}catch{}finally{Error.prepareStackTrace=e}return l()},p=(n,r=`utf8`)=>{let s=l(),c=u(s)??o(s,`..`,`..`,`dist`),d=i(c,`assets`),p=[],m=a(c,f()).split(`\\`).join(`/`).replace(/^(?:dist\/)?(?:esm|cjs)\//,``).replace(/^_virtual\//,``);if(n.startsWith(`./`)||n.startsWith(`../`)){let i=o(d,m,n);if(p.push(i),e(i))return t(i,r)}let h=i(d,n);if(p.push(h),e(h))return t(h,r);if(m){let a=i(d,m,n);if(p.push(a),e(a))return t(a,r)}let g=[`readAsset: file not found.`,`Searched:`,...p.map(e=>`- ${e}`)].join(`
|
|
2
2
|
`);throw Error(g)};export{p as readAsset};
|
package/dist/esm/auth/login.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{openBrowser as e}from"../utils/openBrowser.mjs";import{
|
|
1
|
+
import{openBrowser as e}from"../utils/openBrowser.mjs";import{logConfigDetails as t}from"@intlayer/chokidar/cli";import{ANSIColors as n,colorize as r,colorizePath as i,getAppLogger as a}from"@intlayer/config/logger";import{getConfiguration as o}from"@intlayer/config/node";import s from"node:http";import{URL as c}from"node:url";const l=async l=>{let u=o(l.configOptions);t(l?.configOptions);let d=a(u),f=l.cmsUrl??u.editor.cmsURL;return new Promise(t=>{let a=s.createServer((e,o)=>{let s=new c(e.url??``,`http://${e.headers.host}`);if(o.setHeader(`Access-Control-Allow-Origin`,`*`),o.setHeader(`Access-Control-Allow-Methods`,`GET, OPTIONS`),o.setHeader(`Access-Control-Allow-Headers`,`Content-Type`),e.method===`OPTIONS`){o.writeHead(204),o.end();return}if(s.pathname===`/callback`){let e=s.searchParams.get(`clientId`),c=s.searchParams.get(`clientSecret`);e&&c?(d(``),d(`Log in successful. Client ID and Client Secret received.`),d(``),d([`1. Insert the Client ID and Client Secret in your`,i(`.env`),`file:`]),d(r(`--------------------------------`,n.GREY_DARK)),d([r(`INTLAYER_CLIENT_ID=`,n.GREY_LIGHT),r(e,n.BLUE)].join(``)),d([r(`INTLAYER_CLIENT_SECRET=`,n.GREY_LIGHT),r(c,n.BLUE)].join(``)),d(r(`--------------------------------`,n.GREY_DARK)),d(``),d(`2. Insert in your Intlayer configuration file:`),d(r(`--------------------------------`,n.GREY_DARK)),[`${n.GREY_LIGHT}{`,` editor: {`,` cmsURL: '${i(f,void 0,n.GREY_LIGHT)}',`,` clientId: '${r(`process.env.INTLAYER_CLIENT_ID`,n.BLUE,n.GREY_LIGHT)}',`,` clientSecret: '${r(`process.env.INTLAYER_CLIENT_SECRET`,n.BLUE,n.GREY_LIGHT)}',`,` },`,`}`].forEach(e=>{d(e)}),d(r(`--------------------------------`,n.GREY_DARK)),o.writeHead(200,{"Content-Type":`text/html`}),o.end(`
|
|
2
2
|
<!DOCTYPE html>
|
|
3
3
|
<html lang="en" data-theme="dark">
|
|
4
4
|
<head>
|
|
@@ -70,5 +70,5 @@ import{openBrowser as e}from"../utils/openBrowser.mjs";import{ANSIColors as t,co
|
|
|
70
70
|
<\/script>
|
|
71
71
|
</body>
|
|
72
72
|
</html>
|
|
73
|
-
`),a.close(()=>{
|
|
73
|
+
`),a.close(()=>{t(),process.exit(0)})):(o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Missing parameters`))}else o.writeHead(404,{"Content-Type":`text/plain`}),o.end(`Not found`)});a.listen(0,()=>{let t=a.address(),n=typeof t==`object`&&t?t.port:0,r=Math.random().toString(36).substring(7),o=`${f??process.env.INTLAYER_SITE_URL??`http://localhost:3000`}/en/auth/cli-login?port=${n}&state=${r}`;d(`Opening browser for login...`),d(`If browser does not open, visit: ${i(o)}`),e(o)})})};export{l as login};
|
|
74
74
|
//# sourceMappingURL=login.mjs.map
|
package/dist/esm/build.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{logConfigDetails as e}from"@intlayer/chokidar/cli";import{
|
|
1
|
+
import{logConfigDetails as e}from"@intlayer/chokidar/cli";import{getConfiguration as t}from"@intlayer/config/node";import{runParallel as n}from"@intlayer/chokidar/utils";import{buildAndWatchIntlayer as r}from"@intlayer/chokidar/watcher";const i=async i=>{let a=t(i?.configOptions);e(i?.configOptions);let o=null;i?.with&&(o=n(i.with),o.result.catch(()=>{})),await r({persistent:i?.watch??!1,skipPrepare:i?.skipPrepare??!1,configuration:a}),!i?.watch&&o&&o.kill()};export{i as build};
|
|
2
2
|
//# sourceMappingURL=build.mjs.map
|
package/dist/esm/ci.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{normalize as e,resolve as t}from"node:path";import{listProjects as n}from"@intlayer/chokidar/cli";import{logger as r}from"@intlayer/config/logger";import{spawnSync as i}from"node:child_process";const a=()=>{let e=process.env.npm_config_user_agent;return e?.startsWith(`bun`)?{command:`bun`,args:[`intlayer`]}:e?.startsWith(`pnpm`)?{command:`pnpm`,args:[`exec`,`intlayer`]}:e?.startsWith(`yarn`)?{command:`yarn`,args:[`run`,`intlayer`]}:{command:`npx`,args:[`intlayer`]}},o=async o=>{let s=process.env.INTLAYER_PROJECT_CREDENTIALS,c={};if(s)try{c=JSON.parse(s)}catch{r(`INTLAYER_PROJECT_CREDENTIALS is not valid JSON. Proceeding without credentials.`,{level:`warn`})}let l=process.cwd(),{projectsPath:u}=await n();if(u.length===0){r(`No Intlayer projects found.`,{level:`warn`});return}let d=u.find(e=>l===e),f=d?[d]:u,{command:p,args:m}=a(),h=[...m,...o];r(`CI: Using package manager: ${p}`,{level:`verbose`}),r(d?`CI: Detected project context: ${d}`:`CI: No specific project context detected. Iterating over ${f.length} discovered projects...`,{level:`info`});let g=!1;for(let n of f){let a=Object.entries(c).find(([r])=>t(r)===n||n.endsWith(e(r)))?.[1];r(`\nCI: Executing for ${n}...`,{level:`info`});let o={...process.env};a?(o.INTLAYER_CLIENT_ID=a.clientId,o.INTLAYER_CLIENT_SECRET=a.clientSecret):s&&r(`CI: No matching credentials found for ${n} in INTLAYER_PROJECT_CREDENTIALS.`,{isVerbose:!0}),i(p,h,{cwd:n,stdio:`inherit`,env:o}).status!==0&&(r(`CI: Failed for ${n}`,{level:`error`}),g=!0)}g&&process.exit(1)};export{o as runCI};
|
|
2
2
|
//# sourceMappingURL=ci.mjs.map
|
package/dist/esm/cli.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{build as e}from"./build.mjs";import{runCI as t}from"./ci.mjs";import{login as n}from"./auth/login.mjs";import{getConfig as r}from"./config.mjs";import{startEditor as i}from"./editor.mjs";import{extract as a}from"./extract.mjs";import{testMissingTranslations as o}from"./test/test.mjs";import{fill as s}from"./fill/fill.mjs";import{init as c}from"./init.mjs";import{initSkills as l}from"./initSkills.mjs";import{initMCP as ee}from"./initMCP.mjs";import{listContentDeclaration as u}from"./listContentDeclaration.mjs";import{listProjectsCommand as d}from"./listProjects.mjs";import{liveSync as te}from"./liveSync.mjs";import{pull as f}from"./pull.mjs";import{push as p}from"./push/push.mjs";import{pushConfig as ne}from"./pushConfig.mjs";import{reviewDoc as re}from"./reviewDoc/reviewDoc.mjs";import{searchDoc as ie}from"./searchDoc.mjs";import{translateDoc as ae}from"./translateDoc/translateDoc.mjs";import{getParentPackageJSON as m}from"./utils/getParentPackageJSON.mjs";import{watchContentDeclaration as h}from"./watch.mjs";import{setPrefix as oe}from"@intlayer/config/logger";import{getConfiguration as g}from"@intlayer/config/node";import{dirname as _}from"node:path";import{fileURLToPath as v}from"node:url";import{Command as se}from"commander";const y=typeof import.meta.url==`string`?_(v(import.meta.url)):__dirname,b=m(y),x=[[`--env-file [envFile]`,`Environment file`],[`-e, --env [env]`,`Environment`],[`--base-dir [baseDir]`,`Base directory`],[`--no-cache [noCache]`,`No cache`],...[[`--verbose`,`Verbose (default to true using CLI)`],[`--prefix [prefix]`,`Prefix`]]],S=[[`--provider [provider]`,`Provider`],[`--temperature [temperature]`,`Temperature`],[`--model [model]`,`Model`],[`--api-key [apiKey]`,`Provider API key`],[`--custom-prompt [prompt]`,`Custom prompt`],[`--application-context [applicationContext]`,`Application context`],[`--data-serialization [dataSerialization]`,`Data serialization`]],C=[[`--git-diff [gitDiff]`,`Git diff mode - Check git diff between two refs`],[`--git-diff-base [gitDiffBase]`,`Git diff base ref`],[`--git-diff-current [gitDiffCurrent]`,`Git diff current ref`],[`--uncommitted [uncommitted]`,`Uncommitted`],[`--unpushed [unpushed]`,`Unpushed`],[`--untracked [untracked]`,`Untracked`]],w=(e,t)=>t.filter(t=>e[t]!==void 0),T=(e,t)=>(t.forEach(([t,n])=>{e.option(t,n)}),e),E=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0)),D=e=>T(e,x),O=e=>T(e,S),k=e=>T(e,C),A=e=>{let{apiKey:t,provider:n,model:r,temperature:i,applicationContext:a,customPrompt:o,dataSerialization:s}=e,c=g(),{ai:l}=c;return E({...l,apiKey:t??c.ai?.apiKey,provider:n??c.ai?.provider,model:r??c.ai?.model,temperature:i??c.ai?.temperature,applicationContext:a??c.ai?.applicationContext,customPrompt:o??c.ai?.customPrompt,dataSerialization:s??c.ai?.dataSerialization})},j=[`gitDiff`,`gitDiffBase`,`gitDiffCurrent`,`uncommitted`,`unpushed`,`untracked`],M=e=>{if(w(e,j).length===0)return;let{gitDiff:t,gitDiffBase:n,gitDiffCurrent:r,uncommitted:i,unpushed:a,untracked:o}=e;return E({mode:[t&&`gitDiff`,i&&`uncommitted`,a&&`unpushed`,o&&`untracked`].filter(Boolean),baseRef:n,currentRef:r,absolute:!0})},N=[`baseDir`,`env`,`envFile`,`verbose`,`prefix`,`checkTypes`],P=e=>{if(w(e,N).length===0)return;let{baseDir:t,env:n,envFile:r,verbose:i,noCache:a,checkTypes:o}=e,s=E({mode:i===void 0?void 0:i?`verbose`:`default`}),c=E({checkTypes:o}),l=E({log:Object.keys(s).length>0?s:void 0,build:Object.keys(c).length>0?c:void 0});return E({baseDir:t,env:n,envFile:r,override:Object.keys(l).length>0?l:void 0,cache:a===void 0?void 0:!a})},F=()=>{process.argv.includes(`--with`)||oe(``);let m=new se;m.version(b.version).description(`Intlayer CLI`),m.command(`version`).description(`Print the Intlayer CLI version`).action(()=>{console.log(b.version??`unknown`)});let g=m.command(`login`).description(`Login to Intlayer`).option(`--cms-url [cmsUrl]`,`CMS URL`);D(g),g.action(e=>{let t=P(e)??{override:{log:{prefix:``,mode:`verbose`}}};return n({cmsUrl:e.cmsUrl,configOptions:t})});let _=m.command(`init`).description(`Initialize Intlayer in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>c(e.projectRoot));_.command(`skills`).description(`Initialize Intlayer skills in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>l(e.projectRoot)),_.command(`mcp`).description(`Initialize Intlayer MCP server in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>ee(e.projectRoot));let v=m.command(`dictionary`).alias(`dictionaries`).alias(`dic`).description(`Dictionaries operations`),y={description:`Build the dictionaries`,options:[[`-w, --watch`,`Watch for changes`],[`--skip-prepare`,`Skip the prepare step`],[`--with [with...]`,`Start command in parallel with the build`],[`--check-types`,`Check TypeScript type and log errors`]]},x=v.command(`build`).description(y.description);T(x,y.options),D(x),x.action(t=>{e({...t,configOptions:P(t)})});let S=m.command(`build`).description(y.description);T(S,y.options),D(S),S.action(t=>{e({...t,configOptions:P(t)})});let C={description:`Watch the dictionaries changes`,options:[[`--with [with...]`,`Start command in parallel with the build`]]},w=v.command(`watch`).description(y.description);T(w,C.options),D(w),w.action(e=>{h({...e,configOptions:P(e)})});let E=m.command(`watch`).description(y.description);T(E,C.options),D(E),E.action(e=>{h({...e,configOptions:P(e)})});let j={description:`Pull dictionaries from the server`,options:[[`-d, --dictionaries [ids...]`,`List of dictionary IDs to pull`],[`--dictionary [ids...]`,`List of dictionary IDs to pull (alias for --dictionaries)`],[`--new-dictionaries-path [path]`,`Path to save the new dictionaries`],[`--newDictionariesPath [path]`,`[alias] Path to save the new dictionaries`]]},N=v.command(`pull`).description(j.description);T(N,j.options),D(N),N.action(e=>{let t=[...e.dictionaries??[],...e.dictionary??[]];f({...e,dictionaries:t.length>0?t:void 0,configOptions:{...e.configOptions,baseDir:e.baseDir}})});let F=m.command(`pull`).description(j.description);T(F,j.options),D(F),F.action(e=>{let t=[...e.dictionaries??[],...e.dictionary??[]];f({...e,dictionaries:t.length>0?t:void 0,configOptions:P(e)})});let I={description:`Push all dictionaries. Create or update the pushed dictionaries`,options:[[`-d, --dictionaries [ids...]`,`List of dictionary IDs to push`],[`--dictionary [ids...]`,`List of dictionary IDs to push (alias for --dictionaries)`],[`-r, --delete-locale-dictionary`,`Delete the local dictionaries after pushing`],[`-k, --keep-locale-dictionary`,`Keep the local dictionaries after pushing`],[`--deleteLocaleDictionary`,`[alias] Delete the local dictionaries after pushing`],[`--keepLocaleDictionary`,`[alias] Keep the local dictionaries after pushing`],[`--build [build]`,`Build the dictionaries before pushing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`]]},L=v.command(`push`).description(I.description);T(L,I.options),D(L),k(L),L.action(e=>{let t=[...e.dictionaries||[],...e.dictionary||[]];return p({...e,dictionaries:t.length>0?t:void 0,gitOptions:M(e),configOptions:P(e)})});let R=m.command(`push`).description(I.description);T(R,I.options),D(R),k(R),R.action(e=>{let t=[...e.dictionaries||[],...e.dictionary||[]];return p({...e,dictionaries:t.length>0?t:void 0,gitOptions:M(e),configOptions:P(e)})});let z=m.command(`configuration`).alias(`config`).alias(`conf`).description(`Configuration operations`),B=z.command(`get`).description(`Get the configuration`);D(B),B.action(e=>{r({...e,configOptions:P(e)})});let V=z.command(`push`).description(`Push the configuration`);D(V),V.action(e=>{ne({...e,configOptions:P(e)})}),m.command(`projects`).alias(`project`).description(`List Intlayer projects`).command(`list`).description(`List all Intlayer projects in the directory`).option(`--base-dir [baseDir]`,`Base directory to search from`).option(`--git-root`,`Search from the git root directory instead of the base directory`).option(`--json`,`Output the results as JSON`).action(e=>{d({baseDir:e.baseDir,gitRoot:e.gitRoot,json:e.json})}),m.command(`projects-list`).alias(`pl`).description(`List all Intlayer projects in the directory`).option(`--base-dir [baseDir]`,`Base directory to search from`).option(`--git-root`,`Search from the git root directory instead of the base directory`).option(`--absolute`,`Output the results as absolute paths`).option(`--json`,`Output the results as JSON`).action(e=>{d({baseDir:e.baseDir,gitRoot:e.gitRoot,json:e.json,absolute:e.absolute})});let H=m.command(`content`).description(`Content declaration operations`);H.command(`list`).description(`List the content declaration files`).option(`--json`,`Output the results as JSON`).option(`--absolute`,`Output the results as absolute paths`).action(e=>{u({json:e.json,absolute:e.absolute})}),m.command(`list`).description(`List the content declaration files`).option(`--json`,`Output the results as JSON`).option(`--absolute`,`Output the results as absolute paths`).action(e=>{u({json:e.json,absolute:e.absolute})});let U=H.command(`test`).description(`Test if there are missing translations`).option(`--build [build]`,`Build the dictionaries before testing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`);D(U),U.action(e=>{o({...e,configOptions:P(e)})});let W=m.command(`test`).description(`Test if there are missing translations`).option(`--build [build]`,`Build the dictionaries before testing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`);D(W),W.action(e=>{o({...e,configOptions:P(e)})});let G=m.command(`fill`).description(`Fill the dictionaries`).option(`-f, --file [files...]`,`List of Dictionary files to fill`).option(`--source-locale [sourceLocale]`,`Source locale to translate from`).option(`--output-locales [outputLocales...]`,`Target locales to translate to`).option(`--mode [mode]`,`Fill mode: complete, review. Complete will fill all missing content, review will fill missing content and review existing keys`,`complete`).option(`-k, --keys [keys...]`,`Filter dictionaries based on keys`).option(`--key [keys...]`,`Filter dictionaries based on keys (alias for --keys)`).option(`--excluded-keys [excludedKeys...]`,`Filter out dictionaries based on keys`).option(`--excluded-key [excludedKeys...]`,`Filter out dictionaries based on keys (alias for --excluded-keys)`).option(`--path-filter [pathFilters...]`,`Filter dictionaries based on glob pattern`).option(`--build [build]`,`Build the dictionaries before filling to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`).option(`--skip-metadata`,`Skip filling missing metadata (description, title, tags) for dictionaries`);D(G),O(G),k(G),G.action(e=>{let t=[...e.keys??[],...e.key??[]],n=[...e.excludedKeys??[],...e.excludedKey??[]],r=[...e.dictionaries??[],...e.dictionary??[]];return s({...e,keys:t.length>0?t:void 0,excludedKeys:n.length>0?n:void 0,dictionaries:r.length>0?r:void 0,aiOptions:A(e),gitOptions:M(e),configOptions:P(e)})});let K=[[`--doc-pattern [docPattern...]`,`Documentation pattern`],[`--excluded-glob-pattern [excludedGlobPattern...]`,`Excluded glob pattern`],[`--nb-simultaneous-file-processed [nbSimultaneousFileProcessed]`,`Number of simultaneous file processed`],[`--locales [locales...]`,`Locales`],[`--base-locale [baseLocale]`,`Base locale`],[`--custom-instructions [customInstructions]`,`Custom instructions added to the prompt. Usefull to apply specific rules regarding formatting, urls translation, etc.`],[`--skip-if-modified-before [skipIfModifiedBefore]`,'Skip the file if it has been modified before the given time. Can be an absolute time as "2025-12-05" (string or Date) or a relative time in ms `1 * 60 * 60 * 1000` (1 hour). This option check update time of the file using the `fs.stat` method. So it could be impacted by Git or other tools that modify the file.'],[`--skip-if-modified-after [skipIfModifiedAfter]`,'Skip the file if it has been modified within the given time. Can be an absolute time as "2025-12-05" (string or Date) or a relative time in ms `1 * 60 * 60 * 1000` (1 hour). This option check update time of the file using the `fs.stat` method. So it could be impacted by Git or other tools that modify the file.'],[`--skip-if-exists`,`Skip the file if it already exists`]],q=m.command(`doc`).description(`Documentation operations`),J=q.command(`translate`).description(`Translate the documentation`);D(J),O(J),k(J),T(J,K),J.action(e=>ae({docPattern:e.docPattern,excludedGlobPattern:e.excludedGlobPattern,locales:e.locales,baseLocale:e.baseLocale,aiOptions:A(e),gitOptions:M(e),nbSimultaneousFileProcessed:e.nbSimultaneousFileProcessed,configOptions:P(e),customInstructions:e.customInstructions,skipIfModifiedBefore:e.skipIfModifiedBefore,skipIfModifiedAfter:e.skipIfModifiedAfter,skipIfExists:e.skipIfExists}));let Y=q.command(`review`).description(`Review the documentation`);D(Y),O(Y),k(Y),T(Y,K),Y.action(e=>re({docPattern:e.docPattern,excludedGlobPattern:e.excludedGlobPattern,locales:e.locales,baseLocale:e.baseLocale,aiOptions:A(e),gitOptions:M(e),nbSimultaneousFileProcessed:e.nbSimultaneousFileProcessed,configOptions:P(e),customInstructions:e.customInstructions,skipIfModifiedBefore:e.skipIfModifiedBefore,skipIfModifiedAfter:e.skipIfModifiedAfter,skipIfExists:e.skipIfExists}));let X=q.command(`search`).description(`Search the documentation`).argument(`<query>`,`Search query`).option(`--limit [limit]`,`Limit the number of results`,`10`);D(X),X.action((e,t)=>ie({query:e,limit:t.limit?parseInt(t.limit,10):10,configOptions:P(t)}));let ce=[[`--with [with...]`,`Start command in parallel with the live sync`]],Z=m.command(`live`).description(`Live sync - Watch for changes made on the CMS and update the application content accordingly`);T(Z,ce),D(Z),Z.action(e=>te(e));let Q=m.command(`editor`).description(`Visual editor operations`).command(`start`).description(`Start the Intlayer visual editor`);D(Q),Q.action(e=>{i({env:e.env,envFile:e.envFile})});let $=m.command(`extract`).alias(`ext`).description(`Extract strings from components to be placed in a .content file close to the component`);return $.option(`-f, --file [files...]`,`List of files to extract`).option(`-o, --output-content-declarations [outputContentDeclarations]`,`Path to output content declaration files`).option(`--code-only`,`Only extract the component code`,!1).option(`--declaration-only`,`Only generate content declaration`,!1).action(e=>{a({files:e.file,outputContentDeclarations:e.outputContentDeclarations,configOptions:P(e),codeOnly:e.codeOnly,declarationOnly:e.declarationOnly})}),D($),m.parse(process.argv),m.command(`ci`).description(`Run Intlayer commands with auto-injected credentials from INTLAYER_PROJECT_CREDENTIALS. Detects current project or iterates over all projects.`).argument(`<command...>`,`The intlayer command to execute (e.g., "fill", "push")`).allowUnknownOption().action(e=>{t(e)}),m};export{y as dirname,F as setAPI};
|
|
1
|
+
import{extract as e}from"./extract.mjs";import{listProjectsCommand as t}from"./listProjects.mjs";import{liveSync as n}from"./liveSync.mjs";import{listContentDeclaration as r}from"./listContentDeclaration.mjs";import{init as i}from"./init.mjs";import{startEditor as a}from"./editor.mjs";import{watchContentDeclaration as o}from"./watch.mjs";import{login as s}from"./auth/login.mjs";import{build as c}from"./build.mjs";import{runCI as l}from"./ci.mjs";import{getConfig as ee}from"./config.mjs";import{testMissingTranslations as u}from"./test/test.mjs";import{fill as te}from"./fill/fill.mjs";import{initSkills as d}from"./initSkills.mjs";import{initMCP as ne}from"./initMCP.mjs";import{pull as f}from"./pull.mjs";import{push as p}from"./push/push.mjs";import{pushConfig as re}from"./pushConfig.mjs";import{reviewDoc as ie}from"./reviewDoc/reviewDoc.mjs";import{searchDoc as ae}from"./searchDoc.mjs";import{translateDoc as oe}from"./translateDoc/translateDoc.mjs";import{getParentPackageJSON as m}from"./utils/getParentPackageJSON.mjs";import{dirname as h}from"node:path";import{setPrefix as se}from"@intlayer/config/logger";import{getConfiguration as g}from"@intlayer/config/node";import{fileURLToPath as _}from"node:url";import{Command as v}from"commander";const y=typeof import.meta.url==`string`?h(_(import.meta.url)):__dirname,b=m(y),x=[[`--env-file [envFile]`,`Environment file`],[`-e, --env [env]`,`Environment`],[`--base-dir [baseDir]`,`Base directory`],[`--no-cache [noCache]`,`No cache`],...[[`--verbose`,`Verbose (default to true using CLI)`],[`--prefix [prefix]`,`Prefix`]]],S=[[`--provider [provider]`,`Provider`],[`--temperature [temperature]`,`Temperature`],[`--model [model]`,`Model`],[`--api-key [apiKey]`,`Provider API key`],[`--custom-prompt [prompt]`,`Custom prompt`],[`--application-context [applicationContext]`,`Application context`],[`--data-serialization [dataSerialization]`,`Data serialization`]],C=[[`--git-diff [gitDiff]`,`Git diff mode - Check git diff between two refs`],[`--git-diff-base [gitDiffBase]`,`Git diff base ref`],[`--git-diff-current [gitDiffCurrent]`,`Git diff current ref`],[`--uncommitted [uncommitted]`,`Uncommitted`],[`--unpushed [unpushed]`,`Unpushed`],[`--untracked [untracked]`,`Untracked`]],w=(e,t)=>t.filter(t=>e[t]!==void 0),T=(e,t)=>(t.forEach(([t,n])=>{e.option(t,n)}),e),E=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0)),D=e=>T(e,x),O=e=>T(e,S),k=e=>T(e,C),A=e=>{let{apiKey:t,provider:n,model:r,temperature:i,applicationContext:a,customPrompt:o,dataSerialization:s}=e,c=g(),{ai:l}=c;return E({...l,apiKey:t??c.ai?.apiKey,provider:n??c.ai?.provider,model:r??c.ai?.model,temperature:i??c.ai?.temperature,applicationContext:a??c.ai?.applicationContext,customPrompt:o??c.ai?.customPrompt,dataSerialization:s??c.ai?.dataSerialization})},j=[`gitDiff`,`gitDiffBase`,`gitDiffCurrent`,`uncommitted`,`unpushed`,`untracked`],M=e=>{if(w(e,j).length===0)return;let{gitDiff:t,gitDiffBase:n,gitDiffCurrent:r,uncommitted:i,unpushed:a,untracked:o}=e;return E({mode:[t&&`gitDiff`,i&&`uncommitted`,a&&`unpushed`,o&&`untracked`].filter(Boolean),baseRef:n,currentRef:r,absolute:!0})},N=[`baseDir`,`env`,`envFile`,`verbose`,`prefix`,`checkTypes`],P=e=>{if(w(e,N).length===0)return;let{baseDir:t,env:n,envFile:r,verbose:i,noCache:a,checkTypes:o}=e,s=E({mode:i===void 0?void 0:i?`verbose`:`default`}),c=E({checkTypes:o}),l=E({log:Object.keys(s).length>0?s:void 0,build:Object.keys(c).length>0?c:void 0});return E({baseDir:t,env:n,envFile:r,override:Object.keys(l).length>0?l:void 0,cache:a===void 0?void 0:!a})},F=()=>{process.argv.includes(`--with`)||se(``);let m=new v;m.version(b.version).description(`Intlayer CLI`),m.command(`version`).description(`Print the Intlayer CLI version`).action(()=>{console.log(b.version??`unknown`)});let h=m.command(`login`).description(`Login to Intlayer`).option(`--cms-url [cmsUrl]`,`CMS URL`);D(h),h.action(e=>{let t=P(e)??{override:{log:{prefix:``,mode:`verbose`}}};return s({cmsUrl:e.cmsUrl,configOptions:t})});let g=m.command(`init`).description(`Initialize Intlayer in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>i(e.projectRoot));g.command(`skills`).description(`Initialize Intlayer skills in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>d(e.projectRoot)),g.command(`mcp`).description(`Initialize Intlayer MCP server in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>ne(e.projectRoot));let _=m.command(`dictionary`).alias(`dictionaries`).alias(`dic`).description(`Dictionaries operations`),y={description:`Build the dictionaries`,options:[[`-w, --watch`,`Watch for changes`],[`--skip-prepare`,`Skip the prepare step`],[`--with [with...]`,`Start command in parallel with the build`],[`--check-types`,`Check TypeScript type and log errors`]]},x=_.command(`build`).description(y.description);T(x,y.options),D(x),x.action(e=>{c({...e,configOptions:P(e)})});let S=m.command(`build`).description(y.description);T(S,y.options),D(S),S.action(e=>{c({...e,configOptions:P(e)})});let C={description:`Watch the dictionaries changes`,options:[[`--with [with...]`,`Start command in parallel with the build`]]},w=_.command(`watch`).description(y.description);T(w,C.options),D(w),w.action(e=>{o({...e,configOptions:P(e)})});let E=m.command(`watch`).description(y.description);T(E,C.options),D(E),E.action(e=>{o({...e,configOptions:P(e)})});let j={description:`Pull dictionaries from the server`,options:[[`-d, --dictionaries [ids...]`,`List of dictionary IDs to pull`],[`--dictionary [ids...]`,`List of dictionary IDs to pull (alias for --dictionaries)`],[`--new-dictionaries-path [path]`,`Path to save the new dictionaries`],[`--newDictionariesPath [path]`,`[alias] Path to save the new dictionaries`]]},N=_.command(`pull`).description(j.description);T(N,j.options),D(N),N.action(e=>{let t=[...e.dictionaries??[],...e.dictionary??[]];f({...e,dictionaries:t.length>0?t:void 0,configOptions:{...e.configOptions,baseDir:e.baseDir}})});let F=m.command(`pull`).description(j.description);T(F,j.options),D(F),F.action(e=>{let t=[...e.dictionaries??[],...e.dictionary??[]];f({...e,dictionaries:t.length>0?t:void 0,configOptions:P(e)})});let I={description:`Push all dictionaries. Create or update the pushed dictionaries`,options:[[`-d, --dictionaries [ids...]`,`List of dictionary IDs to push`],[`--dictionary [ids...]`,`List of dictionary IDs to push (alias for --dictionaries)`],[`-r, --delete-locale-dictionary`,`Delete the local dictionaries after pushing`],[`-k, --keep-locale-dictionary`,`Keep the local dictionaries after pushing`],[`--deleteLocaleDictionary`,`[alias] Delete the local dictionaries after pushing`],[`--keepLocaleDictionary`,`[alias] Keep the local dictionaries after pushing`],[`--build [build]`,`Build the dictionaries before pushing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`]]},L=_.command(`push`).description(I.description);T(L,I.options),D(L),k(L),L.action(e=>{let t=[...e.dictionaries||[],...e.dictionary||[]];return p({...e,dictionaries:t.length>0?t:void 0,gitOptions:M(e),configOptions:P(e)})});let R=m.command(`push`).description(I.description);T(R,I.options),D(R),k(R),R.action(e=>{let t=[...e.dictionaries||[],...e.dictionary||[]];return p({...e,dictionaries:t.length>0?t:void 0,gitOptions:M(e),configOptions:P(e)})});let z=m.command(`configuration`).alias(`config`).alias(`conf`).description(`Configuration operations`),B=z.command(`get`).description(`Get the configuration`);D(B),B.action(e=>{ee({...e,configOptions:P(e)})});let V=z.command(`push`).description(`Push the configuration`);D(V),V.action(e=>{re({...e,configOptions:P(e)})}),m.command(`projects`).alias(`project`).description(`List Intlayer projects`).command(`list`).description(`List all Intlayer projects in the directory`).option(`--base-dir [baseDir]`,`Base directory to search from`).option(`--git-root`,`Search from the git root directory instead of the base directory`).option(`--json`,`Output the results as JSON`).action(e=>{t({baseDir:e.baseDir,gitRoot:e.gitRoot,json:e.json})}),m.command(`projects-list`).alias(`pl`).description(`List all Intlayer projects in the directory`).option(`--base-dir [baseDir]`,`Base directory to search from`).option(`--git-root`,`Search from the git root directory instead of the base directory`).option(`--absolute`,`Output the results as absolute paths`).option(`--json`,`Output the results as JSON`).action(e=>{t({baseDir:e.baseDir,gitRoot:e.gitRoot,json:e.json,absolute:e.absolute})});let H=m.command(`content`).description(`Content declaration operations`);H.command(`list`).description(`List the content declaration files`).option(`--json`,`Output the results as JSON`).option(`--absolute`,`Output the results as absolute paths`).action(e=>{r({json:e.json,absolute:e.absolute})}),m.command(`list`).description(`List the content declaration files`).option(`--json`,`Output the results as JSON`).option(`--absolute`,`Output the results as absolute paths`).action(e=>{r({json:e.json,absolute:e.absolute})});let U=H.command(`test`).description(`Test if there are missing translations`).option(`--build [build]`,`Build the dictionaries before testing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`);D(U),U.action(e=>{u({...e,configOptions:P(e)})});let W=m.command(`test`).description(`Test if there are missing translations`).option(`--build [build]`,`Build the dictionaries before testing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`);D(W),W.action(e=>{u({...e,configOptions:P(e)})});let G=m.command(`fill`).description(`Fill the dictionaries`).option(`-f, --file [files...]`,`List of Dictionary files to fill`).option(`--source-locale [sourceLocale]`,`Source locale to translate from`).option(`--output-locales [outputLocales...]`,`Target locales to translate to`).option(`--mode [mode]`,`Fill mode: complete, review. Complete will fill all missing content, review will fill missing content and review existing keys`,`complete`).option(`-k, --keys [keys...]`,`Filter dictionaries based on keys`).option(`--key [keys...]`,`Filter dictionaries based on keys (alias for --keys)`).option(`--excluded-keys [excludedKeys...]`,`Filter out dictionaries based on keys`).option(`--excluded-key [excludedKeys...]`,`Filter out dictionaries based on keys (alias for --excluded-keys)`).option(`--path-filter [pathFilters...]`,`Filter dictionaries based on glob pattern`).option(`--build [build]`,`Build the dictionaries before filling to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`).option(`--skip-metadata`,`Skip filling missing metadata (description, title, tags) for dictionaries`);D(G),O(G),k(G),G.action(e=>{let t=[...e.keys??[],...e.key??[]],n=[...e.excludedKeys??[],...e.excludedKey??[]],r=[...e.dictionaries??[],...e.dictionary??[]];return te({...e,keys:t.length>0?t:void 0,excludedKeys:n.length>0?n:void 0,dictionaries:r.length>0?r:void 0,aiOptions:A(e),gitOptions:M(e),configOptions:P(e)})});let K=[[`--doc-pattern [docPattern...]`,`Documentation pattern`],[`--excluded-glob-pattern [excludedGlobPattern...]`,`Excluded glob pattern`],[`--nb-simultaneous-file-processed [nbSimultaneousFileProcessed]`,`Number of simultaneous file processed`],[`--locales [locales...]`,`Locales`],[`--base-locale [baseLocale]`,`Base locale`],[`--custom-instructions [customInstructions]`,`Custom instructions added to the prompt. Usefull to apply specific rules regarding formatting, urls translation, etc.`],[`--skip-if-modified-before [skipIfModifiedBefore]`,'Skip the file if it has been modified before the given time. Can be an absolute time as "2025-12-05" (string or Date) or a relative time in ms `1 * 60 * 60 * 1000` (1 hour). This option check update time of the file using the `fs.stat` method. So it could be impacted by Git or other tools that modify the file.'],[`--skip-if-modified-after [skipIfModifiedAfter]`,'Skip the file if it has been modified within the given time. Can be an absolute time as "2025-12-05" (string or Date) or a relative time in ms `1 * 60 * 60 * 1000` (1 hour). This option check update time of the file using the `fs.stat` method. So it could be impacted by Git or other tools that modify the file.'],[`--skip-if-exists`,`Skip the file if it already exists`]],q=m.command(`doc`).description(`Documentation operations`),J=q.command(`translate`).description(`Translate the documentation`);D(J),O(J),k(J),T(J,K),J.action(e=>oe({docPattern:e.docPattern,excludedGlobPattern:e.excludedGlobPattern,locales:e.locales,baseLocale:e.baseLocale,aiOptions:A(e),gitOptions:M(e),nbSimultaneousFileProcessed:e.nbSimultaneousFileProcessed,configOptions:P(e),customInstructions:e.customInstructions,skipIfModifiedBefore:e.skipIfModifiedBefore,skipIfModifiedAfter:e.skipIfModifiedAfter,skipIfExists:e.skipIfExists}));let Y=q.command(`review`).description(`Review the documentation`);D(Y),O(Y),k(Y),T(Y,K),Y.action(e=>ie({docPattern:e.docPattern,excludedGlobPattern:e.excludedGlobPattern,locales:e.locales,baseLocale:e.baseLocale,aiOptions:A(e),gitOptions:M(e),nbSimultaneousFileProcessed:e.nbSimultaneousFileProcessed,configOptions:P(e),customInstructions:e.customInstructions,skipIfModifiedBefore:e.skipIfModifiedBefore,skipIfModifiedAfter:e.skipIfModifiedAfter,skipIfExists:e.skipIfExists}));let X=q.command(`search`).description(`Search the documentation`).argument(`<query>`,`Search query`).option(`--limit [limit]`,`Limit the number of results`,`10`);D(X),X.action((e,t)=>ae({query:e,limit:t.limit?parseInt(t.limit,10):10,configOptions:P(t)}));let ce=[[`--with [with...]`,`Start command in parallel with the live sync`]],Z=m.command(`live`).description(`Live sync - Watch for changes made on the CMS and update the application content accordingly`);T(Z,ce),D(Z),Z.action(e=>n(e));let Q=m.command(`editor`).description(`Visual editor operations`).command(`start`).description(`Start the Intlayer visual editor`);D(Q),Q.action(e=>{a({env:e.env,envFile:e.envFile})});let $=m.command(`extract`).alias(`ext`).description(`Extract strings from components to be placed in a .content file close to the component`);return $.option(`-f, --file [files...]`,`List of files to extract`).option(`-o, --output-content-declarations [outputContentDeclarations]`,`Path to output content declaration files`).option(`--code-only`,`Only extract the component code`,!1).option(`--declaration-only`,`Only generate content declaration`,!1).action(t=>{e({files:t.file,outputContentDeclarations:t.outputContentDeclarations,configOptions:P(t),codeOnly:t.codeOnly,declarationOnly:t.declarationOnly})}),D($),m.parse(process.argv),m.command(`ci`).description(`Run Intlayer commands with auto-injected credentials from INTLAYER_PROJECT_CREDENTIALS. Detects current project or iterates over all projects.`).argument(`<command...>`,`The intlayer command to execute (e.g., "fill", "push")`).allowUnknownOption().action(e=>{l(e)}),m};export{y as dirname,F as setAPI};
|
|
2
2
|
//# sourceMappingURL=cli.mjs.map
|