@intlayer/cli 8.9.7 → 8.9.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
- package/dist/cjs/auth/login.cjs +3 -1
- package/dist/cjs/auth/login.cjs.map +1 -1
- package/dist/cjs/auth/sessionToken.cjs.map +1 -1
- package/dist/cjs/build.cjs.map +1 -1
- package/dist/cjs/bundle.cjs.map +1 -1
- package/dist/cjs/ci.cjs.map +1 -1
- package/dist/cjs/cli.cjs.map +1 -1
- package/dist/cjs/config.cjs +1 -1
- package/dist/cjs/config.cjs.map +1 -1
- package/dist/cjs/editor.cjs.map +1 -1
- package/dist/cjs/extract.cjs.map +1 -1
- package/dist/cjs/fill/deepMergeContent.cjs.map +1 -1
- package/dist/cjs/fill/extractTranslatableContent.cjs.map +1 -1
- package/dist/cjs/fill/fill.cjs.map +1 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
- package/dist/cjs/fill/formatFillData.cjs.map +1 -1
- package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs.map +1 -1
- package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs.map +1 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
- package/dist/cjs/fill/translateDictionary.cjs +2 -2
- package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
- package/dist/cjs/fill/writeFill.cjs.map +1 -1
- package/dist/cjs/getTargetDictionary.cjs.map +1 -1
- package/dist/cjs/init.cjs.map +1 -1
- package/dist/cjs/initMCP.cjs.map +1 -1
- package/dist/cjs/initSkills.cjs.map +1 -1
- package/dist/cjs/listContentDeclaration.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/liveSync.cjs.map +1 -1
- package/dist/cjs/pull.cjs +3 -4
- package/dist/cjs/pull.cjs.map +1 -1
- package/dist/cjs/push/pullLog.cjs.map +1 -1
- package/dist/cjs/push/push.cjs +1 -2
- package/dist/cjs/push/push.cjs.map +1 -1
- package/dist/cjs/pushConfig.cjs +6 -4
- package/dist/cjs/pushConfig.cjs.map +1 -1
- package/dist/cjs/pushLog.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
- package/dist/cjs/searchDoc.cjs.map +1 -1
- package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
- package/dist/cjs/test/test.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
- package/dist/cjs/translateDoc/validation.cjs.map +1 -1
- package/dist/cjs/translation-alignment/alignBlocks.cjs.map +1 -1
- package/dist/cjs/translation-alignment/computeSimilarity.cjs.map +1 -1
- package/dist/cjs/translation-alignment/fingerprintBlock.cjs.map +1 -1
- package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs.map +1 -1
- package/dist/cjs/translation-alignment/normalizeBlock.cjs.map +1 -1
- package/dist/cjs/translation-alignment/pipeline.cjs.map +1 -1
- package/dist/cjs/translation-alignment/planActions.cjs.map +1 -1
- package/dist/cjs/translation-alignment/rebuildDocument.cjs.map +1 -1
- package/dist/cjs/translation-alignment/segmentDocument.cjs.map +1 -1
- package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
- package/dist/cjs/utils/checkAccess.cjs +6 -0
- package/dist/cjs/utils/checkAccess.cjs.map +1 -1
- package/dist/cjs/utils/checkConfigConsistency.cjs.map +1 -1
- package/dist/cjs/utils/checkFileModifiedRange.cjs.map +1 -1
- package/dist/cjs/utils/checkLastUpdateTime.cjs.map +1 -1
- package/dist/cjs/utils/chunkInference.cjs +2 -2
- package/dist/cjs/utils/chunkInference.cjs.map +1 -1
- package/dist/cjs/utils/fixChunkStartEndChars.cjs.map +1 -1
- package/dist/cjs/utils/formatTimeDiff.cjs.map +1 -1
- package/dist/cjs/utils/getIsFileUpdatedRecently.cjs.map +1 -1
- package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
- package/dist/cjs/utils/getParentPackageJSON.cjs.map +1 -1
- package/dist/cjs/utils/listSpecialChars.cjs.map +1 -1
- package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
- package/dist/cjs/utils/openBrowser.cjs.map +1 -1
- package/dist/cjs/utils/reorderParagraphs.cjs.map +1 -1
- package/dist/cjs/utils/setupAI.cjs.map +1 -1
- package/dist/cjs/watch.cjs.map +1 -1
- package/dist/esm/IntlayerEventListener.mjs.map +1 -1
- package/dist/esm/auth/login.mjs +3 -1
- package/dist/esm/auth/login.mjs.map +1 -1
- package/dist/esm/auth/sessionToken.mjs.map +1 -1
- package/dist/esm/build.mjs.map +1 -1
- package/dist/esm/bundle.mjs.map +1 -1
- package/dist/esm/ci.mjs.map +1 -1
- package/dist/esm/cli.mjs.map +1 -1
- package/dist/esm/config.mjs +2 -2
- package/dist/esm/config.mjs.map +1 -1
- package/dist/esm/editor.mjs.map +1 -1
- package/dist/esm/extract.mjs.map +1 -1
- package/dist/esm/fill/deepMergeContent.mjs.map +1 -1
- package/dist/esm/fill/extractTranslatableContent.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
- package/dist/esm/fill/formatFillData.mjs.map +1 -1
- package/dist/esm/fill/getAvailableLocalesInDictionary.mjs.map +1 -1
- package/dist/esm/fill/getFilterMissingContentPerLocale.mjs.map +1 -1
- package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -1
- package/dist/esm/fill/translateDictionary.mjs +2 -2
- package/dist/esm/fill/translateDictionary.mjs.map +1 -1
- package/dist/esm/fill/writeFill.mjs.map +1 -1
- package/dist/esm/getTargetDictionary.mjs.map +1 -1
- package/dist/esm/init.mjs.map +1 -1
- package/dist/esm/initMCP.mjs.map +1 -1
- package/dist/esm/initSkills.mjs.map +1 -1
- package/dist/esm/listContentDeclaration.mjs.map +1 -1
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/liveSync.mjs.map +1 -1
- package/dist/esm/pull.mjs +4 -5
- package/dist/esm/pull.mjs.map +1 -1
- package/dist/esm/push/pullLog.mjs.map +1 -1
- package/dist/esm/push/push.mjs +2 -3
- package/dist/esm/push/push.mjs.map +1 -1
- package/dist/esm/pushConfig.mjs +8 -6
- package/dist/esm/pushConfig.mjs.map +1 -1
- package/dist/esm/pushLog.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
- package/dist/esm/searchDoc.mjs.map +1 -1
- package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
- package/dist/esm/test/test.mjs.map +1 -1
- package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
- package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
- package/dist/esm/translateDoc/validation.mjs.map +1 -1
- package/dist/esm/translation-alignment/alignBlocks.mjs.map +1 -1
- package/dist/esm/translation-alignment/computeSimilarity.mjs.map +1 -1
- package/dist/esm/translation-alignment/fingerprintBlock.mjs.map +1 -1
- package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs.map +1 -1
- package/dist/esm/translation-alignment/normalizeBlock.mjs.map +1 -1
- package/dist/esm/translation-alignment/pipeline.mjs.map +1 -1
- package/dist/esm/translation-alignment/planActions.mjs.map +1 -1
- package/dist/esm/translation-alignment/rebuildDocument.mjs.map +1 -1
- package/dist/esm/translation-alignment/segmentDocument.mjs.map +1 -1
- package/dist/esm/utils/calculateChunks.mjs.map +1 -1
- package/dist/esm/utils/checkAccess.mjs +6 -1
- package/dist/esm/utils/checkAccess.mjs.map +1 -1
- package/dist/esm/utils/checkConfigConsistency.mjs.map +1 -1
- package/dist/esm/utils/checkFileModifiedRange.mjs.map +1 -1
- package/dist/esm/utils/checkLastUpdateTime.mjs.map +1 -1
- package/dist/esm/utils/chunkInference.mjs +2 -2
- package/dist/esm/utils/chunkInference.mjs.map +1 -1
- package/dist/esm/utils/fixChunkStartEndChars.mjs.map +1 -1
- package/dist/esm/utils/formatTimeDiff.mjs.map +1 -1
- package/dist/esm/utils/getIsFileUpdatedRecently.mjs.map +1 -1
- package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
- package/dist/esm/utils/getParentPackageJSON.mjs.map +1 -1
- package/dist/esm/utils/listSpecialChars.mjs.map +1 -1
- package/dist/esm/utils/mapChunksBetweenFiles.mjs.map +1 -1
- package/dist/esm/utils/openBrowser.mjs.map +1 -1
- package/dist/esm/utils/reorderParagraphs.mjs.map +1 -1
- package/dist/esm/utils/setupAI.mjs.map +1 -1
- package/dist/esm/watch.mjs.map +1 -1
- package/dist/types/IntlayerEventListener.d.ts.map +1 -1
- package/dist/types/auth/login.d.ts.map +1 -1
- package/dist/types/auth/sessionToken.d.ts +1 -1
- package/dist/types/auth/sessionToken.d.ts.map +1 -1
- package/dist/types/build.d.ts.map +1 -1
- package/dist/types/bundle.d.ts.map +1 -1
- package/dist/types/cli.d.ts.map +1 -1
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/editor.d.ts.map +1 -1
- package/dist/types/extract.d.ts.map +1 -1
- package/dist/types/fill/extractTranslatableContent.d.ts.map +1 -1
- package/dist/types/fill/fill.d.ts.map +1 -1
- package/dist/types/fill/formatFillData.d.ts.map +1 -1
- package/dist/types/fill/getAvailableLocalesInDictionary.d.ts.map +1 -1
- package/dist/types/fill/translateDictionary.d.ts +1 -2
- package/dist/types/fill/translateDictionary.d.ts.map +1 -1
- package/dist/types/index.d.ts +4 -4
- package/dist/types/init.d.ts.map +1 -1
- package/dist/types/initSkills.d.ts.map +1 -1
- package/dist/types/listContentDeclaration.d.ts.map +1 -1
- package/dist/types/listProjects.d.ts.map +1 -1
- package/dist/types/liveSync.d.ts.map +1 -1
- package/dist/types/pull.d.ts.map +1 -1
- package/dist/types/push/pullLog.d.ts.map +1 -1
- package/dist/types/push/push.d.ts.map +1 -1
- package/dist/types/pushConfig.d.ts.map +1 -1
- package/dist/types/pushLog.d.ts.map +1 -1
- package/dist/types/searchDoc.d.ts.map +1 -1
- package/dist/types/test/test.d.ts.map +1 -1
- package/dist/types/translateDoc/types.d.ts.map +1 -1
- package/dist/types/translateDoc/validation.d.ts.map +1 -1
- package/dist/types/translation-alignment/computeSimilarity.d.ts.map +1 -1
- package/dist/types/translation-alignment/normalizeBlock.d.ts.map +1 -1
- package/dist/types/translation-alignment/pipeline.d.ts.map +1 -1
- package/dist/types/translation-alignment/rebuildDocument.d.ts.map +1 -1
- package/dist/types/translation-alignment/segmentDocument.d.ts.map +1 -1
- package/dist/types/translation-alignment/types.d.ts.map +1 -1
- package/dist/types/utils/calculateChunks.d.ts.map +1 -1
- package/dist/types/utils/checkAccess.d.ts +3 -2
- package/dist/types/utils/checkAccess.d.ts.map +1 -1
- package/dist/types/utils/checkConfigConsistency.d.ts.map +1 -1
- package/dist/types/utils/checkFileModifiedRange.d.ts.map +1 -1
- package/dist/types/utils/checkLastUpdateTime.d.ts.map +1 -1
- package/dist/types/utils/chunkInference.d.ts.map +1 -1
- package/dist/types/utils/fixChunkStartEndChars.d.ts.map +1 -1
- package/dist/types/utils/formatTimeDiff.d.ts.map +1 -1
- package/dist/types/utils/getIsFileUpdatedRecently.d.ts.map +1 -1
- package/dist/types/utils/getOutputFilePath.d.ts.map +1 -1
- package/dist/types/utils/getParentPackageJSON.d.ts.map +1 -1
- package/dist/types/utils/listSpecialChars.d.ts.map +1 -1
- package/dist/types/utils/mapChunksBetweenFiles.d.ts.map +1 -1
- package/dist/types/utils/openBrowser.d.ts.map +1 -1
- package/dist/types/utils/reorderParagraphs.d.ts.map +1 -1
- package/dist/types/utils/setupAI.d.ts +1 -2
- package/dist/types/utils/setupAI.d.ts.map +1 -1
- package/dist/types/watch.d.ts.map +1 -1
- package/package.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planActions.mjs","names":[],"sources":["../../../src/translation-alignment/planActions.ts"],"sourcesContent":["import type { AlignmentPair, AlignmentPlan, PlannedAction } from './types';\n\nexport const planAlignmentActions = (\n alignment: AlignmentPair[],\n changedEnglishBlockIndexes: Set<number>\n): AlignmentPlan => {\n const actions: PlannedAction[] = [];\n const seenFrench = new Set<number>();\n\n alignment.forEach((pair) => {\n const englishIndex = pair.englishIndex;\n const frenchIndex = pair.frenchIndex;\n\n // Case 1: Deletion (Exists in FR, not in EN)\n if (englishIndex === -1 && frenchIndex !== null) {\n if (!seenFrench.has(frenchIndex)) {\n actions.push({ kind: 'delete', frenchIndex });\n seenFrench.add(frenchIndex);\n }\n return;\n }\n\n // Case 2: New Insertion (Exists in EN, not in FR)\n if (englishIndex >= 0 && frenchIndex === null) {\n actions.push({ kind: 'insert_new', englishIndex });\n return;\n }\n\n // Case 3: Alignment (Exists in both)\n if (englishIndex >= 0 && frenchIndex !== null) {\n const isChanged = changedEnglishBlockIndexes.has(englishIndex);\n\n // If the block is NOT marked as changed by Git, we REUSE it.\n // We assume the existing translation is correct because the source hasn't been touched.\n // We ignore 'similarityScore' here because EN vs UK text will always have low similarity.\n if (!isChanged) {\n actions.push({ kind: 'reuse', englishIndex, frenchIndex });\n } else {\n // If the block IS changed, we normally Review.\n // OPTIONAL: You could add a check here for 'similarityScore > 0.99'\n // to detect whitespace-only changes, but generally, if Git says changed, we Review.\n actions.push({ kind: 'review', englishIndex, frenchIndex });\n }\n\n seenFrench.add(frenchIndex);\n return;\n }\n });\n\n return { actions };\n};\n"],"mappings":";AAEA,MAAa,wBACX,WACA,+BACkB;CAClB,MAAM,UAA2B,
|
|
1
|
+
{"version":3,"file":"planActions.mjs","names":[],"sources":["../../../src/translation-alignment/planActions.ts"],"sourcesContent":["import type { AlignmentPair, AlignmentPlan, PlannedAction } from './types';\n\nexport const planAlignmentActions = (\n alignment: AlignmentPair[],\n changedEnglishBlockIndexes: Set<number>\n): AlignmentPlan => {\n const actions: PlannedAction[] = [];\n const seenFrench = new Set<number>();\n\n alignment.forEach((pair) => {\n const englishIndex = pair.englishIndex;\n const frenchIndex = pair.frenchIndex;\n\n // Case 1: Deletion (Exists in FR, not in EN)\n if (englishIndex === -1 && frenchIndex !== null) {\n if (!seenFrench.has(frenchIndex)) {\n actions.push({ kind: 'delete', frenchIndex });\n seenFrench.add(frenchIndex);\n }\n return;\n }\n\n // Case 2: New Insertion (Exists in EN, not in FR)\n if (englishIndex >= 0 && frenchIndex === null) {\n actions.push({ kind: 'insert_new', englishIndex });\n return;\n }\n\n // Case 3: Alignment (Exists in both)\n if (englishIndex >= 0 && frenchIndex !== null) {\n const isChanged = changedEnglishBlockIndexes.has(englishIndex);\n\n // If the block is NOT marked as changed by Git, we REUSE it.\n // We assume the existing translation is correct because the source hasn't been touched.\n // We ignore 'similarityScore' here because EN vs UK text will always have low similarity.\n if (!isChanged) {\n actions.push({ kind: 'reuse', englishIndex, frenchIndex });\n } else {\n // If the block IS changed, we normally Review.\n // OPTIONAL: You could add a check here for 'similarityScore > 0.99'\n // to detect whitespace-only changes, but generally, if Git says changed, we Review.\n actions.push({ kind: 'review', englishIndex, frenchIndex });\n }\n\n seenFrench.add(frenchIndex);\n return;\n }\n });\n\n return { actions };\n};\n"],"mappings":";AAEA,MAAa,wBACX,WACA,+BACkB;CAClB,MAAM,UAA2B,CAAC;CAClC,MAAM,6BAAa,IAAI,IAAY;CAEnC,UAAU,SAAS,SAAS;EAC1B,MAAM,eAAe,KAAK;EAC1B,MAAM,cAAc,KAAK;EAGzB,IAAI,iBAAiB,MAAM,gBAAgB,MAAM;GAC/C,IAAI,CAAC,WAAW,IAAI,WAAW,GAAG;IAChC,QAAQ,KAAK;KAAE,MAAM;KAAU;IAAY,CAAC;IAC5C,WAAW,IAAI,WAAW;GAC5B;GACA;EACF;EAGA,IAAI,gBAAgB,KAAK,gBAAgB,MAAM;GAC7C,QAAQ,KAAK;IAAE,MAAM;IAAc;GAAa,CAAC;GACjD;EACF;EAGA,IAAI,gBAAgB,KAAK,gBAAgB,MAAM;GAM7C,IAAI,CALc,2BAA2B,IAAI,YAKpC,GACX,QAAQ,KAAK;IAAE,MAAM;IAAS;IAAc;GAAY,CAAC;QAKzD,QAAQ,KAAK;IAAE,MAAM;IAAU;IAAc;GAAY,CAAC;GAG5D,WAAW,IAAI,WAAW;GAC1B;EACF;CACF,CAAC;CAED,OAAO,EAAE,QAAQ;AACnB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rebuildDocument.mjs","names":[],"sources":["../../../src/translation-alignment/rebuildDocument.ts"],"sourcesContent":["import type { AlignmentPlan, FingerprintedBlock } from './types';\n\nexport type SegmentToReview = {\n englishBlock: FingerprintedBlock;\n frenchBlockText: string | null;\n actionIndex: number;\n};\n\nexport type RebuildInput = {\n englishBlocks: FingerprintedBlock[];\n frenchBlocks: FingerprintedBlock[];\n plan: AlignmentPlan;\n};\n\nexport type RebuildResult = {\n segmentsToReview: SegmentToReview[];\n};\n\n/**\n * Analyzes the alignment plan and returns only the segments that need review/translation.\n * Does not generate output text - that's done by mergeReviewedSegments after translation.\n */\nexport const identifySegmentsToReview = ({\n englishBlocks,\n frenchBlocks,\n plan,\n}: RebuildInput): RebuildResult => {\n const segmentsToReview: SegmentToReview[] = [];\n\n plan.actions.forEach((action, actionIndex) => {\n if (action.kind === 'review') {\n const englishBlock = englishBlocks[action.englishIndex];\n const frenchBlockText =\n action.frenchIndex !== null\n ? frenchBlocks[action.frenchIndex].content\n : null;\n\n segmentsToReview.push({ englishBlock, frenchBlockText, actionIndex });\n } else if (action.kind === 'insert_new') {\n const englishBlock = englishBlocks[action.englishIndex];\n\n segmentsToReview.push({\n englishBlock,\n frenchBlockText: null,\n actionIndex,\n });\n }\n });\n\n return { segmentsToReview };\n};\n\n/**\n * Merges reviewed translations back into the final document following the alignment plan.\n */\nexport const mergeReviewedSegments = (\n plan: AlignmentPlan,\n frenchBlocks: FingerprintedBlock[],\n reviewedSegments: Map<number, string>\n): string => {\n const outputParts: string[] = [];\n\n plan.actions.forEach((action, actionIndex) => {\n if (action.kind === 'reuse') {\n outputParts.push(frenchBlocks[action.frenchIndex].content);\n } else if (action.kind === 'review' || action.kind === 'insert_new') {\n const reviewedContent = reviewedSegments.get(actionIndex);\n\n if (reviewedContent !== undefined) {\n outputParts.push(reviewedContent);\n } else {\n // Fallback: if review failed, use existing or blank\n if (action.kind === 'review' && action.frenchIndex !== null) {\n outputParts.push(frenchBlocks[action.frenchIndex].content);\n } else {\n outputParts.push('\\n');\n }\n }\n }\n // \"delete\" actions are simply skipped - no output\n });\n\n return outputParts.join('');\n};\n"],"mappings":";;;;;AAsBA,MAAa,4BAA4B,EACvC,eACA,cACA,WACiC;CACjC,MAAM,mBAAsC,
|
|
1
|
+
{"version":3,"file":"rebuildDocument.mjs","names":[],"sources":["../../../src/translation-alignment/rebuildDocument.ts"],"sourcesContent":["import type { AlignmentPlan, FingerprintedBlock } from './types';\n\nexport type SegmentToReview = {\n englishBlock: FingerprintedBlock;\n frenchBlockText: string | null;\n actionIndex: number;\n};\n\nexport type RebuildInput = {\n englishBlocks: FingerprintedBlock[];\n frenchBlocks: FingerprintedBlock[];\n plan: AlignmentPlan;\n};\n\nexport type RebuildResult = {\n segmentsToReview: SegmentToReview[];\n};\n\n/**\n * Analyzes the alignment plan and returns only the segments that need review/translation.\n * Does not generate output text - that's done by mergeReviewedSegments after translation.\n */\nexport const identifySegmentsToReview = ({\n englishBlocks,\n frenchBlocks,\n plan,\n}: RebuildInput): RebuildResult => {\n const segmentsToReview: SegmentToReview[] = [];\n\n plan.actions.forEach((action, actionIndex) => {\n if (action.kind === 'review') {\n const englishBlock = englishBlocks[action.englishIndex];\n const frenchBlockText =\n action.frenchIndex !== null\n ? frenchBlocks[action.frenchIndex].content\n : null;\n\n segmentsToReview.push({ englishBlock, frenchBlockText, actionIndex });\n } else if (action.kind === 'insert_new') {\n const englishBlock = englishBlocks[action.englishIndex];\n\n segmentsToReview.push({\n englishBlock,\n frenchBlockText: null,\n actionIndex,\n });\n }\n });\n\n return { segmentsToReview };\n};\n\n/**\n * Merges reviewed translations back into the final document following the alignment plan.\n */\nexport const mergeReviewedSegments = (\n plan: AlignmentPlan,\n frenchBlocks: FingerprintedBlock[],\n reviewedSegments: Map<number, string>\n): string => {\n const outputParts: string[] = [];\n\n plan.actions.forEach((action, actionIndex) => {\n if (action.kind === 'reuse') {\n outputParts.push(frenchBlocks[action.frenchIndex].content);\n } else if (action.kind === 'review' || action.kind === 'insert_new') {\n const reviewedContent = reviewedSegments.get(actionIndex);\n\n if (reviewedContent !== undefined) {\n outputParts.push(reviewedContent);\n } else {\n // Fallback: if review failed, use existing or blank\n if (action.kind === 'review' && action.frenchIndex !== null) {\n outputParts.push(frenchBlocks[action.frenchIndex].content);\n } else {\n outputParts.push('\\n');\n }\n }\n }\n // \"delete\" actions are simply skipped - no output\n });\n\n return outputParts.join('');\n};\n"],"mappings":";;;;;AAsBA,MAAa,4BAA4B,EACvC,eACA,cACA,WACiC;CACjC,MAAM,mBAAsC,CAAC;CAE7C,KAAK,QAAQ,SAAS,QAAQ,gBAAgB;EAC5C,IAAI,OAAO,SAAS,UAAU;GAC5B,MAAM,eAAe,cAAc,OAAO;GAC1C,MAAM,kBACJ,OAAO,gBAAgB,OACnB,aAAa,OAAO,aAAa,UACjC;GAEN,iBAAiB,KAAK;IAAE;IAAc;IAAiB;GAAY,CAAC;EACtE,OAAO,IAAI,OAAO,SAAS,cAAc;GACvC,MAAM,eAAe,cAAc,OAAO;GAE1C,iBAAiB,KAAK;IACpB;IACA,iBAAiB;IACjB;GACF,CAAC;EACH;CACF,CAAC;CAED,OAAO,EAAE,iBAAiB;AAC5B;;;;AAKA,MAAa,yBACX,MACA,cACA,qBACW;CACX,MAAM,cAAwB,CAAC;CAE/B,KAAK,QAAQ,SAAS,QAAQ,gBAAgB;EAC5C,IAAI,OAAO,SAAS,SAClB,YAAY,KAAK,aAAa,OAAO,aAAa,OAAO;OACpD,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,cAAc;GACnE,MAAM,kBAAkB,iBAAiB,IAAI,WAAW;GAExD,IAAI,oBAAoB,QACtB,YAAY,KAAK,eAAe;QAGhC,IAAI,OAAO,SAAS,YAAY,OAAO,gBAAgB,MACrD,YAAY,KAAK,aAAa,OAAO,aAAa,OAAO;QAEzD,YAAY,KAAK,IAAI;EAG3B;CAEF,CAAC;CAED,OAAO,YAAY,KAAK,EAAE;AAC5B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"segmentDocument.mjs","names":[],"sources":["../../../src/translation-alignment/segmentDocument.ts"],"sourcesContent":["import type { Block } from './types';\n\nconst isBlankLine = (line: string): boolean => line.trim().length === 0;\nconst isFencedCodeDelimiter = (line: string): boolean => /^\\s*```/.test(line);\nconst isHeading = (line: string): boolean => /^\\s*#{1,6}\\s+/.test(line);\nconst isFrontmatterDelimiter = (line: string): boolean =>\n /^\\s*---\\s*$/.test(line);\nconst trimTrailingNewlines = (text: string): string =>\n text.replace(/\\n+$/g, '\\n');\n\nexport const segmentDocument = (text: string): Block[] => {\n const lines = text.split('\\n');\n const blocks: Block[] = [];\n\n let index = 0;\n let insideCodeBlock = false;\n\n // Buffers\n let currentSectionLines: string[] = [];\n let currentSectionStartLine = 1;\n\n const flushCurrentSection = (endIndex: number) => {\n if (currentSectionLines.length > 0) {\n // Filter out leading blank lines from the block content to keep it clean,\n // but strictly speaking, we just want to ensure non-empty content.\n const rawContent = currentSectionLines.join('\\n');\n\n if (rawContent.trim().length > 0) {\n blocks.push({\n type: 'paragraph', // Generic type\n content: `${trimTrailingNewlines(rawContent)}\\n`,\n lineStart: currentSectionStartLine,\n lineEnd: endIndex,\n });\n }\n currentSectionLines = [];\n }\n };\n\n while (index < lines.length) {\n const currentLine = lines[index];\n\n // 1. Handle Frontmatter (Must be at start of file)\n if (blocks.length === 0 && isFrontmatterDelimiter(currentLine)) {\n const startLine = index + 1;\n const contentLines: string[] = [currentLine];\n index++;\n\n while (index < lines.length && !isFrontmatterDelimiter(lines[index])) {\n contentLines.push(lines[index]);\n index++;\n }\n\n if (index < lines.length && isFrontmatterDelimiter(lines[index])) {\n contentLines.push(lines[index]);\n index++;\n }\n\n blocks.push({\n type: 'paragraph',\n content: `${trimTrailingNewlines(contentLines.join('\\n'))}\\n`,\n lineStart: startLine,\n lineEnd: index,\n });\n continue;\n }\n\n // 2. Track Code Blocks (Headers inside code blocks are ignored)\n if (isFencedCodeDelimiter(currentLine)) {\n insideCodeBlock = !insideCodeBlock;\n }\n\n const isHeader = !insideCodeBlock && isHeading(currentLine);\n\n // 3. Split on Headers\n if (isHeader) {\n // If we have accumulated content, flush it as the previous block\n if (currentSectionLines.length > 0) {\n flushCurrentSection(index);\n }\n // Start a new section with this header\n currentSectionStartLine = index + 1;\n currentSectionLines = [currentLine];\n } else {\n // Accumulate content\n if (currentSectionLines.length === 0 && !isBlankLine(currentLine)) {\n currentSectionStartLine = index + 1;\n }\n currentSectionLines.push(currentLine);\n }\n\n index++;\n }\n\n // Flush remaining content\n flushCurrentSection(index);\n\n return blocks;\n};\n"],"mappings":";AAEA,MAAM,eAAe,SAA0B,KAAK,
|
|
1
|
+
{"version":3,"file":"segmentDocument.mjs","names":[],"sources":["../../../src/translation-alignment/segmentDocument.ts"],"sourcesContent":["import type { Block } from './types';\n\nconst isBlankLine = (line: string): boolean => line.trim().length === 0;\nconst isFencedCodeDelimiter = (line: string): boolean => /^\\s*```/.test(line);\nconst isHeading = (line: string): boolean => /^\\s*#{1,6}\\s+/.test(line);\nconst isFrontmatterDelimiter = (line: string): boolean =>\n /^\\s*---\\s*$/.test(line);\nconst trimTrailingNewlines = (text: string): string =>\n text.replace(/\\n+$/g, '\\n');\n\nexport const segmentDocument = (text: string): Block[] => {\n const lines = text.split('\\n');\n const blocks: Block[] = [];\n\n let index = 0;\n let insideCodeBlock = false;\n\n // Buffers\n let currentSectionLines: string[] = [];\n let currentSectionStartLine = 1;\n\n const flushCurrentSection = (endIndex: number) => {\n if (currentSectionLines.length > 0) {\n // Filter out leading blank lines from the block content to keep it clean,\n // but strictly speaking, we just want to ensure non-empty content.\n const rawContent = currentSectionLines.join('\\n');\n\n if (rawContent.trim().length > 0) {\n blocks.push({\n type: 'paragraph', // Generic type\n content: `${trimTrailingNewlines(rawContent)}\\n`,\n lineStart: currentSectionStartLine,\n lineEnd: endIndex,\n });\n }\n currentSectionLines = [];\n }\n };\n\n while (index < lines.length) {\n const currentLine = lines[index];\n\n // 1. Handle Frontmatter (Must be at start of file)\n if (blocks.length === 0 && isFrontmatterDelimiter(currentLine)) {\n const startLine = index + 1;\n const contentLines: string[] = [currentLine];\n index++;\n\n while (index < lines.length && !isFrontmatterDelimiter(lines[index])) {\n contentLines.push(lines[index]);\n index++;\n }\n\n if (index < lines.length && isFrontmatterDelimiter(lines[index])) {\n contentLines.push(lines[index]);\n index++;\n }\n\n blocks.push({\n type: 'paragraph',\n content: `${trimTrailingNewlines(contentLines.join('\\n'))}\\n`,\n lineStart: startLine,\n lineEnd: index,\n });\n continue;\n }\n\n // 2. Track Code Blocks (Headers inside code blocks are ignored)\n if (isFencedCodeDelimiter(currentLine)) {\n insideCodeBlock = !insideCodeBlock;\n }\n\n const isHeader = !insideCodeBlock && isHeading(currentLine);\n\n // 3. Split on Headers\n if (isHeader) {\n // If we have accumulated content, flush it as the previous block\n if (currentSectionLines.length > 0) {\n flushCurrentSection(index);\n }\n // Start a new section with this header\n currentSectionStartLine = index + 1;\n currentSectionLines = [currentLine];\n } else {\n // Accumulate content\n if (currentSectionLines.length === 0 && !isBlankLine(currentLine)) {\n currentSectionStartLine = index + 1;\n }\n currentSectionLines.push(currentLine);\n }\n\n index++;\n }\n\n // Flush remaining content\n flushCurrentSection(index);\n\n return blocks;\n};\n"],"mappings":";AAEA,MAAM,eAAe,SAA0B,KAAK,KAAK,EAAE,WAAW;AACtE,MAAM,yBAAyB,SAA0B,UAAU,KAAK,IAAI;AAC5E,MAAM,aAAa,SAA0B,gBAAgB,KAAK,IAAI;AACtE,MAAM,0BAA0B,SAC9B,cAAc,KAAK,IAAI;AACzB,MAAM,wBAAwB,SAC5B,KAAK,QAAQ,SAAS,IAAI;AAE5B,MAAa,mBAAmB,SAA0B;CACxD,MAAM,QAAQ,KAAK,MAAM,IAAI;CAC7B,MAAM,SAAkB,CAAC;CAEzB,IAAI,QAAQ;CACZ,IAAI,kBAAkB;CAGtB,IAAI,sBAAgC,CAAC;CACrC,IAAI,0BAA0B;CAE9B,MAAM,uBAAuB,aAAqB;EAChD,IAAI,oBAAoB,SAAS,GAAG;GAGlC,MAAM,aAAa,oBAAoB,KAAK,IAAI;GAEhD,IAAI,WAAW,KAAK,EAAE,SAAS,GAC7B,OAAO,KAAK;IACV,MAAM;IACN,SAAS,GAAG,qBAAqB,UAAU,EAAE;IAC7C,WAAW;IACX,SAAS;GACX,CAAC;GAEH,sBAAsB,CAAC;EACzB;CACF;CAEA,OAAO,QAAQ,MAAM,QAAQ;EAC3B,MAAM,cAAc,MAAM;EAG1B,IAAI,OAAO,WAAW,KAAK,uBAAuB,WAAW,GAAG;GAC9D,MAAM,YAAY,QAAQ;GAC1B,MAAM,eAAyB,CAAC,WAAW;GAC3C;GAEA,OAAO,QAAQ,MAAM,UAAU,CAAC,uBAAuB,MAAM,MAAM,GAAG;IACpE,aAAa,KAAK,MAAM,MAAM;IAC9B;GACF;GAEA,IAAI,QAAQ,MAAM,UAAU,uBAAuB,MAAM,MAAM,GAAG;IAChE,aAAa,KAAK,MAAM,MAAM;IAC9B;GACF;GAEA,OAAO,KAAK;IACV,MAAM;IACN,SAAS,GAAG,qBAAqB,aAAa,KAAK,IAAI,CAAC,EAAE;IAC1D,WAAW;IACX,SAAS;GACX,CAAC;GACD;EACF;EAGA,IAAI,sBAAsB,WAAW,GACnC,kBAAkB,CAAC;EAMrB,IAHiB,CAAC,mBAAmB,UAAU,WAAW,GAG5C;GAEZ,IAAI,oBAAoB,SAAS,GAC/B,oBAAoB,KAAK;GAG3B,0BAA0B,QAAQ;GAClC,sBAAsB,CAAC,WAAW;EACpC,OAAO;GAEL,IAAI,oBAAoB,WAAW,KAAK,CAAC,YAAY,WAAW,GAC9D,0BAA0B,QAAQ;GAEpC,oBAAoB,KAAK,WAAW;EACtC;EAEA;CACF;CAGA,oBAAoB,KAAK;CAEzB,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"calculateChunks.mjs","names":[],"sources":["../../../src/utils/calculateChunks.ts"],"sourcesContent":["import { splitTextByLines } from '@intlayer/chokidar/utils';\n\nexport type ChunkLineResult = {\n lineStart: number;\n lineLength: number;\n charStart: number;\n charLength: number;\n content: string;\n};\n\nconst DEFAULT_MAX_CHARS_PER_CHUNK = 800;\nconst DEFAULT_OVERLAP_CHARS = 0;\n\nexport const chunkText = (\n text: string,\n maxCharsPerChunk: number = DEFAULT_MAX_CHARS_PER_CHUNK,\n overlapChars: number = DEFAULT_OVERLAP_CHARS\n): ChunkLineResult[] => {\n if (maxCharsPerChunk <= 0) {\n throw new Error('maxCharsPerChunk must be greater than 0');\n }\n\n const splittedText = splitTextByLines(text);\n\n // Split text into lines to facilitate the translation\n const lines: ChunkLineResult[] = [];\n let charStartAcc = 0;\n\n splittedText.forEach((line, index) => {\n lines.push({\n content: line,\n lineStart: index,\n lineLength: 1,\n charStart: charStartAcc,\n charLength: line.length,\n });\n charStartAcc += line.length;\n });\n\n // Group lines\n // as long as the chunk length is less than maxCharsPerChunk\n // if a line longer than maxCharsPerChunk, keep it alone\n // if a line is not longer than maxCharsPerChunk, it is grouped\n const groupedLines: ChunkLineResult[] = lines.reduce(\n (acc: ChunkLineResult[], line) => {\n // If this line alone exceeds maxCharsPerChunk, keep it separate\n if (line.content.length > maxCharsPerChunk) {\n acc.push(line);\n return acc;\n }\n\n // If we have no chunks yet, start with this line\n if (acc.length === 0) {\n acc.push(line);\n return acc;\n }\n\n // Get the last chunk\n const lastChunk = acc[acc.length - 1];\n\n // Calculate what the combined length would be (including newline character)\n const combinedLength = lastChunk.content.length + line.content.length;\n\n // If combining would exceed the limit, start a new chunk\n if (combinedLength > maxCharsPerChunk) {\n acc.push(line);\n return acc;\n }\n\n // Otherwise, combine with the last chunk\n const combinedContent = lastChunk.content + line.content;\n const updatedChunk = {\n content: combinedContent,\n lineStart: lastChunk.lineStart,\n lineLength: lastChunk.lineLength + line.lineLength,\n charStart: lastChunk.charStart,\n charLength: combinedContent.length,\n };\n\n acc[acc.length - 1] = updatedChunk;\n return acc;\n },\n []\n );\n\n // If one line is longer than maxCharsPerChunk, split it into multiple chunks\n const splittedLines: ChunkLineResult[] = groupedLines.flatMap((line) => {\n const chunk: ChunkLineResult[] = [];\n\n if (line.content.length <= maxCharsPerChunk) {\n chunk.push(line);\n return chunk;\n }\n\n for (let i = 0; i < line.content.length; i += maxCharsPerChunk) {\n const slicedContent = line.content.slice(i, i + maxCharsPerChunk);\n chunk.push({\n content: slicedContent,\n lineStart: line.lineStart,\n lineLength: 1,\n charStart: line.charStart + i,\n charLength: slicedContent.length,\n });\n }\n return chunk;\n });\n\n if (overlapChars === 0) return splittedLines;\n\n const overlapChunks: ChunkLineResult[] =\n splittedLines.length > 0 ? [splittedLines[0]] : [];\n\n for (let i = 1; i < splittedLines.length; i++) {\n const previousChunk = splittedLines[i - 1];\n const chunk = splittedLines[i];\n\n const overlapContent = previousChunk.content.slice(-overlapChars);\n const overlapLineNb = splitTextByLines(overlapContent).length;\n\n const overlapContentWithoutPartialLine = overlapContent.slice(\n overlapLineNb > 1 ? overlapContent.indexOf('\\n') + 1 : 0,\n overlapContent.length\n );\n\n const newContent = overlapContentWithoutPartialLine + chunk.content;\n const newLineLength = splitTextByLines(newContent).length;\n const lineDiff = chunk.lineLength - newLineLength;\n\n const overlappedChunk = {\n content: newContent,\n lineStart: chunk.lineStart + lineDiff,\n lineLength: chunk.lineLength - lineDiff,\n charStart: chunk.charStart - overlapContentWithoutPartialLine.length,\n charLength: newContent.length,\n };\n\n overlapChunks.push(overlappedChunk);\n }\n\n return overlapChunks;\n};\n"],"mappings":";;;AAUA,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAE9B,MAAa,aACX,MACA,mBAA2B,6BAC3B,eAAuB,0BACD;CACtB,IAAI,oBAAoB,GACtB,MAAM,IAAI,MAAM,
|
|
1
|
+
{"version":3,"file":"calculateChunks.mjs","names":[],"sources":["../../../src/utils/calculateChunks.ts"],"sourcesContent":["import { splitTextByLines } from '@intlayer/chokidar/utils';\n\nexport type ChunkLineResult = {\n lineStart: number;\n lineLength: number;\n charStart: number;\n charLength: number;\n content: string;\n};\n\nconst DEFAULT_MAX_CHARS_PER_CHUNK = 800;\nconst DEFAULT_OVERLAP_CHARS = 0;\n\nexport const chunkText = (\n text: string,\n maxCharsPerChunk: number = DEFAULT_MAX_CHARS_PER_CHUNK,\n overlapChars: number = DEFAULT_OVERLAP_CHARS\n): ChunkLineResult[] => {\n if (maxCharsPerChunk <= 0) {\n throw new Error('maxCharsPerChunk must be greater than 0');\n }\n\n const splittedText = splitTextByLines(text);\n\n // Split text into lines to facilitate the translation\n const lines: ChunkLineResult[] = [];\n let charStartAcc = 0;\n\n splittedText.forEach((line, index) => {\n lines.push({\n content: line,\n lineStart: index,\n lineLength: 1,\n charStart: charStartAcc,\n charLength: line.length,\n });\n charStartAcc += line.length;\n });\n\n // Group lines\n // as long as the chunk length is less than maxCharsPerChunk\n // if a line longer than maxCharsPerChunk, keep it alone\n // if a line is not longer than maxCharsPerChunk, it is grouped\n const groupedLines: ChunkLineResult[] = lines.reduce(\n (acc: ChunkLineResult[], line) => {\n // If this line alone exceeds maxCharsPerChunk, keep it separate\n if (line.content.length > maxCharsPerChunk) {\n acc.push(line);\n return acc;\n }\n\n // If we have no chunks yet, start with this line\n if (acc.length === 0) {\n acc.push(line);\n return acc;\n }\n\n // Get the last chunk\n const lastChunk = acc[acc.length - 1];\n\n // Calculate what the combined length would be (including newline character)\n const combinedLength = lastChunk.content.length + line.content.length;\n\n // If combining would exceed the limit, start a new chunk\n if (combinedLength > maxCharsPerChunk) {\n acc.push(line);\n return acc;\n }\n\n // Otherwise, combine with the last chunk\n const combinedContent = lastChunk.content + line.content;\n const updatedChunk = {\n content: combinedContent,\n lineStart: lastChunk.lineStart,\n lineLength: lastChunk.lineLength + line.lineLength,\n charStart: lastChunk.charStart,\n charLength: combinedContent.length,\n };\n\n acc[acc.length - 1] = updatedChunk;\n return acc;\n },\n []\n );\n\n // If one line is longer than maxCharsPerChunk, split it into multiple chunks\n const splittedLines: ChunkLineResult[] = groupedLines.flatMap((line) => {\n const chunk: ChunkLineResult[] = [];\n\n if (line.content.length <= maxCharsPerChunk) {\n chunk.push(line);\n return chunk;\n }\n\n for (let i = 0; i < line.content.length; i += maxCharsPerChunk) {\n const slicedContent = line.content.slice(i, i + maxCharsPerChunk);\n chunk.push({\n content: slicedContent,\n lineStart: line.lineStart,\n lineLength: 1,\n charStart: line.charStart + i,\n charLength: slicedContent.length,\n });\n }\n return chunk;\n });\n\n if (overlapChars === 0) return splittedLines;\n\n const overlapChunks: ChunkLineResult[] =\n splittedLines.length > 0 ? [splittedLines[0]] : [];\n\n for (let i = 1; i < splittedLines.length; i++) {\n const previousChunk = splittedLines[i - 1];\n const chunk = splittedLines[i];\n\n const overlapContent = previousChunk.content.slice(-overlapChars);\n const overlapLineNb = splitTextByLines(overlapContent).length;\n\n const overlapContentWithoutPartialLine = overlapContent.slice(\n overlapLineNb > 1 ? overlapContent.indexOf('\\n') + 1 : 0,\n overlapContent.length\n );\n\n const newContent = overlapContentWithoutPartialLine + chunk.content;\n const newLineLength = splitTextByLines(newContent).length;\n const lineDiff = chunk.lineLength - newLineLength;\n\n const overlappedChunk = {\n content: newContent,\n lineStart: chunk.lineStart + lineDiff,\n lineLength: chunk.lineLength - lineDiff,\n charStart: chunk.charStart - overlapContentWithoutPartialLine.length,\n charLength: newContent.length,\n };\n\n overlapChunks.push(overlappedChunk);\n }\n\n return overlapChunks;\n};\n"],"mappings":";;;AAUA,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAE9B,MAAa,aACX,MACA,mBAA2B,6BAC3B,eAAuB,0BACD;CACtB,IAAI,oBAAoB,GACtB,MAAM,IAAI,MAAM,yCAAyC;CAG3D,MAAM,eAAe,iBAAiB,IAAI;CAG1C,MAAM,QAA2B,CAAC;CAClC,IAAI,eAAe;CAEnB,aAAa,SAAS,MAAM,UAAU;EACpC,MAAM,KAAK;GACT,SAAS;GACT,WAAW;GACX,YAAY;GACZ,WAAW;GACX,YAAY,KAAK;EACnB,CAAC;EACD,gBAAgB,KAAK;CACvB,CAAC;CAiDD,MAAM,gBA3CkC,MAAM,QAC3C,KAAwB,SAAS;EAEhC,IAAI,KAAK,QAAQ,SAAS,kBAAkB;GAC1C,IAAI,KAAK,IAAI;GACb,OAAO;EACT;EAGA,IAAI,IAAI,WAAW,GAAG;GACpB,IAAI,KAAK,IAAI;GACb,OAAO;EACT;EAGA,MAAM,YAAY,IAAI,IAAI,SAAS;EAMnC,IAHuB,UAAU,QAAQ,SAAS,KAAK,QAAQ,SAG1C,kBAAkB;GACrC,IAAI,KAAK,IAAI;GACb,OAAO;EACT;EAGA,MAAM,kBAAkB,UAAU,UAAU,KAAK;EACjD,MAAM,eAAe;GACnB,SAAS;GACT,WAAW,UAAU;GACrB,YAAY,UAAU,aAAa,KAAK;GACxC,WAAW,UAAU;GACrB,YAAY,gBAAgB;EAC9B;EAEA,IAAI,IAAI,SAAS,KAAK;EACtB,OAAO;CACT,GACA,CAAC,CAIiD,EAAE,SAAS,SAAS;EACtE,MAAM,QAA2B,CAAC;EAElC,IAAI,KAAK,QAAQ,UAAU,kBAAkB;GAC3C,MAAM,KAAK,IAAI;GACf,OAAO;EACT;EAEA,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,QAAQ,KAAK,kBAAkB;GAC9D,MAAM,gBAAgB,KAAK,QAAQ,MAAM,GAAG,IAAI,gBAAgB;GAChE,MAAM,KAAK;IACT,SAAS;IACT,WAAW,KAAK;IAChB,YAAY;IACZ,WAAW,KAAK,YAAY;IAC5B,YAAY,cAAc;GAC5B,CAAC;EACH;EACA,OAAO;CACT,CAAC;CAED,IAAI,iBAAiB,GAAG,OAAO;CAE/B,MAAM,gBACJ,cAAc,SAAS,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC;CAEnD,KAAK,IAAI,IAAI,GAAG,IAAI,cAAc,QAAQ,KAAK;EAC7C,MAAM,gBAAgB,cAAc,IAAI;EACxC,MAAM,QAAQ,cAAc;EAE5B,MAAM,iBAAiB,cAAc,QAAQ,MAAM,CAAC,YAAY;EAChE,MAAM,gBAAgB,iBAAiB,cAAc,EAAE;EAEvD,MAAM,mCAAmC,eAAe,MACtD,gBAAgB,IAAI,eAAe,QAAQ,IAAI,IAAI,IAAI,GACvD,eAAe,MACjB;EAEA,MAAM,aAAa,mCAAmC,MAAM;EAC5D,MAAM,gBAAgB,iBAAiB,UAAU,EAAE;EACnD,MAAM,WAAW,MAAM,aAAa;EAEpC,MAAM,kBAAkB;GACtB,SAAS;GACT,WAAW,MAAM,YAAY;GAC7B,YAAY,MAAM,aAAa;GAC/B,WAAW,MAAM,YAAY,iCAAiC;GAC9D,YAAY,WAAW;EACzB;EAEA,cAAc,KAAK,eAAe;CACpC;CAEA,OAAO;AACT"}
|
|
@@ -6,6 +6,11 @@ import { getIntlayerAPIProxy } from "@intlayer/api";
|
|
|
6
6
|
import { extractErrorMessage } from "@intlayer/config/utils";
|
|
7
7
|
|
|
8
8
|
//#region src/utils/checkAccess.ts
|
|
9
|
+
const getAuthenticatedAPI = async (configuration) => {
|
|
10
|
+
let sessionData = null;
|
|
11
|
+
if (configuration) sessionData = await readCliSessionToken(configuration);
|
|
12
|
+
return getIntlayerAPIProxy(void 0, configuration, sessionData?.token);
|
|
13
|
+
};
|
|
9
14
|
const checkProjectConfigConsistency = (project, configuration, appLogger) => {
|
|
10
15
|
if (!project?.configuration) return;
|
|
11
16
|
try {
|
|
@@ -97,5 +102,5 @@ const checkAIAccess = async (configuration, aiOptions, shouldCheckConfigConsiste
|
|
|
97
102
|
};
|
|
98
103
|
|
|
99
104
|
//#endregion
|
|
100
|
-
export { checkAIAccess, checkCMSAuth };
|
|
105
|
+
export { checkAIAccess, checkCMSAuth, getAuthenticatedAPI };
|
|
101
106
|
//# sourceMappingURL=checkAccess.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkAccess.mjs","names":[],"sources":["../../../src/utils/checkAccess.ts"],"sourcesContent":["import type { AIOptions } from '@intlayer/api';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { extractErrorMessage } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { readCliSessionToken } from '../auth/sessionToken';\nimport { checkConfigConsistency } from './checkConfigConsistency';\n\nconst checkProjectConfigConsistency = (\n project: { configuration?: any } | null | undefined,\n configuration: IntlayerConfig,\n appLogger: ReturnType<typeof getAppLogger>\n): void => {\n if (!project?.configuration) return;\n\n try {\n let remoteConfigToCheck = project.configuration;\n\n if (\n remoteConfigToCheck.ai &&\n 'apiKeyConfigured' in remoteConfigToCheck.ai\n ) {\n const { apiKeyConfigured, ...restAi } = remoteConfigToCheck.ai as any;\n remoteConfigToCheck = { ...remoteConfigToCheck, ai: restAi };\n }\n\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('https://intlayer.org/doc/concept/cli/push', ANSIColors.GREY),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n { level: 'warn' }\n );\n }\n};\n\nexport const checkCMSAuth = async (\n configuration: IntlayerConfig,\n shouldCheckConfigConsistency: boolean = true\n): Promise<boolean> => {\n const appLogger = getAppLogger(configuration);\n\n // Try CLI session token first (short-lived 2h token stored in tempDir)\n const sessionData = await readCliSessionToken(configuration);\n if (sessionData) {\n const intlayerAPI = getIntlayerAPIProxy(\n undefined,\n configuration,\n sessionData.token\n );\n\n try {\n const result = await intlayerAPI.oAuth.getCliSessionMe();\n const project = result.data?.project;\n\n if (project && shouldCheckConfigConsistency) {\n checkProjectConfigConsistency(project, configuration, appLogger);\n }\n\n return true;\n } catch (error) {\n const message = extractErrorMessage(error);\n appLogger(message, { level: 'error' });\n return false;\n }\n }\n\n // Fall back to client_credentials (access key)\n const hasCMSAuth =\n configuration.editor.clientId && configuration.editor.clientSecret;\n if (!hasCMSAuth) {\n appLogger(\n [\n 'CMS auth not provided. Run',\n colorize('npx intlayer login', ANSIColors.CYAN),\n 'to authenticate, or set',\n colorize('INTLAYER_CLIENT_ID', ANSIColors.GREY_LIGHT),\n 'and',\n colorize('INTLAYER_CLIENT_SECRET', ANSIColors.GREY_LIGHT),\n 'in your .env file',\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 { level: 'error' }\n );\n\n return false;\n }\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 return true;\n }\n\n if (shouldCheckConfigConsistency) {\n checkProjectConfigConsistency(project, configuration, appLogger);\n }\n } catch (error) {\n const message = extractErrorMessage(error);\n appLogger(message, { level: 'error' });\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\n const sessionData = await readCliSessionToken(configuration);\n const hasSessionToken = Boolean(sessionData);\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 && !hasSessionToken) {\n appLogger(\n [\n 'AI options or API key not provided. Run',\n colorize('npx intlayer login', ANSIColors.CYAN),\n 'to authenticate, or provide an API key',\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 { level: 'error' }\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":";;;;;;;;AASA,MAAM,iCACJ,SACA,eACA,cACS;CACT,IAAI,CAAC,SAAS,eAAe;CAE7B,IAAI;EACF,IAAI,sBAAsB,QAAQ;EAElC,IACE,oBAAoB,MACpB,sBAAsB,oBAAoB,IAC1C;GACA,MAAM,EAAE,kBAAkB,GAAG,WAAW,oBAAoB;GAC5D,sBAAsB;IAAE,GAAG;IAAqB,IAAI;
|
|
1
|
+
{"version":3,"file":"checkAccess.mjs","names":[],"sources":["../../../src/utils/checkAccess.ts"],"sourcesContent":["import type { AIOptions, IntlayerAPIProxy } from '@intlayer/api';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { extractErrorMessage } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { type CliSessionData, readCliSessionToken } from '../auth/sessionToken';\nimport { checkConfigConsistency } from './checkConfigConsistency';\n\nexport const getAuthenticatedAPI = async (\n configuration?: IntlayerConfig\n): Promise<IntlayerAPIProxy> => {\n let sessionData: CliSessionData | null = null;\n\n // First use session data if it exists\n if (configuration) {\n sessionData = await readCliSessionToken(configuration);\n }\n\n return getIntlayerAPIProxy(undefined, configuration, sessionData?.token);\n};\n\nconst checkProjectConfigConsistency = (\n project: { configuration?: any } | null | undefined,\n configuration: IntlayerConfig,\n appLogger: ReturnType<typeof getAppLogger>\n): void => {\n if (!project?.configuration) return;\n\n try {\n let remoteConfigToCheck = project.configuration;\n\n if (\n remoteConfigToCheck.ai &&\n 'apiKeyConfigured' in remoteConfigToCheck.ai\n ) {\n const { apiKeyConfigured, ...restAi } = remoteConfigToCheck.ai as any;\n remoteConfigToCheck = { ...remoteConfigToCheck, ai: restAi };\n }\n\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('https://intlayer.org/doc/concept/cli/push', ANSIColors.GREY),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n { level: 'warn' }\n );\n }\n};\n\nexport const checkCMSAuth = async (\n configuration: IntlayerConfig,\n shouldCheckConfigConsistency: boolean = true\n): Promise<boolean> => {\n const appLogger = getAppLogger(configuration);\n\n // Try CLI session token first (short-lived 2h token stored in tempDir)\n const sessionData = await readCliSessionToken(configuration);\n if (sessionData) {\n const intlayerAPI = getIntlayerAPIProxy(\n undefined,\n configuration,\n sessionData.token\n );\n\n try {\n const result = await intlayerAPI.oAuth.getCliSessionMe();\n const project = result.data?.project;\n\n if (project && shouldCheckConfigConsistency) {\n checkProjectConfigConsistency(project, configuration, appLogger);\n }\n\n return true;\n } catch (error) {\n const message = extractErrorMessage(error);\n appLogger(message, { level: 'error' });\n return false;\n }\n }\n\n // Fall back to client_credentials (access key)\n const hasCMSAuth =\n configuration.editor.clientId && configuration.editor.clientSecret;\n if (!hasCMSAuth) {\n appLogger(\n [\n 'CMS auth not provided. Run',\n colorize('npx intlayer login', ANSIColors.CYAN),\n 'to authenticate, or set',\n colorize('INTLAYER_CLIENT_ID', ANSIColors.GREY_LIGHT),\n 'and',\n colorize('INTLAYER_CLIENT_SECRET', ANSIColors.GREY_LIGHT),\n 'in your .env file',\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 { level: 'error' }\n );\n\n return false;\n }\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 return true;\n }\n\n if (shouldCheckConfigConsistency) {\n checkProjectConfigConsistency(project, configuration, appLogger);\n }\n } catch (error) {\n const message = extractErrorMessage(error);\n appLogger(message, { level: 'error' });\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\n const sessionData = await readCliSessionToken(configuration);\n const hasSessionToken = Boolean(sessionData);\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 && !hasSessionToken) {\n appLogger(\n [\n 'AI options or API key not provided. Run',\n colorize('npx intlayer login', ANSIColors.CYAN),\n 'to authenticate, or provide an API key',\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 { level: 'error' }\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":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkConfigConsistency.mjs","names":[],"sources":["../../../src/utils/checkConfigConsistency.ts"],"sourcesContent":["export const checkConfigConsistency = (subset: any, superset: any) => {\n for (const key in subset) {\n const val1 = subset[key];\n const val2 = superset[key];\n\n if (Array.isArray(val1) && Array.isArray(val2)) {\n // Check if arrays are identical in content\n if (JSON.stringify(val1) !== JSON.stringify(val2)) {\n throw new Error(`Configuration mismatch at key \"${key}\"`);\n }\n } else if (typeof val1 === 'object' && val1 !== null) {\n checkConfigConsistency(val1, val2);\n } else if (val1 !== val2) {\n throw new Error(`Configuration mismatch at key \"${key}\"`);\n }\n }\n};\n"],"mappings":";AAAA,MAAa,0BAA0B,QAAa,aAAkB;CACpE,KAAK,MAAM,OAAO,QAAQ;EACxB,MAAM,OAAO,OAAO;EACpB,MAAM,OAAO,SAAS;EAEtB,IAAI,MAAM,QAAQ,KAAK,
|
|
1
|
+
{"version":3,"file":"checkConfigConsistency.mjs","names":[],"sources":["../../../src/utils/checkConfigConsistency.ts"],"sourcesContent":["export const checkConfigConsistency = (subset: any, superset: any) => {\n for (const key in subset) {\n const val1 = subset[key];\n const val2 = superset[key];\n\n if (Array.isArray(val1) && Array.isArray(val2)) {\n // Check if arrays are identical in content\n if (JSON.stringify(val1) !== JSON.stringify(val2)) {\n throw new Error(`Configuration mismatch at key \"${key}\"`);\n }\n } else if (typeof val1 === 'object' && val1 !== null) {\n checkConfigConsistency(val1, val2);\n } else if (val1 !== val2) {\n throw new Error(`Configuration mismatch at key \"${key}\"`);\n }\n }\n};\n"],"mappings":";AAAA,MAAa,0BAA0B,QAAa,aAAkB;CACpE,KAAK,MAAM,OAAO,QAAQ;EACxB,MAAM,OAAO,OAAO;EACpB,MAAM,OAAO,SAAS;EAEtB,IAAI,MAAM,QAAQ,IAAI,KAAK,MAAM,QAAQ,IAAI,GAE3C;OAAI,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,IAAI,GAC9C,MAAM,IAAI,MAAM,kCAAkC,IAAI,EAAE;EAC1D,OACK,IAAI,OAAO,SAAS,YAAY,SAAS,MAC9C,uBAAuB,MAAM,IAAI;OAC5B,IAAI,SAAS,MAClB,MAAM,IAAI,MAAM,kCAAkC,IAAI,EAAE;CAE5D;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkFileModifiedRange.mjs","names":[],"sources":["../../../src/utils/checkFileModifiedRange.ts"],"sourcesContent":["import { checkLastUpdateTime } from './checkLastUpdateTime';\nimport { formatTimeDiff } from './formatTimeDiff';\n\ntype GetTimeRangeResult = {\n relativeTime: Date;\n absoluteTime: Date;\n};\n\n/**\n * Threshold that helps us differentiate between a numeric *timestamp* (ms from epoch)\n * and a numeric *duration* (ms ago).\n * 50 years expressed in milliseconds is far greater than any reasonable\n * \"relative\" duration we expect the helper to receive (e.g. a couple of years).\n */\nconst TIMESTAMP_THRESHOLD_MS = 50 * 365 * 24 * 60 * 60 * 1000; // 50 years\n\n/**\n * Normalises the input date representation into a pair:\n * 1. `relativeTime` – a Date instance whose epoch-time equals the duration\n * between `now` and the absolute date.\n * 2. `absoluteTime` – the concrete point in time represented as a Date.\n *\n * Rules for interpreting the input:\n * • Date => treated as an absolute time.\n * • string => parsed via the Date constructor => absolute time.\n * • number:\n * – if the value is larger than the TIMESTAMP_THRESHOLD_MS we assume it\n * is a unix timestamp (absolute time).\n * – otherwise we treat it as a *relative* duration expressed in\n * milliseconds.\n */\nconst normaliseInputDate = (\n date: Date | number | string,\n now: Date = new Date()\n): GetTimeRangeResult => {\n // Case 1: Already a Date instance\n if (date instanceof Date) {\n return {\n absoluteTime: date,\n relativeTime: new Date(now.getTime() - date.getTime()),\n };\n }\n\n // Case 2: Numeric value – decide between timestamp vs relative ms.\n if (typeof date === 'number') {\n if (date > TIMESTAMP_THRESHOLD_MS) {\n // Treat as *unix timestamp* (absolute)\n const absoluteTime = new Date(date);\n return {\n absoluteTime,\n relativeTime: new Date(now.getTime() - absoluteTime.getTime()),\n };\n }\n\n // Treat as a *relative* duration (milliseconds in the past)\n const relativeMs = date;\n return {\n // Relative duration expressed as a Date object starting at the epoch\n relativeTime: new Date(relativeMs),\n // The concrete date obtained by subtracting the duration from *now*\n absoluteTime: new Date(now.getTime() - relativeMs),\n };\n }\n\n // Case 3: String representation – let Date parse it.\n if (typeof date === 'string') {\n const absoluteTime = new Date(date);\n if (Number.isNaN(absoluteTime.getTime())) {\n throw new Error(`Invalid date string provided: ${date}`);\n }\n\n return {\n absoluteTime,\n relativeTime: new Date(now.getTime() - absoluteTime.getTime()),\n };\n }\n\n throw new Error(`Unsupported date format: ${date}`);\n};\n\ntype CheckFileModifiedRangeResult = {\n isSkipped: boolean;\n message: string;\n};\n\ntype CheckFileModifiedRangeOptions = {\n skipIfModifiedBefore?: Date | number | string;\n skipIfModifiedAfter?: Date | number | string;\n};\n\nexport const checkFileModifiedRange = (\n filePath: string,\n options: CheckFileModifiedRangeOptions\n): CheckFileModifiedRangeResult => {\n const fileLastUpdateTime = checkLastUpdateTime(filePath);\n const { skipIfModifiedBefore, skipIfModifiedAfter } = options;\n\n // Normalise the provided thresholds to concrete dates.\n const now = new Date();\n const minDate = skipIfModifiedBefore\n ? normaliseInputDate(skipIfModifiedBefore, now).absoluteTime\n : undefined;\n const maxDate = skipIfModifiedAfter\n ? normaliseInputDate(skipIfModifiedAfter, now).absoluteTime\n : undefined;\n\n // Determine if the file should be skipped.\n let shouldSkip = false;\n\n if (minDate instanceof Date && maxDate instanceof Date) {\n // Skip when the modification time falls *within* the range [minDate, maxDate]\n shouldSkip = fileLastUpdateTime >= minDate && fileLastUpdateTime <= maxDate;\n } else if (minDate instanceof Date) {\n // Only lower bound – skip when the file was modified *after* minDate\n shouldSkip = fileLastUpdateTime >= minDate;\n } else if (maxDate) {\n // Only upper bound – skip when the file was modified *after* maxDate\n shouldSkip = fileLastUpdateTime >= maxDate;\n }\n\n if (shouldSkip) {\n // For the sake of the message we compute the relative time to *now* using\n // whichever bound was responsible for the skip logic.\n const referenceDate = (\n minDate && maxDate\n ? // When both bounds are present, the *range* caused the skip so we use\n // the distance between the two bounds as the relative duration.\n new Date(Math.abs(maxDate.getTime() - minDate.getTime()))\n : (minDate ?? maxDate)\n )!;\n\n const relativeTime = new Date(now.getTime() - referenceDate.getTime());\n\n return {\n isSkipped: true,\n message: `Skipping file because it has been modified within the last ${formatTimeDiff(relativeTime)} - ${filePath}`,\n };\n }\n\n return {\n isSkipped: false,\n message: `File ${filePath} can be processed - ${filePath}`,\n };\n};\n"],"mappings":";;;;;;;;;;AAcA,MAAM,yBAAyB,KAAK,MAAM,KAAK,KAAK,KAAK;;;;;;;;;;;;;;;;AAiBzD,MAAM,sBACJ,MACA,sBAAY,IAAI,
|
|
1
|
+
{"version":3,"file":"checkFileModifiedRange.mjs","names":[],"sources":["../../../src/utils/checkFileModifiedRange.ts"],"sourcesContent":["import { checkLastUpdateTime } from './checkLastUpdateTime';\nimport { formatTimeDiff } from './formatTimeDiff';\n\ntype GetTimeRangeResult = {\n relativeTime: Date;\n absoluteTime: Date;\n};\n\n/**\n * Threshold that helps us differentiate between a numeric *timestamp* (ms from epoch)\n * and a numeric *duration* (ms ago).\n * 50 years expressed in milliseconds is far greater than any reasonable\n * \"relative\" duration we expect the helper to receive (e.g. a couple of years).\n */\nconst TIMESTAMP_THRESHOLD_MS = 50 * 365 * 24 * 60 * 60 * 1000; // 50 years\n\n/**\n * Normalises the input date representation into a pair:\n * 1. `relativeTime` – a Date instance whose epoch-time equals the duration\n * between `now` and the absolute date.\n * 2. `absoluteTime` – the concrete point in time represented as a Date.\n *\n * Rules for interpreting the input:\n * • Date => treated as an absolute time.\n * • string => parsed via the Date constructor => absolute time.\n * • number:\n * – if the value is larger than the TIMESTAMP_THRESHOLD_MS we assume it\n * is a unix timestamp (absolute time).\n * – otherwise we treat it as a *relative* duration expressed in\n * milliseconds.\n */\nconst normaliseInputDate = (\n date: Date | number | string,\n now: Date = new Date()\n): GetTimeRangeResult => {\n // Case 1: Already a Date instance\n if (date instanceof Date) {\n return {\n absoluteTime: date,\n relativeTime: new Date(now.getTime() - date.getTime()),\n };\n }\n\n // Case 2: Numeric value – decide between timestamp vs relative ms.\n if (typeof date === 'number') {\n if (date > TIMESTAMP_THRESHOLD_MS) {\n // Treat as *unix timestamp* (absolute)\n const absoluteTime = new Date(date);\n return {\n absoluteTime,\n relativeTime: new Date(now.getTime() - absoluteTime.getTime()),\n };\n }\n\n // Treat as a *relative* duration (milliseconds in the past)\n const relativeMs = date;\n return {\n // Relative duration expressed as a Date object starting at the epoch\n relativeTime: new Date(relativeMs),\n // The concrete date obtained by subtracting the duration from *now*\n absoluteTime: new Date(now.getTime() - relativeMs),\n };\n }\n\n // Case 3: String representation – let Date parse it.\n if (typeof date === 'string') {\n const absoluteTime = new Date(date);\n if (Number.isNaN(absoluteTime.getTime())) {\n throw new Error(`Invalid date string provided: ${date}`);\n }\n\n return {\n absoluteTime,\n relativeTime: new Date(now.getTime() - absoluteTime.getTime()),\n };\n }\n\n throw new Error(`Unsupported date format: ${date}`);\n};\n\ntype CheckFileModifiedRangeResult = {\n isSkipped: boolean;\n message: string;\n};\n\ntype CheckFileModifiedRangeOptions = {\n skipIfModifiedBefore?: Date | number | string;\n skipIfModifiedAfter?: Date | number | string;\n};\n\nexport const checkFileModifiedRange = (\n filePath: string,\n options: CheckFileModifiedRangeOptions\n): CheckFileModifiedRangeResult => {\n const fileLastUpdateTime = checkLastUpdateTime(filePath);\n const { skipIfModifiedBefore, skipIfModifiedAfter } = options;\n\n // Normalise the provided thresholds to concrete dates.\n const now = new Date();\n const minDate = skipIfModifiedBefore\n ? normaliseInputDate(skipIfModifiedBefore, now).absoluteTime\n : undefined;\n const maxDate = skipIfModifiedAfter\n ? normaliseInputDate(skipIfModifiedAfter, now).absoluteTime\n : undefined;\n\n // Determine if the file should be skipped.\n let shouldSkip = false;\n\n if (minDate instanceof Date && maxDate instanceof Date) {\n // Skip when the modification time falls *within* the range [minDate, maxDate]\n shouldSkip = fileLastUpdateTime >= minDate && fileLastUpdateTime <= maxDate;\n } else if (minDate instanceof Date) {\n // Only lower bound – skip when the file was modified *after* minDate\n shouldSkip = fileLastUpdateTime >= minDate;\n } else if (maxDate) {\n // Only upper bound – skip when the file was modified *after* maxDate\n shouldSkip = fileLastUpdateTime >= maxDate;\n }\n\n if (shouldSkip) {\n // For the sake of the message we compute the relative time to *now* using\n // whichever bound was responsible for the skip logic.\n const referenceDate = (\n minDate && maxDate\n ? // When both bounds are present, the *range* caused the skip so we use\n // the distance between the two bounds as the relative duration.\n new Date(Math.abs(maxDate.getTime() - minDate.getTime()))\n : (minDate ?? maxDate)\n )!;\n\n const relativeTime = new Date(now.getTime() - referenceDate.getTime());\n\n return {\n isSkipped: true,\n message: `Skipping file because it has been modified within the last ${formatTimeDiff(relativeTime)} - ${filePath}`,\n };\n }\n\n return {\n isSkipped: false,\n message: `File ${filePath} can be processed - ${filePath}`,\n };\n};\n"],"mappings":";;;;;;;;;;AAcA,MAAM,yBAAyB,KAAK,MAAM,KAAK,KAAK,KAAK;;;;;;;;;;;;;;;;AAiBzD,MAAM,sBACJ,MACA,sBAAY,IAAI,KAAK,MACE;CAEvB,IAAI,gBAAgB,MAClB,OAAO;EACL,cAAc;EACd,cAAc,IAAI,KAAK,IAAI,QAAQ,IAAI,KAAK,QAAQ,CAAC;CACvD;CAIF,IAAI,OAAO,SAAS,UAAU;EAC5B,IAAI,OAAO,wBAAwB;GAEjC,MAAM,eAAe,IAAI,KAAK,IAAI;GAClC,OAAO;IACL;IACA,cAAc,IAAI,KAAK,IAAI,QAAQ,IAAI,aAAa,QAAQ,CAAC;GAC/D;EACF;EAGA,MAAM,aAAa;EACnB,OAAO;GAEL,cAAc,IAAI,KAAK,UAAU;GAEjC,cAAc,IAAI,KAAK,IAAI,QAAQ,IAAI,UAAU;EACnD;CACF;CAGA,IAAI,OAAO,SAAS,UAAU;EAC5B,MAAM,eAAe,IAAI,KAAK,IAAI;EAClC,IAAI,OAAO,MAAM,aAAa,QAAQ,CAAC,GACrC,MAAM,IAAI,MAAM,iCAAiC,MAAM;EAGzD,OAAO;GACL;GACA,cAAc,IAAI,KAAK,IAAI,QAAQ,IAAI,aAAa,QAAQ,CAAC;EAC/D;CACF;CAEA,MAAM,IAAI,MAAM,4BAA4B,MAAM;AACpD;AAYA,MAAa,0BACX,UACA,YACiC;CACjC,MAAM,qBAAqB,oBAAoB,QAAQ;CACvD,MAAM,EAAE,sBAAsB,wBAAwB;CAGtD,MAAM,sBAAM,IAAI,KAAK;CACrB,MAAM,UAAU,uBACZ,mBAAmB,sBAAsB,GAAG,EAAE,eAC9C;CACJ,MAAM,UAAU,sBACZ,mBAAmB,qBAAqB,GAAG,EAAE,eAC7C;CAGJ,IAAI,aAAa;CAEjB,IAAI,mBAAmB,QAAQ,mBAAmB,MAEhD,aAAa,sBAAsB,WAAW,sBAAsB;MAC/D,IAAI,mBAAmB,MAE5B,aAAa,sBAAsB;MAC9B,IAAI,SAET,aAAa,sBAAsB;CAGrC,IAAI,YAAY;EAGd,MAAM,gBACJ,WAAW,UAGP,IAAI,KAAK,KAAK,IAAI,QAAQ,QAAQ,IAAI,QAAQ,QAAQ,CAAC,CAAC,IACvD,WAAW;EAKlB,OAAO;GACL,WAAW;GACX,SAAS,8DAA8D,eAAe,IAJ/D,KAAK,IAAI,QAAQ,IAAI,cAAc,QAAQ,CAI+B,CAAC,EAAE,KAAK;EAC3G;CACF;CAEA,OAAO;EACL,WAAW;EACX,SAAS,QAAQ,SAAS,sBAAsB;CAClD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkLastUpdateTime.mjs","names":[],"sources":["../../../src/utils/checkLastUpdateTime.ts"],"sourcesContent":["import { statSync } from 'node:fs';\n\n/**\n * Returns the last modification date of a file.\n *\n * @param filePath - Absolute or relative path to the file to inspect.\n * @returns Date instance representing the file's last modified time (mtime).\n * @throws Will propagate any error thrown by fs.statSync (e.g., file not found).\n */\nexport const checkLastUpdateTime = (filePath: string): Date => {\n const stats = statSync(filePath);\n return new Date(stats.mtime);\n};\n"],"mappings":";;;;;;;;;;AASA,MAAa,uBAAuB,aAA2B;CAC7D,MAAM,QAAQ,SAAS,
|
|
1
|
+
{"version":3,"file":"checkLastUpdateTime.mjs","names":[],"sources":["../../../src/utils/checkLastUpdateTime.ts"],"sourcesContent":["import { statSync } from 'node:fs';\n\n/**\n * Returns the last modification date of a file.\n *\n * @param filePath - Absolute or relative path to the file to inspect.\n * @returns Date instance representing the file's last modified time (mtime).\n * @throws Will propagate any error thrown by fs.statSync (e.g., file not found).\n */\nexport const checkLastUpdateTime = (filePath: string): Date => {\n const stats = statSync(filePath);\n return new Date(stats.mtime);\n};\n"],"mappings":";;;;;;;;;;AASA,MAAa,uBAAuB,aAA2B;CAC7D,MAAM,QAAQ,SAAS,QAAQ;CAC/B,OAAO,IAAI,KAAK,MAAM,KAAK;AAC7B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getAuthenticatedAPI } from "./checkAccess.mjs";
|
|
2
2
|
import { retryManager } from "@intlayer/config/utils";
|
|
3
3
|
|
|
4
4
|
//#region src/utils/chunkInference.ts
|
|
@@ -23,7 +23,7 @@ const chunkInference = async (system, messages, aiOptions, configuration, aiClie
|
|
|
23
23
|
};
|
|
24
24
|
return;
|
|
25
25
|
}
|
|
26
|
-
const response = await
|
|
26
|
+
const response = await (await getAuthenticatedAPI(configuration)).ai.customQuery({
|
|
27
27
|
aiOptions,
|
|
28
28
|
messages
|
|
29
29
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunkInference.mjs","names":[],"sources":["../../../src/utils/chunkInference.ts"],"sourcesContent":["import type {\n AIConfig,\n AIOptions,\n Messages,\n SystemMessage,\n} from '@intlayer/ai';\nimport {
|
|
1
|
+
{"version":3,"file":"chunkInference.mjs","names":[],"sources":["../../../src/utils/chunkInference.ts"],"sourcesContent":["import type {\n AIConfig,\n AIOptions,\n Messages,\n SystemMessage,\n} from '@intlayer/ai';\nimport { retryManager } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getAuthenticatedAPI } from './checkAccess';\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 system: SystemMessage,\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 system,\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 = await getAuthenticatedAPI(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":";;;;;;;;AAoBA,MAAa,iBAAiB,OAC5B,QACA,UACA,WACA,eACA,UACA,aACkC;CAClC,IAAI;CAEJ,MAAM,aAAa,YAAY;EAC7B,IAAI,YAAY,UAAU;GACxB,MAAM,WAAW,MAAM,SAAS,YAAY;IAC1C;IACA;IACA;GACF,CAAC;GAED,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,yBAAyB;GAG3C,MAAM,EAAE,aAAa,cAAc;GAEnC,aAAa;IACX,aAAa,eAAe,WAAW;IACvC;GACF;GAEA;EACF;EAIA,MAAM,WAAW,OAAM,MAFL,oBAAoB,aAAa,GAExB,GAAG,YAAY;GACxC;GACA;EACF,CAAC;EAED,IAAI,CAAC,SAAS,MACZ,MAAM,IAAI,MAAM,yBAAyB;EAG3C,MAAM,EAAE,aAAa,cAAc,SAAS;EAE5C,aAAa;GACX,aAAa,eAAe,WAAW;GACvC;EACF;CACF,CAAC,EAAE;CAEH,OAAO;AACT;AAEA,MAAM,kBAAkB,YAAoB;CAC1C,OAAO,QACJ,WAAW,qBAAqB,EAAE,EAClC,WAAW,oBAAoB,EAAE,EACjC,WAAW,mBAAmB,EAAE,EAChC,WAAW,kBAAkB,EAAE,EAC/B,WAAW,qBAAqB,EAAE,EAClC,WAAW,iBAAiB,EAAE,EAC9B,WAAW,gBAAgB,EAAE,EAC7B,WAAW,eAAe,EAAE,EAC5B,WAAW,kBAAkB,EAAE,EAC/B,WAAW,iBAAiB,EAAE,EAC9B,WAAW,gBAAgB,EAAE,EAC7B,WAAW,eAAe,EAAE,EAC5B,WAAW,eAAe,EAAE,EAC5B,WAAW,cAAc,EAAE,EAC3B,WAAW,aAAa,EAAE,EAC1B,WAAW,YAAY,EAAE;AAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fixChunkStartEndChars.mjs","names":[],"sources":["../../../src/utils/fixChunkStartEndChars.ts"],"sourcesContent":["const CHAR_TO_CHECK_FORMATTING = ['```', '\\n\\n', '\\n', '---', '{{', '}}'];\n\n// Escape a string for use in RegExp\nconst escapeForRegExp = (str: string) =>\n str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\n/g, '\\\\n');\n\n// Build once the regex that matches any combination of the formatting chars appearing\n// sequentially at the beginning or at the end of a string.\nconst FORMATTING_REGEX_SOURCE = `(?:${CHAR_TO_CHECK_FORMATTING.map(escapeForRegExp).join('|')})+`;\nconst LEADING_FORMATTING_REGEX = new RegExp(`^${FORMATTING_REGEX_SOURCE}`);\nconst TRAILING_FORMATTING_REGEX = new RegExp(`${FORMATTING_REGEX_SOURCE}$`);\n\nexport const fixChunkStartEndChars = (\n reviewedChunkResult: string,\n baseChunkContext: string\n) => {\n let result = reviewedChunkResult;\n\n const baseLeading =\n baseChunkContext.match(LEADING_FORMATTING_REGEX)?.[0] ?? '';\n const baseTrailing =\n baseChunkContext.match(TRAILING_FORMATTING_REGEX)?.[0] ?? '';\n\n const resultLeading = result.match(LEADING_FORMATTING_REGEX)?.[0] ?? '';\n const resultTrailing = result.match(TRAILING_FORMATTING_REGEX)?.[0] ?? '';\n\n // Fix leading formatting\n if (baseLeading !== resultLeading) {\n // Remove current leading formatting found in result and prepend the correct one\n result = baseLeading + result.slice(resultLeading.length);\n }\n\n // Fix trailing formatting\n if (baseTrailing !== resultTrailing) {\n // Remove current trailing formatting found in result and append the correct one\n result =\n result.slice(0, result.length - resultTrailing.length) + baseTrailing;\n }\n\n return result;\n};\n"],"mappings":";AAAA,MAAM,2BAA2B;CAAC;CAAO;CAAQ;CAAM;CAAO;CAAM;
|
|
1
|
+
{"version":3,"file":"fixChunkStartEndChars.mjs","names":[],"sources":["../../../src/utils/fixChunkStartEndChars.ts"],"sourcesContent":["const CHAR_TO_CHECK_FORMATTING = ['```', '\\n\\n', '\\n', '---', '{{', '}}'];\n\n// Escape a string for use in RegExp\nconst escapeForRegExp = (str: string) =>\n str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\n/g, '\\\\n');\n\n// Build once the regex that matches any combination of the formatting chars appearing\n// sequentially at the beginning or at the end of a string.\nconst FORMATTING_REGEX_SOURCE = `(?:${CHAR_TO_CHECK_FORMATTING.map(escapeForRegExp).join('|')})+`;\nconst LEADING_FORMATTING_REGEX = new RegExp(`^${FORMATTING_REGEX_SOURCE}`);\nconst TRAILING_FORMATTING_REGEX = new RegExp(`${FORMATTING_REGEX_SOURCE}$`);\n\nexport const fixChunkStartEndChars = (\n reviewedChunkResult: string,\n baseChunkContext: string\n) => {\n let result = reviewedChunkResult;\n\n const baseLeading =\n baseChunkContext.match(LEADING_FORMATTING_REGEX)?.[0] ?? '';\n const baseTrailing =\n baseChunkContext.match(TRAILING_FORMATTING_REGEX)?.[0] ?? '';\n\n const resultLeading = result.match(LEADING_FORMATTING_REGEX)?.[0] ?? '';\n const resultTrailing = result.match(TRAILING_FORMATTING_REGEX)?.[0] ?? '';\n\n // Fix leading formatting\n if (baseLeading !== resultLeading) {\n // Remove current leading formatting found in result and prepend the correct one\n result = baseLeading + result.slice(resultLeading.length);\n }\n\n // Fix trailing formatting\n if (baseTrailing !== resultTrailing) {\n // Remove current trailing formatting found in result and append the correct one\n result =\n result.slice(0, result.length - resultTrailing.length) + baseTrailing;\n }\n\n return result;\n};\n"],"mappings":";AAAA,MAAM,2BAA2B;CAAC;CAAO;CAAQ;CAAM;CAAO;CAAM;AAAI;AAGxE,MAAM,mBAAmB,QACvB,IAAI,QAAQ,uBAAuB,MAAM,EAAE,QAAQ,OAAO,KAAK;AAIjE,MAAM,0BAA0B,MAAM,yBAAyB,IAAI,eAAe,EAAE,KAAK,GAAG,EAAE;AAC9F,MAAM,2BAA2B,IAAI,OAAO,IAAI,yBAAyB;AACzE,MAAM,4BAA4B,IAAI,OAAO,GAAG,wBAAwB,EAAE;AAE1E,MAAa,yBACX,qBACA,qBACG;CACH,IAAI,SAAS;CAEb,MAAM,cACJ,iBAAiB,MAAM,wBAAwB,IAAI,MAAM;CAC3D,MAAM,eACJ,iBAAiB,MAAM,yBAAyB,IAAI,MAAM;CAE5D,MAAM,gBAAgB,OAAO,MAAM,wBAAwB,IAAI,MAAM;CACrE,MAAM,iBAAiB,OAAO,MAAM,yBAAyB,IAAI,MAAM;CAGvE,IAAI,gBAAgB,eAElB,SAAS,cAAc,OAAO,MAAM,cAAc,MAAM;CAI1D,IAAI,iBAAiB,gBAEnB,SACE,OAAO,MAAM,GAAG,OAAO,SAAS,eAAe,MAAM,IAAI;CAG7D,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatTimeDiff.mjs","names":[],"sources":["../../../src/utils/formatTimeDiff.ts"],"sourcesContent":["export const formatTimeDiff = (realtiveTime: Date): string => {\n const diff = realtiveTime.getTime();\n\n const MS_IN_SECOND = 1000;\n const MS_IN_MINUTE = 60 * MS_IN_SECOND;\n const MS_IN_HOUR = 60 * MS_IN_MINUTE;\n const MS_IN_DAY = 24 * MS_IN_HOUR;\n\n const days = Math.floor(diff / MS_IN_DAY);\n const hours = Math.floor((diff % MS_IN_DAY) / MS_IN_HOUR);\n const minutes = Math.floor((diff % MS_IN_HOUR) / MS_IN_MINUTE);\n const seconds = Math.floor((diff % MS_IN_MINUTE) / MS_IN_SECOND);\n\n if (days > 0) {\n return `${days}d ${hours}h ${minutes}m ${seconds}s`;\n }\n if (hours > 0) {\n return `${hours}h ${minutes}m ${seconds}s`;\n }\n\n return `${minutes}m ${seconds}s`;\n};\n"],"mappings":";AAAA,MAAa,kBAAkB,iBAA+B;CAC5D,MAAM,OAAO,aAAa,
|
|
1
|
+
{"version":3,"file":"formatTimeDiff.mjs","names":[],"sources":["../../../src/utils/formatTimeDiff.ts"],"sourcesContent":["export const formatTimeDiff = (realtiveTime: Date): string => {\n const diff = realtiveTime.getTime();\n\n const MS_IN_SECOND = 1000;\n const MS_IN_MINUTE = 60 * MS_IN_SECOND;\n const MS_IN_HOUR = 60 * MS_IN_MINUTE;\n const MS_IN_DAY = 24 * MS_IN_HOUR;\n\n const days = Math.floor(diff / MS_IN_DAY);\n const hours = Math.floor((diff % MS_IN_DAY) / MS_IN_HOUR);\n const minutes = Math.floor((diff % MS_IN_HOUR) / MS_IN_MINUTE);\n const seconds = Math.floor((diff % MS_IN_MINUTE) / MS_IN_SECOND);\n\n if (days > 0) {\n return `${days}d ${hours}h ${minutes}m ${seconds}s`;\n }\n if (hours > 0) {\n return `${hours}h ${minutes}m ${seconds}s`;\n }\n\n return `${minutes}m ${seconds}s`;\n};\n"],"mappings":";AAAA,MAAa,kBAAkB,iBAA+B;CAC5D,MAAM,OAAO,aAAa,QAAQ;CAElC,MAAM,eAAe;CACrB,MAAM,eAAe,KAAK;CAC1B,MAAM,aAAa,KAAK;CACxB,MAAM,YAAY,KAAK;CAEvB,MAAM,OAAO,KAAK,MAAM,OAAO,SAAS;CACxC,MAAM,QAAQ,KAAK,MAAO,OAAO,YAAa,UAAU;CACxD,MAAM,UAAU,KAAK,MAAO,OAAO,aAAc,YAAY;CAC7D,MAAM,UAAU,KAAK,MAAO,OAAO,eAAgB,YAAY;CAE/D,IAAI,OAAO,GACT,OAAO,GAAG,KAAK,IAAI,MAAM,IAAI,QAAQ,IAAI,QAAQ;CAEnD,IAAI,QAAQ,GACV,OAAO,GAAG,MAAM,IAAI,QAAQ,IAAI,QAAQ;CAG1C,OAAO,GAAG,QAAQ,IAAI,QAAQ;AAChC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getIsFileUpdatedRecently.mjs","names":[],"sources":["../../../src/utils/getIsFileUpdatedRecently.ts"],"sourcesContent":["import { statSync } from 'node:fs';\n\nconst SKIP_RANGE_OF_LAST_UPDATE_TIME: number = 0; //2 * 60 * 60 * 1000; // 2 hours\n\n/**\n * Check if file was updated recently, to skip re-translation\n */\nexport const getIsFileUpdatedRecently = (localeFilePath: string): boolean => {\n const stats = statSync(localeFilePath);\n const lastModified = new Date(stats.mtime);\n const threshold = new Date(Date.now() - SKIP_RANGE_OF_LAST_UPDATE_TIME);\n\n return lastModified > threshold;\n};\n"],"mappings":";;;AAEA,MAAM,iCAAyC;;;;AAK/C,MAAa,4BAA4B,mBAAoC;CAC3E,MAAM,QAAQ,SAAS,
|
|
1
|
+
{"version":3,"file":"getIsFileUpdatedRecently.mjs","names":[],"sources":["../../../src/utils/getIsFileUpdatedRecently.ts"],"sourcesContent":["import { statSync } from 'node:fs';\n\nconst SKIP_RANGE_OF_LAST_UPDATE_TIME: number = 0; //2 * 60 * 60 * 1000; // 2 hours\n\n/**\n * Check if file was updated recently, to skip re-translation\n */\nexport const getIsFileUpdatedRecently = (localeFilePath: string): boolean => {\n const stats = statSync(localeFilePath);\n const lastModified = new Date(stats.mtime);\n const threshold = new Date(Date.now() - SKIP_RANGE_OF_LAST_UPDATE_TIME);\n\n return lastModified > threshold;\n};\n"],"mappings":";;;AAEA,MAAM,iCAAyC;;;;AAK/C,MAAa,4BAA4B,mBAAoC;CAC3E,MAAM,QAAQ,SAAS,cAAc;CAIrC,OAAO,IAHkB,KAAK,MAAM,KAGlB,IAAI,IAFA,KAAK,KAAK,IAAI,IAAI,8BAEV;AAChC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getOutputFilePath.mjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import { resolveRelativePath } from '@intlayer/chokidar/utils';\nimport { parseStringPattern } from '@intlayer/config/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { Fill } from '@intlayer/types/dictionary';\nimport type {\n FilePathPattern,\n FilePathPatternContext,\n} from '@intlayer/types/filePathPattern';\nimport 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\n/**\n * Get the effective FilePathPattern for a given locale from a Fill/CompilerOutput value.\n *\n * - If Fill is an object, returns the pattern for that locale (or `false` if disabled/missing).\n * - If Fill is a string/function, returns it as-is (applies to all locales).\n * - If Fill is `false`, returns `false` (disabled for all locales).\n * - If Fill is `true` or a locale entry is `true`, returns `undefined` (use default).\n */\nexport const getPatternForLocale = (\n output: Fill,\n locale: Locale\n): FilePathPattern | false | undefined => {\n if (output === false) return false;\n if (output === true) return undefined;\n if (typeof output === 'string' || typeof output === 'function')\n return output as FilePathPattern;\n if (typeof output === 'object' && output !== null) {\n const entry = (output as Record<string, boolean | FilePathPattern>)[locale];\n if (entry === undefined || entry === false) return false;\n if (entry === true) return undefined;\n return entry as FilePathPattern;\n }\n return false;\n};\n\n/**\n * Resolve a Fill/CompilerOutput pattern to an absolute file path for a given locale.\n * Returns `false` if the locale is disabled or no pattern is configured.\n */\nexport const resolveOutputPattern = async (\n output: Fill,\n locale: Locale,\n context: FilePathPatternContext,\n sourceFilePath: string,\n baseDir: string\n): Promise<string | false> => {\n const pattern = getPatternForLocale(output, locale);\n if (pattern === false || pattern === undefined) return false;\n\n const rawPath =\n typeof pattern === 'function'\n ? await pattern(context)\n : parseStringPattern(pattern, context);\n\n return resolveRelativePath(rawPath, sourceFilePath, baseDir);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,qBACX,UACA,QACA,eACW;CACX,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,YAC3B,MAAM,IAAI,MAAM
|
|
1
|
+
{"version":3,"file":"getOutputFilePath.mjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import { resolveRelativePath } from '@intlayer/chokidar/utils';\nimport { parseStringPattern } from '@intlayer/config/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { Fill } from '@intlayer/types/dictionary';\nimport type {\n FilePathPattern,\n FilePathPatternContext,\n} from '@intlayer/types/filePathPattern';\nimport 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\n/**\n * Get the effective FilePathPattern for a given locale from a Fill/CompilerOutput value.\n *\n * - If Fill is an object, returns the pattern for that locale (or `false` if disabled/missing).\n * - If Fill is a string/function, returns it as-is (applies to all locales).\n * - If Fill is `false`, returns `false` (disabled for all locales).\n * - If Fill is `true` or a locale entry is `true`, returns `undefined` (use default).\n */\nexport const getPatternForLocale = (\n output: Fill,\n locale: Locale\n): FilePathPattern | false | undefined => {\n if (output === false) return false;\n if (output === true) return undefined;\n if (typeof output === 'string' || typeof output === 'function')\n return output as FilePathPattern;\n if (typeof output === 'object' && output !== null) {\n const entry = (output as Record<string, boolean | FilePathPattern>)[locale];\n if (entry === undefined || entry === false) return false;\n if (entry === true) return undefined;\n return entry as FilePathPattern;\n }\n return false;\n};\n\n/**\n * Resolve a Fill/CompilerOutput pattern to an absolute file path for a given locale.\n * Returns `false` if the locale is disabled or no pattern is configured.\n */\nexport const resolveOutputPattern = async (\n output: Fill,\n locale: Locale,\n context: FilePathPatternContext,\n sourceFilePath: string,\n baseDir: string\n): Promise<string | false> => {\n const pattern = getPatternForLocale(output, locale);\n if (pattern === false || pattern === undefined) return false;\n\n const rawPath =\n typeof pattern === 'function'\n ? await pattern(context)\n : parseStringPattern(pattern, context);\n\n return resolveRelativePath(rawPath, sourceFilePath, baseDir);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,qBACX,UACA,QACA,eACW;CACX,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,YAC3B,MAAM,IAAI,MAAM,+CAA+C;CAGjE,IAAI,iBAAiB;CAGrB,MAAM,eAAe;EAEnB;GACE,SAAS;GACT,aAAa;EACf;EACA;GACE,SAAS;GACT,aAAa;EACf;EAGA;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,IAAI,GAAG;GAC1C,aAAa,IAAI,OAAO;EAC1B;EACA;GAEE,SAAS,IAAI,OAAO,OAAO,WAAW,OAAO,GAAG;GAChD,aAAa,KAAK,OAAO;EAC3B;EAGA;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,MAAM,GAAG;GAC5C,aAAa,IAAI,OAAO;EAC1B;EACA;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,IAAI,GAAG;GAC1C,aAAa,IAAI,OAAO;EAC1B;EACA;GAEE,SAAS,IAAI,OAAO,YAAY,WAAW,IAAI,GAAG;GAClD,aAAa,KAAK,OAAO;EAC3B;EACA;GAEE,SAAS,IAAI,OAAO,MAAM,WAAW,MAAM,GAAG;GAC9C,aAAa,IAAI,OAAO;EAC1B;CACF;CAGA,KAAK,MAAM,EAAE,SAAS,iBAAiB,cACrC,iBAAiB,eAAe,QAAQ,SAAS,WAAW;CAI9D,IAAI,mBAAmB,UAAU;EAC/B,MAAM,eAAe,SAAS,YAAY,GAAG;EAC7C,IAAI,eAAe,GAEjB,OAAO,GAAG,SAAS,MAAM,GAAG,YAAY,EAAE,GAAG,SAAS,SAAS,MAAM,YAAY;OAGjF,OAAO,GAAG,SAAS,GAAG;CAE1B;CAEA,OAAO;AACT;;;;;;;;;AAUA,MAAa,uBACX,QACA,WACwC;CACxC,IAAI,WAAW,OAAO,OAAO;CAC7B,IAAI,WAAW,MAAM,OAAO;CAC5B,IAAI,OAAO,WAAW,YAAY,OAAO,WAAW,YAClD,OAAO;CACT,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM;EACjD,MAAM,QAAS,OAAqD;EACpE,IAAI,UAAU,UAAa,UAAU,OAAO,OAAO;EACnD,IAAI,UAAU,MAAM,OAAO;EAC3B,OAAO;CACT;CACA,OAAO;AACT;;;;;AAMA,MAAa,uBAAuB,OAClC,QACA,QACA,SACA,gBACA,YAC4B;CAC5B,MAAM,UAAU,oBAAoB,QAAQ,MAAM;CAClD,IAAI,YAAY,SAAS,YAAY,QAAW,OAAO;CAOvD,OAAO,oBAJL,OAAO,YAAY,aACf,MAAM,QAAQ,OAAO,IACrB,mBAAmB,SAAS,OAAO,GAEL,gBAAgB,OAAO;AAC7D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getParentPackageJSON.mjs","names":[],"sources":["../../../src/utils/getParentPackageJSON.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\n\ntype PackageJSON = {\n name?: string;\n version?: string;\n private: boolean;\n description?: string;\n homepage?: string;\n bugs: {\n url?: string;\n };\n repository: {\n type?: string;\n url?: string;\n };\n license?: string;\n author: {\n name?: string;\n url?: string;\n };\n contributors?: {\n name?: string;\n email?: string;\n url?: string;\n }[];\n type?: string;\n scripts: Record<string, string>;\n devDependencies: Record<string, string>;\n packageManager?: string;\n engines: Record<string, string>;\n};\n\nexport const getParentPackageJSON = (startDir: string): PackageJSON => {\n let currentDir = startDir;\n\n while (currentDir !== dirname(currentDir)) {\n // Stop when we reach the root\n const packageJsonPath = resolve(currentDir, 'package.json');\n\n if (existsSync(packageJsonPath)) {\n return JSON.parse(readFileSync(packageJsonPath, 'utf8'));\n }\n\n // Move up one directory level\n currentDir = dirname(currentDir);\n }\n\n // Check the root directory as well\n const rootPackageJsonPath = resolve(currentDir, 'package.json');\n if (existsSync(rootPackageJsonPath)) {\n return JSON.parse(readFileSync(rootPackageJsonPath, 'utf8'));\n }\n\n // If no package.json is found in any parent directory\n throw new Error(\n `No package.json found in any parent directory of ${startDir}`\n );\n};\n"],"mappings":";;;;AAiCA,MAAa,wBAAwB,aAAkC;CACrE,IAAI,aAAa;CAEjB,OAAO,eAAe,QAAQ,
|
|
1
|
+
{"version":3,"file":"getParentPackageJSON.mjs","names":[],"sources":["../../../src/utils/getParentPackageJSON.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\n\ntype PackageJSON = {\n name?: string;\n version?: string;\n private: boolean;\n description?: string;\n homepage?: string;\n bugs: {\n url?: string;\n };\n repository: {\n type?: string;\n url?: string;\n };\n license?: string;\n author: {\n name?: string;\n url?: string;\n };\n contributors?: {\n name?: string;\n email?: string;\n url?: string;\n }[];\n type?: string;\n scripts: Record<string, string>;\n devDependencies: Record<string, string>;\n packageManager?: string;\n engines: Record<string, string>;\n};\n\nexport const getParentPackageJSON = (startDir: string): PackageJSON => {\n let currentDir = startDir;\n\n while (currentDir !== dirname(currentDir)) {\n // Stop when we reach the root\n const packageJsonPath = resolve(currentDir, 'package.json');\n\n if (existsSync(packageJsonPath)) {\n return JSON.parse(readFileSync(packageJsonPath, 'utf8'));\n }\n\n // Move up one directory level\n currentDir = dirname(currentDir);\n }\n\n // Check the root directory as well\n const rootPackageJsonPath = resolve(currentDir, 'package.json');\n if (existsSync(rootPackageJsonPath)) {\n return JSON.parse(readFileSync(rootPackageJsonPath, 'utf8'));\n }\n\n // If no package.json is found in any parent directory\n throw new Error(\n `No package.json found in any parent directory of ${startDir}`\n );\n};\n"],"mappings":";;;;AAiCA,MAAa,wBAAwB,aAAkC;CACrE,IAAI,aAAa;CAEjB,OAAO,eAAe,QAAQ,UAAU,GAAG;EAEzC,MAAM,kBAAkB,QAAQ,YAAY,cAAc;EAE1D,IAAI,WAAW,eAAe,GAC5B,OAAO,KAAK,MAAM,aAAa,iBAAiB,MAAM,CAAC;EAIzD,aAAa,QAAQ,UAAU;CACjC;CAGA,MAAM,sBAAsB,QAAQ,YAAY,cAAc;CAC9D,IAAI,WAAW,mBAAmB,GAChC,OAAO,KAAK,MAAM,aAAa,qBAAqB,MAAM,CAAC;CAI7D,MAAM,IAAI,MACR,oDAAoD,UACtD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listSpecialChars.mjs","names":[],"sources":["../../../src/utils/listSpecialChars.ts"],"sourcesContent":["type ListCharResult = {\n char: string;\n /** First line index contained in this chunk (0-based) */\n lineStart: number;\n /** Start character index in the original text (0-based, inclusive)*/\n charStart: number;\n}[];\n\nconst SPECIAL_CHARS = [\n ' ',\n '\\\\',\n '|',\n '(',\n ')',\n '{',\n '}',\n '[',\n ']',\n '<',\n '>',\n '\"',\n '=',\n '+',\n '*',\n '&',\n '#',\n '%',\n '$',\n '!',\n '?',\n ':',\n ';',\n '~',\n];\n\nexport const listSpecialChars = (text: string): ListCharResult => {\n const results: ListCharResult = [];\n\n let lineIndex = 0;\n\n for (let i = 0; i < text.length; i++) {\n const currentChar = text[i];\n\n // Handle newline characters (\"\\n\"): treat them as a \"\\\\\" special char\n if (currentChar === '\\n') {\n results.push({\n char: '\\\\',\n lineStart: lineIndex,\n charStart: i,\n });\n\n // Move to the next line after recording the special char\n lineIndex++;\n continue;\n }\n\n // Check if the current character is one of the special characters\n if (SPECIAL_CHARS.includes(currentChar)) {\n results.push({\n char: currentChar,\n lineStart: lineIndex,\n charStart: i,\n });\n }\n }\n\n return results;\n};\n"],"mappings":";AAQA,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;
|
|
1
|
+
{"version":3,"file":"listSpecialChars.mjs","names":[],"sources":["../../../src/utils/listSpecialChars.ts"],"sourcesContent":["type ListCharResult = {\n char: string;\n /** First line index contained in this chunk (0-based) */\n lineStart: number;\n /** Start character index in the original text (0-based, inclusive)*/\n charStart: number;\n}[];\n\nconst SPECIAL_CHARS = [\n ' ',\n '\\\\',\n '|',\n '(',\n ')',\n '{',\n '}',\n '[',\n ']',\n '<',\n '>',\n '\"',\n '=',\n '+',\n '*',\n '&',\n '#',\n '%',\n '$',\n '!',\n '?',\n ':',\n ';',\n '~',\n];\n\nexport const listSpecialChars = (text: string): ListCharResult => {\n const results: ListCharResult = [];\n\n let lineIndex = 0;\n\n for (let i = 0; i < text.length; i++) {\n const currentChar = text[i];\n\n // Handle newline characters (\"\\n\"): treat them as a \"\\\\\" special char\n if (currentChar === '\\n') {\n results.push({\n char: '\\\\',\n lineStart: lineIndex,\n charStart: i,\n });\n\n // Move to the next line after recording the special char\n lineIndex++;\n continue;\n }\n\n // Check if the current character is one of the special characters\n if (SPECIAL_CHARS.includes(currentChar)) {\n results.push({\n char: currentChar,\n lineStart: lineIndex,\n charStart: i,\n });\n }\n }\n\n return results;\n};\n"],"mappings":";AAQA,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,oBAAoB,SAAiC;CAChE,MAAM,UAA0B,CAAC;CAEjC,IAAI,YAAY;CAEhB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,cAAc,KAAK;EAGzB,IAAI,gBAAgB,MAAM;GACxB,QAAQ,KAAK;IACX,MAAM;IACN,WAAW;IACX,WAAW;GACb,CAAC;GAGD;GACA;EACF;EAGA,IAAI,cAAc,SAAS,WAAW,GACpC,QAAQ,KAAK;GACX,MAAM;GACN,WAAW;GACX,WAAW;EACb,CAAC;CAEL;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mapChunksBetweenFiles.mjs","names":[],"sources":["../../../src/utils/mapChunksBetweenFiles.ts"],"sourcesContent":["import { splitTextByLines } from '@intlayer/chokidar/utils';\nimport { type ChunkLineResult, chunkText } from './calculateChunks';\n\nexport interface ChunkMapping {\n baseChunk: ChunkLineResult;\n updatedChunk: ChunkLineResult | null; // null if the chunk was deleted\n hasChanges: boolean;\n}\n\n/**\n * Maps chunks from base file to corresponding chunks in updated file,\n * handling insertions, deletions, and modifications properly.\n */\nexport const mapChunksBetweenFiles = (\n baseFileContent: string,\n updatedFileContent: string,\n maxCharsPerChunk: number = 800,\n changedLines?: number[]\n): ChunkMapping[] => {\n const baseChunks = chunkText(baseFileContent, maxCharsPerChunk, 0);\n const baseLines = splitTextByLines(baseFileContent);\n const updatedLines = splitTextByLines(updatedFileContent);\n\n // Create a simple line mapping using LCS (Longest Common Subsequence) approach\n const lineMapping = createLineMapping(baseLines, updatedLines);\n\n return baseChunks.map((baseChunk): ChunkMapping => {\n // Map the base chunk's line range to the updated file\n const mappedRange = mapLineRange(\n baseChunk.lineStart,\n baseChunk.lineLength,\n lineMapping\n );\n\n if (!mappedRange) {\n // This chunk was completely deleted\n return {\n baseChunk,\n updatedChunk: null,\n hasChanges: true,\n };\n }\n\n // Create the corresponding chunk in the updated file\n const updatedChunk: ChunkLineResult = {\n lineStart: mappedRange.start,\n lineLength: mappedRange.length,\n charStart: 0, // Will be calculated when needed\n charLength: 0, // Will be calculated when needed\n content: extractLinesFromRange(\n updatedLines,\n mappedRange.start,\n mappedRange.length\n ),\n };\n\n // Calculate character positions\n updatedChunk.charStart = getCharStartForLine(\n updatedFileContent,\n updatedChunk.lineStart\n );\n updatedChunk.charLength = updatedChunk.content.length;\n\n // Determine if this chunk has changes\n const hasChanges = determineIfChunkHasChanges(\n baseChunk,\n updatedChunk,\n changedLines\n );\n\n return {\n baseChunk,\n updatedChunk,\n hasChanges,\n };\n });\n};\n\n/**\n * Creates a mapping between line numbers in base file and updated file\n * Returns a map where key = base line number, value = updated line number (or null if deleted)\n */\nconst createLineMapping = (\n baseLines: string[],\n updatedLines: string[]\n): Map<number, number | null> => {\n const mapping = new Map<number, number | null>();\n\n // Use a simple diff algorithm (similar to Myers algorithm but simplified)\n const dp: number[][] = Array(baseLines.length + 1)\n .fill(null)\n .map(() => Array(updatedLines.length + 1).fill(0));\n\n // Fill the DP table\n for (let i = 1; i <= baseLines.length; i++) {\n for (let j = 1; j <= updatedLines.length; j++) {\n if (baseLines[i - 1] === updatedLines[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1] + 1;\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n\n // Backtrack to create the mapping\n let i = baseLines.length;\n let j = updatedLines.length;\n\n while (i > 0 || j > 0) {\n if (i > 0 && j > 0 && baseLines[i - 1] === updatedLines[j - 1]) {\n // Lines match\n mapping.set(i - 1, j - 1);\n i--;\n j--;\n } else if (i > 0 && (j === 0 || dp[i - 1][j] >= dp[i][j - 1])) {\n // Line was deleted from base\n mapping.set(i - 1, null);\n i--;\n } else {\n // Line was added to updated (no mapping needed for base)\n j--;\n }\n }\n\n return mapping;\n};\n\n/**\n * Maps a line range from base file to updated file using the line mapping\n */\nconst mapLineRange = (\n baseStart: number,\n baseLength: number,\n lineMapping: Map<number, number | null>\n): { start: number; length: number } | null => {\n const mappedLines: number[] = [];\n\n for (let i = baseStart; i < baseStart + baseLength; i++) {\n const mappedLine = lineMapping.get(i);\n if (mappedLine !== null && mappedLine !== undefined) {\n mappedLines.push(mappedLine);\n }\n }\n\n if (mappedLines.length === 0) {\n return null; // All lines were deleted\n }\n\n // Find the continuous range in the mapped lines\n mappedLines.sort((a, b) => a - b);\n const start = mappedLines[0];\n const end = mappedLines[mappedLines.length - 1];\n\n return {\n start,\n length: end - start + 1,\n };\n};\n\n/**\n * Extracts lines from a range in the lines array\n */\nconst extractLinesFromRange = (\n lines: string[],\n start: number,\n length: number\n): string => {\n const endIndex = Math.min(start + length, lines.length);\n return lines.slice(start, endIndex).join('');\n};\n\n/**\n * Gets the character position where a line starts in the text\n */\nconst getCharStartForLine = (text: string, lineNumber: number): number => {\n const lines = splitTextByLines(text);\n let charStart = 0;\n\n for (let i = 0; i < Math.min(lineNumber, lines.length); i++) {\n charStart += lines[i].length;\n }\n\n return charStart;\n};\n\n/**\n * Determines if a chunk has changes based on git changed lines or content comparison\n */\nconst determineIfChunkHasChanges = (\n baseChunk: ChunkLineResult,\n updatedChunk: ChunkLineResult,\n changedLines?: number[]\n): boolean => {\n // If we have git changed lines, use them for precise detection\n if (changedLines && changedLines.length > 0) {\n return changedLines.some(\n (line) =>\n line >= updatedChunk.lineStart &&\n line < updatedChunk.lineStart + updatedChunk.lineLength\n );\n }\n\n // Fallback to content comparison\n return baseChunk.content !== updatedChunk.content;\n};\n"],"mappings":";;;;;;;;AAaA,MAAa,yBACX,iBACA,oBACA,mBAA2B,KAC3B,iBACmB;CACnB,MAAM,aAAa,UAAU,iBAAiB,kBAAkB,
|
|
1
|
+
{"version":3,"file":"mapChunksBetweenFiles.mjs","names":[],"sources":["../../../src/utils/mapChunksBetweenFiles.ts"],"sourcesContent":["import { splitTextByLines } from '@intlayer/chokidar/utils';\nimport { type ChunkLineResult, chunkText } from './calculateChunks';\n\nexport interface ChunkMapping {\n baseChunk: ChunkLineResult;\n updatedChunk: ChunkLineResult | null; // null if the chunk was deleted\n hasChanges: boolean;\n}\n\n/**\n * Maps chunks from base file to corresponding chunks in updated file,\n * handling insertions, deletions, and modifications properly.\n */\nexport const mapChunksBetweenFiles = (\n baseFileContent: string,\n updatedFileContent: string,\n maxCharsPerChunk: number = 800,\n changedLines?: number[]\n): ChunkMapping[] => {\n const baseChunks = chunkText(baseFileContent, maxCharsPerChunk, 0);\n const baseLines = splitTextByLines(baseFileContent);\n const updatedLines = splitTextByLines(updatedFileContent);\n\n // Create a simple line mapping using LCS (Longest Common Subsequence) approach\n const lineMapping = createLineMapping(baseLines, updatedLines);\n\n return baseChunks.map((baseChunk): ChunkMapping => {\n // Map the base chunk's line range to the updated file\n const mappedRange = mapLineRange(\n baseChunk.lineStart,\n baseChunk.lineLength,\n lineMapping\n );\n\n if (!mappedRange) {\n // This chunk was completely deleted\n return {\n baseChunk,\n updatedChunk: null,\n hasChanges: true,\n };\n }\n\n // Create the corresponding chunk in the updated file\n const updatedChunk: ChunkLineResult = {\n lineStart: mappedRange.start,\n lineLength: mappedRange.length,\n charStart: 0, // Will be calculated when needed\n charLength: 0, // Will be calculated when needed\n content: extractLinesFromRange(\n updatedLines,\n mappedRange.start,\n mappedRange.length\n ),\n };\n\n // Calculate character positions\n updatedChunk.charStart = getCharStartForLine(\n updatedFileContent,\n updatedChunk.lineStart\n );\n updatedChunk.charLength = updatedChunk.content.length;\n\n // Determine if this chunk has changes\n const hasChanges = determineIfChunkHasChanges(\n baseChunk,\n updatedChunk,\n changedLines\n );\n\n return {\n baseChunk,\n updatedChunk,\n hasChanges,\n };\n });\n};\n\n/**\n * Creates a mapping between line numbers in base file and updated file\n * Returns a map where key = base line number, value = updated line number (or null if deleted)\n */\nconst createLineMapping = (\n baseLines: string[],\n updatedLines: string[]\n): Map<number, number | null> => {\n const mapping = new Map<number, number | null>();\n\n // Use a simple diff algorithm (similar to Myers algorithm but simplified)\n const dp: number[][] = Array(baseLines.length + 1)\n .fill(null)\n .map(() => Array(updatedLines.length + 1).fill(0));\n\n // Fill the DP table\n for (let i = 1; i <= baseLines.length; i++) {\n for (let j = 1; j <= updatedLines.length; j++) {\n if (baseLines[i - 1] === updatedLines[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1] + 1;\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n\n // Backtrack to create the mapping\n let i = baseLines.length;\n let j = updatedLines.length;\n\n while (i > 0 || j > 0) {\n if (i > 0 && j > 0 && baseLines[i - 1] === updatedLines[j - 1]) {\n // Lines match\n mapping.set(i - 1, j - 1);\n i--;\n j--;\n } else if (i > 0 && (j === 0 || dp[i - 1][j] >= dp[i][j - 1])) {\n // Line was deleted from base\n mapping.set(i - 1, null);\n i--;\n } else {\n // Line was added to updated (no mapping needed for base)\n j--;\n }\n }\n\n return mapping;\n};\n\n/**\n * Maps a line range from base file to updated file using the line mapping\n */\nconst mapLineRange = (\n baseStart: number,\n baseLength: number,\n lineMapping: Map<number, number | null>\n): { start: number; length: number } | null => {\n const mappedLines: number[] = [];\n\n for (let i = baseStart; i < baseStart + baseLength; i++) {\n const mappedLine = lineMapping.get(i);\n if (mappedLine !== null && mappedLine !== undefined) {\n mappedLines.push(mappedLine);\n }\n }\n\n if (mappedLines.length === 0) {\n return null; // All lines were deleted\n }\n\n // Find the continuous range in the mapped lines\n mappedLines.sort((a, b) => a - b);\n const start = mappedLines[0];\n const end = mappedLines[mappedLines.length - 1];\n\n return {\n start,\n length: end - start + 1,\n };\n};\n\n/**\n * Extracts lines from a range in the lines array\n */\nconst extractLinesFromRange = (\n lines: string[],\n start: number,\n length: number\n): string => {\n const endIndex = Math.min(start + length, lines.length);\n return lines.slice(start, endIndex).join('');\n};\n\n/**\n * Gets the character position where a line starts in the text\n */\nconst getCharStartForLine = (text: string, lineNumber: number): number => {\n const lines = splitTextByLines(text);\n let charStart = 0;\n\n for (let i = 0; i < Math.min(lineNumber, lines.length); i++) {\n charStart += lines[i].length;\n }\n\n return charStart;\n};\n\n/**\n * Determines if a chunk has changes based on git changed lines or content comparison\n */\nconst determineIfChunkHasChanges = (\n baseChunk: ChunkLineResult,\n updatedChunk: ChunkLineResult,\n changedLines?: number[]\n): boolean => {\n // If we have git changed lines, use them for precise detection\n if (changedLines && changedLines.length > 0) {\n return changedLines.some(\n (line) =>\n line >= updatedChunk.lineStart &&\n line < updatedChunk.lineStart + updatedChunk.lineLength\n );\n }\n\n // Fallback to content comparison\n return baseChunk.content !== updatedChunk.content;\n};\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openBrowser.mjs","names":[],"sources":["../../../src/utils/openBrowser.ts"],"sourcesContent":["import { exec } from 'node:child_process';\nimport { platform } from 'node:os';\n\nexport const openBrowser = (url: string) => {\n const osPlatform = platform();\n let command = '';\n\n if (osPlatform === 'darwin') {\n command = `open \"${url}\"`;\n } else if (osPlatform === 'win32') {\n command = `start \"${url}\"`;\n } else {\n command = `xdg-open \"${url}\"`;\n }\n\n exec(command, (error) => {\n if (error) {\n console.error(`Failed to open browser: ${error.message}`);\n }\n });\n};\n"],"mappings":";;;;AAGA,MAAa,eAAe,QAAgB;CAC1C,MAAM,aAAa,
|
|
1
|
+
{"version":3,"file":"openBrowser.mjs","names":[],"sources":["../../../src/utils/openBrowser.ts"],"sourcesContent":["import { exec } from 'node:child_process';\nimport { platform } from 'node:os';\n\nexport const openBrowser = (url: string) => {\n const osPlatform = platform();\n let command = '';\n\n if (osPlatform === 'darwin') {\n command = `open \"${url}\"`;\n } else if (osPlatform === 'win32') {\n command = `start \"${url}\"`;\n } else {\n command = `xdg-open \"${url}\"`;\n }\n\n exec(command, (error) => {\n if (error) {\n console.error(`Failed to open browser: ${error.message}`);\n }\n });\n};\n"],"mappings":";;;;AAGA,MAAa,eAAe,QAAgB;CAC1C,MAAM,aAAa,SAAS;CAC5B,IAAI,UAAU;CAEd,IAAI,eAAe,UACjB,UAAU,SAAS,IAAI;MAClB,IAAI,eAAe,SACxB,UAAU,UAAU,IAAI;MAExB,UAAU,aAAa,IAAI;CAG7B,KAAK,UAAU,UAAU;EACvB,IAAI,OACF,QAAQ,MAAM,2BAA2B,MAAM,SAAS;CAE5D,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reorderParagraphs.mjs","names":[],"sources":["../../../src/utils/reorderParagraphs.ts"],"sourcesContent":["import { listSpecialChars } from './listSpecialChars';\n\n/**\n * Split a text into paragraphs.\n *\n * We consider a paragraph boundary to be a block of at least two consecutive\n * new-lines that is immediately followed by a non-white-space character. This\n * way, internal blank lines that are part of the same paragraph (e.g. a list\n * item that purposely contains a visual break) are preserved while true\n * paragraph breaks – the ones generated when calling `arr.join(\"\\n\\n\")` in\n * the tests – are still detected.\n */\nconst splitByParagraph = (text: string): string[] => {\n const paragraphs: string[] = [];\n\n // Capture the delimiter so that we can inspect how many new-lines it\n // contains. We know that the test strings only use LF, so we keep the\n // regex simple here.\n const tokens = text.split(/(\\n{2,})/);\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n\n // Even-indexed tokens are the actual paragraph contents.\n if (i % 2 === 0) {\n if (token) paragraphs.push(token);\n continue;\n }\n\n // Odd-indexed tokens are the delimiters (>= two consecutive new-lines).\n // The first and last pairs represent the natural separators that are\n // added when paragraphs are later joined with \"\\n\\n\". Any additional\n // pairs in between correspond to *explicit* blank paragraphs that were\n // present in the original text and must therefore be preserved.\n const pairsOfNewlines = Math.floor(token.length / 2);\n const blankParagraphs = Math.max(0, pairsOfNewlines - 2);\n\n for (let j = 0; j < blankParagraphs; j++) {\n paragraphs.push('\\n\\n');\n }\n }\n\n return paragraphs;\n};\n\n/**\n * Determine whether two paragraphs match – either exactly, or by sharing the\n * same \"special-character signature\".\n */\nconst paragraphMatches = (\n paragraph: string,\n baseParagraph: string,\n paragraphSignature: ReturnType<typeof listSpecialChars>,\n baseSignature: ReturnType<typeof listSpecialChars>\n): boolean => {\n if (paragraph === baseParagraph) return true;\n // fallback to special-character signature comparison\n if (paragraphSignature.length !== baseSignature.length) return false;\n\n for (let i = 0; i < paragraphSignature.length; i++) {\n if (paragraphSignature[i].char !== baseSignature[i].char) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Re-order `textToReorder` so that its paragraphs follow the ordering found in\n * `baseFileContent`, while preserving any extra paragraphs (those not present\n * in the base file) in a position that is intuitive for a human reader: right\n * after the closest preceding paragraph coming from the base file.\n */\nexport const reorderParagraphs = (\n textToReorder: string,\n baseFileContent: string\n): string => {\n // 1. Split both texts into paragraphs and pre-compute their signatures.\n const baseFileParagraphs = splitByParagraph(baseFileContent);\n const textToReorderParagraphs = splitByParagraph(textToReorder);\n\n const baseSignatures = baseFileParagraphs.map((p) => listSpecialChars(p));\n const textSignatures = textToReorderParagraphs.map((p) =>\n listSpecialChars(p)\n );\n\n // 2. For every paragraph in the text to reorder, find the *first* base\n // paragraph it matches. We only allow each base paragraph to be matched\n // once. Any further identical paragraphs will be treated as \"extra\" and\n // will be positioned later on, next to their closest neighbour.\n const firstMatchIndexForBase: number[] = Array(\n baseFileParagraphs.length\n ).fill(-1);\n const paragraphMatchedBaseIdx: (number | null)[] = Array(\n textToReorderParagraphs.length\n ).fill(null);\n\n for (let i = 0; i < textToReorderParagraphs.length; i++) {\n const paragraph = textToReorderParagraphs[i];\n const sig = textSignatures[i];\n\n // exact match pass first for performance\n let foundIdx = baseFileParagraphs.findIndex(\n (baseParagraph, idx) =>\n firstMatchIndexForBase[idx] === -1 && paragraph === baseParagraph\n );\n\n if (foundIdx === -1) {\n // fallback to the signature comparison\n foundIdx = baseFileParagraphs.findIndex(\n (baseParagraph, idx) =>\n firstMatchIndexForBase[idx] === -1 &&\n paragraphMatches(paragraph, baseParagraph, sig, baseSignatures[idx])\n );\n }\n\n if (foundIdx !== -1) {\n firstMatchIndexForBase[foundIdx] = i;\n paragraphMatchedBaseIdx[i] = foundIdx;\n }\n }\n\n // 3. For the paragraphs that *didn't* get matched to a base paragraph, we\n // record the highest-numbered base paragraph that was matched *before* it\n // in the original text. The extra paragraph will later be placed right\n // after that paragraph in the final ordering.\n const insertAfterBaseIdx: number[] = Array(\n textToReorderParagraphs.length\n ).fill(-1);\n let maxBaseIdxEncountered = -1;\n\n for (let i = 0; i < textToReorderParagraphs.length; i++) {\n const matchedBase = paragraphMatchedBaseIdx[i];\n\n if (matchedBase !== null) {\n if (matchedBase > maxBaseIdxEncountered) {\n maxBaseIdxEncountered = matchedBase;\n }\n } else {\n insertAfterBaseIdx[i] = maxBaseIdxEncountered;\n }\n }\n\n // 4. Build the final, reordered list of paragraphs.\n const result: string[] = [];\n\n // Helper: quickly retrieve all indices of paragraphs that should be inserted\n // after a given base index, while keeping their original order.\n const extraParagraphsBuckets: Record<number, number[]> = {};\n insertAfterBaseIdx.forEach((afterIdx, paragraphIdx) => {\n if (afterIdx === -1) return; // will be handled later (if any)\n extraParagraphsBuckets[afterIdx] = extraParagraphsBuckets[afterIdx] || [];\n extraParagraphsBuckets[afterIdx].push(paragraphIdx);\n });\n\n for (let bIdx = 0; bIdx < baseFileParagraphs.length; bIdx++) {\n const matchedParagraphIdx = firstMatchIndexForBase[bIdx];\n\n if (matchedParagraphIdx !== -1) {\n result.push(textToReorderParagraphs[matchedParagraphIdx]);\n }\n\n if (extraParagraphsBuckets[bIdx]) {\n extraParagraphsBuckets[bIdx].forEach((pIdx) => {\n result.push(textToReorderParagraphs[pIdx]);\n });\n }\n }\n\n // Finally, if there were extra paragraphs appearing *before* any matched\n // base paragraph (insertAfterBaseIdx === -1), we prepend them to the output\n // in their original order.\n const leadingExtras: string[] = [];\n insertAfterBaseIdx.forEach((afterIdx, pIdx) => {\n if (afterIdx === -1 && paragraphMatchedBaseIdx[pIdx] === null) {\n leadingExtras.push(textToReorderParagraphs[pIdx]);\n }\n });\n\n return [...leadingExtras, ...result].join('\\n\\n');\n};\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,oBAAoB,SAA2B;CACnD,MAAM,aAAuB,
|
|
1
|
+
{"version":3,"file":"reorderParagraphs.mjs","names":[],"sources":["../../../src/utils/reorderParagraphs.ts"],"sourcesContent":["import { listSpecialChars } from './listSpecialChars';\n\n/**\n * Split a text into paragraphs.\n *\n * We consider a paragraph boundary to be a block of at least two consecutive\n * new-lines that is immediately followed by a non-white-space character. This\n * way, internal blank lines that are part of the same paragraph (e.g. a list\n * item that purposely contains a visual break) are preserved while true\n * paragraph breaks – the ones generated when calling `arr.join(\"\\n\\n\")` in\n * the tests – are still detected.\n */\nconst splitByParagraph = (text: string): string[] => {\n const paragraphs: string[] = [];\n\n // Capture the delimiter so that we can inspect how many new-lines it\n // contains. We know that the test strings only use LF, so we keep the\n // regex simple here.\n const tokens = text.split(/(\\n{2,})/);\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n\n // Even-indexed tokens are the actual paragraph contents.\n if (i % 2 === 0) {\n if (token) paragraphs.push(token);\n continue;\n }\n\n // Odd-indexed tokens are the delimiters (>= two consecutive new-lines).\n // The first and last pairs represent the natural separators that are\n // added when paragraphs are later joined with \"\\n\\n\". Any additional\n // pairs in between correspond to *explicit* blank paragraphs that were\n // present in the original text and must therefore be preserved.\n const pairsOfNewlines = Math.floor(token.length / 2);\n const blankParagraphs = Math.max(0, pairsOfNewlines - 2);\n\n for (let j = 0; j < blankParagraphs; j++) {\n paragraphs.push('\\n\\n');\n }\n }\n\n return paragraphs;\n};\n\n/**\n * Determine whether two paragraphs match – either exactly, or by sharing the\n * same \"special-character signature\".\n */\nconst paragraphMatches = (\n paragraph: string,\n baseParagraph: string,\n paragraphSignature: ReturnType<typeof listSpecialChars>,\n baseSignature: ReturnType<typeof listSpecialChars>\n): boolean => {\n if (paragraph === baseParagraph) return true;\n // fallback to special-character signature comparison\n if (paragraphSignature.length !== baseSignature.length) return false;\n\n for (let i = 0; i < paragraphSignature.length; i++) {\n if (paragraphSignature[i].char !== baseSignature[i].char) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Re-order `textToReorder` so that its paragraphs follow the ordering found in\n * `baseFileContent`, while preserving any extra paragraphs (those not present\n * in the base file) in a position that is intuitive for a human reader: right\n * after the closest preceding paragraph coming from the base file.\n */\nexport const reorderParagraphs = (\n textToReorder: string,\n baseFileContent: string\n): string => {\n // 1. Split both texts into paragraphs and pre-compute their signatures.\n const baseFileParagraphs = splitByParagraph(baseFileContent);\n const textToReorderParagraphs = splitByParagraph(textToReorder);\n\n const baseSignatures = baseFileParagraphs.map((p) => listSpecialChars(p));\n const textSignatures = textToReorderParagraphs.map((p) =>\n listSpecialChars(p)\n );\n\n // 2. For every paragraph in the text to reorder, find the *first* base\n // paragraph it matches. We only allow each base paragraph to be matched\n // once. Any further identical paragraphs will be treated as \"extra\" and\n // will be positioned later on, next to their closest neighbour.\n const firstMatchIndexForBase: number[] = Array(\n baseFileParagraphs.length\n ).fill(-1);\n const paragraphMatchedBaseIdx: (number | null)[] = Array(\n textToReorderParagraphs.length\n ).fill(null);\n\n for (let i = 0; i < textToReorderParagraphs.length; i++) {\n const paragraph = textToReorderParagraphs[i];\n const sig = textSignatures[i];\n\n // exact match pass first for performance\n let foundIdx = baseFileParagraphs.findIndex(\n (baseParagraph, idx) =>\n firstMatchIndexForBase[idx] === -1 && paragraph === baseParagraph\n );\n\n if (foundIdx === -1) {\n // fallback to the signature comparison\n foundIdx = baseFileParagraphs.findIndex(\n (baseParagraph, idx) =>\n firstMatchIndexForBase[idx] === -1 &&\n paragraphMatches(paragraph, baseParagraph, sig, baseSignatures[idx])\n );\n }\n\n if (foundIdx !== -1) {\n firstMatchIndexForBase[foundIdx] = i;\n paragraphMatchedBaseIdx[i] = foundIdx;\n }\n }\n\n // 3. For the paragraphs that *didn't* get matched to a base paragraph, we\n // record the highest-numbered base paragraph that was matched *before* it\n // in the original text. The extra paragraph will later be placed right\n // after that paragraph in the final ordering.\n const insertAfterBaseIdx: number[] = Array(\n textToReorderParagraphs.length\n ).fill(-1);\n let maxBaseIdxEncountered = -1;\n\n for (let i = 0; i < textToReorderParagraphs.length; i++) {\n const matchedBase = paragraphMatchedBaseIdx[i];\n\n if (matchedBase !== null) {\n if (matchedBase > maxBaseIdxEncountered) {\n maxBaseIdxEncountered = matchedBase;\n }\n } else {\n insertAfterBaseIdx[i] = maxBaseIdxEncountered;\n }\n }\n\n // 4. Build the final, reordered list of paragraphs.\n const result: string[] = [];\n\n // Helper: quickly retrieve all indices of paragraphs that should be inserted\n // after a given base index, while keeping their original order.\n const extraParagraphsBuckets: Record<number, number[]> = {};\n insertAfterBaseIdx.forEach((afterIdx, paragraphIdx) => {\n if (afterIdx === -1) return; // will be handled later (if any)\n extraParagraphsBuckets[afterIdx] = extraParagraphsBuckets[afterIdx] || [];\n extraParagraphsBuckets[afterIdx].push(paragraphIdx);\n });\n\n for (let bIdx = 0; bIdx < baseFileParagraphs.length; bIdx++) {\n const matchedParagraphIdx = firstMatchIndexForBase[bIdx];\n\n if (matchedParagraphIdx !== -1) {\n result.push(textToReorderParagraphs[matchedParagraphIdx]);\n }\n\n if (extraParagraphsBuckets[bIdx]) {\n extraParagraphsBuckets[bIdx].forEach((pIdx) => {\n result.push(textToReorderParagraphs[pIdx]);\n });\n }\n }\n\n // Finally, if there were extra paragraphs appearing *before* any matched\n // base paragraph (insertAfterBaseIdx === -1), we prepend them to the output\n // in their original order.\n const leadingExtras: string[] = [];\n insertAfterBaseIdx.forEach((afterIdx, pIdx) => {\n if (afterIdx === -1 && paragraphMatchedBaseIdx[pIdx] === null) {\n leadingExtras.push(textToReorderParagraphs[pIdx]);\n }\n });\n\n return [...leadingExtras, ...result].join('\\n\\n');\n};\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setupAI.mjs","names":[],"sources":["../../../src/utils/setupAI.ts"],"sourcesContent":["import type { AIConfig, AIOptions } from '@intlayer/ai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger, type logger } 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 projectOptions: configuration.ai as 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":";;;;;AAgBA,WAAW,sBAAsB;AAEjC,MAAM,eAAe,WAAsB,cAA6B;CACtE,UAAU;EACR,SAAS,aAAa,WAAW,
|
|
1
|
+
{"version":3,"file":"setupAI.mjs","names":[],"sources":["../../../src/utils/setupAI.ts"],"sourcesContent":["import type { AIConfig, AIOptions } from '@intlayer/ai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger, type logger } 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 projectOptions: configuration.ai as 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":";;;;;AAgBA,WAAW,sBAAsB;AAEjC,MAAM,eAAe,WAAsB,cAA6B;CACtE,UAAU;EACR,SAAS,aAAa,WAAW,SAAS;EAC1C,SAAS,WAAW,YAAY,aAAa,WAAW,IAAI;EAC5D,SAAS,YAAY,WAAW,SAAS;EACzC,SAAS,WAAW,SAAS,aAAa,WAAW,IAAI;EACzD,SAAS,cAAc,WAAW,SAAS;EAC3C,SAAS,WAAW,SAAS,MAAM,aAAa,WAAW,IAAI;CACjE,CAAC;AACH;;;;;;AAOA,MAAa,UAAU,OACrB,eACA,cACuC;CACvC,MAAM,YAAY,aAAa,aAAa;CAQ5C,IALE,WAAW,UACX,WAAW,aAAa,YACxB,cAAc,IAAI,UAClB,cAAc,IAAI,aAAa,UAElB;EAEb,IAAI;EAEJ,IAAI;GACF,WAAW,MAAM,OAAO;EAC1B,QAAQ;GAEN,UACE;IACE,SAAS,2CAA2C,WAAW,IAAI;IACnE,SAAS,gBAAgB,WAAW,UAAU;IAC9C,SACE,iFACA,WAAW,IACb;GACF,GACA,EACE,OAAO,OACT,CACF;GAGA,MAAM,cAAc,MAAM,cAAc,eAAe,SAAS;GAChE,YAAY,aAAa,CAAC,GAAG,SAAS;GACtC,OAAO;IACL,YAAY;IACZ;GACF;EACF;EAGA,UAAU,CACR,SAAS,gBAAgB,WAAW,UAAU,GAC9C,SAAS,+BAA+B,WAAW,SAAS,CAC9D,CAAC;EAED,MAAM,WAAW,MAAM,SAAS,YAAY;GAC1C,aAAa;GACb,gBAAgB,cAAc;GAC9B,YAAY,CAAC,QAAQ;EACvB,CAAC;EAED,YAAY,aAAa,CAAC,GAAG,SAAS;EAEtC,OAAO;GACL;GACA;GACA,YAAY;GACZ,aAAa;EACf;CACF;CAGA,MAAM,cAAc,MAAM,cAAc,eAAe,SAAS;CAChE,YAAY,aAAa,CAAC,GAAG,SAAS;CAEtC,OAAO;EACL,YAAY;EACZ;CACF;AACF"}
|
package/dist/esm/watch.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watch.mjs","names":[],"sources":["../../src/watch.ts"],"sourcesContent":["import { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { runParallel } from '@intlayer/chokidar/utils';\nimport { watch } from '@intlayer/chokidar/watcher';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\n\ntype WatchOptions = {\n skipPrepare?: boolean;\n with?: string | string[];\n configOptions?: GetConfigurationOptions;\n};\n\n/**\n * Get locales dictionaries .content.{json|ts|tsx|js|jsx|mjs|cjs} and build the JSON dictionaries in the .intlayer directory.\n * Watch mode available to get the change in the .content.{json|ts|tsx|js|jsx|mjs|cjs}\n */\nexport const watchContentDeclaration = async (options?: WatchOptions) => {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const appLogger = getAppLogger(config);\n\n // Store references to the child process\n let parallelProcess: ReturnType<typeof runParallel> | undefined;\n\n if (options?.with) {\n parallelProcess = runParallel(options.with);\n // Handle the promise to avoid unhandled rejection\n parallelProcess.result.catch(() => {\n // Parallel process failed or was terminated\n process.exit(1);\n });\n }\n\n // Capture the watcher instance\n const watcher = await watch({\n persistent: true,\n skipPrepare: options?.skipPrepare ?? false,\n });\n\n // Define a Graceful Shutdown function\n let isShuttingDown = false;\n const handleShutdown = async () => {\n // Prevent multiple calls\n if (isShuttingDown) return;\n isShuttingDown = true;\n\n appLogger('Stopping Intlayer watcher...');\n\n try {\n // Kill the parallel process (e.g., Next.js) before closing the watcher\n if (parallelProcess) {\n parallelProcess.kill();\n }\n\n // Close the file watcher to stop \"esbuild service not running\" errors\n await watcher.close();\n } catch (error) {\n console.error('Error during shutdown:', error);\n } finally {\n process.exit(0);\n }\n };\n\n // Attach Signal Listeners\n process.on('SIGINT', handleShutdown);\n process.on('SIGTERM', handleShutdown);\n};\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,0BAA0B,OAAO,YAA2B;CACvE,MAAM,SAAS,iBAAiB,SAAS,
|
|
1
|
+
{"version":3,"file":"watch.mjs","names":[],"sources":["../../src/watch.ts"],"sourcesContent":["import { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { runParallel } from '@intlayer/chokidar/utils';\nimport { watch } from '@intlayer/chokidar/watcher';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\n\ntype WatchOptions = {\n skipPrepare?: boolean;\n with?: string | string[];\n configOptions?: GetConfigurationOptions;\n};\n\n/**\n * Get locales dictionaries .content.{json|ts|tsx|js|jsx|mjs|cjs} and build the JSON dictionaries in the .intlayer directory.\n * Watch mode available to get the change in the .content.{json|ts|tsx|js|jsx|mjs|cjs}\n */\nexport const watchContentDeclaration = async (options?: WatchOptions) => {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const appLogger = getAppLogger(config);\n\n // Store references to the child process\n let parallelProcess: ReturnType<typeof runParallel> | undefined;\n\n if (options?.with) {\n parallelProcess = runParallel(options.with);\n // Handle the promise to avoid unhandled rejection\n parallelProcess.result.catch(() => {\n // Parallel process failed or was terminated\n process.exit(1);\n });\n }\n\n // Capture the watcher instance\n const watcher = await watch({\n persistent: true,\n skipPrepare: options?.skipPrepare ?? false,\n });\n\n // Define a Graceful Shutdown function\n let isShuttingDown = false;\n const handleShutdown = async () => {\n // Prevent multiple calls\n if (isShuttingDown) return;\n isShuttingDown = true;\n\n appLogger('Stopping Intlayer watcher...');\n\n try {\n // Kill the parallel process (e.g., Next.js) before closing the watcher\n if (parallelProcess) {\n parallelProcess.kill();\n }\n\n // Close the file watcher to stop \"esbuild service not running\" errors\n await watcher.close();\n } catch (error) {\n console.error('Error during shutdown:', error);\n } finally {\n process.exit(0);\n }\n };\n\n // Attach Signal Listeners\n process.on('SIGINT', handleShutdown);\n process.on('SIGTERM', handleShutdown);\n};\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,0BAA0B,OAAO,YAA2B;CACvE,MAAM,SAAS,iBAAiB,SAAS,aAAa;CACtD,iBAAiB,SAAS,aAAa;CAEvC,MAAM,YAAY,aAAa,MAAM;CAGrC,IAAI;CAEJ,IAAI,SAAS,MAAM;EACjB,kBAAkB,YAAY,QAAQ,IAAI;EAE1C,gBAAgB,OAAO,YAAY;GAEjC,QAAQ,KAAK,CAAC;EAChB,CAAC;CACH;CAGA,MAAM,UAAU,MAAM,MAAM;EAC1B,YAAY;EACZ,aAAa,SAAS,eAAe;CACvC,CAAC;CAGD,IAAI,iBAAiB;CACrB,MAAM,iBAAiB,YAAY;EAEjC,IAAI,gBAAgB;EACpB,iBAAiB;EAEjB,UAAU,8BAA8B;EAExC,IAAI;GAEF,IAAI,iBACF,gBAAgB,KAAK;GAIvB,MAAM,QAAQ,MAAM;EACtB,SAAS,OAAO;GACd,QAAQ,MAAM,0BAA0B,KAAK;EAC/C,UAAU;GACR,QAAQ,KAAK,CAAC;EAChB;CACF;CAGA,QAAQ,GAAG,UAAU,cAAc;CACnC,QAAQ,GAAG,WAAW,cAAc;AACtC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IntlayerEventListener.d.ts","names":[],"sources":["../../src/IntlayerEventListener.ts"],"mappings":";;;;KAQY,oBAAA,GAAuB,
|
|
1
|
+
{"version":3,"file":"IntlayerEventListener.d.ts","names":[],"sources":["../../src/IntlayerEventListener.ts"],"mappings":";;;;KAQY,oBAAA,GAAuB,YAAY;;AAA/C;;;;AAA+C;AA0B/C;;;;;;;;;;;;;;;;;;cAAa,qBAAA;EAAA,QAmCS,cAAA;EAAA,QAlCZ,SAAA;EAAA,QAEA,WAAA;EAAA,QACA,iBAAA;EAAA,QACA,oBAAA;EAAA,QACA,cAAA;EAAA,QACA,sBAAA;EAAA,QACA,gBAAA;EAesB;;;EAVvB,iBAAA,IAAqB,UAAA,EAAY,aAAA;EAoBZ;;;EAfrB,kBAAA,IAAsB,UAAA,EAAY,aAAA;EAyB5B;;;EApBN,mBAAA,IAAuB,UAAA,EAAY,aAAA;EAgGlC;;;EA3FD,gBAAA;EA6KY;;;EAxKZ,iBAAA,IAAqB,KAAA,EAAO,KAAA;cAEf,cAAA,GAAgB,cAAA;;;;;EAQvB,UAAA,CAAA,GAAc,OAAA;;;;UAQb,OAAA;;;;EAmDP,OAAA,CAAA;;;;UAiBC,iBAAA;;;;;UAoCM,aAAA;;;;UA8CN,WAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login.d.ts","names":[],"sources":["../../../src/auth/login.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"login.d.ts","names":[],"sources":["../../../src/auth/login.ts"],"mappings":";;;KAiEK,YAAA;EACH,MAAA;EACA,aAAA,GAAgB,uBAAuB;AAAA;AAAA,cAG5B,KAAA,GAAe,OAAA,EAAS,YAAA,KAAY,OAAA"}
|
|
@@ -9,5 +9,5 @@ declare const writeCliSessionToken: (config: IntlayerConfig, token: string, expi
|
|
|
9
9
|
declare const readCliSessionToken: (config: IntlayerConfig) => Promise<CliSessionData | null>;
|
|
10
10
|
declare const clearCliSessionToken: (config: IntlayerConfig) => Promise<void>;
|
|
11
11
|
//#endregion
|
|
12
|
-
export { clearCliSessionToken, readCliSessionToken, writeCliSessionToken };
|
|
12
|
+
export { CliSessionData, clearCliSessionToken, readCliSessionToken, writeCliSessionToken };
|
|
13
13
|
//# sourceMappingURL=sessionToken.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionToken.d.ts","names":[],"sources":["../../../src/auth/sessionToken.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"sessionToken.d.ts","names":[],"sources":["../../../src/auth/sessionToken.ts"],"mappings":";;;KAMY,cAAA;EACV,KAAA;EACA,SAAS;AAAA;AAAA,cAME,oBAAA,GACX,MAAA,EAAQ,cAAA,EACR,KAAA,UACA,SAAA,EAAW,IAAA,KACV,OAAA;AAAA,cASU,mBAAA,GACX,MAAA,EAAQ,cAAA,KACP,OAAA,CAAQ,cAAA;AAAA,cAsBE,oBAAA,GACX,MAAA,EAAQ,cAAA,KACP,OAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.ts","names":[],"sources":["../../src/build.ts"],"mappings":";;;KAQK,YAAA;EACH,KAAA;EACA,WAAA;EACA,IAAA;EACA,aAAA,GAAgB,
|
|
1
|
+
{"version":3,"file":"build.d.ts","names":[],"sources":["../../src/build.ts"],"mappings":";;;KAQK,YAAA;EACH,KAAA;EACA,WAAA;EACA,IAAA;EACA,aAAA,GAAgB,uBAAuB;AAAA;;;;;cAO5B,KAAA,GAAe,OAAA,GAAU,YAAA,KAAY,OAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.d.ts","names":[],"sources":["../../src/bundle.ts"],"mappings":";;;cAEa,MAAA,GAAgB,OAAA,EAAS,qBAAA,KAAwB,
|
|
1
|
+
{"version":3,"file":"bundle.d.ts","names":[],"sources":["../../src/bundle.ts"],"mappings":";;;cAEa,MAAA,GAAgB,OAAA,EAAS,qBAAA,KAAwB,OAAO"}
|
package/dist/types/cli.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","names":[],"sources":["../../src/cli.ts"],"mappings":";;;cA0Ca,OAAA;AAAA,KA4IR,UAAA;EACH,MAAA;EACA,
|
|
1
|
+
{"version":3,"file":"cli.d.ts","names":[],"sources":["../../src/cli.ts"],"mappings":";;;cA0Ca,OAAA;AAAA,KA4IR,UAAA;EACH,MAAA;EACA,OAAO;AAAA;AAAA,KAGG,oBAAA;EACV,OAAA;EACA,GAAA;EACA,OAAA;EACA,OAAA;EACA,UAAA;AAAA,IACE,UAAU;AANd;;;;;;;;AAAA,cAuEa,MAAA,QAAa,OAiuBzB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","names":[],"sources":["../../src/config.ts"],"mappings":";;;KAOK,aAAA;EACH,aAAA,GAAgB,
|
|
1
|
+
{"version":3,"file":"config.d.ts","names":[],"sources":["../../src/config.ts"],"mappings":";;;KAOK,aAAA;EACH,aAAA,GAAgB,uBAAuB;AAAA;AAAA,cAG5B,SAAA,GAAa,OAAuB,GAAb,aAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor.d.ts","names":[],"sources":["../../src/editor.ts"],"mappings":";KAKK,kBAAA;EACH,GAAA;EACA,
|
|
1
|
+
{"version":3,"file":"editor.d.ts","names":[],"sources":["../../src/editor.ts"],"mappings":";KAKK,kBAAA;EACH,GAAA;EACA,OAAO;AAAA;AAAA,cAGI,WAAA,GAAe,OAA2B,EAAlB,kBAAkB"}
|