@intlayer/cli 8.4.4 → 8.4.5
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 +186 -1
- package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +29 -0
- package/dist/cjs/_virtual/_utils_asset.cjs +98 -0
- package/dist/cjs/auth/login.cjs +90 -2
- package/dist/cjs/auth/login.cjs.map +1 -1
- package/dist/cjs/build.cjs +30 -1
- package/dist/cjs/build.cjs.map +1 -1
- package/dist/cjs/ci.cjs +76 -1
- package/dist/cjs/ci.cjs.map +1 -1
- package/dist/cjs/cli.cjs +485 -1
- package/dist/cjs/cli.cjs.map +1 -1
- package/dist/cjs/config.cjs +15 -1
- package/dist/cjs/config.cjs.map +1 -1
- package/dist/cjs/editor.cjs +50 -1
- package/dist/cjs/editor.cjs.map +1 -1
- package/dist/cjs/extract.cjs +108 -1
- package/dist/cjs/extract.cjs.map +1 -1
- package/dist/cjs/fill/deepMergeContent.cjs +27 -1
- package/dist/cjs/fill/deepMergeContent.cjs.map +1 -1
- package/dist/cjs/fill/fill.cjs +84 -1
- package/dist/cjs/fill/fill.cjs.map +1 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs +32 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
- package/dist/cjs/fill/formatFillData.cjs +87 -1
- package/dist/cjs/fill/formatFillData.cjs.map +1 -1
- package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs +26 -1
- package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs.map +1 -1
- package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs +51 -1
- package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs.map +1 -1
- package/dist/cjs/fill/index.cjs +6 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs +72 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
- package/dist/cjs/fill/translateDictionary.cjs +240 -1
- package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
- package/dist/cjs/fill/writeFill.cjs +55 -1
- package/dist/cjs/fill/writeFill.cjs.map +1 -1
- package/dist/cjs/getTargetDictionary.cjs +36 -1
- package/dist/cjs/getTargetDictionary.cjs.map +1 -1
- package/dist/cjs/index.cjs +44 -1
- package/dist/cjs/init.cjs +22 -1
- package/dist/cjs/init.cjs.map +1 -1
- package/dist/cjs/initMCP.cjs +69 -1
- package/dist/cjs/initMCP.cjs.map +1 -1
- package/dist/cjs/initSkills.cjs +93 -1
- package/dist/cjs/initSkills.cjs.map +1 -1
- package/dist/cjs/listContentDeclaration.cjs +42 -1
- package/dist/cjs/listContentDeclaration.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs +28 -1
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/liveSync.cjs +153 -8
- package/dist/cjs/liveSync.cjs.map +1 -1
- package/dist/cjs/pull.cjs +153 -1
- package/dist/cjs/pull.cjs.map +1 -1
- package/dist/cjs/push/pullLog.cjs +105 -3
- package/dist/cjs/push/pullLog.cjs.map +1 -1
- package/dist/cjs/push/push.cjs +212 -1
- package/dist/cjs/push/push.cjs.map +1 -1
- package/dist/cjs/pushConfig.cjs +22 -1
- package/dist/cjs/pushConfig.cjs.map +1 -1
- package/dist/cjs/pushLog.cjs +86 -3
- package/dist/cjs/pushLog.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs +73 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +98 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
- package/dist/cjs/searchDoc.cjs +41 -1
- package/dist/cjs/searchDoc.cjs.map +1 -1
- package/dist/cjs/test/index.cjs +7 -1
- package/dist/cjs/test/listMissingTranslations.cjs +52 -1
- package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
- package/dist/cjs/test/test.cjs +56 -1
- package/dist/cjs/test/test.cjs.map +1 -1
- package/dist/cjs/translateDoc/index.cjs +9 -1
- package/dist/cjs/translateDoc/translateDoc.cjs +79 -1
- package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateFile.cjs +106 -2
- package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
- package/dist/cjs/translateDoc/validation.cjs +49 -5
- package/dist/cjs/translateDoc/validation.cjs.map +1 -1
- package/dist/cjs/translation-alignment/alignBlocks.cjs +67 -1
- package/dist/cjs/translation-alignment/alignBlocks.cjs.map +1 -1
- package/dist/cjs/translation-alignment/computeSimilarity.cjs +25 -1
- package/dist/cjs/translation-alignment/computeSimilarity.cjs.map +1 -1
- package/dist/cjs/translation-alignment/fingerprintBlock.cjs +23 -1
- package/dist/cjs/translation-alignment/fingerprintBlock.cjs.map +1 -1
- package/dist/cjs/translation-alignment/index.cjs +22 -1
- package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs +18 -1
- package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs.map +1 -1
- package/dist/cjs/translation-alignment/normalizeBlock.cjs +22 -1
- package/dist/cjs/translation-alignment/normalizeBlock.cjs.map +1 -1
- package/dist/cjs/translation-alignment/pipeline.cjs +37 -1
- package/dist/cjs/translation-alignment/pipeline.cjs.map +1 -1
- package/dist/cjs/translation-alignment/planActions.cjs +46 -1
- package/dist/cjs/translation-alignment/planActions.cjs.map +1 -1
- package/dist/cjs/translation-alignment/rebuildDocument.cjs +49 -2
- package/dist/cjs/translation-alignment/rebuildDocument.cjs.map +1 -1
- package/dist/cjs/translation-alignment/segmentDocument.cjs +66 -5
- package/dist/cjs/translation-alignment/segmentDocument.cjs.map +1 -1
- package/dist/cjs/utils/calculateChunks.cjs +89 -2
- package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
- package/dist/cjs/utils/checkAccess.cjs +83 -1
- package/dist/cjs/utils/checkAccess.cjs.map +1 -1
- package/dist/cjs/utils/checkConfigConsistency.cjs +16 -1
- package/dist/cjs/utils/checkConfigConsistency.cjs.map +1 -1
- package/dist/cjs/utils/checkFileModifiedRange.cjs +81 -1
- package/dist/cjs/utils/checkFileModifiedRange.cjs.map +1 -1
- package/dist/cjs/utils/checkLastUpdateTime.cjs +19 -1
- package/dist/cjs/utils/checkLastUpdateTime.cjs.map +1 -1
- package/dist/cjs/utils/chunkInference.cjs +45 -1
- package/dist/cjs/utils/chunkInference.cjs.map +1 -1
- package/dist/cjs/utils/fixChunkStartEndChars.cjs +27 -3
- package/dist/cjs/utils/fixChunkStartEndChars.cjs.map +1 -1
- package/dist/cjs/utils/formatTimeDiff.cjs +20 -1
- package/dist/cjs/utils/formatTimeDiff.cjs.map +1 -1
- package/dist/cjs/utils/getIsFileUpdatedRecently.cjs +16 -1
- package/dist/cjs/utils/getIsFileUpdatedRecently.cjs.map +1 -1
- package/dist/cjs/utils/getOutputFilePath.cjs +74 -1
- package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
- package/dist/cjs/utils/getParentPackageJSON.cjs +20 -1
- package/dist/cjs/utils/getParentPackageJSON.cjs.map +1 -1
- package/dist/cjs/utils/listSpecialChars.cjs +54 -2
- package/dist/cjs/utils/listSpecialChars.cjs.map +1 -1
- package/dist/cjs/utils/mapChunksBetweenFiles.cjs +102 -1
- package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
- package/dist/cjs/utils/openBrowser.cjs +19 -1
- package/dist/cjs/utils/openBrowser.cjs.map +1 -1
- package/dist/cjs/utils/reorderParagraphs.cjs +91 -3
- package/dist/cjs/utils/reorderParagraphs.cjs.map +1 -1
- package/dist/cjs/utils/setupAI.cjs +66 -1
- package/dist/cjs/utils/setupAI.cjs.map +1 -1
- package/dist/cjs/watch.cjs +47 -1
- package/dist/cjs/watch.cjs.map +1 -1
- package/dist/esm/IntlayerEventListener.mjs +183 -1
- package/dist/esm/IntlayerEventListener.mjs.map +1 -1
- package/dist/esm/_virtual/_rolldown/runtime.mjs +8 -0
- package/dist/esm/_virtual/_utils_asset.mjs +97 -0
- package/dist/esm/auth/login.mjs +86 -2
- package/dist/esm/auth/login.mjs.map +1 -1
- package/dist/esm/build.mjs +28 -1
- package/dist/esm/build.mjs.map +1 -1
- package/dist/esm/ci.mjs +74 -1
- package/dist/esm/ci.mjs.map +1 -1
- package/dist/esm/cli.mjs +482 -1
- package/dist/esm/cli.mjs.map +1 -1
- package/dist/esm/config.mjs +13 -1
- package/dist/esm/config.mjs.map +1 -1
- package/dist/esm/editor.mjs +50 -1
- package/dist/esm/editor.mjs.map +1 -0
- package/dist/esm/extract.mjs +104 -1
- package/dist/esm/extract.mjs.map +1 -1
- package/dist/esm/fill/deepMergeContent.mjs +25 -1
- package/dist/esm/fill/deepMergeContent.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs +81 -1
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs +30 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
- package/dist/esm/fill/formatFillData.mjs +85 -1
- package/dist/esm/fill/formatFillData.mjs.map +1 -1
- package/dist/esm/fill/getAvailableLocalesInDictionary.mjs +24 -1
- package/dist/esm/fill/getAvailableLocalesInDictionary.mjs.map +1 -1
- package/dist/esm/fill/getFilterMissingContentPerLocale.mjs +49 -1
- package/dist/esm/fill/getFilterMissingContentPerLocale.mjs.map +1 -1
- package/dist/esm/fill/index.mjs +4 -1
- package/dist/esm/fill/listTranslationsTasks.mjs +69 -1
- package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -1
- package/dist/esm/fill/translateDictionary.mjs +237 -1
- package/dist/esm/fill/translateDictionary.mjs.map +1 -1
- package/dist/esm/fill/writeFill.mjs +53 -1
- package/dist/esm/fill/writeFill.mjs.map +1 -1
- package/dist/esm/getTargetDictionary.mjs +33 -1
- package/dist/esm/getTargetDictionary.mjs.map +1 -1
- package/dist/esm/index.mjs +20 -1
- package/dist/esm/init.mjs +19 -1
- package/dist/esm/init.mjs.map +1 -1
- package/dist/esm/initMCP.mjs +65 -1
- package/dist/esm/initMCP.mjs.map +1 -1
- package/dist/esm/initSkills.mjs +87 -1
- package/dist/esm/initSkills.mjs.map +1 -1
- package/dist/esm/listContentDeclaration.mjs +39 -1
- package/dist/esm/listContentDeclaration.mjs.map +1 -1
- package/dist/esm/listProjects.mjs +26 -1
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/liveSync.mjs +150 -8
- package/dist/esm/liveSync.mjs.map +1 -1
- package/dist/esm/pull.mjs +150 -1
- package/dist/esm/pull.mjs.map +1 -1
- package/dist/esm/push/pullLog.mjs +102 -3
- package/dist/esm/push/pullLog.mjs.map +1 -1
- package/dist/esm/push/push.mjs +208 -1
- package/dist/esm/push/push.mjs.map +1 -1
- package/dist/esm/pushConfig.mjs +20 -1
- package/dist/esm/pushConfig.mjs.map +1 -1
- package/dist/esm/pushLog.mjs +83 -3
- package/dist/esm/pushLog.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs +69 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +95 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
- package/dist/esm/searchDoc.mjs +39 -1
- package/dist/esm/searchDoc.mjs.map +1 -1
- package/dist/esm/test/index.mjs +4 -1
- package/dist/esm/test/listMissingTranslations.mjs +49 -1
- package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
- package/dist/esm/test/test.mjs +53 -1
- package/dist/esm/test/test.mjs.map +1 -1
- package/dist/esm/translateDoc/index.mjs +5 -1
- package/dist/esm/translateDoc/translateDoc.mjs +75 -1
- package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
- package/dist/esm/translateDoc/translateFile.mjs +103 -2
- package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
- package/dist/esm/translateDoc/validation.mjs +46 -5
- package/dist/esm/translateDoc/validation.mjs.map +1 -1
- package/dist/esm/translation-alignment/alignBlocks.mjs +66 -1
- package/dist/esm/translation-alignment/alignBlocks.mjs.map +1 -1
- package/dist/esm/translation-alignment/computeSimilarity.mjs +22 -1
- package/dist/esm/translation-alignment/computeSimilarity.mjs.map +1 -1
- package/dist/esm/translation-alignment/fingerprintBlock.mjs +20 -1
- package/dist/esm/translation-alignment/fingerprintBlock.mjs.map +1 -1
- package/dist/esm/translation-alignment/index.mjs +11 -1
- package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs +16 -1
- package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs.map +1 -1
- package/dist/esm/translation-alignment/normalizeBlock.mjs +20 -1
- package/dist/esm/translation-alignment/normalizeBlock.mjs.map +1 -1
- package/dist/esm/translation-alignment/pipeline.mjs +35 -1
- package/dist/esm/translation-alignment/pipeline.mjs.map +1 -1
- package/dist/esm/translation-alignment/planActions.mjs +44 -1
- package/dist/esm/translation-alignment/planActions.mjs.map +1 -1
- package/dist/esm/translation-alignment/rebuildDocument.mjs +46 -2
- package/dist/esm/translation-alignment/rebuildDocument.mjs.map +1 -1
- package/dist/esm/translation-alignment/segmentDocument.mjs +64 -5
- package/dist/esm/translation-alignment/segmentDocument.mjs.map +1 -1
- package/dist/esm/utils/calculateChunks.mjs +87 -2
- package/dist/esm/utils/calculateChunks.mjs.map +1 -1
- package/dist/esm/utils/checkAccess.mjs +79 -1
- package/dist/esm/utils/checkAccess.mjs.map +1 -1
- package/dist/esm/utils/checkConfigConsistency.mjs +14 -1
- package/dist/esm/utils/checkConfigConsistency.mjs.map +1 -1
- package/dist/esm/utils/checkFileModifiedRange.mjs +80 -1
- package/dist/esm/utils/checkFileModifiedRange.mjs.map +1 -1
- package/dist/esm/utils/checkLastUpdateTime.mjs +17 -1
- package/dist/esm/utils/checkLastUpdateTime.mjs.map +1 -1
- package/dist/esm/utils/chunkInference.mjs +43 -1
- package/dist/esm/utils/chunkInference.mjs.map +1 -1
- package/dist/esm/utils/fixChunkStartEndChars.mjs +25 -3
- package/dist/esm/utils/fixChunkStartEndChars.mjs.map +1 -1
- package/dist/esm/utils/formatTimeDiff.mjs +18 -1
- package/dist/esm/utils/formatTimeDiff.mjs.map +1 -1
- package/dist/esm/utils/getIsFileUpdatedRecently.mjs +14 -1
- package/dist/esm/utils/getIsFileUpdatedRecently.mjs.map +1 -1
- package/dist/esm/utils/getOutputFilePath.mjs +72 -1
- package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
- package/dist/esm/utils/getParentPackageJSON.mjs +18 -1
- package/dist/esm/utils/getParentPackageJSON.mjs.map +1 -1
- package/dist/esm/utils/listSpecialChars.mjs +52 -2
- package/dist/esm/utils/listSpecialChars.mjs.map +1 -1
- package/dist/esm/utils/mapChunksBetweenFiles.mjs +100 -1
- package/dist/esm/utils/mapChunksBetweenFiles.mjs.map +1 -1
- package/dist/esm/utils/openBrowser.mjs +17 -1
- package/dist/esm/utils/openBrowser.mjs.map +1 -1
- package/dist/esm/utils/reorderParagraphs.mjs +90 -3
- package/dist/esm/utils/reorderParagraphs.mjs.map +1 -1
- package/dist/esm/utils/setupAI.mjs +63 -1
- package/dist/esm/utils/setupAI.mjs.map +1 -1
- package/dist/esm/watch.mjs +45 -1
- package/dist/esm/watch.mjs.map +1 -1
- package/dist/types/fill/fill.d.ts +1 -1
- package/dist/types/fill/translateDictionary.d.ts +1 -1
- package/dist/types/getTargetDictionary.d.ts +19 -2
- package/dist/types/getTargetDictionary.d.ts.map +1 -0
- package/dist/types/index.d.ts +2 -2
- package/dist/types/reviewDoc/reviewDocBlockAware.d.ts +1 -1
- package/dist/types/test/index.d.ts +2 -2
- package/dist/types/test/listMissingTranslations.d.ts +28 -2
- package/dist/types/test/listMissingTranslations.d.ts.map +1 -0
- package/dist/types/test/test.d.ts +11 -2
- package/dist/types/test/test.d.ts.map +1 -0
- package/dist/types/translateDoc/index.d.ts +1 -1
- package/dist/types/translateDoc/translateDoc.d.ts +1 -1
- package/dist/types/translateDoc/translateFile.d.ts +1 -1
- package/dist/types/translateDoc/types.d.ts +48 -2
- package/dist/types/translateDoc/types.d.ts.map +1 -0
- package/dist/types/utils/chunkInference.d.ts +1 -1
- package/dist/types/utils/setupAI.d.ts +21 -2
- package/dist/types/utils/setupAI.d.ts.map +1 -0
- package/package.json +12 -12
- package/dist/cjs/_utils_asset-ghp_Cjwk.cjs +0 -2
- package/dist/cjs/chunk-Bmb41Sf3.cjs +0 -1
- package/dist/esm/_utils_asset-B187VPMw.mjs +0 -2
- package/dist/esm/editor-D8BGlLzF.mjs +0 -2
- package/dist/esm/editor-D8BGlLzF.mjs.map +0 -1
- package/dist/types/getTargetDictionary-RBSRtaQj.d.ts +0 -19
- package/dist/types/getTargetDictionary-RBSRtaQj.d.ts.map +0 -1
- package/dist/types/listMissingTranslations-DxKw7nqI.d.ts +0 -28
- package/dist/types/listMissingTranslations-DxKw7nqI.d.ts.map +0 -1
- package/dist/types/setupAI-Bosjx7ah.d.ts +0 -21
- package/dist/types/setupAI-Bosjx7ah.d.ts.map +0 -1
- package/dist/types/test-DUTiJR5_.d.ts +0 -11
- package/dist/types/test-DUTiJR5_.d.ts.map +0 -1
- package/dist/types/types-BKvc3FmV.d.ts +0 -48
- package/dist/types/types-BKvc3FmV.d.ts.map +0 -1
|
@@ -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":"
|
|
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,eAAe;AAItC,QAHqB,IAAI,KAAK,MAAM,MAAM,GACxB,IAAI,KAAK,KAAK,KAAK,GAAG,+BAA+B"}
|
|
@@ -1,2 +1,73 @@
|
|
|
1
|
-
|
|
1
|
+
//#region src/utils/getOutputFilePath.ts
|
|
2
|
+
/**
|
|
3
|
+
* Get the output file path by replacing the base locale with the target locale
|
|
4
|
+
*
|
|
5
|
+
* This function handles two types of replacements:
|
|
6
|
+
* 1. Actual locale values (e.g., `/en/` → `/fr/`)
|
|
7
|
+
* 2. Template placeholders (e.g., `{{baseLocale}}` → `{{locale}}`, `{{baseLocaleName}}` → `{{localeName}}`)
|
|
8
|
+
*
|
|
9
|
+
* Replacement patterns:
|
|
10
|
+
* - `/baseLocale/` → `/locale/`
|
|
11
|
+
* - `\baseLocale\` → `\locale\`
|
|
12
|
+
* - `_baseLocale.` → `_locale.`
|
|
13
|
+
* - `baseLocale_` → `locale_`
|
|
14
|
+
* - `.baseLocaleName.` → `.localeName.`
|
|
15
|
+
* - `{{baseLocale}}` → `{{locale}}`
|
|
16
|
+
* - `{{baseLocaleName}}` → `{{localeName}}`
|
|
17
|
+
*
|
|
18
|
+
* If no patterns match, appends `.locale` to the file extension.
|
|
19
|
+
*
|
|
20
|
+
* @param filePath - The input file path
|
|
21
|
+
* @param locale - The target locale
|
|
22
|
+
* @param baseLocale - The base locale to replace
|
|
23
|
+
* @returns The output file path with locale replacements
|
|
24
|
+
*/
|
|
25
|
+
const getOutputFilePath = (filePath, locale, baseLocale) => {
|
|
26
|
+
if (!filePath || !locale || !baseLocale) throw new Error("filePath, locale, and baseLocale are required");
|
|
27
|
+
let outputFilePath = filePath;
|
|
28
|
+
const replacements = [
|
|
29
|
+
{
|
|
30
|
+
pattern: /\{\{baseLocale\}\}/g,
|
|
31
|
+
replacement: "{{locale}}"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
pattern: /\{\{baseLocaleName\}\}/g,
|
|
35
|
+
replacement: "{{localeName}}"
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
pattern: new RegExp(`/${baseLocale}/`, "g"),
|
|
39
|
+
replacement: `/${locale}/`
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
pattern: new RegExp(`\\\\${baseLocale}\\\\`, "g"),
|
|
43
|
+
replacement: `\\${locale}\\`
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
pattern: new RegExp(`_${baseLocale}\\.`, "g"),
|
|
47
|
+
replacement: `_${locale}.`
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
pattern: new RegExp(`/${baseLocale}_`, "g"),
|
|
51
|
+
replacement: `/${locale}_`
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
pattern: new RegExp(`(^|[\\/])${baseLocale}_`, "g"),
|
|
55
|
+
replacement: `$1${locale}_`
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
pattern: new RegExp(`\\.${baseLocale}\\.`, "g"),
|
|
59
|
+
replacement: `.${locale}.`
|
|
60
|
+
}
|
|
61
|
+
];
|
|
62
|
+
for (const { pattern, replacement } of replacements) outputFilePath = outputFilePath.replace(pattern, replacement);
|
|
63
|
+
if (outputFilePath === filePath) {
|
|
64
|
+
const lastDotIndex = filePath.lastIndexOf(".");
|
|
65
|
+
if (lastDotIndex > 0) return `${filePath.slice(0, lastDotIndex)}.${locale}${filePath.slice(lastDotIndex)}`;
|
|
66
|
+
else return `${filePath}.${locale}`;
|
|
67
|
+
}
|
|
68
|
+
return outputFilePath;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
export { getOutputFilePath };
|
|
2
73
|
//# sourceMappingURL=getOutputFilePath.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getOutputFilePath.mjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Get the output file path by replacing the base locale with the target locale\n *\n * This function handles two types of replacements:\n * 1. Actual locale values (e.g., `/en/` → `/fr/`)\n * 2. Template placeholders (e.g., `{{baseLocale}}` → `{{locale}}`, `{{baseLocaleName}}` → `{{localeName}}`)\n *\n * Replacement patterns:\n * - `/baseLocale/` → `/locale/`\n * - `\\baseLocale\\` → `\\locale\\`\n * - `_baseLocale.` → `_locale.`\n * - `baseLocale_` → `locale_`\n * - `.baseLocaleName.` → `.localeName.`\n * - `{{baseLocale}}` → `{{locale}}`\n * - `{{baseLocaleName}}` → `{{localeName}}`\n *\n * If no patterns match, appends `.locale` to the file extension.\n *\n * @param filePath - The input file path\n * @param locale - The target locale\n * @param baseLocale - The base locale to replace\n * @returns The output file path with locale replacements\n */\nexport const getOutputFilePath = (\n filePath: string,\n locale: LocalesValues,\n baseLocale: LocalesValues\n): string => {\n if (!filePath || !locale || !baseLocale) {\n throw new Error('filePath, locale, and baseLocale are required');\n }\n\n let outputFilePath = filePath;\n\n // Define replacement patterns with global flag to replace all occurrences\n const replacements = [\n // Template placeholders (processed first)\n {\n pattern: /\\{\\{baseLocale\\}\\}/g,\n replacement: '{{locale}}',\n },\n {\n pattern: /\\{\\{baseLocaleName\\}\\}/g,\n replacement: '{{localeName}}',\n },\n\n // Path separators (most specific first)\n {\n // Unix path separators\n pattern: new RegExp(`/${baseLocale}/`, 'g'),\n replacement: `/${locale}/`,\n },\n {\n // Windows path separators\n pattern: new RegExp(`\\\\\\\\${baseLocale}\\\\\\\\`, 'g'),\n replacement: `\\\\${locale}\\\\`,\n },\n\n // File naming patterns\n {\n // file_en.md → file_fr.md\n pattern: new RegExp(`_${baseLocale}\\\\.`, 'g'),\n replacement: `_${locale}.`,\n },\n {\n // /file_en.md → /file_fr.md\n pattern: new RegExp(`/${baseLocale}_`, 'g'),\n replacement: `/${locale}_`,\n },\n {\n // Start of filename pattern en_guide.md → fr_guide.md (or after path separator)\n pattern: new RegExp(`(^|[\\\\/])${baseLocale}_`, 'g'),\n replacement: `$1${locale}_`,\n },\n {\n // Dot delimited pattern guide.en.md → guide.fr.md\n pattern: new RegExp(`\\\\.${baseLocale}\\\\.`, 'g'),\n replacement: `.${locale}.`,\n },\n ];\n\n // Apply all replacements\n for (const { pattern, replacement } of replacements) {\n outputFilePath = outputFilePath.replace(pattern, replacement);\n }\n\n // If no changes were made, append locale as extension\n if (outputFilePath === filePath) {\n const lastDotIndex = filePath.lastIndexOf('.');\n if (lastDotIndex > 0) {\n // Insert locale before the file extension\n return `${filePath.slice(0, lastDotIndex)}.${locale}${filePath.slice(lastDotIndex)}`;\n } else {\n // No extension found, just append\n return `${filePath}.${locale}`;\n }\n }\n\n return outputFilePath;\n};\n"],"mappings":"AAyBA,MAAa,
|
|
1
|
+
{"version":3,"file":"getOutputFilePath.mjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Get the output file path by replacing the base locale with the target locale\n *\n * This function handles two types of replacements:\n * 1. Actual locale values (e.g., `/en/` → `/fr/`)\n * 2. Template placeholders (e.g., `{{baseLocale}}` → `{{locale}}`, `{{baseLocaleName}}` → `{{localeName}}`)\n *\n * Replacement patterns:\n * - `/baseLocale/` → `/locale/`\n * - `\\baseLocale\\` → `\\locale\\`\n * - `_baseLocale.` → `_locale.`\n * - `baseLocale_` → `locale_`\n * - `.baseLocaleName.` → `.localeName.`\n * - `{{baseLocale}}` → `{{locale}}`\n * - `{{baseLocaleName}}` → `{{localeName}}`\n *\n * If no patterns match, appends `.locale` to the file extension.\n *\n * @param filePath - The input file path\n * @param locale - The target locale\n * @param baseLocale - The base locale to replace\n * @returns The output file path with locale replacements\n */\nexport const getOutputFilePath = (\n filePath: string,\n locale: LocalesValues,\n baseLocale: LocalesValues\n): string => {\n if (!filePath || !locale || !baseLocale) {\n throw new Error('filePath, locale, and baseLocale are required');\n }\n\n let outputFilePath = filePath;\n\n // Define replacement patterns with global flag to replace all occurrences\n const replacements = [\n // Template placeholders (processed first)\n {\n pattern: /\\{\\{baseLocale\\}\\}/g,\n replacement: '{{locale}}',\n },\n {\n pattern: /\\{\\{baseLocaleName\\}\\}/g,\n replacement: '{{localeName}}',\n },\n\n // Path separators (most specific first)\n {\n // Unix path separators\n pattern: new RegExp(`/${baseLocale}/`, 'g'),\n replacement: `/${locale}/`,\n },\n {\n // Windows path separators\n pattern: new RegExp(`\\\\\\\\${baseLocale}\\\\\\\\`, 'g'),\n replacement: `\\\\${locale}\\\\`,\n },\n\n // File naming patterns\n {\n // file_en.md → file_fr.md\n pattern: new RegExp(`_${baseLocale}\\\\.`, 'g'),\n replacement: `_${locale}.`,\n },\n {\n // /file_en.md → /file_fr.md\n pattern: new RegExp(`/${baseLocale}_`, 'g'),\n replacement: `/${locale}_`,\n },\n {\n // Start of filename pattern en_guide.md → fr_guide.md (or after path separator)\n pattern: new RegExp(`(^|[\\\\/])${baseLocale}_`, 'g'),\n replacement: `$1${locale}_`,\n },\n {\n // Dot delimited pattern guide.en.md → guide.fr.md\n pattern: new RegExp(`\\\\.${baseLocale}\\\\.`, 'g'),\n replacement: `.${locale}.`,\n },\n ];\n\n // Apply all replacements\n for (const { pattern, replacement } of replacements) {\n outputFilePath = outputFilePath.replace(pattern, replacement);\n }\n\n // If no changes were made, append locale as extension\n if (outputFilePath === filePath) {\n const lastDotIndex = filePath.lastIndexOf('.');\n if (lastDotIndex > 0) {\n // Insert locale before the file extension\n return `${filePath.slice(0, lastDotIndex)}.${locale}${filePath.slice(lastDotIndex)}`;\n } else {\n // No extension found, just append\n return `${filePath}.${locale}`;\n }\n }\n\n return outputFilePath;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,qBACX,UACA,QACA,eACW;AACX,KAAI,CAAC,YAAY,CAAC,UAAU,CAAC,WAC3B,OAAM,IAAI,MAAM,gDAAgD;CAGlE,IAAI,iBAAiB;CAGrB,MAAM,eAAe;EAEnB;GACE,SAAS;GACT,aAAa;GACd;EACD;GACE,SAAS;GACT,aAAa;GACd;EAGD;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,IAAI,IAAI;GAC3C,aAAa,IAAI,OAAO;GACzB;EACD;GAEE,SAAS,IAAI,OAAO,OAAO,WAAW,OAAO,IAAI;GACjD,aAAa,KAAK,OAAO;GAC1B;EAGD;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,MAAM,IAAI;GAC7C,aAAa,IAAI,OAAO;GACzB;EACD;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,IAAI,IAAI;GAC3C,aAAa,IAAI,OAAO;GACzB;EACD;GAEE,SAAS,IAAI,OAAO,YAAY,WAAW,IAAI,IAAI;GACnD,aAAa,KAAK,OAAO;GAC1B;EACD;GAEE,SAAS,IAAI,OAAO,MAAM,WAAW,MAAM,IAAI;GAC/C,aAAa,IAAI,OAAO;GACzB;EACF;AAGD,MAAK,MAAM,EAAE,SAAS,iBAAiB,aACrC,kBAAiB,eAAe,QAAQ,SAAS,YAAY;AAI/D,KAAI,mBAAmB,UAAU;EAC/B,MAAM,eAAe,SAAS,YAAY,IAAI;AAC9C,MAAI,eAAe,EAEjB,QAAO,GAAG,SAAS,MAAM,GAAG,aAAa,CAAC,GAAG,SAAS,SAAS,MAAM,aAAa;MAGlF,QAAO,GAAG,SAAS,GAAG;;AAI1B,QAAO"}
|
|
@@ -1,2 +1,19 @@
|
|
|
1
|
-
import{existsSync
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region src/utils/getParentPackageJSON.ts
|
|
5
|
+
const getParentPackageJSON = (startDir) => {
|
|
6
|
+
let currentDir = startDir;
|
|
7
|
+
while (currentDir !== dirname(currentDir)) {
|
|
8
|
+
const packageJsonPath = resolve(currentDir, "package.json");
|
|
9
|
+
if (existsSync(packageJsonPath)) return JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
|
10
|
+
currentDir = dirname(currentDir);
|
|
11
|
+
}
|
|
12
|
+
const rootPackageJsonPath = resolve(currentDir, "package.json");
|
|
13
|
+
if (existsSync(rootPackageJsonPath)) return JSON.parse(readFileSync(rootPackageJsonPath, "utf8"));
|
|
14
|
+
throw new Error(`No package.json found in any parent directory of ${startDir}`);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
//#endregion
|
|
18
|
+
export { getParentPackageJSON };
|
|
2
19
|
//# sourceMappingURL=getParentPackageJSON.mjs.map
|
|
@@ -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":"
|
|
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;AAEjB,QAAO,eAAe,QAAQ,WAAW,EAAE;EAEzC,MAAM,kBAAkB,QAAQ,YAAY,eAAe;AAE3D,MAAI,WAAW,gBAAgB,CAC7B,QAAO,KAAK,MAAM,aAAa,iBAAiB,OAAO,CAAC;AAI1D,eAAa,QAAQ,WAAW;;CAIlC,MAAM,sBAAsB,QAAQ,YAAY,eAAe;AAC/D,KAAI,WAAW,oBAAoB,CACjC,QAAO,KAAK,MAAM,aAAa,qBAAqB,OAAO,CAAC;AAI9D,OAAM,IAAI,MACR,oDAAoD,WACrD"}
|
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
//#region src/utils/listSpecialChars.ts
|
|
2
|
+
const SPECIAL_CHARS = [
|
|
3
|
+
" ",
|
|
4
|
+
"\\",
|
|
5
|
+
"|",
|
|
6
|
+
"(",
|
|
7
|
+
")",
|
|
8
|
+
"{",
|
|
9
|
+
"}",
|
|
10
|
+
"[",
|
|
11
|
+
"]",
|
|
12
|
+
"<",
|
|
13
|
+
">",
|
|
14
|
+
"\"",
|
|
15
|
+
"=",
|
|
16
|
+
"+",
|
|
17
|
+
"*",
|
|
18
|
+
"&",
|
|
19
|
+
"#",
|
|
20
|
+
"%",
|
|
21
|
+
"$",
|
|
22
|
+
"!",
|
|
23
|
+
"?",
|
|
24
|
+
":",
|
|
25
|
+
";",
|
|
26
|
+
"~"
|
|
27
|
+
];
|
|
28
|
+
const listSpecialChars = (text) => {
|
|
29
|
+
const results = [];
|
|
30
|
+
let lineIndex = 0;
|
|
31
|
+
for (let i = 0; i < text.length; i++) {
|
|
32
|
+
const currentChar = text[i];
|
|
33
|
+
if (currentChar === "\n") {
|
|
34
|
+
results.push({
|
|
35
|
+
char: "\\",
|
|
36
|
+
lineStart: lineIndex,
|
|
37
|
+
charStart: i
|
|
38
|
+
});
|
|
39
|
+
lineIndex++;
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (SPECIAL_CHARS.includes(currentChar)) results.push({
|
|
43
|
+
char: currentChar,
|
|
44
|
+
lineStart: lineIndex,
|
|
45
|
+
charStart: i
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return results;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
//#endregion
|
|
52
|
+
export { listSpecialChars };
|
|
3
53
|
//# sourceMappingURL=listSpecialChars.mjs.map
|
|
@@ -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,
|
|
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;CACD;AAED,MAAa,oBAAoB,SAAiC;CAChE,MAAM,UAA0B,EAAE;CAElC,IAAI,YAAY;AAEhB,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,cAAc,KAAK;AAGzB,MAAI,gBAAgB,MAAM;AACxB,WAAQ,KAAK;IACX,MAAM;IACN,WAAW;IACX,WAAW;IACZ,CAAC;AAGF;AACA;;AAIF,MAAI,cAAc,SAAS,YAAY,CACrC,SAAQ,KAAK;GACX,MAAM;GACN,WAAW;GACX,WAAW;GACZ,CAAC;;AAIN,QAAO"}
|
|
@@ -1,2 +1,101 @@
|
|
|
1
|
-
import{chunkText
|
|
1
|
+
import { chunkText } from "./calculateChunks.mjs";
|
|
2
|
+
import { splitTextByLines } from "@intlayer/chokidar/utils";
|
|
3
|
+
|
|
4
|
+
//#region src/utils/mapChunksBetweenFiles.ts
|
|
5
|
+
/**
|
|
6
|
+
* Maps chunks from base file to corresponding chunks in updated file,
|
|
7
|
+
* handling insertions, deletions, and modifications properly.
|
|
8
|
+
*/
|
|
9
|
+
const mapChunksBetweenFiles = (baseFileContent, updatedFileContent, maxCharsPerChunk = 800, changedLines) => {
|
|
10
|
+
const baseChunks = chunkText(baseFileContent, maxCharsPerChunk, 0);
|
|
11
|
+
const baseLines = splitTextByLines(baseFileContent);
|
|
12
|
+
const updatedLines = splitTextByLines(updatedFileContent);
|
|
13
|
+
const lineMapping = createLineMapping(baseLines, updatedLines);
|
|
14
|
+
return baseChunks.map((baseChunk) => {
|
|
15
|
+
const mappedRange = mapLineRange(baseChunk.lineStart, baseChunk.lineLength, lineMapping);
|
|
16
|
+
if (!mappedRange) return {
|
|
17
|
+
baseChunk,
|
|
18
|
+
updatedChunk: null,
|
|
19
|
+
hasChanges: true
|
|
20
|
+
};
|
|
21
|
+
const updatedChunk = {
|
|
22
|
+
lineStart: mappedRange.start,
|
|
23
|
+
lineLength: mappedRange.length,
|
|
24
|
+
charStart: 0,
|
|
25
|
+
charLength: 0,
|
|
26
|
+
content: extractLinesFromRange(updatedLines, mappedRange.start, mappedRange.length)
|
|
27
|
+
};
|
|
28
|
+
updatedChunk.charStart = getCharStartForLine(updatedFileContent, updatedChunk.lineStart);
|
|
29
|
+
updatedChunk.charLength = updatedChunk.content.length;
|
|
30
|
+
return {
|
|
31
|
+
baseChunk,
|
|
32
|
+
updatedChunk,
|
|
33
|
+
hasChanges: determineIfChunkHasChanges(baseChunk, updatedChunk, changedLines)
|
|
34
|
+
};
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Creates a mapping between line numbers in base file and updated file
|
|
39
|
+
* Returns a map where key = base line number, value = updated line number (or null if deleted)
|
|
40
|
+
*/
|
|
41
|
+
const createLineMapping = (baseLines, updatedLines) => {
|
|
42
|
+
const mapping = /* @__PURE__ */ new Map();
|
|
43
|
+
const dp = Array(baseLines.length + 1).fill(null).map(() => Array(updatedLines.length + 1).fill(0));
|
|
44
|
+
for (let i = 1; i <= baseLines.length; i++) for (let j = 1; j <= updatedLines.length; j++) if (baseLines[i - 1] === updatedLines[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
|
|
45
|
+
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
|
|
46
|
+
let i = baseLines.length;
|
|
47
|
+
let j = updatedLines.length;
|
|
48
|
+
while (i > 0 || j > 0) if (i > 0 && j > 0 && baseLines[i - 1] === updatedLines[j - 1]) {
|
|
49
|
+
mapping.set(i - 1, j - 1);
|
|
50
|
+
i--;
|
|
51
|
+
j--;
|
|
52
|
+
} else if (i > 0 && (j === 0 || dp[i - 1][j] >= dp[i][j - 1])) {
|
|
53
|
+
mapping.set(i - 1, null);
|
|
54
|
+
i--;
|
|
55
|
+
} else j--;
|
|
56
|
+
return mapping;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Maps a line range from base file to updated file using the line mapping
|
|
60
|
+
*/
|
|
61
|
+
const mapLineRange = (baseStart, baseLength, lineMapping) => {
|
|
62
|
+
const mappedLines = [];
|
|
63
|
+
for (let i = baseStart; i < baseStart + baseLength; i++) {
|
|
64
|
+
const mappedLine = lineMapping.get(i);
|
|
65
|
+
if (mappedLine !== null && mappedLine !== void 0) mappedLines.push(mappedLine);
|
|
66
|
+
}
|
|
67
|
+
if (mappedLines.length === 0) return null;
|
|
68
|
+
mappedLines.sort((a, b) => a - b);
|
|
69
|
+
const start = mappedLines[0];
|
|
70
|
+
return {
|
|
71
|
+
start,
|
|
72
|
+
length: mappedLines[mappedLines.length - 1] - start + 1
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Extracts lines from a range in the lines array
|
|
77
|
+
*/
|
|
78
|
+
const extractLinesFromRange = (lines, start, length) => {
|
|
79
|
+
const endIndex = Math.min(start + length, lines.length);
|
|
80
|
+
return lines.slice(start, endIndex).join("");
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Gets the character position where a line starts in the text
|
|
84
|
+
*/
|
|
85
|
+
const getCharStartForLine = (text, lineNumber) => {
|
|
86
|
+
const lines = splitTextByLines(text);
|
|
87
|
+
let charStart = 0;
|
|
88
|
+
for (let i = 0; i < Math.min(lineNumber, lines.length); i++) charStart += lines[i].length;
|
|
89
|
+
return charStart;
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Determines if a chunk has changes based on git changed lines or content comparison
|
|
93
|
+
*/
|
|
94
|
+
const determineIfChunkHasChanges = (baseChunk, updatedChunk, changedLines) => {
|
|
95
|
+
if (changedLines && changedLines.length > 0) return changedLines.some((line) => line >= updatedChunk.lineStart && line < updatedChunk.lineStart + updatedChunk.lineLength);
|
|
96
|
+
return baseChunk.content !== updatedChunk.content;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
//#endregion
|
|
100
|
+
export { mapChunksBetweenFiles };
|
|
2
101
|
//# sourceMappingURL=mapChunksBetweenFiles.mjs.map
|
|
@@ -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":"
|
|
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,EAAE;CAClE,MAAM,YAAY,iBAAiB,gBAAgB;CACnD,MAAM,eAAe,iBAAiB,mBAAmB;CAGzD,MAAM,cAAc,kBAAkB,WAAW,aAAa;AAE9D,QAAO,WAAW,KAAK,cAA4B;EAEjD,MAAM,cAAc,aAClB,UAAU,WACV,UAAU,YACV,YACD;AAED,MAAI,CAAC,YAEH,QAAO;GACL;GACA,cAAc;GACd,YAAY;GACb;EAIH,MAAM,eAAgC;GACpC,WAAW,YAAY;GACvB,YAAY,YAAY;GACxB,WAAW;GACX,YAAY;GACZ,SAAS,sBACP,cACA,YAAY,OACZ,YAAY,OACb;GACF;AAGD,eAAa,YAAY,oBACvB,oBACA,aAAa,UACd;AACD,eAAa,aAAa,aAAa,QAAQ;AAS/C,SAAO;GACL;GACA;GACA,YATiB,2BACjB,WACA,cACA,aACD;GAMA;GACD;;;;;;AAOJ,MAAM,qBACJ,WACA,iBAC+B;CAC/B,MAAM,0BAAU,IAAI,KAA4B;CAGhD,MAAM,KAAiB,MAAM,UAAU,SAAS,EAAE,CAC/C,KAAK,KAAK,CACV,UAAU,MAAM,aAAa,SAAS,EAAE,CAAC,KAAK,EAAE,CAAC;AAGpD,MAAK,IAAI,IAAI,GAAG,KAAK,UAAU,QAAQ,IACrC,MAAK,IAAI,IAAI,GAAG,KAAK,aAAa,QAAQ,IACxC,KAAI,UAAU,IAAI,OAAO,aAAa,IAAI,GACxC,IAAG,GAAG,KAAK,GAAG,IAAI,GAAG,IAAI,KAAK;KAE9B,IAAG,GAAG,KAAK,KAAK,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,GAAG,IAAI,GAAG;CAMrD,IAAI,IAAI,UAAU;CAClB,IAAI,IAAI,aAAa;AAErB,QAAO,IAAI,KAAK,IAAI,EAClB,KAAI,IAAI,KAAK,IAAI,KAAK,UAAU,IAAI,OAAO,aAAa,IAAI,IAAI;AAE9D,UAAQ,IAAI,IAAI,GAAG,IAAI,EAAE;AACzB;AACA;YACS,IAAI,MAAM,MAAM,KAAK,GAAG,IAAI,GAAG,MAAM,GAAG,GAAG,IAAI,KAAK;AAE7D,UAAQ,IAAI,IAAI,GAAG,KAAK;AACxB;OAGA;AAIJ,QAAO;;;;;AAMT,MAAM,gBACJ,WACA,YACA,gBAC6C;CAC7C,MAAM,cAAwB,EAAE;AAEhC,MAAK,IAAI,IAAI,WAAW,IAAI,YAAY,YAAY,KAAK;EACvD,MAAM,aAAa,YAAY,IAAI,EAAE;AACrC,MAAI,eAAe,QAAQ,eAAe,OACxC,aAAY,KAAK,WAAW;;AAIhC,KAAI,YAAY,WAAW,EACzB,QAAO;AAIT,aAAY,MAAM,GAAG,MAAM,IAAI,EAAE;CACjC,MAAM,QAAQ,YAAY;AAG1B,QAAO;EACL;EACA,QAJU,YAAY,YAAY,SAAS,KAI7B,QAAQ;EACvB;;;;;AAMH,MAAM,yBACJ,OACA,OACA,WACW;CACX,MAAM,WAAW,KAAK,IAAI,QAAQ,QAAQ,MAAM,OAAO;AACvD,QAAO,MAAM,MAAM,OAAO,SAAS,CAAC,KAAK,GAAG;;;;;AAM9C,MAAM,uBAAuB,MAAc,eAA+B;CACxE,MAAM,QAAQ,iBAAiB,KAAK;CACpC,IAAI,YAAY;AAEhB,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,IAAI,YAAY,MAAM,OAAO,EAAE,IACtD,cAAa,MAAM,GAAG;AAGxB,QAAO;;;;;AAMT,MAAM,8BACJ,WACA,cACA,iBACY;AAEZ,KAAI,gBAAgB,aAAa,SAAS,EACxC,QAAO,aAAa,MACjB,SACC,QAAQ,aAAa,aACrB,OAAO,aAAa,YAAY,aAAa,WAChD;AAIH,QAAO,UAAU,YAAY,aAAa"}
|
|
@@ -1,2 +1,18 @@
|
|
|
1
|
-
import{exec
|
|
1
|
+
import { exec } from "node:child_process";
|
|
2
|
+
import { platform } from "node:os";
|
|
3
|
+
|
|
4
|
+
//#region src/utils/openBrowser.ts
|
|
5
|
+
const openBrowser = (url) => {
|
|
6
|
+
const osPlatform = platform();
|
|
7
|
+
let command = "";
|
|
8
|
+
if (osPlatform === "darwin") command = `open "${url}"`;
|
|
9
|
+
else if (osPlatform === "win32") command = `start "${url}"`;
|
|
10
|
+
else command = `xdg-open "${url}"`;
|
|
11
|
+
exec(command, (error) => {
|
|
12
|
+
if (error) console.error(`Failed to open browser: ${error.message}`);
|
|
13
|
+
});
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
//#endregion
|
|
17
|
+
export { openBrowser };
|
|
2
18
|
//# sourceMappingURL=openBrowser.mjs.map
|
|
@@ -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":"
|
|
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,UAAU;CAC7B,IAAI,UAAU;AAEd,KAAI,eAAe,SACjB,WAAU,SAAS,IAAI;UACd,eAAe,QACxB,WAAU,UAAU,IAAI;KAExB,WAAU,aAAa,IAAI;AAG7B,MAAK,UAAU,UAAU;AACvB,MAAI,MACF,SAAQ,MAAM,2BAA2B,MAAM,UAAU;GAE3D"}
|
|
@@ -1,6 +1,93 @@
|
|
|
1
|
-
import{listSpecialChars
|
|
1
|
+
import { listSpecialChars } from "./listSpecialChars.mjs";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
//#region src/utils/reorderParagraphs.ts
|
|
4
|
+
/**
|
|
5
|
+
* Split a text into paragraphs.
|
|
6
|
+
*
|
|
7
|
+
* We consider a paragraph boundary to be a block of at least two consecutive
|
|
8
|
+
* new-lines that is immediately followed by a non-white-space character. This
|
|
9
|
+
* way, internal blank lines that are part of the same paragraph (e.g. a list
|
|
10
|
+
* item that purposely contains a visual break) are preserved while true
|
|
11
|
+
* paragraph breaks – the ones generated when calling `arr.join("\n\n")` in
|
|
12
|
+
* the tests – are still detected.
|
|
13
|
+
*/
|
|
14
|
+
const splitByParagraph = (text) => {
|
|
15
|
+
const paragraphs = [];
|
|
16
|
+
const tokens = text.split(/(\n{2,})/);
|
|
17
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
18
|
+
const token = tokens[i];
|
|
19
|
+
if (i % 2 === 0) {
|
|
20
|
+
if (token) paragraphs.push(token);
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
const pairsOfNewlines = Math.floor(token.length / 2);
|
|
24
|
+
const blankParagraphs = Math.max(0, pairsOfNewlines - 2);
|
|
25
|
+
for (let j = 0; j < blankParagraphs; j++) paragraphs.push("\n\n");
|
|
26
|
+
}
|
|
27
|
+
return paragraphs;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Determine whether two paragraphs match – either exactly, or by sharing the
|
|
31
|
+
* same "special-character signature".
|
|
32
|
+
*/
|
|
33
|
+
const paragraphMatches = (paragraph, baseParagraph, paragraphSignature, baseSignature) => {
|
|
34
|
+
if (paragraph === baseParagraph) return true;
|
|
35
|
+
if (paragraphSignature.length !== baseSignature.length) return false;
|
|
36
|
+
for (let i = 0; i < paragraphSignature.length; i++) if (paragraphSignature[i].char !== baseSignature[i].char) return false;
|
|
37
|
+
return true;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Re-order `textToReorder` so that its paragraphs follow the ordering found in
|
|
41
|
+
* `baseFileContent`, while preserving any extra paragraphs (those not present
|
|
42
|
+
* in the base file) in a position that is intuitive for a human reader: right
|
|
43
|
+
* after the closest preceding paragraph coming from the base file.
|
|
44
|
+
*/
|
|
45
|
+
const reorderParagraphs = (textToReorder, baseFileContent) => {
|
|
46
|
+
const baseFileParagraphs = splitByParagraph(baseFileContent);
|
|
47
|
+
const textToReorderParagraphs = splitByParagraph(textToReorder);
|
|
48
|
+
const baseSignatures = baseFileParagraphs.map((p) => listSpecialChars(p));
|
|
49
|
+
const textSignatures = textToReorderParagraphs.map((p) => listSpecialChars(p));
|
|
50
|
+
const firstMatchIndexForBase = Array(baseFileParagraphs.length).fill(-1);
|
|
51
|
+
const paragraphMatchedBaseIdx = Array(textToReorderParagraphs.length).fill(null);
|
|
52
|
+
for (let i = 0; i < textToReorderParagraphs.length; i++) {
|
|
53
|
+
const paragraph = textToReorderParagraphs[i];
|
|
54
|
+
const sig = textSignatures[i];
|
|
55
|
+
let foundIdx = baseFileParagraphs.findIndex((baseParagraph, idx) => firstMatchIndexForBase[idx] === -1 && paragraph === baseParagraph);
|
|
56
|
+
if (foundIdx === -1) foundIdx = baseFileParagraphs.findIndex((baseParagraph, idx) => firstMatchIndexForBase[idx] === -1 && paragraphMatches(paragraph, baseParagraph, sig, baseSignatures[idx]));
|
|
57
|
+
if (foundIdx !== -1) {
|
|
58
|
+
firstMatchIndexForBase[foundIdx] = i;
|
|
59
|
+
paragraphMatchedBaseIdx[i] = foundIdx;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const insertAfterBaseIdx = Array(textToReorderParagraphs.length).fill(-1);
|
|
63
|
+
let maxBaseIdxEncountered = -1;
|
|
64
|
+
for (let i = 0; i < textToReorderParagraphs.length; i++) {
|
|
65
|
+
const matchedBase = paragraphMatchedBaseIdx[i];
|
|
66
|
+
if (matchedBase !== null) {
|
|
67
|
+
if (matchedBase > maxBaseIdxEncountered) maxBaseIdxEncountered = matchedBase;
|
|
68
|
+
} else insertAfterBaseIdx[i] = maxBaseIdxEncountered;
|
|
69
|
+
}
|
|
70
|
+
const result = [];
|
|
71
|
+
const extraParagraphsBuckets = {};
|
|
72
|
+
insertAfterBaseIdx.forEach((afterIdx, paragraphIdx) => {
|
|
73
|
+
if (afterIdx === -1) return;
|
|
74
|
+
extraParagraphsBuckets[afterIdx] = extraParagraphsBuckets[afterIdx] || [];
|
|
75
|
+
extraParagraphsBuckets[afterIdx].push(paragraphIdx);
|
|
76
|
+
});
|
|
77
|
+
for (let bIdx = 0; bIdx < baseFileParagraphs.length; bIdx++) {
|
|
78
|
+
const matchedParagraphIdx = firstMatchIndexForBase[bIdx];
|
|
79
|
+
if (matchedParagraphIdx !== -1) result.push(textToReorderParagraphs[matchedParagraphIdx]);
|
|
80
|
+
if (extraParagraphsBuckets[bIdx]) extraParagraphsBuckets[bIdx].forEach((pIdx) => {
|
|
81
|
+
result.push(textToReorderParagraphs[pIdx]);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const leadingExtras = [];
|
|
85
|
+
insertAfterBaseIdx.forEach((afterIdx, pIdx) => {
|
|
86
|
+
if (afterIdx === -1 && paragraphMatchedBaseIdx[pIdx] === null) leadingExtras.push(textToReorderParagraphs[pIdx]);
|
|
87
|
+
});
|
|
88
|
+
return [...leadingExtras, ...result].join("\n\n");
|
|
89
|
+
};
|
|
4
90
|
|
|
5
|
-
|
|
91
|
+
//#endregion
|
|
92
|
+
export { reorderParagraphs };
|
|
6
93
|
//# sourceMappingURL=reorderParagraphs.mjs.map
|
|
@@ -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":"
|
|
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,EAAE;CAK/B,MAAM,SAAS,KAAK,MAAM,WAAW;AAErC,MAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;EACtC,MAAM,QAAQ,OAAO;AAGrB,MAAI,IAAI,MAAM,GAAG;AACf,OAAI,MAAO,YAAW,KAAK,MAAM;AACjC;;EAQF,MAAM,kBAAkB,KAAK,MAAM,MAAM,SAAS,EAAE;EACpD,MAAM,kBAAkB,KAAK,IAAI,GAAG,kBAAkB,EAAE;AAExD,OAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,IACnC,YAAW,KAAK,OAAO;;AAI3B,QAAO;;;;;;AAOT,MAAM,oBACJ,WACA,eACA,oBACA,kBACY;AACZ,KAAI,cAAc,cAAe,QAAO;AAExC,KAAI,mBAAmB,WAAW,cAAc,OAAQ,QAAO;AAE/D,MAAK,IAAI,IAAI,GAAG,IAAI,mBAAmB,QAAQ,IAC7C,KAAI,mBAAmB,GAAG,SAAS,cAAc,GAAG,KAClD,QAAO;AAGX,QAAO;;;;;;;;AAST,MAAa,qBACX,eACA,oBACW;CAEX,MAAM,qBAAqB,iBAAiB,gBAAgB;CAC5D,MAAM,0BAA0B,iBAAiB,cAAc;CAE/D,MAAM,iBAAiB,mBAAmB,KAAK,MAAM,iBAAiB,EAAE,CAAC;CACzE,MAAM,iBAAiB,wBAAwB,KAAK,MAClD,iBAAiB,EAAE,CACpB;CAMD,MAAM,yBAAmC,MACvC,mBAAmB,OACpB,CAAC,KAAK,GAAG;CACV,MAAM,0BAA6C,MACjD,wBAAwB,OACzB,CAAC,KAAK,KAAK;AAEZ,MAAK,IAAI,IAAI,GAAG,IAAI,wBAAwB,QAAQ,KAAK;EACvD,MAAM,YAAY,wBAAwB;EAC1C,MAAM,MAAM,eAAe;EAG3B,IAAI,WAAW,mBAAmB,WAC/B,eAAe,QACd,uBAAuB,SAAS,MAAM,cAAc,cACvD;AAED,MAAI,aAAa,GAEf,YAAW,mBAAmB,WAC3B,eAAe,QACd,uBAAuB,SAAS,MAChC,iBAAiB,WAAW,eAAe,KAAK,eAAe,KAAK,CACvE;AAGH,MAAI,aAAa,IAAI;AACnB,0BAAuB,YAAY;AACnC,2BAAwB,KAAK;;;CAQjC,MAAM,qBAA+B,MACnC,wBAAwB,OACzB,CAAC,KAAK,GAAG;CACV,IAAI,wBAAwB;AAE5B,MAAK,IAAI,IAAI,GAAG,IAAI,wBAAwB,QAAQ,KAAK;EACvD,MAAM,cAAc,wBAAwB;AAE5C,MAAI,gBAAgB,MAClB;OAAI,cAAc,sBAChB,yBAAwB;QAG1B,oBAAmB,KAAK;;CAK5B,MAAM,SAAmB,EAAE;CAI3B,MAAM,yBAAmD,EAAE;AAC3D,oBAAmB,SAAS,UAAU,iBAAiB;AACrD,MAAI,aAAa,GAAI;AACrB,yBAAuB,YAAY,uBAAuB,aAAa,EAAE;AACzE,yBAAuB,UAAU,KAAK,aAAa;GACnD;AAEF,MAAK,IAAI,OAAO,GAAG,OAAO,mBAAmB,QAAQ,QAAQ;EAC3D,MAAM,sBAAsB,uBAAuB;AAEnD,MAAI,wBAAwB,GAC1B,QAAO,KAAK,wBAAwB,qBAAqB;AAG3D,MAAI,uBAAuB,MACzB,wBAAuB,MAAM,SAAS,SAAS;AAC7C,UAAO,KAAK,wBAAwB,MAAM;IAC1C;;CAON,MAAM,gBAA0B,EAAE;AAClC,oBAAmB,SAAS,UAAU,SAAS;AAC7C,MAAI,aAAa,MAAM,wBAAwB,UAAU,KACvD,eAAc,KAAK,wBAAwB,MAAM;GAEnD;AAEF,QAAO,CAAC,GAAG,eAAe,GAAG,OAAO,CAAC,KAAK,OAAO"}
|
|
@@ -1,2 +1,64 @@
|
|
|
1
|
-
import{checkAIAccess
|
|
1
|
+
import { checkAIAccess } from "./checkAccess.mjs";
|
|
2
|
+
import * as ANSIColors from "@intlayer/config/colors";
|
|
3
|
+
import { colorize, getAppLogger } from "@intlayer/config/logger";
|
|
4
|
+
|
|
5
|
+
//#region src/utils/setupAI.ts
|
|
6
|
+
globalThis.AI_SDK_LOG_WARNINGS = false;
|
|
7
|
+
const logAIConfig = (aiOptions, appLogger) => {
|
|
8
|
+
appLogger([
|
|
9
|
+
colorize("Provider:", ANSIColors.GREY_DARK),
|
|
10
|
+
colorize(aiOptions?.provider ?? "(default)", ANSIColors.BLUE),
|
|
11
|
+
colorize("- Model:", ANSIColors.GREY_DARK),
|
|
12
|
+
colorize(aiOptions?.model ?? "(default)", ANSIColors.BLUE),
|
|
13
|
+
colorize("- API Key:", ANSIColors.GREY_DARK),
|
|
14
|
+
colorize(aiOptions?.apiKey ? "✓" : "(not set)", ANSIColors.BLUE)
|
|
15
|
+
]);
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Checks if the @intlayer/ai package is available and configured when an API key is provided.
|
|
19
|
+
* If API key is present but package is missing, logs a warning.
|
|
20
|
+
* Also checks if the user has access to AI (either via local key or CMS auth).
|
|
21
|
+
*/
|
|
22
|
+
const setupAI = async (configuration, aiOptions) => {
|
|
23
|
+
const appLogger = getAppLogger(configuration);
|
|
24
|
+
if (aiOptions?.apiKey || aiOptions?.provider === "ollama" || configuration.ai?.apiKey || configuration.ai?.provider === "ollama") {
|
|
25
|
+
let aiClient;
|
|
26
|
+
try {
|
|
27
|
+
aiClient = await import("@intlayer/ai");
|
|
28
|
+
} catch {
|
|
29
|
+
appLogger([
|
|
30
|
+
colorize("Using your API key, you can install the", ANSIColors.GREY),
|
|
31
|
+
colorize("@intlayer/ai", ANSIColors.GREY_LIGHT),
|
|
32
|
+
colorize("package to run the process locally, with no dependency on the Intlayer server", ANSIColors.GREY)
|
|
33
|
+
], { level: "warn" });
|
|
34
|
+
const hasAIAccess = await checkAIAccess(configuration, aiOptions);
|
|
35
|
+
logAIConfig(aiOptions ?? {}, appLogger);
|
|
36
|
+
return {
|
|
37
|
+
isCustomAI: false,
|
|
38
|
+
hasAIAccess
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
appLogger([colorize("@intlayer/ai", ANSIColors.GREY_LIGHT), colorize("found - Run process locally", ANSIColors.GREY_DARK)]);
|
|
42
|
+
const aiConfig = await aiClient.getAIConfig({
|
|
43
|
+
userOptions: aiOptions,
|
|
44
|
+
accessType: ["public"]
|
|
45
|
+
});
|
|
46
|
+
logAIConfig(aiOptions ?? {}, appLogger);
|
|
47
|
+
return {
|
|
48
|
+
aiClient,
|
|
49
|
+
aiConfig,
|
|
50
|
+
isCustomAI: true,
|
|
51
|
+
hasAIAccess: true
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const hasAIAccess = await checkAIAccess(configuration, aiOptions);
|
|
55
|
+
logAIConfig(aiOptions ?? {}, appLogger);
|
|
56
|
+
return {
|
|
57
|
+
isCustomAI: false,
|
|
58
|
+
hasAIAccess
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
//#endregion
|
|
63
|
+
export { setupAI };
|
|
2
64
|
//# sourceMappingURL=setupAI.mjs.map
|