@intlayer/chokidar 8.2.4 → 8.3.0-canary.1
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/build.cjs +1 -1
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs +1 -1
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/processContentDeclaration.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs +4 -4
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs +2 -2
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs.map +1 -1
- package/dist/cjs/cleanOutputDir.cjs.map +1 -1
- package/dist/cjs/cleanRemovedContentDeclaration.cjs +1 -1
- package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
- package/dist/cjs/cli.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createType/createModuleAugmentation.cjs +2 -2
- package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
- package/dist/cjs/createType/createType.cjs.map +1 -1
- package/dist/cjs/detectFormatCommand.cjs +1 -1
- package/dist/cjs/detectFormatCommand.cjs.map +1 -1
- package/dist/cjs/fetchDistantDictionaries.cjs +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
- package/dist/cjs/formatDictionary.cjs.map +1 -1
- package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs +7 -1
- package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs.map +1 -1
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs +1 -1
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileChange.cjs +1 -1
- package/dist/cjs/handleContentDeclarationFileChange.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileMoved.cjs +1 -1
- package/dist/cjs/handleContentDeclarationFileMoved.cjs.map +1 -1
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs +1 -1
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/init/index.cjs +1 -1
- package/dist/cjs/initConfig/index.cjs +1 -1
- package/dist/cjs/listDictionariesPath.cjs.map +1 -1
- package/dist/cjs/listGitFiles.cjs +3 -3
- package/dist/cjs/listProjects.cjs +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/index.cjs +1 -1
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +2 -2
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs +1 -1
- package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs +1 -1
- package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs.map +1 -1
- package/dist/cjs/logConfigDetails.cjs +2 -1
- package/dist/cjs/logConfigDetails.cjs.map +1 -1
- package/dist/cjs/prepareIntlayer.cjs +1 -1
- package/dist/cjs/prepareIntlayer.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/applyMask.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs.map +1 -1
- package/dist/cjs/utils/autoDecorateContent.cjs +1 -1
- package/dist/cjs/utils/autoDecorateContent.cjs.map +1 -1
- package/dist/cjs/utils/buildFilesList.cjs +1 -1
- package/dist/cjs/utils/buildFilesList.cjs.map +1 -1
- package/dist/cjs/utils/formatter.cjs +1 -1
- package/dist/cjs/utils/formatter.cjs.map +1 -1
- package/dist/cjs/utils/getComponentTransformPattern.cjs +1 -1
- package/dist/cjs/utils/getComponentTransformPattern.cjs.map +1 -1
- package/dist/cjs/utils/getContentExtension.cjs +2 -0
- package/dist/cjs/utils/getContentExtension.cjs.map +1 -0
- package/dist/cjs/utils/getFormatFromExtension.cjs +1 -1
- package/dist/cjs/utils/getFormatFromExtension.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +1 -1
- package/dist/cjs/utils/resolveRelativePath.cjs +2 -0
- package/dist/cjs/utils/resolveRelativePath.cjs.map +1 -0
- package/dist/cjs/watcher.cjs +1 -1
- package/dist/cjs/watcher.cjs.map +1 -1
- package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs +1 -1
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs +3 -1
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs +2 -1
- package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +1 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
- package/dist/esm/build.mjs +1 -1
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs +1 -1
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/processContentDeclaration.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs +4 -4
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeFetchDictionary.mjs +2 -2
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs +1 -1
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs +1 -1
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeUnmergedDictionary.mjs.map +1 -1
- package/dist/esm/cleanOutputDir.mjs.map +1 -1
- package/dist/esm/cleanRemovedContentDeclaration.mjs +1 -1
- package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
- package/dist/esm/cli.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs.map +1 -1
- package/dist/esm/createType/createModuleAugmentation.mjs +2 -2
- package/dist/esm/createType/createModuleAugmentation.mjs.map +1 -1
- package/dist/esm/createType/createType.mjs.map +1 -1
- package/dist/esm/detectFormatCommand.mjs +1 -1
- package/dist/esm/detectFormatCommand.mjs.map +1 -1
- package/dist/esm/fetchDistantDictionaries.mjs +1 -1
- package/dist/esm/filterInvalidDictionaries.mjs.map +1 -1
- package/dist/esm/formatDictionary.mjs.map +1 -1
- package/dist/esm/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs +7 -1
- package/dist/esm/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs.map +1 -1
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs +1 -1
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/handleContentDeclarationFileChange.mjs +1 -1
- package/dist/esm/handleContentDeclarationFileChange.mjs.map +1 -1
- package/dist/esm/handleContentDeclarationFileMoved.mjs +1 -1
- package/dist/esm/handleContentDeclarationFileMoved.mjs.map +1 -1
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs +1 -1
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/init/index.mjs +1 -1
- package/dist/esm/initConfig/index.mjs +1 -1
- package/dist/esm/listDictionariesPath.mjs.map +1 -1
- package/dist/esm/listGitFiles.mjs +4 -4
- package/dist/esm/listProjects.mjs +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
- package/dist/esm/loadDictionaries/index.mjs +1 -1
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs +2 -2
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadDictionaries.mjs +1 -1
- package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs +1 -1
- package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs +1 -1
- package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs.map +1 -1
- package/dist/esm/logConfigDetails.mjs +2 -1
- package/dist/esm/logConfigDetails.mjs.map +1 -1
- package/dist/esm/prepareIntlayer.mjs +1 -1
- package/dist/esm/prepareIntlayer.mjs.map +1 -1
- package/dist/esm/reduceDictionaryContent/applyMask.mjs.map +1 -1
- package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs.map +1 -1
- package/dist/esm/utils/autoDecorateContent.mjs +1 -1
- package/dist/esm/utils/autoDecorateContent.mjs.map +1 -1
- package/dist/esm/utils/buildFilesList.mjs +1 -1
- package/dist/esm/utils/buildFilesList.mjs.map +1 -1
- package/dist/esm/utils/formatter.mjs +1 -1
- package/dist/esm/utils/formatter.mjs.map +1 -1
- package/dist/esm/utils/getComponentTransformPattern.mjs +1 -1
- package/dist/esm/utils/getComponentTransformPattern.mjs.map +1 -1
- package/dist/esm/utils/getContentExtension.mjs +2 -0
- package/dist/esm/utils/getContentExtension.mjs.map +1 -0
- package/dist/esm/utils/getFormatFromExtension.mjs +1 -1
- package/dist/esm/utils/getFormatFromExtension.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +1 -1
- package/dist/esm/utils/resolveRelativePath.mjs +2 -0
- package/dist/esm/utils/resolveRelativePath.mjs.map +1 -0
- package/dist/esm/watcher.mjs +1 -1
- package/dist/esm/watcher.mjs.map +1 -1
- package/dist/esm/writeConfiguration/index.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs +1 -1
- package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/transformJSFile.mjs +3 -1
- package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/transformJSONFile.mjs +2 -1
- package/dist/esm/writeContentDeclaration/transformJSONFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +1 -1
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs +1 -1
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -1
- package/dist/types/build.d.ts +2 -2
- package/dist/types/buildIntlayerDictionary/buildIntlayerDictionary.d.ts +3 -3
- package/dist/types/buildIntlayerDictionary/buildIntlayerDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/processContentDeclaration.d.ts +2 -1
- package/dist/types/buildIntlayerDictionary/processContentDeclaration.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeDynamicDictionary.d.ts +5 -4
- package/dist/types/buildIntlayerDictionary/writeDynamicDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeFetchDictionary.d.ts +3 -3
- package/dist/types/buildIntlayerDictionary/writeFetchDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeMergedDictionary.d.ts +3 -3
- package/dist/types/buildIntlayerDictionary/writeMergedDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeRemoteDictionary.d.ts +3 -3
- package/dist/types/buildIntlayerDictionary/writeRemoteDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeUnmergedDictionary.d.ts +2 -1
- package/dist/types/buildIntlayerDictionary/writeUnmergedDictionary.d.ts.map +1 -1
- package/dist/types/cleanOutputDir.d.ts +1 -1
- package/dist/types/cleanRemovedContentDeclaration.d.ts +1 -1
- package/dist/types/cleanRemovedContentDeclaration.d.ts.map +1 -1
- package/dist/types/createDictionaryEntryPoint/createDictionaryEntryPoint.d.ts +2 -2
- package/dist/types/createDictionaryEntryPoint/createDictionaryEntryPoint.d.ts.map +1 -1
- package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts +2 -2
- package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts.map +1 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltDictionariesPath.d.ts +1 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.d.ts +1 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.d.ts +1 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.d.ts +1 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.d.ts +1 -1
- package/dist/types/createType/createModuleAugmentation.d.ts +1 -1
- package/dist/types/createType/createModuleAugmentation.d.ts.map +1 -1
- package/dist/types/createType/createType.d.ts +2 -1
- package/dist/types/createType/createType.d.ts.map +1 -1
- package/dist/types/detectFormatCommand.d.ts +1 -1
- package/dist/types/filterInvalidDictionaries.d.ts +2 -1
- package/dist/types/filterInvalidDictionaries.d.ts.map +1 -1
- package/dist/types/formatDictionary.d.ts +21 -20
- package/dist/types/formatDictionary.d.ts.map +1 -1
- package/dist/types/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.d.ts +1 -1
- package/dist/types/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.d.ts.map +1 -1
- package/dist/types/handleAdditionalContentDeclarationFile.d.ts +1 -1
- package/dist/types/handleContentDeclarationFileChange.d.ts +1 -1
- package/dist/types/handleContentDeclarationFileMoved.d.ts +1 -1
- package/dist/types/handleUnlinkedContentDeclarationFile.d.ts +1 -1
- package/dist/types/listDictionariesPath.d.ts +1 -1
- package/dist/types/loadDictionaries/getIntlayerBundle.d.ts +1 -1
- package/dist/types/loadDictionaries/index.d.ts +2 -2
- package/dist/types/loadDictionaries/loadContentDeclaration.d.ts +5 -2
- package/dist/types/loadDictionaries/loadContentDeclaration.d.ts.map +1 -1
- package/dist/types/loadDictionaries/loadDictionaries.d.ts +2 -1
- package/dist/types/loadDictionaries/loadDictionaries.d.ts.map +1 -1
- package/dist/types/loadDictionaries/loadLocalDictionaries.d.ts +2 -1
- package/dist/types/loadDictionaries/loadLocalDictionaries.d.ts.map +1 -1
- package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts +3 -3
- package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts.map +1 -1
- package/dist/types/loadDictionaries/logTypeScriptErrors.d.ts +1 -1
- package/dist/types/logConfigDetails.d.ts.map +1 -1
- package/dist/types/prepareIntlayer.d.ts +1 -1
- package/dist/types/reduceDictionaryContent/applyMask.d.ts +1 -1
- package/dist/types/reduceDictionaryContent/reduceDictionaryContent.d.ts +1 -1
- package/dist/types/utils/buildFilesList.d.ts.map +1 -1
- package/dist/types/utils/formatter.d.ts +1 -1
- package/dist/types/utils/formatter.d.ts.map +1 -1
- package/dist/types/utils/getComponentTransformPattern.d.ts +1 -1
- package/dist/types/utils/getComponentTransformPattern.d.ts.map +1 -1
- package/dist/types/utils/getContentExtension.d.ts +15 -0
- package/dist/types/utils/getContentExtension.d.ts.map +1 -0
- package/dist/types/utils/getFormatFromExtension.d.ts +2 -2
- package/dist/types/utils/getFormatFromExtension.d.ts.map +1 -1
- package/dist/types/utils/index.d.ts +3 -1
- package/dist/types/utils/resolveRelativePath.d.ts +5 -0
- package/dist/types/utils/resolveRelativePath.d.ts.map +1 -0
- package/dist/types/watcher.d.ts +1 -1
- package/dist/types/writeConfiguration/index.d.ts +1 -1
- package/dist/types/writeContentDeclaration/processContentDeclarationContent.d.ts +1 -1
- package/dist/types/writeContentDeclaration/processContentDeclarationContent.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/transformJSFile.d.ts +3 -2
- package/dist/types/writeContentDeclaration/transformJSFile.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/transformJSONFile.d.ts +2 -2
- package/dist/types/writeContentDeclaration/transformJSONFile.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts +4 -1
- package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/writeJSFile.d.ts +3 -2
- package/dist/types/writeContentDeclaration/writeJSFile.d.ts.map +1 -1
- package/package.json +21 -20
- package/dist/assets/getContentDeclarationFileTemplate/cjsTemplate.txt +0 -10
- package/dist/assets/getContentDeclarationFileTemplate/esmTemplate.txt +0 -10
- package/dist/assets/getContentDeclarationFileTemplate/jsonTemplate.txt +0 -6
- package/dist/assets/getContentDeclarationFileTemplate/tsTemplate.txt +0 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildFilesList.mjs","names":[],"sources":["../../../src/utils/buildFilesList.ts"],"sourcesContent":["import { join } from 'node:path';\nimport fg from 'fast-glob';\n\n/**\n * Options for building the files list\n */\nexport type BuildFilesListOptions = {\n /**\n * Glob patterns to match files\n */\n transformPattern: string | string[];\n /**\n * Glob patterns to exclude files\n */\n excludePattern: string | string[];\n /**\n * Base directory for file resolution\n */\n baseDir: string;\n};\n\n/**\n * Normalizes a pattern value to an array\n */\nconst normalizeToArray = <T>(value: T | T[]): T[]
|
|
1
|
+
{"version":3,"file":"buildFilesList.mjs","names":[],"sources":["../../../src/utils/buildFilesList.ts"],"sourcesContent":["import { join, normalize } from 'node:path';\nimport fg from 'fast-glob';\n\n/**\n * Options for building the files list\n */\nexport type BuildFilesListOptions = {\n /**\n * Glob patterns to match files\n */\n transformPattern: string | string[];\n /**\n * Glob patterns to exclude files\n */\n excludePattern: string | string[];\n /**\n * Base directory for file resolution\n */\n baseDir: string;\n};\n\n/**\n * Normalizes a pattern value to an array\n */\nconst normalizeToArray = <T>(value: T | T[]): T[] =>\n Array.isArray(value) ? value : [value];\n\n/**\n * Builds a list of files matching the given patterns.\n *\n * This utility consolidates the file listing logic used across multiple compilers\n * (Vue, Svelte, Vite) to avoid code duplication.\n *\n * @param options - Configuration options for building the file list\n * @returns Array of absolute file paths matching the patterns\n *\n * @example\n * // Basic usage\n * const files = buildFilesList({\n * transformPattern: 'src/**\\/*.{ts,tsx}',\n * excludePattern: ['**\\/node_modules;\\/**'],\n * baseDir: '/path/to/project',\n * });\n *\n * @example\n * // With framework extension (Vue)\n * const files = buildFilesList({\n * transformPattern: 'src/**\\/*.{ts,tsx}',\n * excludePattern: ['**\\/node_modules\\/**'],\n * baseDir: '/path/to/project',\n * });\n */\nexport const buildFilesList = (options: BuildFilesListOptions): string[] => {\n const { transformPattern, excludePattern, baseDir } = options;\n\n // Ensure patterns are strings and not empty\n const patterns = normalizeToArray(transformPattern)\n .filter(\n (pattern): pattern is string =>\n typeof pattern === 'string' && !pattern.startsWith('!')\n )\n .map(normalize); // Ensure it works with Windows\n\n // Filter out undefined/null from the combined exclude list\n const excludePatterns = [\n ...normalizeToArray(excludePattern),\n ...normalizeToArray(transformPattern)\n .filter(\n (pattern): pattern is string =>\n typeof pattern === 'string' && pattern.startsWith('!')\n )\n .map((pattern) => pattern.slice(1)),\n ]\n .filter((pattern): pattern is string => typeof pattern === 'string')\n .map(normalize); // Ensure it works with Windows\n\n const files = fg\n .sync(patterns, {\n cwd: baseDir,\n ignore: excludePatterns,\n })\n .map((file) => join(baseDir, file));\n\n return files;\n};\n"],"mappings":"yEAwBA,MAAM,EAAuB,GAC3B,MAAM,QAAQ,EAAM,CAAG,EAAQ,CAAC,EAAM,CA2B3B,EAAkB,GAA6C,CAC1E,GAAM,CAAE,mBAAkB,iBAAgB,WAAY,EAGhD,EAAW,EAAiB,EAAiB,CAChD,OACE,GACC,OAAO,GAAY,UAAY,CAAC,EAAQ,WAAW,IAAI,CAC1D,CACA,IAAI,EAAU,CAGX,EAAkB,CACtB,GAAG,EAAiB,EAAe,CACnC,GAAG,EAAiB,EAAiB,CAClC,OACE,GACC,OAAO,GAAY,UAAY,EAAQ,WAAW,IAAI,CACzD,CACA,IAAK,GAAY,EAAQ,MAAM,EAAE,CAAC,CACtC,CACE,OAAQ,GAA+B,OAAO,GAAY,SAAS,CACnE,IAAI,EAAU,CASjB,OAPc,EACX,KAAK,EAAU,CACd,IAAK,EACL,OAAQ,EACT,CAAC,CACD,IAAK,GAAS,EAAK,EAAS,EAAK,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{relative as e}from"node:path";import{ANSIColors as t,colorize as n,colorizePath as r}from"@intlayer/config/logger";import i from"@intlayer/config/built";import{getLocaleName as a}from"@intlayer/core/localization";import
|
|
1
|
+
import{relative as e}from"node:path";import{ANSIColors as t,colorize as n,colorizePath as r}from"@intlayer/config/logger";import i from"@intlayer/config/built";import{getLocaleName as a}from"@intlayer/core/localization";import*as o from"@intlayer/types/locales";const s=(t,n)=>[t].flat().map(t=>t.startsWith(`/`)?e(i.system.baseDir,t):t).map(e=>n===!1?e:r(e,n)).join(`, `),c=(e,r=t.GREEN)=>[e].flat().map(e=>`${a(e,o.ENGLISH)} (${e})`).map(e=>r===!1?e:n(e,r)).join(`, `);export{c as formatLocale,s as formatPath};
|
|
2
2
|
//# sourceMappingURL=formatter.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatter.mjs","names":[],"sources":["../../../src/utils/formatter.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport configuration from '@intlayer/config/built';\nimport { ANSIColors, colorize, colorizePath } from '@intlayer/config/logger';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport
|
|
1
|
+
{"version":3,"file":"formatter.mjs","names":[],"sources":["../../../src/utils/formatter.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport configuration from '@intlayer/config/built';\nimport { ANSIColors, colorize, colorizePath } from '@intlayer/config/logger';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport * as Locales from '@intlayer/types/locales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\nexport const formatPath = (\n path: string | string[],\n color?: ANSIColors | false\n) =>\n [path]\n .flat()\n .map((path) =>\n path.startsWith('/') ? relative(configuration.system.baseDir, path) : path\n )\n .map((relativePath) =>\n color === false ? relativePath : colorizePath(relativePath, color)\n )\n .join(`, `);\n\nexport const formatLocale = (\n locale: LocalesValues | LocalesValues[],\n color: ANSIColors | false = ANSIColors.GREEN\n) =>\n [locale]\n .flat()\n .map((locale) => `${getLocaleName(locale, Locales.ENGLISH)} (${locale})`)\n .map((text) => (color === false ? text : colorize(text, color)))\n .join(`, `);\n"],"mappings":"sQAOA,MAAa,GACX,EACA,IAEA,CAAC,EAAK,CACH,MAAM,CACN,IAAK,GACJ,EAAK,WAAW,IAAI,CAAG,EAAS,EAAc,OAAO,QAAS,EAAK,CAAG,EACvE,CACA,IAAK,GACJ,IAAU,GAAQ,EAAe,EAAa,EAAc,EAAM,CACnE,CACA,KAAK,KAAK,CAEF,GACX,EACA,EAA4B,EAAW,QAEvC,CAAC,EAAO,CACL,MAAM,CACN,IAAK,GAAW,GAAG,EAAc,EAAQ,EAAQ,QAAQ,CAAC,IAAI,EAAO,GAAG,CACxE,IAAK,GAAU,IAAU,GAAQ,EAAO,EAAS,EAAM,EAAM,CAAE,CAC/D,KAAK,KAAK"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isAbsolute as e,relative as t,resolve as n}from"node:path";import r from"fast-glob";const i=r=>{let i=Array.from(new Set(r.map(e=>n(e))));return i.sort((e,t)=>e.length-t.length),i.reduce((n,r)=>(n.some(n=>{let i=t(n,r);return!i.startsWith(`..`)&&!e(i)&&i!==``})||n.push(r),n),[])},a=async e=>{let{baseDir:t,codeDir:n}=e.content,{traversePattern:a}=e.build,o=i([t,...n]).map(e=>r(a,{cwd:e,absolute:!0,dot:!0})),s=(await Promise.all(o)).flat();return Array.from(new Set(s))},o=e=>{let{baseDir:t,codeDir:n}=e.content,{traversePattern:a}=e.build,o=i([t,...n]).flatMap(e=>r.sync(a,{cwd:e,absolute:!0,dot:!0}));return Array.from(new Set(o))};export{a as getComponentTransformPattern,o as getComponentTransformPatternSync};
|
|
1
|
+
import{isAbsolute as e,relative as t,resolve as n}from"node:path";import r from"fast-glob";const i=r=>{let i=Array.from(new Set(r.map(e=>n(e))));return i.sort((e,t)=>e.length-t.length),i.reduce((n,r)=>(n.some(n=>{let i=t(n,r);return!i.startsWith(`..`)&&!e(i)&&i!==``})||n.push(r),n),[])},a=async e=>{let{baseDir:t}=e.system,{codeDir:n}=e.content,{traversePattern:a}=e.build,o=i([t,...n]).map(e=>r(a,{cwd:e,absolute:!0,dot:!0})),s=(await Promise.all(o)).flat();return Array.from(new Set(s))},o=e=>{let{baseDir:t}=e.system,{codeDir:n}=e.content,{traversePattern:a}=e.build,o=i([t,...n]).flatMap(e=>r.sync(a,{cwd:e,absolute:!0,dot:!0}));return Array.from(new Set(o))};export{a as getComponentTransformPattern,o as getComponentTransformPatternSync};
|
|
2
2
|
//# sourceMappingURL=getComponentTransformPattern.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getComponentTransformPattern.mjs","names":[],"sources":["../../../src/utils/getComponentTransformPattern.ts"],"sourcesContent":["import { isAbsolute, relative, resolve } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport fg from 'fast-glob';\n\n/**\n * Helper to remove directories that are subdirectories of others in the list.\n * Example: ['/root', '/root/src'] -> ['/root']\n * This prevents scanning the same files twice.\n */\nconst getDistinctRootDirs = (dirs: string[]): string[] => {\n // Resolve to absolute paths and remove exact duplicates\n const uniqueDirs = Array.from(new Set(dirs.map((dir) => resolve(dir))));\n\n // Sort by length (shortest paths first) so parents appear before children\n uniqueDirs.sort((a, b) => a.length - b.length);\n\n // Filter out any directory that is inside a parent already in the accepted list\n return uniqueDirs.reduce((acc: string[], dir) => {\n const isNested = acc.some((parent) => {\n const relativePath = relative(parent, dir);\n return (\n !relativePath.startsWith('..') && // It is inside the parent\n !isAbsolute(relativePath) && // It is not a different drive/root\n relativePath !== '' // It is not the parent itself (already handled by Set, but good for safety)\n );\n });\n\n if (!isNested) {\n acc.push(dir);\n }\n return acc;\n }, []);\n};\n\nexport const getComponentTransformPattern = async (\n intlayerConfig: IntlayerConfig\n): Promise<string[]> => {\n const { baseDir
|
|
1
|
+
{"version":3,"file":"getComponentTransformPattern.mjs","names":[],"sources":["../../../src/utils/getComponentTransformPattern.ts"],"sourcesContent":["import { isAbsolute, relative, resolve } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * Helper to remove directories that are subdirectories of others in the list.\n * Example: ['/root', '/root/src'] -> ['/root']\n * This prevents scanning the same files twice.\n */\nconst getDistinctRootDirs = (dirs: string[]): string[] => {\n // Resolve to absolute paths and remove exact duplicates\n const uniqueDirs = Array.from(new Set(dirs.map((dir) => resolve(dir))));\n\n // Sort by length (shortest paths first) so parents appear before children\n uniqueDirs.sort((a, b) => a.length - b.length);\n\n // Filter out any directory that is inside a parent already in the accepted list\n return uniqueDirs.reduce((acc: string[], dir) => {\n const isNested = acc.some((parent) => {\n const relativePath = relative(parent, dir);\n return (\n !relativePath.startsWith('..') && // It is inside the parent\n !isAbsolute(relativePath) && // It is not a different drive/root\n relativePath !== '' // It is not the parent itself (already handled by Set, but good for safety)\n );\n });\n\n if (!isNested) {\n acc.push(dir);\n }\n return acc;\n }, []);\n};\n\nexport const getComponentTransformPattern = async (\n intlayerConfig: IntlayerConfig\n): Promise<string[]> => {\n const { baseDir } = intlayerConfig.system;\n const { codeDir } = intlayerConfig.content;\n const { traversePattern } = intlayerConfig.build;\n\n // Optimize: Filter out codeDir paths if they are already covered by baseDir\n const distinctRoots = getDistinctRootDirs([baseDir, ...codeDir]);\n\n const filesListPatternPromises = distinctRoots.map((cwd) =>\n fg(traversePattern, {\n cwd,\n absolute: true,\n dot: true,\n })\n );\n\n const filesList = (await Promise.all(filesListPatternPromises)).flat();\n\n // Deduplicate files just in case of overlapping patterns or symlinks\n return Array.from(new Set(filesList));\n};\n\nexport const getComponentTransformPatternSync = (\n intlayerConfig: IntlayerConfig\n): string[] => {\n const { baseDir } = intlayerConfig.system;\n const { codeDir } = intlayerConfig.content;\n const { traversePattern } = intlayerConfig.build;\n\n // Optimize: Filter out codeDir paths if they are already covered by baseDir\n const distinctRoots = getDistinctRootDirs([baseDir, ...codeDir]);\n\n const filesList = distinctRoots.flatMap((cwd) =>\n fg.sync(traversePattern, {\n cwd,\n absolute: true,\n dot: true,\n })\n );\n\n return Array.from(new Set(filesList));\n};\n"],"mappings":"2FASA,MAAM,EAAuB,GAA6B,CAExD,IAAM,EAAa,MAAM,KAAK,IAAI,IAAI,EAAK,IAAK,GAAQ,EAAQ,EAAI,CAAC,CAAC,CAAC,CAMvE,OAHA,EAAW,MAAM,EAAG,IAAM,EAAE,OAAS,EAAE,OAAO,CAGvC,EAAW,QAAQ,EAAe,KACtB,EAAI,KAAM,GAAW,CACpC,IAAM,EAAe,EAAS,EAAQ,EAAI,CAC1C,MACE,CAAC,EAAa,WAAW,KAAK,EAC9B,CAAC,EAAW,EAAa,EACzB,IAAiB,IAEnB,EAGA,EAAI,KAAK,EAAI,CAER,GACN,EAAE,CAAC,EAGK,EAA+B,KAC1C,IACsB,CACtB,GAAM,CAAE,WAAY,EAAe,OAC7B,CAAE,WAAY,EAAe,QAC7B,CAAE,mBAAoB,EAAe,MAKrC,EAFgB,EAAoB,CAAC,EAAS,GAAG,EAAQ,CAAC,CAEjB,IAAK,GAClD,EAAG,EAAiB,CAClB,MACA,SAAU,GACV,IAAK,GACN,CAAC,CACH,CAEK,GAAa,MAAM,QAAQ,IAAI,EAAyB,EAAE,MAAM,CAGtE,OAAO,MAAM,KAAK,IAAI,IAAI,EAAU,CAAC,EAG1B,EACX,GACa,CACb,GAAM,CAAE,WAAY,EAAe,OAC7B,CAAE,WAAY,EAAe,QAC7B,CAAE,mBAAoB,EAAe,MAKrC,EAFgB,EAAoB,CAAC,EAAS,GAAG,EAAQ,CAAC,CAEhC,QAAS,GACvC,EAAG,KAAK,EAAiB,CACvB,MACA,SAAU,GACV,IAAK,GACN,CAAC,CACH,CAED,OAAO,MAAM,KAAK,IAAI,IAAI,EAAU,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=(e,t)=>{let n=`.ts`;switch(e){case`json`:n=`.json`;break;case`cjs`:n=`.cjs`;break;case`esm`:n=`.js`;break}return t.content.fileExtensions.find(e=>e.endsWith(n))??t.content.fileExtensions[0]??`.content${n}`};export{e as getContentExtension};
|
|
2
|
+
//# sourceMappingURL=getContentExtension.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getContentExtension.mjs","names":[],"sources":["../../../src/utils/getContentExtension.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Generates the .content file extension based on the desired format\n * and the project's fileExtensions configuration.\n *\n * Example:\n * format 'ts' -> '.content.ts'\n * format 'esm' -> '.content.js' (if matching .content.js is found in config)\n */\nexport const getContentExtension = (\n format: 'ts' | 'esm' | 'cjs' | 'json' | 'jsonc' | 'json5' | (string & {}),\n configuration: IntlayerConfig\n): string => {\n let contentFileExtension = '.ts';\n switch (format) {\n case 'json':\n contentFileExtension = '.json';\n break;\n case 'cjs':\n contentFileExtension = '.cjs';\n break;\n case 'esm':\n contentFileExtension = '.js';\n break;\n }\n\n // Find the configured extension that matches the format's extension\n const pickedFileExtension = configuration.content.fileExtensions.find(\n (extension) => extension.endsWith(contentFileExtension)\n );\n\n return (\n pickedFileExtension ??\n configuration.content.fileExtensions[0] ??\n `.content${contentFileExtension}`\n );\n};\n"],"mappings":"AAUA,MAAa,GACX,EACA,IACW,CACX,IAAI,EAAuB,MAC3B,OAAQ,EAAR,CACE,IAAK,OACH,EAAuB,QACvB,MACF,IAAK,MACH,EAAuB,OACvB,MACF,IAAK,MACH,EAAuB,MACvB,MAQJ,OAJ4B,EAAc,QAAQ,eAAe,KAC9D,GAAc,EAAU,SAAS,EAAqB,CACxD,EAIC,EAAc,QAAQ,eAAe,IACrC,WAAW"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=e=>{switch(e){case`.ts`:case`.tsx`:return`ts`;case`.cjs`:case`.cjsx`:return`cjs`;case`.mjs`:return`esm`;case`.json`:case`.jsonc`:case`.json5`:return`json`}return`ts`},t=e=>{switch(e){case`ts`:return`.ts`;case`cjs`:return`.cjs`;case`json`:return`.json`;case`jsonc`:return`.jsonc`;case`json5`:return`.json5`;case`esm`:return`.mjs`}return`.ts`};export{t as getExtensionFromFormat,e as getFormatFromExtension};
|
|
1
|
+
const e=e=>{switch(e){case`.ts`:case`.tsx`:return`ts`;case`.cjs`:case`.cjsx`:return`cjs`;case`.js`:case`.jsx`:case`.mjs`:case`.mjsx`:return`esm`;case`.json`:case`.jsonc`:case`.json5`:return`json`}return`ts`},t=e=>{switch(e){case`ts`:return`.ts`;case`cjs`:return`.cjs`;case`json`:return`.json`;case`jsonc`:return`.jsonc`;case`json5`:return`.json5`;case`esm`:return`.mjs`}return`.ts`};export{t as getExtensionFromFormat,e as getFormatFromExtension};
|
|
2
2
|
//# sourceMappingURL=getFormatFromExtension.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getFormatFromExtension.mjs","names":[],"sources":["../../../src/utils/getFormatFromExtension.ts"],"sourcesContent":["export type Format = 'ts' | 'cjs' | 'esm' | 'json' | 'jsonc' | 'json5';\nexport type Extension =\n | '.ts'\n | '.tsx'\n | '.js'\n | '.jsx'\n | '.cjs'\n | '.cjsx'\n | '.mjs'\n | '.mjsx'\n | '.json'\n | '.jsonc'\n | '.json5';\n\nexport const getFormatFromExtension = (extension: Extension): Format => {\n switch (extension) {\n case '.ts':\n case '.tsx':\n return 'ts';\n case '.cjs':\n case '.cjsx':\n return 'cjs';\n case '.mjs':\n return 'esm';\n case '.json':\n case '.jsonc':\n case '.json5':\n return 'json';\n }\n\n return 'ts';\n};\n\nexport const getExtensionFromFormat = (format: Format): Extension => {\n switch (format) {\n case 'ts':\n return '.ts';\n case 'cjs':\n return '.cjs';\n case 'json':\n return '.json';\n case 'jsonc':\n return '.jsonc';\n case 'json5':\n return '.json5';\n case 'esm':\n return '.mjs';\n }\n\n return '.ts';\n};\n"],"mappings":"AAcA,MAAa,
|
|
1
|
+
{"version":3,"file":"getFormatFromExtension.mjs","names":[],"sources":["../../../src/utils/getFormatFromExtension.ts"],"sourcesContent":["export type Format = 'ts' | 'cjs' | 'esm' | 'json' | 'jsonc' | 'json5';\nexport type Extension =\n | '.ts'\n | '.tsx'\n | '.js'\n | '.jsx'\n | '.cjs'\n | '.cjsx'\n | '.mjs'\n | '.mjsx'\n | '.json'\n | '.jsonc'\n | '.json5';\n\nexport const getFormatFromExtension = (\n extension: Extension | (string & {})\n): Format => {\n switch (extension) {\n case '.ts':\n case '.tsx':\n return 'ts';\n case '.cjs':\n case '.cjsx':\n return 'cjs';\n case '.js':\n case '.jsx':\n case '.mjs':\n case '.mjsx':\n return 'esm';\n case '.json':\n case '.jsonc':\n case '.json5':\n return 'json';\n }\n\n return 'ts';\n};\n\nexport const getExtensionFromFormat = (\n format: Format | (string & {})\n): Extension => {\n switch (format) {\n case 'ts':\n return '.ts';\n case 'cjs':\n return '.cjs';\n case 'json':\n return '.json';\n case 'jsonc':\n return '.jsonc';\n case 'json5':\n return '.json5';\n case 'esm':\n return '.mjs';\n }\n\n return '.ts';\n};\n"],"mappings":"AAcA,MAAa,EACX,GACW,CACX,OAAQ,EAAR,CACE,IAAK,MACL,IAAK,OACH,MAAO,KACT,IAAK,OACL,IAAK,QACH,MAAO,MACT,IAAK,MACL,IAAK,OACL,IAAK,OACL,IAAK,QACH,MAAO,MACT,IAAK,QACL,IAAK,SACL,IAAK,SACH,MAAO,OAGX,MAAO,MAGI,EACX,GACc,CACd,OAAQ,EAAR,CACE,IAAK,KACH,MAAO,MACT,IAAK,MACH,MAAO,OACT,IAAK,OACH,MAAO,QACT,IAAK,QACH,MAAO,SACT,IAAK,QACH,MAAO,SACT,IAAK,MACH,MAAO,OAGX,MAAO"}
|
package/dist/esm/utils/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Queue as e,pLimit as t}from"./pLimit.mjs";import{parallelize as n}from"./parallelize.mjs";import{
|
|
1
|
+
import{Queue as e,pLimit as t}from"./pLimit.mjs";import{parallelize as n}from"./parallelize.mjs";import{getPathHash as r}from"./getPathHash.mjs";import{formatLocale as i,formatPath as a}from"./formatter.mjs";import{autoDecorateContent as o}from"./autoDecorateContent.mjs";import{buildFilesList as s}from"./buildFilesList.mjs";import{splitTextByLines as c}from"./splitTextByLine.mjs";import{getChunk as l}from"./getChunk.mjs";import{assembleJSON as u,chunkJSON as d,reconstructFromSingleChunk as f}from"./chunkJSON.mjs";import{getComponentTransformPattern as p,getComponentTransformPatternSync as m}from"./getComponentTransformPattern.mjs";import{getContentExtension as h}from"./getContentExtension.mjs";import{getExtensionFromFormat as g,getFormatFromExtension as _}from"./getFormatFromExtension.mjs";import{mergeChunks as v}from"./mergeChunks.mjs";import{getGlobalLimiter as y,getTaskLimiter as b,parallelizeGlobal as x}from"./parallelizeGlobal.mjs";import{reduceObjectFormat as S}from"./reduceObjectFormat.mjs";import{resolveObjectPromises as C}from"./resolveObjectPromises.mjs";import{resolveRelativePath as w}from"./resolveRelativePath.mjs";import{runOnce as T}from"./runOnce.mjs";import{runParallel as E}from"./runParallel/index.mjs";import{sortAlphabetically as D}from"./sortAlphabetically.mjs";import{verifyIdenticObjectFormat as O}from"./verifyIdenticObjectFormat.mjs";export{e as Queue,u as assembleJSON,o as autoDecorateContent,s as buildFilesList,d as chunkJSON,i as formatLocale,a as formatPath,l as getChunk,p as getComponentTransformPattern,m as getComponentTransformPatternSync,h as getContentExtension,g as getExtensionFromFormat,_ as getFormatFromExtension,y as getGlobalLimiter,r as getPathHash,b as getTaskLimiter,v as mergeChunks,t as pLimit,n as parallelize,x as parallelizeGlobal,f as reconstructFromSingleChunk,S as reduceObjectFormat,C as resolveObjectPromises,w as resolveRelativePath,T as runOnce,E as runParallel,D as sortAlphabetically,c as splitTextByLines,O as verifyIdenticObjectFormat};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{dirname as e,isAbsolute as t,normalize as n,resolve as r}from"node:path";const i=(i,a,o)=>{if(t(i)){let e=n(i),t=n(o);if(i.startsWith(`/`)&&!e.startsWith(t)){let e=r(o,i.substring(1));if(!i.startsWith(`/usr/`)&&!i.startsWith(`/etc/`)&&!i.startsWith(`/var/`)&&!i.startsWith(`/home/`)&&!i.startsWith(`/Users/`)&&!i.startsWith(`/tmp/`)&&!i.startsWith(`/private/`)&&!i.startsWith(`/opt/`))return e}return e}return i.startsWith(`./`)||i.startsWith(`../`)?r(e(a),i):r(o,i)};export{i as resolveRelativePath};
|
|
2
|
+
//# sourceMappingURL=resolveRelativePath.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolveRelativePath.mjs","names":[],"sources":["../../../src/utils/resolveRelativePath.ts"],"sourcesContent":["import { dirname, isAbsolute, normalize, resolve } from 'node:path';\n\nexport const resolveRelativePath = (\n path: string,\n sourcePath: string,\n baseDir: string\n) => {\n // Handle absolute paths\n if (isAbsolute(path)) {\n const normalizedResult = normalize(path);\n const normalizedBaseDir = normalize(baseDir);\n\n // Check if it's relative to baseDir (starts with /)\n // but not a system path (like /usr/local)\n if (\n path.startsWith('/') &&\n !normalizedResult.startsWith(normalizedBaseDir)\n ) {\n // Try to resolve it relative to baseDir first\n const relativeToBase = resolve(baseDir, path.substring(1));\n\n // If the path doesn't exist in common system directories, treat as relative to baseDir\n if (\n !path.startsWith('/usr/') &&\n !path.startsWith('/etc/') &&\n !path.startsWith('/var/') &&\n !path.startsWith('/home/') &&\n !path.startsWith('/Users/') &&\n !path.startsWith('/tmp/') &&\n !path.startsWith('/private/') &&\n !path.startsWith('/opt/')\n ) {\n return relativeToBase;\n }\n }\n\n // It's a true system absolute path\n return normalizedResult;\n }\n\n // Handle relative paths (starting with ./ or ../)\n if (path.startsWith('./') || path.startsWith('../')) {\n const fileDir = dirname(sourcePath);\n return resolve(fileDir, path);\n }\n\n // Default case: treat as relative to baseDir\n return resolve(baseDir, path);\n};\n"],"mappings":"gFAEA,MAAa,GACX,EACA,EACA,IACG,CAEH,GAAI,EAAW,EAAK,CAAE,CACpB,IAAM,EAAmB,EAAU,EAAK,CAClC,EAAoB,EAAU,EAAQ,CAI5C,GACE,EAAK,WAAW,IAAI,EACpB,CAAC,EAAiB,WAAW,EAAkB,CAC/C,CAEA,IAAM,EAAiB,EAAQ,EAAS,EAAK,UAAU,EAAE,CAAC,CAG1D,GACE,CAAC,EAAK,WAAW,QAAQ,EACzB,CAAC,EAAK,WAAW,QAAQ,EACzB,CAAC,EAAK,WAAW,QAAQ,EACzB,CAAC,EAAK,WAAW,SAAS,EAC1B,CAAC,EAAK,WAAW,UAAU,EAC3B,CAAC,EAAK,WAAW,QAAQ,EACzB,CAAC,EAAK,WAAW,YAAY,EAC7B,CAAC,EAAK,WAAW,QAAQ,CAEzB,OAAO,EAKX,OAAO,EAUT,OANI,EAAK,WAAW,KAAK,EAAI,EAAK,WAAW,MAAM,CAE1C,EADS,EAAQ,EAAW,CACX,EAAK,CAIxB,EAAQ,EAAS,EAAK"}
|
package/dist/esm/watcher.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{handleContentDeclarationFileChange as e}from"./handleContentDeclarationFileChange.mjs";import{handleContentDeclarationFileMoved as t}from"./handleContentDeclarationFileMoved.mjs";import{handleAdditionalContentDeclarationFile as n}from"./handleAdditionalContentDeclarationFile.mjs";import{handleUnlinkedContentDeclarationFile as r}from"./handleUnlinkedContentDeclarationFile.mjs";import{prepareIntlayer as i}from"./prepareIntlayer.mjs";import{writeContentDeclaration as a}from"./writeContentDeclaration/writeContentDeclaration.mjs";import{readFile as o}from"node:fs/promises";import{basename as s}from"node:path";import{getAppLogger as c}from"@intlayer/config/logger";import{getConfiguration as l,getConfigurationAndFilePath as u}from"@intlayer/config/node";import{clearAllCache as d,clearModuleCache as f}from"@intlayer/config/utils";import{watch as p}from"chokidar";const m=new Map;let h=Promise.resolve();const g=e=>{h=h.then(async()=>{try{await e()}catch(e){console.error(e)}})},_=l=>{let h=u(l?.configOptions),_=h.configurationFilePath,v=l?.configuration??h.configuration,y=c(v),{watch:b,watchedFilesPatternWithPath:x,fileExtensions:S}=v.content,C=[...Array.isArray(x)?x:[x],..._?[_]:[]];if(v.content.watch)return y(`Watching Intlayer content declarations`),p(C,{persistent:b,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:1e3,pollInterval:100},ignored:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.intlayer/**`],...l}).on(`add`,async e=>{let r=s(e),i=!1,c;for(let[e]of m)if(s(e)===r){c=e;break}if(!c&&m.size===1&&(c=m.keys().next().value),c){let t=m.get(c);t&&(clearTimeout(t.timer),m.delete(c)),i=!0,y(`File moved from ${c} to ${e}`)}g(async()=>{if(i&&c)await t(c,e,v);else{if(await o(e,`utf-8`)===``){let t=S.map(e=>e.replace(/\./g,`\\.`)).join(`|`);await a({key:r.replace(RegExp(`(${t})$`),``),content:{},filePath:e},v)}await n(e,v)}})}).on(`change`,async t=>g(async()=>{if(_&&t===_){y(`Configuration file changed, repreparing Intlayer`),f(_),d();let{configuration:e}=u(l?.configOptions);v=l?.configuration??e,await i(v,{clean:!1})}else await e(t,v)})).on(`unlink`,async e=>{let t=setTimeout(async()=>{m.delete(e),g(async()=>r(e,v))},200);m.set(e,{timer:t,oldPath:e})}).on(`error`,async e=>{y(`Watcher error: ${e}`,{level:`error`}),y(`Restarting watcher`),await i(v)})},v=async e=>{let{skipPrepare:t,...n}=e??{},r=e?.configuration??l(e?.configOptions);t||await i(r,{forceRun:!0}),(r.content.watch||e?.persistent)&&_({...n,configuration:r})};export{v as buildAndWatchIntlayer,_ as watch};
|
|
2
2
|
//# sourceMappingURL=watcher.mjs.map
|
package/dist/esm/watcher.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watcher.mjs","names":["chokidarWatch"],"sources":["../../src/watcher.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n getConfigurationAndFilePath,\n} from '@intlayer/config/node';\nimport { clearAllCache, clearModuleCache } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions' */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport { handleAdditionalContentDeclarationFile } from './handleAdditionalContentDeclarationFile';\nimport { handleContentDeclarationFileChange } from './handleContentDeclarationFileChange';\nimport { handleContentDeclarationFileMoved } from './handleContentDeclarationFileMoved';\nimport { handleUnlinkedContentDeclarationFile } from './handleUnlinkedContentDeclarationFile';\nimport { prepareIntlayer } from './prepareIntlayer';\nimport { writeContentDeclaration } from './writeContentDeclaration';\n\n// Map to track files that were recently unlinked: oldPath -> { timer, timestamp }\nconst pendingUnlinks = new Map<\n string,\n { timer: NodeJS.Timeout; oldPath: string }\n>();\n\n// Task queue to ensure sequential processing of file events\nlet processingQueue = Promise.resolve();\nconst processEvent = (task: () => Promise<void>) => {\n processingQueue = processingQueue.then(async () => {\n try {\n await task();\n } catch (error) {\n console.error(error);\n }\n });\n};\n\ntype WatchOptions = ChokidarOptions & {\n configuration?: IntlayerConfig;\n configOptions?: GetConfigurationOptions;\n skipPrepare?: boolean;\n};\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: WatchOptions) => {\n const configResult = getConfigurationAndFilePath(options?.configOptions);\n const configurationFilePath = configResult.configurationFilePath;\n let configuration: IntlayerConfig =\n options?.configuration ?? configResult.configuration;\n const appLogger = getAppLogger(configuration);\n\n const {\n watch: isWatchMode,\n watchedFilesPatternWithPath,\n fileExtensions,\n } = configuration.content;\n\n const pathsToWatch = [\n ...(Array.isArray(watchedFilesPatternWithPath)\n ? watchedFilesPatternWithPath\n : [watchedFilesPatternWithPath]),\n ...(configurationFilePath ? [configurationFilePath] : []),\n ];\n\n if (!configuration.content.watch) return;\n\n appLogger('Watching Intlayer content declarations');\n\n return chokidarWatch(pathsToWatch, {\n persistent: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n awaitWriteFinish: {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n ignored: [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.intlayer/**',\n ],\n ...options,\n })\n .on('add', async (filePath) => {\n const fileName = basename(filePath);\n let isMove = false;\n\n // Check if this Add corresponds to a pending Unlink (Move/Rename detection)\n // Heuristic:\n // - Priority A: Exact basename match (Moved to different folder)\n // - Priority B: Single entry in pendingUnlinks (Renamed file)\n let matchedOldPath: string | undefined;\n\n // Search for basename match\n for (const [oldPath] of pendingUnlinks) {\n if (basename(oldPath) === fileName) {\n matchedOldPath = oldPath;\n break;\n }\n }\n\n // If no basename match, but exactly one file was recently unlinked, assume it's a rename\n if (!matchedOldPath && pendingUnlinks.size === 1) {\n matchedOldPath = pendingUnlinks.keys().next().value;\n }\n\n if (matchedOldPath) {\n // It is a move! Cancel the unlink handler\n const pending = pendingUnlinks.get(matchedOldPath);\n if (pending) {\n clearTimeout(pending.timer);\n pendingUnlinks.delete(matchedOldPath);\n }\n\n isMove = true;\n appLogger(`File moved from ${matchedOldPath} to ${filePath}`);\n }\n\n processEvent(async () => {\n if (isMove && matchedOldPath) {\n await handleContentDeclarationFileMoved(\n matchedOldPath,\n filePath,\n configuration\n );\n } else {\n const fileContent = await readFile(filePath, 'utf-8');\n const isEmpty = fileContent === '';\n\n // Fill template content declaration file if it is empty\n if (isEmpty) {\n const extensionPattern = fileExtensions\n .map((ext) => ext.replace(/\\./g, '\\\\.'))\n .join('|');\n const name = fileName.replace(\n new RegExp(`(${extensionPattern})$`),\n ''\n );\n\n await writeContentDeclaration(\n {\n key: name,\n content: {},\n filePath,\n },\n configuration\n );\n }\n\n await handleAdditionalContentDeclarationFile(filePath, configuration);\n }\n });\n })\n .on('change', async (filePath) =>\n processEvent(async () => {\n if (configurationFilePath && filePath === configurationFilePath) {\n appLogger('Configuration file changed, repreparing Intlayer');\n\n clearModuleCache(configurationFilePath);\n clearAllCache();\n\n const { configuration: newConfiguration } =\n getConfigurationAndFilePath(options?.configOptions);\n\n configuration = options?.configuration ?? newConfiguration;\n\n await prepareIntlayer(configuration, { clean: false });\n } else {\n await handleContentDeclarationFileChange(filePath, configuration);\n }\n })\n )\n .on('unlink', async (filePath) => {\n // Delay unlink processing to see if an 'add' event occurs (indicating a move)\n const timer = setTimeout(async () => {\n // If timer fires, the file was genuinely removed\n pendingUnlinks.delete(filePath);\n processEvent(async () =>\n handleUnlinkedContentDeclarationFile(filePath, configuration)\n );\n }, 200); // 200ms window to catch the 'add' event\n\n pendingUnlinks.set(filePath, { timer, oldPath: filePath });\n })\n .on('error', async (error) => {\n appLogger(`Watcher error: ${error}`, {\n level: 'error',\n });\n\n appLogger('Restarting watcher');\n\n await prepareIntlayer(configuration);\n });\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const { skipPrepare, ...rest } = options ?? {};\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n\n if (!skipPrepare) {\n await prepareIntlayer(configuration, { forceRun: true });\n }\n\n if (configuration.content.watch || options?.persistent) {\n watch({ ...rest, configuration });\n }\n};\n"],"mappings":"02BAoBA,MAAM,EAAiB,IAAI,IAM3B,IAAI,EAAkB,QAAQ,SAAS,CACvC,MAAM,EAAgB,GAA8B,CAClD,EAAkB,EAAgB,KAAK,SAAY,CACjD,GAAI,CACF,MAAM,GAAM,OACL,EAAO,CACd,QAAQ,MAAM,EAAM,GAEtB,EAUS,EAAS,GAA2B,CAC/C,IAAM,EAAe,EAA4B,GAAS,cAAc,CAClE,EAAwB,EAAa,sBACvC,EACF,GAAS,eAAiB,EAAa,cACnC,EAAY,EAAa,EAAc,CAEvC,CACJ,MAAO,EACP,8BACA,kBACE,EAAc,QAEZ,EAAe,CACnB,GAAI,MAAM,QAAQ,EAA4B,CAC1C,EACA,CAAC,EAA4B,CACjC,GAAI,EAAwB,CAAC,EAAsB,CAAG,EAAE,CACzD,CAEI,KAAc,QAAQ,MAI3B,OAFA,EAAU,yCAAyC,CAE5CA,EAAc,EAAc,CACjC,WAAY,EACZ,cAAe,GACf,iBAAkB,CAChB,mBAAoB,IACpB,aAAc,IACf,CACD,QAAS,CACP,qBACA,aACA,cACA,kBACD,CACD,GAAG,EACJ,CAAC,CACC,GAAG,MAAO,KAAO,IAAa,CAC7B,IAAM,EAAW,EAAS,EAAS,CAC/B,EAAS,GAMT,EAGJ,IAAK,GAAM,CAAC,KAAY,EACtB,GAAI,EAAS,EAAQ,GAAK,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BAAqB,CAE/B,MAAM,EAAgB,EAAc,EACpC,EAGO,EAAwB,KAAO,IAA2B,CACrE,GAAM,CAAE,cAAa,GAAG,GAAS,GAAW,EAAE,CACxC,EACJ,GAAS,eAAiB,EAAiB,GAAS,cAAc,CAE/D,GACH,MAAM,EAAgB,EAAe,CAAE,SAAU,GAAM,CAAC,EAGtD,EAAc,QAAQ,OAAS,GAAS,aAC1C,EAAM,CAAE,GAAG,EAAM,gBAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"watcher.mjs","names":["chokidarWatch"],"sources":["../../src/watcher.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n getConfigurationAndFilePath,\n} from '@intlayer/config/node';\nimport { clearAllCache, clearModuleCache } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions' */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport { handleAdditionalContentDeclarationFile } from './handleAdditionalContentDeclarationFile';\nimport { handleContentDeclarationFileChange } from './handleContentDeclarationFileChange';\nimport { handleContentDeclarationFileMoved } from './handleContentDeclarationFileMoved';\nimport { handleUnlinkedContentDeclarationFile } from './handleUnlinkedContentDeclarationFile';\nimport { prepareIntlayer } from './prepareIntlayer';\nimport { writeContentDeclaration } from './writeContentDeclaration';\n\n// Map to track files that were recently unlinked: oldPath -> { timer, timestamp }\nconst pendingUnlinks = new Map<\n string,\n { timer: NodeJS.Timeout; oldPath: string }\n>();\n\n// Task queue to ensure sequential processing of file events\nlet processingQueue = Promise.resolve();\nconst processEvent = (task: () => Promise<void>) => {\n processingQueue = processingQueue.then(async () => {\n try {\n await task();\n } catch (error) {\n console.error(error);\n }\n });\n};\n\ntype WatchOptions = ChokidarOptions & {\n configuration?: IntlayerConfig;\n configOptions?: GetConfigurationOptions;\n skipPrepare?: boolean;\n};\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: WatchOptions) => {\n const configResult = getConfigurationAndFilePath(options?.configOptions);\n const configurationFilePath = configResult.configurationFilePath;\n let configuration: IntlayerConfig =\n options?.configuration ?? configResult.configuration;\n const appLogger = getAppLogger(configuration);\n\n const {\n watch: isWatchMode,\n watchedFilesPatternWithPath,\n fileExtensions,\n } = configuration.content;\n\n const pathsToWatch = [\n ...(Array.isArray(watchedFilesPatternWithPath)\n ? watchedFilesPatternWithPath\n : [watchedFilesPatternWithPath]),\n ...(configurationFilePath ? [configurationFilePath] : []),\n ];\n\n if (!configuration.content.watch) return;\n\n appLogger('Watching Intlayer content declarations');\n\n return chokidarWatch(pathsToWatch, {\n persistent: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n awaitWriteFinish: {\n stabilityThreshold: 1000,\n pollInterval: 100,\n },\n ignored: [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.intlayer/**',\n ],\n ...options,\n })\n .on('add', async (filePath) => {\n const fileName = basename(filePath);\n let isMove = false;\n\n // Check if this Add corresponds to a pending Unlink (Move/Rename detection)\n // Heuristic:\n // - Priority A: Exact basename match (Moved to different folder)\n // - Priority B: Single entry in pendingUnlinks (Renamed file)\n let matchedOldPath: string | undefined;\n\n // Search for basename match\n for (const [oldPath] of pendingUnlinks) {\n if (basename(oldPath) === fileName) {\n matchedOldPath = oldPath;\n break;\n }\n }\n\n // If no basename match, but exactly one file was recently unlinked, assume it's a rename\n if (!matchedOldPath && pendingUnlinks.size === 1) {\n matchedOldPath = pendingUnlinks.keys().next().value;\n }\n\n if (matchedOldPath) {\n // It is a move! Cancel the unlink handler\n const pending = pendingUnlinks.get(matchedOldPath);\n if (pending) {\n clearTimeout(pending.timer);\n pendingUnlinks.delete(matchedOldPath);\n }\n\n isMove = true;\n appLogger(`File moved from ${matchedOldPath} to ${filePath}`);\n }\n\n processEvent(async () => {\n if (isMove && matchedOldPath) {\n await handleContentDeclarationFileMoved(\n matchedOldPath,\n filePath,\n configuration\n );\n } else {\n const fileContent = await readFile(filePath, 'utf-8');\n const isEmpty = fileContent === '';\n\n // Fill template content declaration file if it is empty\n if (isEmpty) {\n const extensionPattern = fileExtensions\n .map((ext) => ext.replace(/\\./g, '\\\\.'))\n .join('|');\n const name = fileName.replace(\n new RegExp(`(${extensionPattern})$`),\n ''\n );\n\n await writeContentDeclaration(\n {\n key: name,\n content: {},\n filePath,\n },\n configuration\n );\n }\n\n await handleAdditionalContentDeclarationFile(filePath, configuration);\n }\n });\n })\n .on('change', async (filePath) =>\n processEvent(async () => {\n if (configurationFilePath && filePath === configurationFilePath) {\n appLogger('Configuration file changed, repreparing Intlayer');\n\n clearModuleCache(configurationFilePath);\n clearAllCache();\n\n const { configuration: newConfiguration } =\n getConfigurationAndFilePath(options?.configOptions);\n\n configuration = options?.configuration ?? newConfiguration;\n\n await prepareIntlayer(configuration, { clean: false });\n } else {\n await handleContentDeclarationFileChange(filePath, configuration);\n }\n })\n )\n .on('unlink', async (filePath) => {\n // Delay unlink processing to see if an 'add' event occurs (indicating a move)\n const timer = setTimeout(async () => {\n // If timer fires, the file was genuinely removed\n pendingUnlinks.delete(filePath);\n processEvent(async () =>\n handleUnlinkedContentDeclarationFile(filePath, configuration)\n );\n }, 200); // 200ms window to catch the 'add' event\n\n pendingUnlinks.set(filePath, { timer, oldPath: filePath });\n })\n .on('error', async (error) => {\n appLogger(`Watcher error: ${error}`, {\n level: 'error',\n });\n\n appLogger('Restarting watcher');\n\n await prepareIntlayer(configuration);\n });\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const { skipPrepare, ...rest } = options ?? {};\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n\n if (!skipPrepare) {\n await prepareIntlayer(configuration, { forceRun: true });\n }\n\n if (configuration.content.watch || options?.persistent) {\n watch({ ...rest, configuration });\n }\n};\n"],"mappings":"02BAoBA,MAAM,EA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AQ,EAAI,QAAQ,MAAO,MAAM,CAAC,CACvC,KAAK,IAAI,CAMZ,MAAM,EACJ,CACE,IAPS,EAAS,QAChB,OAAO,IAAI,EAAiB,IAAI,CACpC,GACD,CAKG,QAAS,EAAE,CACX,WACD,CACD,EACD,CAGH,MAAM,EAAuC,EAAU,EAAc,GAEvE,EACF,CACD,GAAG,SAAU,KAAO,IACnB,EAAa,SAAY,CACvB,GAAI,GAAyB,IAAa,EAAuB,CAC/D,EAAU,mDAAmD,CAE7D,EAAiB,EAAsB,CACvC,GAAe,CAEf,GAAM,CAAE,cAAe,GACrB,EAA4B,GAAS,cAAc,CAErD,EAAgB,GAAS,eAAiB,EAE1C,MAAM,EAAgB,EAAe,CAAE,MAAO,GAAO,CAAC,MAEtD,MAAM,EAAmC,EAAU,EAAc,EAEnE,CACH,CACA,GAAG,SAAU,KAAO,IAAa,CAEhC,IAAM,EAAQ,WAAW,SAAY,CAEnC,EAAe,OAAO,EAAS,CAC/B,EAAa,SACX,EAAqC,EAAU,EAAc,CAC9D,EACA,IAAI,CAEP,EAAe,IAAI,EAAU,CAAE,QAAO,QAAS,EAAU,CAAC,EAC1D,CACD,GAAG,QAAS,KAAO,IAAU,CAC5B,EAAU,kBAAkB,IAAS,CACnC,MAAO,QACR,CAAC,CAEF,EAAU,qBAAqB,CAE/B,MAAM,EAAgB,EAAc,EACpC,EAGO,EAAwB,KAAO,IAA2B,CACrE,GAAM,CAAE,cAAa,GAAG,GAAS,GAAW,EAAE,CACxC,EACJ,GAAS,eAAiB,EAAiB,GAAS,cAAc,CAE/D,GACH,MAAM,EAAgB,EAAe,CAAE,SAAU,GAAM,CAAC,EAGtD,EAAc,QAAQ,OAAS,GAAS,aAC1C,EAAM,CAAE,GAAG,EAAM,gBAAe,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/writeConfiguration/index.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\n\nconst getCachedConfiguration = async (configuration: IntlayerConfig) => {\n const configFilePath = join(\n configuration.system.configDir,\n 'configuration.json'\n );\n\n const configurationContent = await readFile(configFilePath, 'utf8');\n return JSON.parse(configurationContent);\n};\n\nexport const isCachedConfigurationUpToDate = async (\n configuration: IntlayerConfig\n): Promise<boolean | null> => {\n try {\n const cleanedConfiguration = cleanConfiguration(configuration);\n const cachedConfiguration =\n await getCachedConfiguration(cleanedConfiguration);\n\n const isSimilar = isDeepStrictEqual(\n cachedConfiguration,\n cleanedConfiguration\n );\n\n return isSimilar;\n } catch {\n return null;\n }\n};\n\nconst cleanConfiguration = (configuration: IntlayerConfig): IntlayerConfig => {\n const {\n // Remove schema, and plugins because only useful at build time\n schemas,\n plugins,\n compiler,\n build,\n ...filteredConfiguration\n } = configuration;\n\n const parsedConfiguration = JSON.parse(JSON.stringify(filteredConfiguration));\n\n return parsedConfiguration;\n};\n\nexport const writeConfiguration = async (configuration: IntlayerConfig) => {\n const { system } = configuration;\n const { configDir } = system;\n\n // Ensure target directory exists\n // configDir is expected to be the directory where configuration.json will live\n await mkdir(configDir, { recursive: true });\n\n const configFilePath = join(configDir, 'configuration.json');\n\n const cleanedConfiguration = cleanConfiguration(configuration);\n\n await writeJsonIfChanged(configFilePath, cleanedConfiguration);\n};\n"],"mappings":"qMAMA,MAAM,EAAyB,KAAO,IAAkC,CAMtE,IAAM,EAAuB,MAAM,EALZ,EACrB,EAAc,OAAO,UACrB,qBACD,CAE2D,OAAO,CACnE,OAAO,KAAK,MAAM,EAAqB,EAG5B,EAAgC,KAC3C,IAC4B,CAC5B,GAAI,CACF,IAAM,EAAuB,EAAmB,EAAc,CAS9D,OALkB,EAFhB,MAAM,EAAuB,EAAqB,CAIlD,EACD,MAGK,CACN,OAAO,OAIL,EAAsB,GAAkD,CAC5E,GAAM,CAEJ,UACA,UACA,WACA,QACA,GAAG,GACD,EAIJ,OAF4B,KAAK,MAAM,KAAK,UAAU,EAAsB,CAAC,EAKlE,EAAqB,KAAO,IAAkC,CACzE,GAAM,CAAE,UAAW,EACb,CAAE,aAAc,EAItB,MAAM,EAAM,EAAW,CAAE,UAAW,GAAM,CAAC,CAM3C,MAAM,EAJiB,EAAK,EAAW,qBAAqB,CAE/B,EAAmB,EAAc,CAEA"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/writeConfiguration/index.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\n\nconst getCachedConfiguration = async (configuration: IntlayerConfig) => {\n const configFilePath = join(\n configuration.system.configDir,\n 'configuration.json'\n );\n\n const configurationContent = await readFile(configFilePath, 'utf8');\n return JSON.parse(configurationContent);\n};\n\nexport const isCachedConfigurationUpToDate = async (\n configuration: IntlayerConfig\n): Promise<boolean | null> => {\n try {\n const cleanedConfiguration = cleanConfiguration(configuration);\n const cachedConfiguration =\n await getCachedConfiguration(cleanedConfiguration);\n\n const isSimilar = isDeepStrictEqual(\n cachedConfiguration,\n cleanedConfiguration\n );\n\n return isSimilar;\n } catch {\n return null;\n }\n};\n\nconst cleanConfiguration = (configuration: IntlayerConfig): IntlayerConfig => {\n const {\n // Remove schema, and plugins because only useful at build time\n schemas,\n plugins,\n compiler,\n build,\n ...filteredConfiguration\n } = configuration;\n\n const parsedConfiguration = JSON.parse(JSON.stringify(filteredConfiguration));\n\n return parsedConfiguration;\n};\n\nexport const writeConfiguration = async (configuration: IntlayerConfig) => {\n const { system } = configuration;\n const { configDir } = system;\n\n // Ensure target directory exists\n // configDir is expected to be the directory where configuration.json will live\n await mkdir(configDir, { recursive: true });\n\n const configFilePath = join(configDir, 'configuration.json');\n\n const cleanedConfiguration = cleanConfiguration(configuration);\n\n await writeJsonIfChanged(configFilePath, cleanedConfiguration);\n};\n"],"mappings":"qMAMA,MAAM,EAAyB,KAAO,IAAkC,CAMtE,IAAM,EAAuB,MAAM,EALZ,EACrB,EAAc,OAAO,UACrB,qBACD,CAE2D,OAAO,CACnE,OAAO,KAAK,MAAM,EAAqB,EAG5B,EAAgC,KAC3C,IAC4B,CAC5B,GAAI,CACF,IAAM,EAAuB,EAAmB,EAAc,CAS9D,OALkB,EAFhB,MAAM,EAAuB,EAAqB,CAIlD,EACD,MAGK,CACN,OAAO,OAIL,EAAsB,GAAkD,CAC5E,GAAM,CAEJ,UACA,UACA,WACA,QACA,GAAG,GACD,EAIJ,OAF4B,KAAK,MAAM,KAAK,UAAU,EAAsB,CAAC,EAKlE,EAAqB,KAAO,IAAkC,CACzE,GAAM,CAAE,UAAW,EACb,CAAE,aAAc,EAItB,MAAM,EAAM,EAAW,CAAE,UAAW,GAAM,CAAC,CAM3C,MAAM,EAJiB,EAAK,EAAW,qBAAqB,CAE/B,EAAmB,EAAc,CAEA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{dirname as e,join as t}from"node:path";import{colorizePath as n,x as r}from"@intlayer/config/logger";import{existsSync as i,mkdirSync as a,writeFileSync as o}from"node:fs";import{deepTransformNode as s}from"@intlayer/core/interpreter";import{NodeType as c}from"@intlayer/types";const l={id:`write-file-plugin`,canHandle:e=>typeof e==`object`&&e?.nodeType===c.File,transform:s=>{let l=s.content,u=s.fixedPath;if(typeof l!=`string`)throw Error(`File content must be a string`);if(typeof u!=`string`)throw Error(`File path must be a string`);try{let n=t(process.cwd(),u),r=e(n);i(r)||a(r,{recursive:!0}),o(n,l)}catch(e){throw Error(`${r} Error writing file to ${n(u)}: ${e}`)}return{nodeType:c.File,[c.File]:s.file}}},u={id:`markdown-file-plugin`,canHandle:e=>typeof e==`object`&&e?.nodeType===c.Markdown,transform:(e,t,n)=>({nodeType:c.Markdown,[c.Markdown]:n(e.markdown,t)})},d={id:`insertion-file-plugin`,canHandle:e=>typeof e==`object`&&e?.nodeType===c.Insertion,transform:(e,t,n)=>({nodeType:c.Insertion,[c.Insertion]:n(e.insertion,t)})},f={id:`html-file-plugin`,canHandle:e=>typeof e==`object`&&e?.nodeType===c.HTML,transform:(e,t,n)=>({nodeType:c.HTML,[c.HTML]:n(e.html,t)})},p=async e=>s(e,{dictionaryKey:e.key,keyPath:[],plugins:[l,u,d,f]});export{p as processContentDeclarationContent};
|
|
1
|
+
import{dirname as e,join as t}from"node:path";import{colorizePath as n,x as r}from"@intlayer/config/logger";import{existsSync as i,mkdirSync as a,writeFileSync as o}from"node:fs";import{deepTransformNode as s}from"@intlayer/core/interpreter";import{NodeType as c}from"@intlayer/types/nodeType";const l={id:`write-file-plugin`,canHandle:e=>typeof e==`object`&&e?.nodeType===c.File,transform:s=>{let l=s.content,u=s.fixedPath;if(typeof l!=`string`)throw Error(`File content must be a string`);if(typeof u!=`string`)throw Error(`File path must be a string`);try{let n=t(process.cwd(),u),r=e(n);i(r)||a(r,{recursive:!0}),o(n,l)}catch(e){throw Error(`${r} Error writing file to ${n(u)}: ${e}`)}return{nodeType:c.File,[c.File]:s.file}}},u={id:`markdown-file-plugin`,canHandle:e=>typeof e==`object`&&e?.nodeType===c.Markdown,transform:(e,t,n)=>({nodeType:c.Markdown,[c.Markdown]:n(e.markdown,t)})},d={id:`insertion-file-plugin`,canHandle:e=>typeof e==`object`&&e?.nodeType===c.Insertion,transform:(e,t,n)=>({nodeType:c.Insertion,[c.Insertion]:n(e.insertion,t)})},f={id:`html-file-plugin`,canHandle:e=>typeof e==`object`&&e?.nodeType===c.HTML,transform:(e,t,n)=>({nodeType:c.HTML,[c.HTML]:n(e.html,t)})},p=async e=>s(e,{dictionaryKey:e.key,keyPath:[],plugins:[l,u,d,f]});export{p as processContentDeclarationContent};
|
|
2
2
|
//# sourceMappingURL=processContentDeclarationContent.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processContentDeclarationContent.mjs","names":[],"sources":["../../../src/writeContentDeclaration/processContentDeclarationContent.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { colorizePath, x } from '@intlayer/config/logger';\nimport { deepTransformNode, type Plugins } from '@intlayer/core/interpreter';\nimport type {\n FileContent,\n FileContentConstructor,\n HTMLContent,\n HTMLContentConstructor,\n InsertionContent,\n InsertionContentConstructor,\n MarkdownContent,\n MarkdownContentConstructor,\n} from '@intlayer/core/transpiler';\nimport {
|
|
1
|
+
{"version":3,"file":"processContentDeclarationContent.mjs","names":[],"sources":["../../../src/writeContentDeclaration/processContentDeclarationContent.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { colorizePath, x } from '@intlayer/config/logger';\nimport { deepTransformNode, type Plugins } from '@intlayer/core/interpreter';\nimport type {\n FileContent,\n FileContentConstructor,\n HTMLContent,\n HTMLContentConstructor,\n InsertionContent,\n InsertionContentConstructor,\n MarkdownContent,\n MarkdownContentConstructor,\n} from '@intlayer/core/transpiler';\nimport type { Dictionary } from '@intlayer/types/dictionary';;\nimport { NodeType } from '@intlayer/types/nodeType';\n\n/**\n * Write file plugin\n */\n\nconst writeFilePlugin: Plugins = {\n id: 'write-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.File,\n transform: (node: FileContent) => {\n const fileContent = node.content;\n const filePath = node.fixedPath;\n\n if (typeof fileContent !== 'string') {\n throw new Error('File content must be a string');\n }\n\n if (typeof filePath !== 'string') {\n throw new Error('File path must be a string');\n }\n\n // Write the file to the file system\n try {\n const absoluteFilePath = join(process.cwd(), filePath);\n\n // Create the file directory if it doesn't exist\n const fileDirectory = dirname(absoluteFilePath);\n\n if (!existsSync(fileDirectory)) {\n mkdirSync(fileDirectory, { recursive: true });\n }\n\n // Write the file\n writeFileSync(absoluteFilePath, fileContent);\n } catch (error) {\n throw new Error(\n `${x} Error writing file to ${colorizePath(filePath)}: ${error}`\n );\n }\n\n const transformedFileContent: FileContentConstructor = {\n nodeType: NodeType.File,\n [NodeType.File]: node.file,\n };\n\n return transformedFileContent;\n },\n};\n\n/**\n * Markdown file plugin\n */\n\nconst markdownFilePlugin: Plugins = {\n id: 'markdown-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Markdown,\n transform: (node: MarkdownContent, props, deepTransformNode) => {\n const simplifiedMarkdownNode: MarkdownContentConstructor = {\n nodeType: NodeType.Markdown,\n [NodeType.Markdown]: deepTransformNode(node.markdown, props),\n };\n\n return simplifiedMarkdownNode;\n },\n};\n\n/**\n * Insertion file plugin\n */\n\nconst insertionFilePlugin: Plugins = {\n id: 'insertion-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Insertion,\n transform: (node: InsertionContent, props, deepTransformNode) => {\n const simplifiedInsertionNode: InsertionContentConstructor = {\n nodeType: NodeType.Insertion,\n [NodeType.Insertion]: deepTransformNode(node.insertion, props),\n };\n\n return simplifiedInsertionNode;\n },\n};\n\n/**\n * HTML file plugin\n */\n\nconst htmlFilePlugin: Plugins = {\n id: 'html-file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.HTML,\n transform: (node: HTMLContent, props, deepTransformNode) => {\n const simplifiedHTMLNode: HTMLContentConstructor = {\n nodeType: NodeType.HTML,\n [NodeType.HTML]: deepTransformNode(node.html, props),\n };\n\n return simplifiedHTMLNode;\n },\n};\n\n/**\n * Process content declaration content\n *\n * It filter node that are autogenerated by intlayer to do not rewrite them in the content declaration file.\n *\n * And write external sources as file content if necessary.\n */\nexport const processContentDeclarationContent = async (\n dictionary: Dictionary\n) =>\n deepTransformNode(dictionary, {\n dictionaryKey: dictionary.key,\n keyPath: [],\n plugins: [\n writeFilePlugin,\n markdownFilePlugin,\n insertionFilePlugin,\n htmlFilePlugin,\n ],\n });\n"],"mappings":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AS,CACP,EACA,EACA,EACA,EACD,CACF,CAAC"}
|
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{getNodeType as e}from"@intlayer/core/dictionaryManipulator";import{NodeType as t}from"@intlayer/types/nodeType";import*as n from"recast";import*as r from"recast/parsers/babel-ts.js";const i=n.types.builders,a=n.types.namedTypes,o=e=>{for(;e&&(a.TSSatisfiesExpression?.check(e)||a.TSAsExpression?.check(e)||a.TSTypeAssertion?.check(e)||a.TSNonNullExpression?.check(e)||[`TSSatisfiesExpression`,`TSAsExpression`,`TSTypeAssertion`,`TSNonNullExpression`].includes(e.type));)e=e.expression;return e},s=(e,t)=>e.properties.find(e=>!!((a.Property.check(e)||a.ObjectProperty.check(e))&&(a.Identifier.check(e.key)&&e.key.name===t||a.StringLiteral.check(e.key)&&e.key.value===t||a.Literal.check(e.key)&&e.key.value===t))),c=(e,t,n)=>{let r=n.match(/\d+(?!.*\d)/);if(!r)return;let o=r[0];if(a.ObjectExpression.check(e)){for(let n of e.properties)if(a.Property.check(n)||a.ObjectProperty.check(n)){let e=``;if(a.Identifier.check(n.key)?e=n.key.name:(a.Literal.check(n.key)&&typeof n.key.value==`string`||a.StringLiteral.check(n.key))&&(e=n.key.value),e&&e!==t){if(a.Literal.check(n.value)&&typeof n.value.value==`string`){let e=n.value.value;e.match(/\d+(?!.*\d)/)&&(n.value=i.literal(e.replace(/(\d+)(?!.*\d)/,o)))}else if(a.StringLiteral.check(n.value)){let e=n.value.value;e.match(/\d+(?!.*\d)/)&&(n.value=i.stringLiteral(e.replace(/(\d+)(?!.*\d)/,o)))}}}}},l=n=>{if(typeof n!=`object`||!n||Array.isArray(n))return!1;let r=e(n);if(r===t.Translation)return!0;if(r===t.Markdown||r===t.HTML||r===t.Insertion)return l(n[r]);if(r===t.Enumeration||r===t.Condition||r===t.Gender){let e=n[r];if(e&&typeof e==`object`)return Object.values(e).some(e=>l(e))}return!1},u=(n,r,s,f)=>{let p=o(r);if(p&&!(a.Literal.check(p)||a.StringLiteral.check(p)||a.NumericLiteral.check(p)||a.BooleanLiteral.check(p)||a.TemplateLiteral.check(p)||a.ObjectExpression.check(p)||a.ArrayExpression.check(p)||a.CallExpression.check(p)&&a.Identifier.check(p.callee)&&[`t`,`enu`,`cond`,`gender`,`insert`,`md`,`html`,`file`,`nest`].includes(p.callee.name)))return r;if(s&&!r&&!l(n)){if(n===null)return i.literal(null);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)return typeof n==`string`&&n.includes(`
|
|
2
|
+
`)?i.templateLiteral([i.templateElement({raw:n,cooked:n},!0)],[]):i.literal(n)}if(s&&r&&!l(n)){if(a.CallExpression.check(r)&&a.Identifier.check(r.callee)&&r.callee.name===`t`){let e=o(r.arguments[0]);if(a.ObjectExpression.check(e))return typeof n==`string`&&c(e,s,n),d(e,{[s]:n},s,f),s||f.add(`t`),r}if((!n||typeof n!=`object`)&&a.CallExpression.check(r)&&a.Identifier.check(r.callee)&&r.callee.name===`md`){let e=r.arguments[0];if(a.CallExpression.check(e)&&a.Identifier.check(e.callee)&&e.callee.name===`t`){let t=o(e.arguments[0]);if(a.ObjectExpression.check(t))return typeof n==`string`&&c(t,s,n),d(t,{[s]:n},s,f),f.add(`md`),f.add(`t`),r}}}if(n===null)return i.literal(null);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`){if(p){if(a.TemplateLiteral.check(p)&&p.expressions.length===0)return p.quasis[0].value.raw=String(n),p.quasis[0].value.cooked=String(n),r;if(a.Literal.check(p)||a.StringLiteral.check(p))return p.value=n,r}return typeof n==`string`&&n.includes(`
|
|
3
|
+
`)?i.templateLiteral([i.templateElement({raw:n,cooked:n},!0)],[]):i.literal(n)}if(Array.isArray(n))if(p&&a.ArrayExpression.check(p)){let e=[...p.elements];return n.forEach((t,n)=>{e[n]=u(t,e[n],s,f)}),e.length>n.length&&(e.length=n.length),p.elements=e,r}else return i.arrayExpression(n.map(e=>u(e,null,s,f)));let m=n&&typeof n==`object`&&!Array.isArray(n)?e(n):null;if(m&&Object.values(t).includes(m)&&m!==t.Text){let e=n[m],o=``;m===t.Translation?o=`t`:m===t.Enumeration?o=`enu`:m===t.Condition?o=`cond`:m===t.Gender?o=`gender`:m===t.Insertion?o=`insert`:m===t.Markdown?o=`md`:m===t.HTML?o=`html`:m===t.File?o=`file`:m===t.Nested&&(o=`nest`),o&&f.add(o);let c=r&&a.CallExpression.check(r)&&a.Identifier.check(r.callee)&&r.callee.name===o;if([`t`,`enu`,`cond`,`gender`].includes(o)){let t=null;return t=c&&r.arguments.length>0&&a.ObjectExpression.check(r.arguments[0])?r.arguments[0]:i.objectExpression([]),d(t,e,s,f),c?r:i.callExpression(i.identifier(o),[t])}if([`md`,`html`,`insert`,`file`].includes(o)){let t=u(e,c&&r.arguments.length>0?r.arguments[0]:null,s,f);return c?(r.arguments[0]=t,r):i.callExpression(i.identifier(o),[t])}if(o===`nest`){let t=[i.literal(e.dictionaryKey)];return e.path&&t.push(i.literal(e.path)),c?(r.arguments=t,r):i.callExpression(i.identifier(`nest`),t)}}let h=p&&a.ObjectExpression.check(p)?p:i.objectExpression([]);return d(h,n,s,f),r&&p===r?h:r||h},d=(e,t,n,r)=>{for(let[a,o]of Object.entries(t)){if(o===void 0)continue;let t=s(e,a);if(t)t.value=u(o,t.value,n,r);else{let t=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(a)?i.identifier(a):i.literal(a),s=u(o,null,n,r);e.properties.push(i.property(`init`,t,s))}}},f=(e,t,r)=>{if(t.size===0)return;let o=new Set,s=null;n.visit(e,{visitImportDeclaration(e){return e.node.source.value===`intlayer`&&(s=e,e.node.specifiers?.forEach(e=>{a.ImportSpecifier.check(e)&&typeof e.imported.name==`string`&&o.add(e.imported.name)})),!1},visitVariableDeclaration(e){return e.node.declarations.forEach(e=>{if(a.VariableDeclarator.check(e)&&a.CallExpression.check(e.init)&&a.Identifier.check(e.init.callee)&&e.init.callee.name===`require`){let t=e.init.arguments[0];a.Literal.check(t)&&t.value===`intlayer`&&(a.ObjectPattern.check(e.id)?e.id.properties.forEach(e=>{if(a.Property.check(e)&&(a.Identifier.check(e.key)||a.Identifier.check(e.value))){let t=a.Identifier.check(e.key)?e.key.name:e.value.name;o.add(t)}}):a.Identifier.check(e.id)&&o.add(e.id.name))}}),!1}});let c=Array.from(t).filter(e=>!o.has(e));if(c.length!==0)if(r)if(s)c.forEach(e=>{s.node.specifiers.push(i.importSpecifier(i.identifier(e)))}),s.node.specifiers.sort((e,t)=>e.imported.name.localeCompare(t.imported.name));else{let t=c.sort().map(e=>i.importSpecifier(i.identifier(e))),n=i.importDeclaration(t,i.literal(`intlayer`));e.program.body.unshift(n)}else{let t=0;e.program.body.length>0&&a.ExpressionStatement.check(e.program.body[0])&&a.Literal.check(e.program.body[0].expression)&&(t=1);let n=[],r=c.sort().map(e=>{let t=i.property(`init`,i.identifier(e),i.identifier(e));return t.shorthand=!0,t});n.push(i.variableDeclaration(`const`,[i.variableDeclarator(i.objectPattern(r),i.callExpression(i.identifier(`require`),[i.literal(`intlayer`)]))])),e.program.body.splice(t,0,...n)}},p=async(e,t,s,c)=>{if(!t||typeof t!=`object`)return e;let l;try{l=n.parse(e,{parser:r})}catch(t){return console.error({error:t}),e}let u=null,p=!1;if(n.visit(l,{visitExportDefaultDeclaration(){return p=!0,!1},visitImportDeclaration(){return p=!0,!1}}),n.visit(l,{visitExportDefaultDeclaration(e){let t=e.node.declaration,r=o(t);if(a.ObjectExpression.check(r))u=r;else if(a.Identifier.check(r)){let e=r.name;n.visit(l,{visitVariableDeclarator(t){let n=o(t.node.init);return a.Identifier.check(t.node.id)&&t.node.id.name===e&&a.ObjectExpression.check(n)&&(u=n),!1}})}return!1},visitAssignmentExpression(e){let t=e.node.left;if(a.MemberExpression.check(t)){if(a.Identifier.check(t.object)&&t.object.name===`module`&&a.Identifier.check(t.property)&&t.property.name===`exports`){let t=o(e.node.right);a.ObjectExpression.check(t)&&(u=t)}if(a.Identifier.check(t.object)&&t.object.name===`exports`&&a.Identifier.check(t.property)&&t.property.name===`default`){let t=o(e.node.right);a.ObjectExpression.check(t)&&(u=t)}}this.traverse(e)}}),u||n.visit(l,{visitVariableDeclarator(e){let t=o(e.node.init);return!u&&a.ObjectExpression.check(t)&&(u=t),!1}}),!u)return e;let m=new Set,h=s??`en`,g=[`id`,`locale`,`filled`,`fill`,`title`,`description`,`tags`,`version`,`priority`,`contentAutoTransformation`];if(c)u.properties=u.properties.filter(e=>{if(a.Property.check(e)||a.ObjectProperty.check(e)){let t=``;return a.Identifier.check(e.key)?t=e.key.name:a.StringLiteral.check(e.key)?t=e.key.value:a.Literal.check(e.key)&&(t=String(e.key.value)),![`key`,`content`,...g].includes(t)}return!0}),n.visit(l,{visitNode(e){let t=e.node;(a.TSSatisfiesExpression?.check(t)||t.type===`TSSatisfiesExpression`)&&t.typeAnnotation&&a.TSTypeReference.check(t.typeAnnotation)&&a.Identifier.check(t.typeAnnotation.typeName)&&t.typeAnnotation.typeName.name===`Dictionary`&&(t.typeAnnotation=i.tsIndexedAccessType(i.tsTypeReference(i.identifier(`Dictionary`)),i.tsLiteralType(i.stringLiteral(`content`)))),this.traverse(e)}});else for(let e of g)t[e]!==void 0&&d(u,{[e]:t[e]},void 0,m);return t.content!==void 0&&d(u,c?t.content:{content:t.content},h,m),f(l,m,p),n.print(l).code};export{p as transformJSFile};
|
|
2
4
|
//# sourceMappingURL=transformJSFile.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformJSFile.mjs","names":[],"sources":["../../../src/writeContentDeclaration/transformJSFile.ts"],"sourcesContent":["import { getNodeType } from '@intlayer/core/dictionaryManipulator';\nimport type { ContentNode, Dictionary, Locale } from '@intlayer/types';\nimport { NodeType } from '@intlayer/types';\nimport * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Unwraps TypeScript/Babel expression wrappers (satisfies, as, !, <Type>).\n */\nconst unwrap = (node: any) => {\n while (\n node &&\n (n.TSSatisfiesExpression?.check(node) ||\n n.TSAsExpression?.check(node) ||\n n.TSTypeAssertion?.check(node) ||\n n.TSNonNullExpression?.check(node))\n ) {\n node = node.expression;\n }\n return node;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n\n return false;\n });\n};\n\n/**\n * Synchronizes numeric suffixes across locales.\n * E.g. \"Hello 1\" -> \"Hello 3\" updates \"Bonjour 1\" to \"Bonjour 3\".\n */\nconst syncNumericSuffixAcrossLocales = (\n existingNode: any,\n fallbackLocaleCode: string,\n newFallbackValue: string\n) => {\n const trailingNumberMatch = newFallbackValue.match(/\\d+(?!.*\\d)/);\n if (!trailingNumberMatch) return;\n const newTrailingNumber = trailingNumberMatch[0];\n\n if (n.ObjectExpression.check(existingNode)) {\n for (const prop of existingNode.properties) {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (\n n.Literal.check(prop.key) &&\n typeof prop.key.value === 'string'\n )\n propName = prop.key.value;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n\n if (propName && propName !== fallbackLocaleCode) {\n if (\n n.Literal.check(prop.value) &&\n typeof prop.value.value === 'string'\n ) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.literal(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n } else if (n.StringLiteral.check(prop.value)) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.stringLiteral(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n }\n }\n }\n }\n }\n};\n\n/**\n * Checks if a value represents a multilingual Intlayer node.\n * A node is multilingual if it is a Translation node, or if it is a specialized node\n * (Markdown, HTML, etc.) that contains a Translation node.\n */\nconst isMultilingualNode = (val: any): boolean => {\n if (typeof val !== 'object' || val === null || Array.isArray(val)) {\n return false;\n }\n\n const nodeType = getNodeType(val as ContentNode);\n\n if (nodeType === NodeType.Translation) {\n return true;\n }\n\n if (\n nodeType === NodeType.Markdown ||\n nodeType === NodeType.HTML ||\n nodeType === NodeType.Insertion\n ) {\n return isMultilingualNode((val as any)[nodeType]);\n }\n\n if (\n nodeType === NodeType.Enumeration ||\n nodeType === NodeType.Condition ||\n nodeType === NodeType.Gender\n ) {\n const data = (val as any)[nodeType];\n\n if (data && typeof data === 'object') {\n return Object.values(data).some((v) => isMultilingualNode(v));\n }\n }\n\n return false;\n};\n\n/**\n * Recursively builds or updates an AST node for a given dictionary value.\n */\nconst buildNodeForValue = (\n val: any,\n existingNode: any,\n fallbackLocale: string | undefined,\n requiredImports: Set<string>\n): any => {\n if (fallbackLocale && existingNode && !isMultilingualNode(val)) {\n if (\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 't'\n ) {\n const arg = unwrap(existingNode.arguments[0]);\n\n if (n.ObjectExpression.check(arg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(arg, fallbackLocale, val);\n }\n updateObjectLiteral(\n arg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n requiredImports.add('t');\n\n return existingNode;\n }\n }\n\n if (\n (!val || typeof val !== 'object') &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 'md'\n ) {\n const innerArg = existingNode.arguments[0];\n\n if (\n n.CallExpression.check(innerArg) &&\n n.Identifier.check(innerArg.callee) &&\n innerArg.callee.name === 't'\n ) {\n const tArg = unwrap(innerArg.arguments[0]);\n\n if (n.ObjectExpression.check(tArg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(tArg, fallbackLocale, val);\n }\n updateObjectLiteral(\n tArg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n requiredImports.add('md');\n requiredImports.add('t');\n\n return existingNode;\n }\n }\n }\n }\n\n // 1. Primitives\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return b.literal(val);\n }\n\n // 2. Arrays\n if (Array.isArray(val)) {\n const unwrappedExisting = unwrap(existingNode);\n\n if (unwrappedExisting && n.ArrayExpression.check(unwrappedExisting)) {\n const elements = [...unwrappedExisting.elements];\n val.forEach((item, i) => {\n elements[i] = buildNodeForValue(\n item,\n elements[i],\n fallbackLocale,\n requiredImports\n );\n });\n\n if (elements.length > val.length) elements.length = val.length;\n unwrappedExisting.elements = elements as any;\n\n return existingNode;\n } else {\n return b.arrayExpression(\n val.map((item) =>\n buildNodeForValue(item, null, fallbackLocale, requiredImports)\n )\n );\n }\n }\n\n // 3. Intlayer Specialized Nodes (t, enu, cond, gender, insert, md, html, file, nest)\n const nodeType =\n val && typeof val === 'object' && !Array.isArray(val)\n ? getNodeType(val as ContentNode)\n : null;\n\n if (\n nodeType &&\n Object.values(NodeType).includes(nodeType as any) &&\n nodeType !== NodeType.Text\n ) {\n const nodeData = (val as any)[nodeType];\n let calleeName = '';\n\n if (nodeType === NodeType.Translation) calleeName = 't';\n else if (nodeType === NodeType.Enumeration) calleeName = 'enu';\n else if (nodeType === NodeType.Condition) calleeName = 'cond';\n else if (nodeType === NodeType.Gender) calleeName = 'gender';\n else if (nodeType === NodeType.Insertion) calleeName = 'insert';\n else if (nodeType === NodeType.Markdown) calleeName = 'md';\n else if (nodeType === NodeType.HTML) calleeName = 'html';\n else if (nodeType === NodeType.File) calleeName = 'file';\n else if (nodeType === NodeType.Nested) calleeName = 'nest';\n\n if (calleeName) requiredImports.add(calleeName);\n\n const isMatchingCall =\n existingNode &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === calleeName;\n\n if (['t', 'enu', 'cond', 'gender'].includes(calleeName)) {\n let objArg: any = null;\n\n if (\n isMatchingCall &&\n existingNode.arguments.length > 0 &&\n n.ObjectExpression.check(existingNode.arguments[0])\n ) {\n objArg = existingNode.arguments[0];\n } else {\n objArg = b.objectExpression([]);\n }\n updateObjectLiteral(objArg, nodeData, fallbackLocale, requiredImports);\n\n return isMatchingCall\n ? existingNode\n : b.callExpression(b.identifier(calleeName), [objArg]);\n }\n\n if (['md', 'html', 'insert', 'file'].includes(calleeName)) {\n const argNode = buildNodeForValue(\n nodeData,\n isMatchingCall && existingNode.arguments.length > 0\n ? existingNode.arguments[0]\n : null,\n fallbackLocale,\n requiredImports\n );\n\n if (isMatchingCall) {\n existingNode.arguments[0] = argNode;\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(calleeName), [argNode]);\n }\n\n if (calleeName === 'nest') {\n const args = [b.literal(nodeData.dictionaryKey)];\n\n if (nodeData.path) args.push(b.literal(nodeData.path));\n\n if (isMatchingCall) {\n existingNode.arguments = args;\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier('nest'), args);\n }\n }\n\n // 4. Plain Object\n const unwrappedExisting = unwrap(existingNode);\n const objNode =\n unwrappedExisting && n.ObjectExpression.check(unwrappedExisting)\n ? unwrappedExisting\n : b.objectExpression([]);\n updateObjectLiteral(objNode, val, fallbackLocale, requiredImports);\n\n return existingNode && unwrappedExisting === existingNode\n ? objNode\n : existingNode || objNode;\n};\n\n/**\n * Recursively updates the AST object literal properties.\n */\nconst updateObjectLiteral = (\n node: recast.types.namedTypes.ObjectExpression,\n data: Record<string, any>,\n fallbackLocale: string | undefined,\n requiredImports: Set<string>\n) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp) {\n existingProp.value = buildNodeForValue(\n val,\n existingProp.value,\n fallbackLocale,\n requiredImports\n );\n } else {\n const isValidId = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);\n const keyNode = isValidId ? b.identifier(key) : b.literal(key);\n const valueNode = buildNodeForValue(\n val,\n null,\n fallbackLocale,\n requiredImports\n );\n node.properties.push(b.property('init', keyNode, valueNode));\n }\n }\n};\n\n/**\n * Modifies the AST's top-level imports to inject dynamically needed helper utilities seamlessly.\n */\nconst addImports = (ast: any, requiredImports: Set<string>, isESM: boolean) => {\n if (requiredImports.size === 0) return;\n\n const existingCoreImports = new Set<string>();\n let hasFileImport = false;\n let coreImportPath: any = null;\n\n recast.visit(ast, {\n visitImportDeclaration(path) {\n const source = path.node.source.value;\n\n if (source === 'intlayer') {\n coreImportPath = path;\n path.node.specifiers?.forEach((spec) => {\n if (\n n.ImportSpecifier.check(spec) &&\n typeof spec.imported.name === 'string'\n ) {\n existingCoreImports.add(spec.imported.name);\n }\n });\n } else if (source === 'intlayer/file') {\n hasFileImport = true;\n }\n\n return false;\n },\n visitVariableDeclaration(path) {\n path.node.declarations.forEach((decl) => {\n if (\n n.VariableDeclarator.check(decl) &&\n n.CallExpression.check(decl.init) &&\n n.Identifier.check(decl.init.callee) &&\n decl.init.callee.name === 'require'\n ) {\n const arg = decl.init.arguments[0];\n\n if (n.Literal.check(arg)) {\n if (arg.value === 'intlayer') {\n if (n.ObjectPattern.check(decl.id)) {\n decl.id.properties.forEach((prop) => {\n if (n.Property.check(prop) && n.Identifier.check(prop.key)) {\n existingCoreImports.add(prop.key.name);\n }\n });\n }\n } else if (arg.value === 'intlayer/file') {\n hasFileImport = true;\n }\n }\n }\n });\n\n return false;\n },\n });\n\n const missingCore = Array.from(requiredImports).filter(\n (imp) => imp !== 'file' && !existingCoreImports.has(imp)\n );\n const needsFile = requiredImports.has('file') && !hasFileImport;\n\n if (missingCore.length === 0 && !needsFile) return;\n\n if (isESM) {\n if (missingCore.length > 0) {\n if (coreImportPath) {\n missingCore.forEach((imp) => {\n coreImportPath.node.specifiers.push(\n b.importSpecifier(b.identifier(imp))\n );\n });\n coreImportPath.node.specifiers.sort((a: any, b: any) =>\n a.imported.name.localeCompare(b.imported.name)\n );\n } else {\n const specifiers = missingCore\n .sort()\n .map((imp) => b.importSpecifier(b.identifier(imp)));\n const newImport = b.importDeclaration(\n specifiers,\n b.literal('intlayer')\n );\n ast.program.body.unshift(newImport);\n }\n }\n\n if (needsFile) {\n let insertIndex = 0;\n ast.program.body.forEach((node: any, i: number) => {\n if (\n n.ImportDeclaration.check(node) &&\n node.source.value === 'intlayer'\n ) {\n insertIndex = i + 1;\n }\n });\n const fileImport = b.importDeclaration(\n [b.importSpecifier(b.identifier('file'))],\n b.literal('intlayer/file')\n );\n ast.program.body.splice(insertIndex, 0, fileImport);\n }\n } else {\n let insertIndex = 0;\n\n if (\n ast.program.body.length > 0 &&\n n.ExpressionStatement.check(ast.program.body[0]) &&\n n.Literal.check(ast.program.body[0].expression)\n ) {\n insertIndex = 1; // Insert after 'use strict'\n }\n const cjsLines: any[] = [];\n\n if (missingCore.length > 0) {\n const properties = missingCore.sort().map((imp) => {\n const prop = b.property('init', b.identifier(imp), b.identifier(imp));\n prop.shorthand = true;\n\n return prop;\n });\n cjsLines.push(\n b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern(properties),\n b.callExpression(b.identifier('require'), [b.literal('intlayer')])\n ),\n ])\n );\n }\n\n if (needsFile) {\n const prop = b.property(\n 'init',\n b.identifier('file'),\n b.identifier('file')\n );\n prop.shorthand = true;\n cjsLines.push(\n b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern([prop]),\n b.callExpression(b.identifier('require'), [\n b.literal('intlayer/file'),\n ])\n ),\n ])\n );\n }\n ast.program.body.splice(insertIndex, 0, ...cjsLines);\n }\n};\n\n/**\n * Updates a JS/TS file seamlessly to map new localization keys, arrays, complex nodes and nested dictionaries gracefully using AST updates via Recast parser.\n */\nexport const transformJSFile = async (\n fileContent: string,\n dictionary: Dictionary,\n fallbackLocale?: Locale\n): Promise<string> => {\n if (!dictionary || typeof dictionary !== 'object') return fileContent;\n\n let ast: any;\n try {\n ast = recast.parse(fileContent, {\n parser: require('recast/parsers/typescript'),\n });\n } catch {\n try {\n ast = recast.parse(fileContent); // Strict ESM fallback\n } catch {\n return fileContent;\n }\n }\n\n let rootObject: any = null;\n let isESM = false;\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n isESM = true;\n\n return false;\n },\n visitImportDeclaration() {\n isESM = true;\n\n return false;\n },\n });\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n const unwrappedDecl = unwrap(decl);\n\n if (n.ObjectExpression.check(unwrappedDecl)) {\n rootObject = unwrappedDecl;\n } else if (n.Identifier.check(unwrappedDecl)) {\n const varName = unwrappedDecl.name;\n recast.visit(ast, {\n visitVariableDeclarator(vp) {\n const unwrappedInit = unwrap(vp.node.init);\n\n if (\n n.Identifier.check(vp.node.id) &&\n vp.node.id.name === varName &&\n n.ObjectExpression.check(unwrappedInit)\n ) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n return false;\n },\n visitAssignmentExpression(path) {\n const left = path.node.left;\n\n if (n.MemberExpression.check(left)) {\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'module' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'exports'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'exports' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'default'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n }\n this.traverse(path);\n },\n });\n\n if (!rootObject) {\n recast.visit(ast, {\n visitVariableDeclarator(path) {\n const unwrappedInit = unwrap(path.node.init);\n\n if (!rootObject && n.ObjectExpression.check(unwrappedInit)) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n if (!rootObject) return fileContent;\n\n const requiredImports = new Set<string>();\n const effectiveFallbackLocale = (fallbackLocale as string) ?? 'en';\n\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n ];\n\n for (const prop of metadataProperties) {\n if ((dictionary as any)[prop] !== undefined) {\n updateObjectLiteral(\n rootObject,\n { [prop]: (dictionary as any)[prop] },\n undefined,\n requiredImports\n );\n }\n }\n\n if (dictionary.content !== undefined) {\n updateObjectLiteral(\n rootObject,\n { content: dictionary.content },\n effectiveFallbackLocale,\n requiredImports\n );\n }\n\n addImports(ast, requiredImports, isESM);\n\n return recast.print(ast).code;\n};\n"],"mappings":"qMAKA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,EAAU,GAAc,CAC5B,KACE,IACC,EAAE,uBAAuB,MAAM,EAAK,EACnC,EAAE,gBAAgB,MAAM,EAAK,EAC7B,EAAE,iBAAiB,MAAM,EAAK,EAC9B,EAAE,qBAAqB,MAAM,EAAK,GAEpC,EAAO,EAAK,WAEd,OAAO,GAOH,GAAuB,EAAW,IAC/B,EAAK,WAAW,KAAM,GAC3B,IAAI,EAAE,SAAS,MAAM,EAAK,EAAI,EAAE,eAAe,MAAM,EAAK,IACpD,EAAE,WAAW,MAAM,EAAK,IAAI,EAAI,EAAK,IAAI,OAAS,GAElD,EAAE,cAAc,MAAM,EAAK,IAAI,EAAI,EAAK,IAAI,QAAU,GAGtD,EAAE,QAAQ,MAAM,EAAK,IAAI,EAAI,EAAK,IAAI,QAAU,IAItD,CAOE,GACJ,EACA,EACA,IACG,CACH,IAAM,EA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MAAM,EAAK,CAAE,CAClC,GACE,EAAE,WAAW,MAAM,EAAK,OAAO,EAC/B,EAAK,OAAO,OAAS,UACrB,EAAE,WAAW,MAAM,EAAK,SAAS,EACjC,EAAK,SAAS,OAAS,UACvB,CACA,IAAM,EAAiB,EAAO,EAAK,KAAK,MAAM,CAE1C,EAAE,iBAAiB,MAAM,EAAe,GAC1C,EAAa,GAIjB,GACE,EAAE,WAAW,MAAM,EAAK,OAAO,EAC/B,EAAK,OAAO,OAAS,WACrB,EAAE,WAAW,MAAM,EAAK,SAAS,EACjC,EAAK,SAAS,OAAS,UACvB,CACA,IAAM,EAAiB,EAAO,EAAK,KAAK,MAAM,CAE1C,EAAE,iBAAiB,MAAM,EAAe,GAC1C,EAAa,IAInB,KAAK,SAAS,EAAK,EAEtB,CAAC,CAEG,GACH,EAAO,MAAM,EAAK,CAChB,wBAAwB,EAAM,CAC5B,IAAM,EAAgB,EAAO,EAAK,KAAK,KAAK,CAM5C,MAJI,CAAC,GAAc,EAAE,iBAAiB,MAAM,EAAc,GACxD,EAAa,GAGR,IAEV,CAAC,CAGA,CAAC,EAAY,OAAO,EAExB,IAAM,EAAkB,IAAI,IACtB,EAA2B,GAA6B,KAe9D,IAAK,IAAM,IAbgB,CACzB,KACA,SACA,SACA,OACA,QACA,cACA,OACA,UACA,WACA,4BACD,CAGM,EAAmB,KAAU,IAAA,IAChC,EACE,EACA,EAAG,GAAQ,EAAmB,GAAO,CACrC,IAAA,GACA,EACD,CAeL,OAXI,EAAW,UAAY,IAAA,IACzB,EACE,EACA,CAAE,QAAS,EAAW,QAAS,CAC/B,EACA,EACD,CAGH,EAAW,EAAK,EAAiB,EAAM,CAEhC,EAAO,MAAM,EAAI,CAAC"}
|
|
1
|
+
{"version":3,"file":"transformJSFile.mjs","names":[],"sources":["../../../src/writeContentDeclaration/transformJSFile.ts"],"sourcesContent":["import { getNodeType } from '@intlayer/core/dictionaryManipulator';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { ContentNode, Dictionary } from '@intlayer/types/dictionary';\nimport { NodeType } from '@intlayer/types/nodeType';\nimport * as recast from 'recast';\nimport * as babelTsParser from 'recast/parsers/babel-ts.js';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Unwraps TypeScript/Babel expression wrappers (satisfies, as, !, <Type>).\n * Uses string fallbacks to bypass outdated ast-types definitions.\n */\nconst unwrap = (node: any) => {\n while (\n node &&\n (n.TSSatisfiesExpression?.check(node) ||\n n.TSAsExpression?.check(node) ||\n n.TSTypeAssertion?.check(node) ||\n n.TSNonNullExpression?.check(node) ||\n [\n 'TSSatisfiesExpression',\n 'TSAsExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n ].includes(node.type))\n ) {\n node = node.expression;\n }\n return node;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n\n return false;\n });\n};\n\n/**\n * Synchronizes numeric suffixes across locales.\n * E.g. \"Hello 1\" -> \"Hello 3\" updates \"Bonjour 1\" to \"Bonjour 3\".\n */\nconst syncNumericSuffixAcrossLocales = (\n existingNode: any,\n fallbackLocaleCode: string,\n newFallbackValue: string\n) => {\n const trailingNumberMatch = newFallbackValue.match(/\\d+(?!.*\\d)/);\n if (!trailingNumberMatch) return;\n const newTrailingNumber = trailingNumberMatch[0];\n\n if (n.ObjectExpression.check(existingNode)) {\n for (const prop of existingNode.properties) {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (\n n.Literal.check(prop.key) &&\n typeof prop.key.value === 'string'\n )\n propName = prop.key.value;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n\n if (propName && propName !== fallbackLocaleCode) {\n if (\n n.Literal.check(prop.value) &&\n typeof prop.value.value === 'string'\n ) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.literal(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n } else if (n.StringLiteral.check(prop.value)) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.stringLiteral(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n }\n }\n }\n }\n }\n};\n\n/**\n * Checks if a value represents a multilingual Intlayer node.\n * A node is multilingual if it is a Translation node, or if it is a specialized node\n * (Markdown, HTML, etc.) that contains a Translation node.\n */\nconst isMultilingualNode = (val: any): boolean => {\n if (typeof val !== 'object' || val === null || Array.isArray(val)) {\n return false;\n }\n\n const nodeType = getNodeType(val as ContentNode);\n\n if (nodeType === NodeType.Translation) {\n return true;\n }\n\n if (\n nodeType === NodeType.Markdown ||\n nodeType === NodeType.HTML ||\n nodeType === NodeType.Insertion\n ) {\n return isMultilingualNode((val as any)[nodeType]);\n }\n\n if (\n nodeType === NodeType.Enumeration ||\n nodeType === NodeType.Condition ||\n nodeType === NodeType.Gender\n ) {\n const data = (val as any)[nodeType];\n\n if (data && typeof data === 'object') {\n return Object.values(data).some((v) => isMultilingualNode(v));\n }\n }\n\n return false;\n};\n\n/**\n * Recursively builds or updates an AST node for a given dictionary value.\n */\nconst buildNodeForValue = (\n val: any,\n existingNode: any,\n fallbackLocale: string | undefined, // In per-locale mode, this is the locale of the file\n requiredImports: Set<string>\n): any => {\n const unwrappedExisting = unwrap(existingNode);\n\n // --- CRITICAL GUARD: STRICT AST PRESERVATION ---\n // If the existing node is code (JSX, Variables, standard functions), leave it alone.\n // Only allow updates to literals, plain objects, arrays, and Intlayer helpers.\n if (unwrappedExisting) {\n const isUpdatableNode =\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting) ||\n n.NumericLiteral.check(unwrappedExisting) ||\n n.BooleanLiteral.check(unwrappedExisting) ||\n n.TemplateLiteral.check(unwrappedExisting) ||\n n.ObjectExpression.check(unwrappedExisting) ||\n n.ArrayExpression.check(unwrappedExisting) ||\n (n.CallExpression.check(unwrappedExisting) &&\n n.Identifier.check(unwrappedExisting.callee) &&\n [\n 't',\n 'enu',\n 'cond',\n 'gender',\n 'insert',\n 'md',\n 'html',\n 'file',\n 'nest',\n ].includes(unwrappedExisting.callee.name));\n\n if (!isUpdatableNode) {\n return existingNode;\n }\n }\n\n // If we are in per-locale mode (fallbackLocale is set)\n // and the value is not already a complex translation node,\n // we want to store it as a simple literal, NOT wrapped in t().\n if (fallbackLocale && !existingNode && !isMultilingualNode(val)) {\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n }\n\n if (fallbackLocale && existingNode && !isMultilingualNode(val)) {\n if (\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 't'\n ) {\n const arg = unwrap(existingNode.arguments[0]);\n\n if (n.ObjectExpression.check(arg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(arg, fallbackLocale, val);\n }\n updateObjectLiteral(\n arg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n\n if (!fallbackLocale) {\n requiredImports.add('t');\n }\n\n return existingNode;\n }\n }\n\n if (\n (!val || typeof val !== 'object') &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 'md'\n ) {\n const innerArg = existingNode.arguments[0];\n\n if (\n n.CallExpression.check(innerArg) &&\n n.Identifier.check(innerArg.callee) &&\n innerArg.callee.name === 't'\n ) {\n const tArg = unwrap(innerArg.arguments[0]);\n\n if (n.ObjectExpression.check(tArg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(tArg, fallbackLocale, val);\n }\n updateObjectLiteral(\n tArg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n requiredImports.add('md');\n requiredImports.add('t');\n\n return existingNode;\n }\n }\n }\n }\n\n // 1. Primitives\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (unwrappedExisting) {\n // Preserve existing template literals (backticks)\n if (\n n.TemplateLiteral.check(unwrappedExisting) &&\n unwrappedExisting.expressions.length === 0\n ) {\n unwrappedExisting.quasis[0].value.raw = String(val);\n unwrappedExisting.quasis[0].value.cooked = String(val);\n return existingNode;\n }\n // Preserve existing standard literals (keeps quote styling)\n if (\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting)\n ) {\n unwrappedExisting.value = val;\n return existingNode;\n }\n }\n\n // Force multiline strings to use Template Literals\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n\n // 2. Arrays\n if (Array.isArray(val)) {\n if (unwrappedExisting && n.ArrayExpression.check(unwrappedExisting)) {\n const elements = [...unwrappedExisting.elements];\n val.forEach((item, i) => {\n elements[i] = buildNodeForValue(\n item,\n elements[i],\n fallbackLocale,\n requiredImports\n );\n });\n\n if (elements.length > val.length) elements.length = val.length;\n unwrappedExisting.elements = elements as any;\n\n return existingNode;\n } else {\n return b.arrayExpression(\n val.map((item) =>\n buildNodeForValue(item, null, fallbackLocale, requiredImports)\n )\n );\n }\n }\n\n // 3. Intlayer Specialized Nodes\n const nodeType =\n val && typeof val === 'object' && !Array.isArray(val)\n ? getNodeType(val as ContentNode)\n : null;\n\n if (\n nodeType &&\n Object.values(NodeType).includes(nodeType as any) &&\n nodeType !== NodeType.Text\n ) {\n const nodeData = (val as any)[nodeType];\n let calleeName = '';\n\n if (nodeType === NodeType.Translation) calleeName = 't';\n else if (nodeType === NodeType.Enumeration) calleeName = 'enu';\n else if (nodeType === NodeType.Condition) calleeName = 'cond';\n else if (nodeType === NodeType.Gender) calleeName = 'gender';\n else if (nodeType === NodeType.Insertion) calleeName = 'insert';\n else if (nodeType === NodeType.Markdown) calleeName = 'md';\n else if (nodeType === NodeType.HTML) calleeName = 'html';\n else if (nodeType === NodeType.File) calleeName = 'file';\n else if (nodeType === NodeType.Nested) calleeName = 'nest';\n\n if (calleeName) requiredImports.add(calleeName);\n\n const isMatchingCall =\n existingNode &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === calleeName;\n\n if (['t', 'enu', 'cond', 'gender'].includes(calleeName)) {\n let objArg: any = null;\n\n if (\n isMatchingCall &&\n existingNode.arguments.length > 0 &&\n n.ObjectExpression.check(existingNode.arguments[0])\n ) {\n objArg = existingNode.arguments[0];\n } else {\n objArg = b.objectExpression([]);\n }\n updateObjectLiteral(objArg, nodeData, fallbackLocale, requiredImports);\n\n return isMatchingCall\n ? existingNode\n : b.callExpression(b.identifier(calleeName), [objArg]);\n }\n\n if (['md', 'html', 'insert', 'file'].includes(calleeName)) {\n const argNode = buildNodeForValue(\n nodeData,\n isMatchingCall && existingNode.arguments.length > 0\n ? existingNode.arguments[0]\n : null,\n fallbackLocale,\n requiredImports\n );\n\n if (isMatchingCall) {\n existingNode.arguments[0] = argNode;\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(calleeName), [argNode]);\n }\n\n if (calleeName === 'nest') {\n const args = [b.literal(nodeData.dictionaryKey)];\n\n if (nodeData.path) args.push(b.literal(nodeData.path));\n\n if (isMatchingCall) {\n existingNode.arguments = args;\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier('nest'), args);\n }\n }\n\n // 4. Plain Object\n const objNode =\n unwrappedExisting && n.ObjectExpression.check(unwrappedExisting)\n ? unwrappedExisting\n : b.objectExpression([]);\n\n updateObjectLiteral(objNode, val, fallbackLocale, requiredImports);\n\n return existingNode && unwrappedExisting === existingNode\n ? objNode\n : existingNode || objNode;\n};\n\n/**\n * Recursively updates the AST object literal properties.\n */\nconst updateObjectLiteral = (\n node: recast.types.namedTypes.ObjectExpression,\n data: Record<string, any>,\n fallbackLocale: string | undefined,\n requiredImports: Set<string>\n) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp) {\n existingProp.value = buildNodeForValue(\n val,\n existingProp.value,\n fallbackLocale,\n requiredImports\n );\n } else {\n const isValidId = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);\n const keyNode = isValidId ? b.identifier(key) : b.literal(key);\n const valueNode = buildNodeForValue(\n val,\n null,\n fallbackLocale,\n requiredImports\n );\n node.properties.push(b.property('init', keyNode, valueNode));\n }\n }\n};\n\n/**\n * Modifies the AST's top-level imports to inject dynamically needed helper utilities seamlessly.\n */\nconst addImports = (ast: any, requiredImports: Set<string>, isESM: boolean) => {\n if (requiredImports.size === 0) return;\n\n const existingCoreImports = new Set<string>();\n let coreImportPath: any = null;\n\n recast.visit(ast, {\n visitImportDeclaration(path) {\n const source = path.node.source.value;\n\n if (source === 'intlayer') {\n coreImportPath = path;\n path.node.specifiers?.forEach((spec) => {\n if (\n n.ImportSpecifier.check(spec) &&\n typeof spec.imported.name === 'string'\n ) {\n existingCoreImports.add(spec.imported.name);\n }\n });\n }\n\n return false;\n },\n visitVariableDeclaration(path) {\n path.node.declarations.forEach((decl) => {\n if (\n n.VariableDeclarator.check(decl) &&\n n.CallExpression.check(decl.init) &&\n n.Identifier.check(decl.init.callee) &&\n decl.init.callee.name === 'require'\n ) {\n const arg = decl.init.arguments[0];\n\n if (n.Literal.check(arg)) {\n if (arg.value === 'intlayer') {\n if (n.ObjectPattern.check(decl.id)) {\n decl.id.properties.forEach((prop) => {\n if (\n n.Property.check(prop) &&\n (n.Identifier.check(prop.key) ||\n n.Identifier.check(prop.value))\n ) {\n const name = n.Identifier.check(prop.key)\n ? prop.key.name\n : (prop.value as any).name;\n existingCoreImports.add(name);\n }\n });\n } else if (n.Identifier.check(decl.id)) {\n // Handle const intlayer = require('intlayer')\n existingCoreImports.add(decl.id.name);\n }\n }\n }\n }\n });\n\n return false;\n },\n });\n\n const missingCore = Array.from(requiredImports).filter(\n (imp) => !existingCoreImports.has(imp)\n );\n\n if (missingCore.length === 0) return;\n\n if (isESM) {\n if (coreImportPath) {\n missingCore.forEach((imp) => {\n coreImportPath.node.specifiers.push(\n b.importSpecifier(b.identifier(imp))\n );\n });\n coreImportPath.node.specifiers.sort((a: any, b: any) =>\n a.imported.name.localeCompare(b.imported.name)\n );\n } else {\n const specifiers = missingCore\n .sort()\n .map((imp) => b.importSpecifier(b.identifier(imp)));\n const newImport = b.importDeclaration(specifiers, b.literal('intlayer'));\n ast.program.body.unshift(newImport);\n }\n } else {\n let insertIndex = 0;\n\n if (\n ast.program.body.length > 0 &&\n n.ExpressionStatement.check(ast.program.body[0]) &&\n n.Literal.check(ast.program.body[0].expression)\n ) {\n insertIndex = 1; // Insert after 'use strict'\n }\n const cjsLines: any[] = [];\n\n const properties = missingCore.sort().map((imp) => {\n const prop = b.property('init', b.identifier(imp), b.identifier(imp));\n prop.shorthand = true;\n\n return prop;\n });\n cjsLines.push(\n b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern(properties),\n b.callExpression(b.identifier('require'), [b.literal('intlayer')])\n ),\n ])\n );\n\n ast.program.body.splice(insertIndex, 0, ...cjsLines);\n }\n};\n\n/**\n * Updates a JS/TS file seamlessly to map new localization keys, arrays, complex nodes and nested dictionaries gracefully using AST updates via Recast parser.\n */\nexport const transformJSFile = async (\n fileContent: string,\n dictionary: Dictionary,\n fallbackLocale?: Locale,\n noMetadata?: boolean\n): Promise<string> => {\n if (!dictionary || typeof dictionary !== 'object') return fileContent;\n\n let ast: any;\n try {\n ast = recast.parse(fileContent, {\n parser: babelTsParser,\n });\n } catch (error) {\n console.error({ error });\n return fileContent;\n }\n\n let rootObject: any = null;\n let isESM = false;\n\n recast.visit(ast, {\n visitExportDefaultDeclaration() {\n isESM = true;\n\n return false;\n },\n visitImportDeclaration() {\n isESM = true;\n\n return false;\n },\n });\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n const unwrappedDecl = unwrap(decl);\n\n if (n.ObjectExpression.check(unwrappedDecl)) {\n rootObject = unwrappedDecl;\n } else if (n.Identifier.check(unwrappedDecl)) {\n const varName = unwrappedDecl.name;\n recast.visit(ast, {\n visitVariableDeclarator(vp) {\n const unwrappedInit = unwrap(vp.node.init);\n\n if (\n n.Identifier.check(vp.node.id) &&\n vp.node.id.name === varName &&\n n.ObjectExpression.check(unwrappedInit)\n ) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n return false;\n },\n visitAssignmentExpression(path) {\n const left = path.node.left;\n\n if (n.MemberExpression.check(left)) {\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'module' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'exports'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'exports' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'default'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n }\n this.traverse(path);\n },\n });\n\n if (!rootObject) {\n recast.visit(ast, {\n visitVariableDeclarator(path) {\n const unwrappedInit = unwrap(path.node.init);\n\n if (!rootObject && n.ObjectExpression.check(unwrappedInit)) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n if (!rootObject) return fileContent;\n\n const requiredImports = new Set<string>();\n const effectiveFallbackLocale = (fallbackLocale as string) ?? 'en';\n\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n ];\n\n if (noMetadata) {\n // Remove key, content and metadata properties if they exist\n rootObject.properties = rootObject.properties.filter((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n return !['key', 'content', ...metadataProperties].includes(propName);\n }\n return true;\n });\n\n // Update satisfies type if exists\n recast.visit(ast, {\n visitNode(path) {\n const node = path.node;\n if (\n (n.TSSatisfiesExpression?.check(node) ||\n node.type === 'TSSatisfiesExpression') &&\n (node as any).typeAnnotation &&\n n.TSTypeReference.check((node as any).typeAnnotation) &&\n n.Identifier.check((node as any).typeAnnotation.typeName) &&\n (node as any).typeAnnotation.typeName.name === 'Dictionary'\n ) {\n (node as any).typeAnnotation = b.tsIndexedAccessType(\n b.tsTypeReference(b.identifier('Dictionary')),\n b.tsLiteralType(b.stringLiteral('content'))\n );\n }\n this.traverse(path);\n },\n });\n } else {\n for (const prop of metadataProperties) {\n if ((dictionary as any)[prop] !== undefined) {\n updateObjectLiteral(\n rootObject,\n { [prop]: (dictionary as any)[prop] },\n undefined,\n requiredImports\n );\n }\n }\n }\n\n if (dictionary.content !== undefined) {\n updateObjectLiteral(\n rootObject,\n noMetadata\n ? (dictionary.content as Record<string, any>)\n : { content: dictionary.content },\n effectiveFallbackLocale,\n requiredImports\n );\n }\n\n addImports(ast, requiredImports, isESM);\n\n return recast.print(ast).code;\n};\n"],"mappings":"6LAOA,MAAM,EAAI,EA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AK,EACnC,EAAK,OAAS,0BACf,EAAa,gBACd,EAAE,gBAAgB,MAAO,EAAa,eAAe,EACrD,EAAE,WAAW,MAAO,EAAa,eAAe,SAAS,EACxD,EAAa,eAAe,SAAS,OAAS,eAE9C,EAAa,eAAiB,EAAE,oBAC/B,EAAE,gBAAgB,EAAE,WAAW,aAAa,CAAC,CAC7C,EAAE,cAAc,EAAE,cAAc,UAAU,CAAC,CAC5C,EAEH,KAAK,SAAS,EAAK,EAEtB,CAAC,MAEF,IAAK,IAAM,KAAQ,EACZ,EAAmB,KAAU,IAAA,IAChC,EACE,EACA,EAAG,GAAQ,EAAmB,GAAO,CACrC,IAAA,GACA,EACD,CAkBP,OAbI,EAAW,UAAY,IAAA,IACzB,EACE,EACA,EACK,EAAW,QACZ,CAAE,QAAS,EAAW,QAAS,CACnC,EACA,EACD,CAGH,EAAW,EAAK,EAAiB,EAAM,CAEhC,EAAO,MAAM,EAAI,CAAC"}
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import*as e from"recast";const t=e.types.builders,n=e.types.namedTypes,r=e=>typeof e==`object`&&!!e&&!Array.isArray(e),i=(e,t)=>e.properties.find(e=>!!((n.Property.check(e)||n.ObjectProperty.check(e))&&(n.Identifier.check(e.key)&&e.key.name===t||n.StringLiteral.check(e.key)&&e.key.value===t||n.Literal.check(e.key)&&e.key.value===t))),
|
|
1
|
+
import*as e from"recast";const t=e.types.builders,n=e.types.namedTypes,r=e=>typeof e==`object`&&!!e&&!Array.isArray(e),i=(e,t)=>t===null?n.Literal.check(e)&&e.value===null:typeof t==`string`||typeof t==`number`||typeof t==`boolean`?(n.Literal.check(e)||n.StringLiteral.check(e)||n.NumericLiteral.check(e)||n.BooleanLiteral.check(e))&&e.value===t:!1,a=(e,t)=>e.properties.find(e=>!!((n.Property.check(e)||n.ObjectProperty.check(e))&&(n.Identifier.check(e.key)&&e.key.name===t||n.StringLiteral.check(e.key)&&e.key.value===t||n.Literal.check(e.key)&&e.key.value===t))),o=e=>e===null?t.literal(null):typeof e==`string`||typeof e==`number`||typeof e==`boolean`?t.literal(e):Array.isArray(e)?t.arrayExpression(e.map(e=>o(e))):r(e)?t.objectExpression(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,n])=>t.property(`init`,t.stringLiteral(e),o(n)))):t.literal(null),s=(e,c)=>{for(let[l,u]of Object.entries(c)){if(u===void 0)continue;let c=a(e,l);c?.comments&&c.comments.forEach(e=>{(e.type===`Line`||e.type===`CommentLine`)&&(e.type=e.type===`Line`?`Block`:`CommentBlock`,e.value=`__INLINE_LINE__${e.value}`,e.leading=!1,e.trailing=!0)}),r(u)?c&&n.ObjectExpression.check(c.value)?s(c.value,u):c?n.Literal.check(c.value)&&c.value.value===u||(c.value=o(u)):e.properties.push(t.property(`init`,t.stringLiteral(l),o(u))):c?i(c.value,u)||(c.value=o(u)):e.properties.push(t.property(`init`,t.stringLiteral(l),o(u)))}},c=(t,r,i)=>{let a=`const _config = ${t.trim()||`{}`};`,o;try{o=e.parse(a)}catch{return JSON.stringify(i?r.content:r,null,2)}let c=o.program.body[0],l;if(n.VariableDeclaration.check(c)&&c.declarations.length>0&&n.VariableDeclarator.check(c.declarations[0])&&n.ObjectExpression.check(c.declarations[0].init)&&(l=c.declarations[0].init),i){let e=[`id`,`locale`,`filled`,`fill`,`title`,`description`,`tags`,`version`,`priority`,`contentAutoTransformation`,`$schema`];for(let t=l.properties.length-1;t>=0;t--){let r=l.properties[t];if(n.Property.check(r)||n.ObjectProperty.check(r)){let i=``;n.Identifier.check(r.key)?i=r.key.name:n.StringLiteral.check(r.key)?i=r.key.value:n.Literal.check(r.key)&&(i=String(r.key.value)),[`key`,`content`,...e].includes(i)&&l.properties.splice(t,1)}}}s(l,i?r.content:r);let u=e.print(o,{tabWidth:2,quote:`double`,trailingComma:!1}).code,d=u.indexOf(`{`),f=u.lastIndexOf(`}`),p=u.substring(d,f+1);return p=p.replace(/\s*\/\*__INLINE_LINE__(.*?)\*\/(\s*,?)/g,`$2 //$1`),p=p.replace(/\n[ \t]*\n/g,`
|
|
2
|
+
`),p};export{c as transformJSONFile};
|
|
2
3
|
//# sourceMappingURL=transformJSONFile.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformJSONFile.mjs","names":[],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types';\nimport * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a value is a plain object (and not null/array)\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n return false;\n });\n};\n\n/**\n * Recursively builds a clean recast AST node from a plain JS value.\n * Because these nodes lack `loc` tracking, recast is forced to pretty-print them.\n */\nconst buildASTNode = (val: unknown): any => {\n if (val === null) return b.literal(null);\n\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return b.literal(val);\n }\n\n if (Array.isArray(val)) {\n return b.arrayExpression(val.map((item) => buildASTNode(item)));\n }\n\n if (isPlainObject(val)) {\n return b.objectExpression(\n Object.entries(val)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) =>\n b.property('init', b.stringLiteral(k), buildASTNode(v))\n )\n );\n }\n\n return b.literal(null); // Fallback\n};\n\n/**\n * Recursively updates the AST object literal with new data.\n */\nconst updateObjectLiteral = (node: any, data: Record<string, any>) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (isPlainObject(val)) {\n if (existingProp && n.ObjectExpression.check(existingProp.value)) {\n updateObjectLiteral(existingProp.value, val);\n } else {\n const valueNode = buildASTNode(val);\n if (existingProp) {\n existingProp.value = valueNode;\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), valueNode)\n );\n }\n }\n } else {\n const valueNode = buildASTNode(val);\n if (existingProp) {\n existingProp.value = valueNode;\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), valueNode)\n );\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary\n): string => {\n // Wrap content to create valid syntax for the parser\n const wrappedContent = `const _config = ${fileContent.trim() || '{}'};`;\n\n let ast: ReturnType<typeof recast.parse>;\n try {\n ast = recast.parse(wrappedContent);\n } catch {\n // Fallback if parsing failed\n return JSON.stringify(dictionary, null, 2);\n }\n\n // Navigate the AST to locate the object literal initialized to `_config`\n const declaration = ast.program.body[0];\n let objectLiteral: any;\n\n if (\n n.VariableDeclaration.check(declaration) &&\n declaration.declarations.length > 0 &&\n n.VariableDeclarator.check(declaration.declarations[0]) &&\n n.ObjectExpression.check(declaration.declarations[0].init)\n ) {\n objectLiteral = declaration.declarations[0].init;\n }\n\n if (!objectLiteral) {\n // Fallback if the AST structure isn't what we expect\n return JSON.stringify(dictionary, null, 2);\n }\n\n // Update the AST in place\n updateObjectLiteral(objectLiteral, dictionary);\n\n // Print only the target object literal node\n return recast.print(objectLiteral, {\n tabWidth: 2,\n quote: 'double',\n trailingComma: false,\n }).code;\n};\n"],"mappings":"yBAGA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,EAAiB,GACd,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,EAAM,CAOvE,GAAuB,EAAW,IAC/B,EAAK,WAAW,KAAM,GAC3B,IAAI,EAAE,SAAS,MAAM,EAAK,EAAI,EAAE,eAAe,MAAM,EAAK,IACpD,EAAE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,EAAI,KAAK,GAEjE,EACJ,GAAI,CACF,EAAM,EAAO,MAAM,EAAe,MAC5B,CAEN,OAAO,KAAK,UAAU,EAAY,KAAM,EAAE,CAI5C,IAAM,EAAc,EAAI,QAAQ,KAAK,GACjC,EAoBJ,OAjBE,EAAE,oBAAoB,MAAM,EAAY,EACxC,EAAY,aAAa,OAAS,GAClC,EAAE,mBAAmB,MAAM,EAAY,aAAa,GAAG,EACvD,EAAE,iBAAiB,MAAM,EAAY,aAAa,GAAG,KAAK,GAE1D,EAAgB,EAAY,aAAa,GAAG,MAGzC,GAML,EAAoB,EAAe,EAAW,CAGvC,EAAO,MAAM,EAAe,CACjC,SAAU,EACV,MAAO,SACP,cAAe,GAChB,CAAC,CAAC,MAXM,KAAK,UAAU,EAAY,KAAM,EAAE"}
|
|
1
|
+
{"version":3,"file":"transformJSONFile.mjs","names":[],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a value is a plain object (and not null/array)\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Checks if a recast AST node value matches the incoming primitive value.\n */\nconst isPrimitiveEqual = (astNode: any, val: unknown): boolean => {\n if (val === null) {\n return n.Literal.check(astNode) && astNode.value === null;\n }\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return (\n (n.Literal.check(astNode) ||\n n.StringLiteral.check(astNode) ||\n n.NumericLiteral.check(astNode) ||\n n.BooleanLiteral.check(astNode)) &&\n astNode.value === val\n );\n }\n return false;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n return false;\n });\n};\n\n/**\n * Recursively builds a clean recast AST node from a plain JS value.\n * Because these nodes lack `loc` tracking, recast is forced to pretty-print them.\n */\nconst buildASTNode = (val: unknown): any => {\n if (val === null) return b.literal(null);\n\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return b.literal(val);\n }\n\n if (Array.isArray(val)) {\n return b.arrayExpression(val.map((item) => buildASTNode(item)));\n }\n\n if (isPlainObject(val)) {\n return b.objectExpression(\n Object.entries(val)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) =>\n b.property('init', b.stringLiteral(k), buildASTNode(v))\n )\n );\n }\n\n return b.literal(null); // Fallback\n};\n\n/**\n * Recursively updates the AST object literal with new data.\n */\nconst updateObjectLiteral = (node: any, data: Record<string, any>) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) {\n continue;\n }\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp?.comments) {\n existingProp.comments.forEach((c: any) => {\n if (c.type === 'Line' || c.type === 'CommentLine') {\n // Convert to block comment and tag it to force Recast to print it inline\n c.type = c.type === 'Line' ? 'Block' : 'CommentBlock';\n c.value = `__INLINE_LINE__${c.value}`;\n c.leading = false;\n c.trailing = true;\n }\n });\n }\n\n if (isPlainObject(val)) {\n if (existingProp && n.ObjectExpression.check(existingProp.value)) {\n updateObjectLiteral(existingProp.value, val);\n } else {\n if (existingProp) {\n // Prevent AST invalidation if the primitive value is identical\n const isIdentical =\n n.Literal.check(existingProp.value) &&\n existingProp.value.value === val;\n\n if (!isIdentical) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n } else {\n // Handle primitives and arrays\n if (existingProp) {\n // Skip assignment if the primitive value is identical\n if (!isPrimitiveEqual(existingProp.value, val)) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary,\n noMetadata?: boolean\n): string => {\n // Wrap content to create valid syntax for the parser\n const wrappedContent = `const _config = ${fileContent.trim() || '{}'};`;\n\n let ast: ReturnType<typeof recast.parse>;\n try {\n ast = recast.parse(wrappedContent);\n } catch {\n // Fallback if parsing failed\n return JSON.stringify(\n noMetadata ? dictionary.content : dictionary,\n null,\n 2\n );\n }\n\n // Navigate the AST to locate the object literal initialized to `_config`\n const declaration = ast.program.body[0];\n let objectLiteral: any;\n\n if (\n n.VariableDeclaration.check(declaration) &&\n declaration.declarations.length > 0 &&\n n.VariableDeclarator.check(declaration.declarations[0]) &&\n n.ObjectExpression.check(declaration.declarations[0].init)\n ) {\n objectLiteral = declaration.declarations[0].init;\n }\n\n if (noMetadata) {\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n '$schema',\n ];\n\n // Mutate the array backwards instead of using .filter() to prevent layout invalidation\n for (let i = objectLiteral.properties.length - 1; i >= 0; i--) {\n const prop = objectLiteral.properties[i];\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n if (['key', 'content', ...metadataProperties].includes(propName)) {\n objectLiteral.properties.splice(i, 1);\n }\n }\n }\n }\n\n // Update the AST in place\n updateObjectLiteral(\n objectLiteral,\n noMetadata ? (dictionary.content as Record<string, any>) : dictionary\n );\n\n // Print the full AST to utilize the global token stream for inline comments\n const printedCode = recast.print(ast, {\n tabWidth: 2,\n quote: 'double',\n trailingComma: false,\n }).code;\n\n // Extract the target object literal cleanly\n const startIndex = printedCode.indexOf('{');\n const endIndex = printedCode.lastIndexOf('}');\n let finalOutput = printedCode.substring(startIndex, endIndex + 1);\n\n // Revert the tagged block comment back to an inline line comment and fix comma placement\n finalOutput = finalOutput.replace(\n /\\s*\\/\\*__INLINE_LINE__(.*?)\\*\\/(\\s*,?)/g,\n '$2 //$1'\n );\n\n // Collapse empty lines injected by Recast around commented properties\n finalOutput = finalOutput.replace(/\\n[ \\t]*\\n/g, '\\n');\n\n return finalOutput;\n};\n"],"mappings":"yBAGA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,EAAiB,GACd,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,EAAM,CAMvE,GAAoB,EAAc,IAClC,IAAQ,KACH,EAAE,QAAQ,MAAM,EAAQ,EAAI,EAAQ,QAAU,KAGrD,OAAO,GAAQ,UACf,OAAO,GAAQ,UACf,OAAO,GAAQ,WAGZ,EAAE,QAAQ,MAAM,EAAQ,EACvB,EAAE,cAAc,MAAM,EAAQ,EAC9B,EAAE,eAAe,MAAM,EAAQ,EAC/B,EAAE,eAAe,MAAM,EAAQ,GACjC,EAAQ,QAAU,EAGf,GAOH,GAAuB,EAAW,IAC/B,EAAK,WAAW,KAAM,GAC3B,IAAI,EAAE,SAAS,MAAM,EAAK,EAAI,EAAE,eAAe,MAAM,EAAK,IACpD,EAAE,WAAW,MAAM,EAAK,IAAI,EAAI,EAAK,IAAI,OAAS,GAClD,EAAE,cAAc,MAAM,EAAK,IAAI,EAAI,EAAK,IAAI,QAAU,GAEtD,EAAE,QAAQ,MAAM,EAAK,IAAI,EAAI,EAAK,IAAI,QAAU,IAGtD,CAOE,EAAgB,GAChB,IAAQ,KAAa,EAAE,QAAQ,KAAK,CAGtC,OAAO,GAAQ,UACf,OAAO,GAAQ,UACf,OAAO,GAAQ,UAER,EAAE,QAAQ,EAAI,CAGnB,M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-
import{getFormatFromExtension as e}from"../utils/getFormatFromExtension.mjs";import{detectFormatCommand as t}from"../detectFormatCommand.mjs";import{processContentDeclarationContent as n}from"./processContentDeclarationContent.mjs";import{transformJSONFile as r}from"./transformJSONFile.mjs";import{writeJSFile as i}from"./writeJSFile.mjs";import{
|
|
1
|
+
import{getFormatFromExtension as e}from"../utils/getFormatFromExtension.mjs";import{detectFormatCommand as t}from"../detectFormatCommand.mjs";import{processContentDeclarationContent as n}from"./processContentDeclarationContent.mjs";import{transformJSONFile as r}from"./transformJSONFile.mjs";import{writeJSFile as i}from"./writeJSFile.mjs";import{mkdir as a,readFile as o,rename as s,rm as c,writeFile as l}from"node:fs/promises";import{basename as u,dirname as d,extname as f,join as p,resolve as m}from"node:path";import{DefaultValues as h}from"@intlayer/config/client";import{getUnmergedDictionaries as g}from"@intlayer/unmerged-dictionaries-entry";import{existsSync as _}from"node:fs";import{getFilteredLocalesDictionary as v,getPerLocaleDictionary as y}from"@intlayer/core/plugins";import{execSync as b}from"node:child_process";import{isDeepStrictEqual as x}from"node:util";const S=async(t,r,i)=>{let a=await n(t),o=a.content;t.locale?o=y(a,t.locale).content:i&&(o=v(a,i).content);let s={...t,content:o};for await(let e of r.plugins??[])if(e.formatOutput){let t=await e.formatOutput?.({dictionary:s,configuration:r});t&&(s=t)}if(!(s.content&&s.key))return s;let c={key:t.key,id:t.id,title:t.title,description:t.description,tags:t.tags,locale:t.locale,fill:t.fill,filled:t.filled,priority:t.priority,importMode:t.importMode,version:t.version,content:o};return e(t.filePath?f(t.filePath):`.json`)===`json`&&s.content&&s.key&&(c={$schema:`https://intlayer.org/schema.json`,...c}),c},C={newDictionariesPath:`intlayer-dictionaries`},w=async(e,t,n)=>{let{system:r,compiler:i}=t,{baseDir:a}=r,o=i?.noMetadata??h.Compiler.COMPILER_NO_METADATA,{newDictionariesPath:s,localeList:c}={...C,...n},l=p(a,s),u=g(t)[e.key]?.find(t=>t.localId===e.localId),d=await S(e,t,c);if(u?.filePath){let n=x(u,e),r=m(t.system.baseDir,u.filePath);return n?{status:`up-to-date`,path:r}:(await T(r,d,t,o),{status:`updated`,path:r})}if(e.filePath){let n=m(t.system.baseDir,e.filePath);return await T(n,d,t,o),{status:`created`,path:n}}let f=p(l,`${e.key}.content.json`);return await T(f,d,t,o),{status:`imported`,path:f}},T=async(e,n,m,h)=>{await a(d(e),{recursive:!0});let g=f(e);if([`.json`,`.jsonc`,`.json5`].includes(g)){let i=`{}`;if(_(e))try{i=await o(e,`utf-8`)}catch{}let d=r(i,n,h),f=m.system?.tempDir;f&&await a(f,{recursive:!0});let g=`${u(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,v=f?p(f,g):`${e}.${g}`;try{await l(v,d,`utf-8`),await s(v,e)}catch(e){try{await c(v,{force:!0})}catch{}throw e}let y=t(m);if(y)try{b(y.replace(`{{file}}`,e),{stdio:`inherit`,cwd:m.system.baseDir})}catch(e){console.error(e)}return}await i(e,n,m,h);try{await c(p(m.system.cacheDir,`intlayer-prepared.lock`),{recursive:!0})}catch{}};export{w as writeContentDeclaration};
|
|
2
2
|
//# sourceMappingURL=writeContentDeclaration.mjs.map
|