@intlayer/chokidar 8.4.0 → 8.4.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/_utils_asset-SJVy1xMD.cjs +2 -0
- 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 +1 -1
- package/dist/cjs/buildIntlayerDictionary/processContentDeclaration.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs.map +1 -1
- 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 +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs.map +1 -1
- package/dist/cjs/{_virtual/_rolldown/runtime.cjs → chunk-Bmb41Sf3.cjs} +1 -1
- package/dist/cjs/cleanOutputDir.cjs +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/createDictionaryEntryPoint.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs.map +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 +1 -1
- package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
- package/dist/cjs/createType/createType.cjs +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/fetchDistantDictionaries.cjs.map +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
- package/dist/cjs/formatDictionary.cjs +1 -1
- package/dist/cjs/formatDictionary.cjs.map +1 -1
- package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs +1 -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/init/index.cjs.map +1 -1
- package/dist/cjs/init/utils/configManipulation.cjs +1 -1
- package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
- package/dist/cjs/init/utils/fileSystem.cjs +1 -1
- package/dist/cjs/init/utils/fileSystem.cjs.map +1 -1
- package/dist/cjs/init/utils/tsConfig.cjs +1 -1
- package/dist/cjs/init/utils/tsConfig.cjs.map +1 -1
- package/dist/cjs/initConfig/index.cjs +1 -1
- package/dist/cjs/initConfig/index.cjs.map +1 -1
- package/dist/cjs/installMCP/installMCP.cjs +1 -1
- package/dist/cjs/installMCP/installMCP.cjs.map +1 -1
- package/dist/cjs/installSkills/index.cjs +1 -1
- package/dist/cjs/installSkills/index.cjs.map +1 -1
- package/dist/cjs/listDictionariesPath.cjs +1 -1
- package/dist/cjs/listDictionariesPath.cjs.map +1 -1
- package/dist/cjs/listGitFiles.cjs +1 -1
- package/dist/cjs/listGitFiles.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs +1 -1
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +1 -1
- 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 +1 -1
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/log.cjs +1 -1
- package/dist/cjs/loadDictionaries/log.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 +1 -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/reduceDictionaryContent.cjs +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/buildComponentFilesList.cjs +1 -1
- package/dist/cjs/utils/buildComponentFilesList.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/getPathHash.cjs +1 -1
- package/dist/cjs/utils/getPathHash.cjs.map +1 -1
- package/dist/cjs/utils/resolveRelativePath.cjs +1 -1
- package/dist/cjs/utils/resolveRelativePath.cjs.map +1 -1
- package/dist/cjs/utils/runOnce.cjs +1 -1
- package/dist/cjs/utils/runOnce.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/bin.cjs +1 -1
- package/dist/cjs/utils/runParallel/bin.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/index.cjs +1 -1
- package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/pidTree.cjs +1 -1
- package/dist/cjs/utils/runParallel/pidTree.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/ps.cjs +1 -1
- package/dist/cjs/utils/runParallel/ps.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/runTask.cjs +1 -1
- package/dist/cjs/utils/runParallel/runTask.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/spawnPosix.cjs +1 -1
- package/dist/cjs/utils/runParallel/spawnPosix.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/spawnWin32.cjs +1 -1
- package/dist/cjs/utils/runParallel/spawnWin32.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/wmic.cjs +1 -1
- package/dist/cjs/utils/runParallel/wmic.cjs.map +1 -1
- package/dist/cjs/watcher.cjs +1 -1
- package/dist/cjs/watcher.cjs.map +1 -1
- package/dist/cjs/writeConfiguration/index.cjs +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 +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs +1 -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/cjs/writeFileIfChanged.cjs +1 -1
- package/dist/cjs/writeFileIfChanged.cjs.map +1 -1
- package/dist/esm/{_virtual/_utils_asset.mjs → _utils_asset-4w8dPH9r.mjs} +1 -1
- package/dist/esm/build.mjs +1 -1
- package/dist/esm/{_virtual/_rolldown/runtime.mjs → chunk-DDgYwkfe.mjs} +1 -1
- package/dist/esm/cli.mjs +1 -1
- package/dist/esm/init/index.mjs +1 -1
- package/dist/esm/init/index.mjs.map +1 -1
- package/dist/esm/init/utils/configManipulation.mjs +1 -1
- package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
- package/dist/esm/initConfig/index.mjs +1 -1
- package/dist/esm/initConfig/index.mjs.map +1 -1
- package/dist/esm/installMCP/installMCP.mjs +1 -1
- package/dist/esm/installMCP/installMCP.mjs.map +1 -1
- package/dist/esm/installSkills/index.mjs +1 -1
- package/dist/esm/installSkills/index.mjs.map +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
- package/dist/esm/utils/formatter.mjs +1 -1
- package/dist/esm/utils/formatter.mjs.map +1 -1
- package/dist/esm/watcher.mjs +1 -1
- package/dist/esm/watcher.mjs.map +1 -1
- package/dist/esm/writeConfiguration/index.mjs +1 -1
- package/dist/esm/writeConfiguration/index.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs.map +1 -1
- package/dist/types/build.d.ts +20 -20
- package/dist/types/buildIntlayerDictionary/buildIntlayerDictionary.d.ts +2 -24
- package/dist/types/buildIntlayerDictionary/index.d.ts +2 -2
- package/dist/types/buildIntlayerDictionary/processContentDeclaration.d.ts +2 -11
- package/dist/types/buildIntlayerDictionary/writeDynamicDictionary.d.ts +2 -36
- package/dist/types/buildIntlayerDictionary/writeFetchDictionary.d.ts +1 -1
- package/dist/types/buildIntlayerDictionary/writeFetchDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeMergedDictionary.d.ts +2 -30
- package/dist/types/buildIntlayerDictionary/writeUnmergedDictionary.d.ts +2 -34
- package/dist/types/buildIntlayerDictionary-BGj5jDFy.d.ts +24 -0
- package/dist/types/buildIntlayerDictionary-BGj5jDFy.d.ts.map +1 -0
- package/dist/types/cli.d.ts +6 -6
- package/dist/types/createDictionaryEntryPoint/createDictionaryEntryPoint.d.ts +2 -14
- package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts +2 -10
- package/dist/types/createDictionaryEntryPoint/getBuiltDictionariesPath.d.ts +2 -10
- package/dist/types/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.d.ts +2 -10
- package/dist/types/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.d.ts +2 -10
- package/dist/types/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.d.ts +2 -10
- package/dist/types/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.d.ts +2 -10
- package/dist/types/createDictionaryEntryPoint/index.d.ts +7 -7
- package/dist/types/createDictionaryEntryPoint-Bc5lHSiY.d.ts +14 -0
- package/dist/types/createDictionaryEntryPoint-Bc5lHSiY.d.ts.map +1 -0
- package/dist/types/createModuleAugmentation-D1eIVnjg.d.ts +9 -0
- package/dist/types/createModuleAugmentation-D1eIVnjg.d.ts.map +1 -0
- package/dist/types/createType/createModuleAugmentation.d.ts +2 -9
- package/dist/types/createType/createType.d.ts +2 -12
- package/dist/types/createType/index.d.ts +2 -2
- package/dist/types/createType--rDwdg2t.d.ts +12 -0
- package/dist/types/createType--rDwdg2t.d.ts.map +1 -0
- package/dist/types/detectExportedComponentName-DVXsp_FG.d.ts +12 -0
- package/dist/types/detectExportedComponentName-DVXsp_FG.d.ts.map +1 -0
- package/dist/types/dictionaryStatus-DPVO37qe.d.ts +5 -0
- package/dist/types/dictionaryStatus-DPVO37qe.d.ts.map +1 -0
- package/dist/types/fetchDistantDictionaries.d.ts +1 -1
- package/dist/types/fetchDistantDictionaries.d.ts.map +1 -1
- package/dist/types/generateDictionaryListContent-DAtHG6SR.d.ts +10 -0
- package/dist/types/generateDictionaryListContent-DAtHG6SR.d.ts.map +1 -0
- package/dist/types/getBuiltDictionariesPath-C4it65a1.d.ts +10 -0
- package/dist/types/getBuiltDictionariesPath-C4it65a1.d.ts.map +1 -0
- package/dist/types/getBuiltDynamicDictionariesPath-Cj9EWnjT.d.ts +10 -0
- package/dist/types/getBuiltDynamicDictionariesPath-Cj9EWnjT.d.ts.map +1 -0
- package/dist/types/getBuiltFetchDictionariesPath-1JleRhT3.d.ts +10 -0
- package/dist/types/getBuiltFetchDictionariesPath-1JleRhT3.d.ts.map +1 -0
- package/dist/types/getBuiltRemoteDictionariesPath-DHOmqNCr.d.ts +10 -0
- package/dist/types/getBuiltRemoteDictionariesPath-DHOmqNCr.d.ts.map +1 -0
- package/dist/types/getBuiltUnmergedDictionariesPath-GUmmLxTB.d.ts +10 -0
- package/dist/types/getBuiltUnmergedDictionariesPath-GUmmLxTB.d.ts.map +1 -0
- package/dist/types/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.d.ts +2 -7
- package/dist/types/getContentDeclarationFileTemplate/index.d.ts +1 -1
- package/dist/types/getContentDeclarationFileTemplate-Dz3rnFy9.d.ts +7 -0
- package/dist/types/getContentDeclarationFileTemplate-Dz3rnFy9.d.ts.map +1 -0
- package/dist/types/getFormatFromExtension-SdXYWfPx.d.ts +8 -0
- package/dist/types/getFormatFromExtension-SdXYWfPx.d.ts.map +1 -0
- package/dist/types/loadContentDeclaration-CBMS4vkA.d.ts +12 -0
- package/dist/types/loadContentDeclaration-CBMS4vkA.d.ts.map +1 -0
- package/dist/types/loadDictionaries/index.d.ts +4 -4
- package/dist/types/loadDictionaries/loadContentDeclaration.d.ts +2 -12
- package/dist/types/loadDictionaries/loadDictionaries.d.ts +2 -23
- package/dist/types/loadDictionaries/loadLocalDictionaries.d.ts +2 -8
- package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts +2 -15
- package/dist/types/loadDictionaries/log.d.ts +1 -1
- package/dist/types/loadDictionaries-BIqHwtYE.d.ts +23 -0
- package/dist/types/loadDictionaries-BIqHwtYE.d.ts.map +1 -0
- package/dist/types/loadLocalDictionaries-CNmVaw0c.d.ts +8 -0
- package/dist/types/loadLocalDictionaries-CNmVaw0c.d.ts.map +1 -0
- package/dist/types/loadRemoteDictionaries-MoITTb7W.d.ts +15 -0
- package/dist/types/loadRemoteDictionaries-MoITTb7W.d.ts.map +1 -0
- package/dist/types/processContentDeclaration-CAvrHaIT.d.ts +11 -0
- package/dist/types/processContentDeclaration-CAvrHaIT.d.ts.map +1 -0
- package/dist/types/transformJSFile-Cg0LkeLb.d.ts +11 -0
- package/dist/types/transformJSFile-Cg0LkeLb.d.ts.map +1 -0
- package/dist/types/utils/getFormatFromExtension.d.ts +2 -8
- package/dist/types/utils/index.d.ts +1 -1
- package/dist/types/writeConfiguration/index.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/detectExportedComponentName.d.ts +2 -12
- package/dist/types/writeContentDeclaration/dictionaryStatus.d.ts +2 -5
- package/dist/types/writeContentDeclaration/index.d.ts +5 -5
- package/dist/types/writeContentDeclaration/transformJSFile.d.ts +2 -11
- package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts +2 -19
- package/dist/types/writeContentDeclaration/writeJSFile.d.ts +2 -14
- package/dist/types/writeContentDeclaration-XdGxj0KP.d.ts +19 -0
- package/dist/types/writeContentDeclaration-XdGxj0KP.d.ts.map +1 -0
- package/dist/types/writeDynamicDictionary-DE3SJg-g.d.ts +36 -0
- package/dist/types/writeDynamicDictionary-DE3SJg-g.d.ts.map +1 -0
- package/dist/types/writeJSFile-kK95jzg_.d.ts +14 -0
- package/dist/types/writeJSFile-kK95jzg_.d.ts.map +1 -0
- package/dist/types/writeMergedDictionary-C4EvgXbL.d.ts +30 -0
- package/dist/types/writeMergedDictionary-C4EvgXbL.d.ts.map +1 -0
- package/dist/types/writeUnmergedDictionary-Cxx51isz.d.ts +34 -0
- package/dist/types/writeUnmergedDictionary-Cxx51isz.d.ts.map +1 -0
- package/package.json +8 -8
- package/dist/cjs/_virtual/_utils_asset.cjs +0 -2
- package/dist/types/buildIntlayerDictionary/buildIntlayerDictionary.d.ts.map +0 -1
- package/dist/types/buildIntlayerDictionary/processContentDeclaration.d.ts.map +0 -1
- package/dist/types/buildIntlayerDictionary/writeDynamicDictionary.d.ts.map +0 -1
- package/dist/types/buildIntlayerDictionary/writeMergedDictionary.d.ts.map +0 -1
- package/dist/types/buildIntlayerDictionary/writeUnmergedDictionary.d.ts.map +0 -1
- package/dist/types/createDictionaryEntryPoint/createDictionaryEntryPoint.d.ts.map +0 -1
- package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts.map +0 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltDictionariesPath.d.ts.map +0 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.d.ts.map +0 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.d.ts.map +0 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.d.ts.map +0 -1
- package/dist/types/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.d.ts.map +0 -1
- package/dist/types/createType/createModuleAugmentation.d.ts.map +0 -1
- package/dist/types/createType/createType.d.ts.map +0 -1
- package/dist/types/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.d.ts.map +0 -1
- package/dist/types/loadDictionaries/loadContentDeclaration.d.ts.map +0 -1
- package/dist/types/loadDictionaries/loadDictionaries.d.ts.map +0 -1
- package/dist/types/loadDictionaries/loadLocalDictionaries.d.ts.map +0 -1
- package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts.map +0 -1
- package/dist/types/utils/getFormatFromExtension.d.ts.map +0 -1
- package/dist/types/writeContentDeclaration/detectExportedComponentName.d.ts.map +0 -1
- package/dist/types/writeContentDeclaration/dictionaryStatus.d.ts.map +0 -1
- package/dist/types/writeContentDeclaration/transformJSFile.d.ts.map +0 -1
- package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts.map +0 -1
- package/dist/types/writeContentDeclaration/writeJSFile.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformJSFile.cjs","names":["NodeType","babelTsParser"],"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":"kTAOA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAMjB,EAAU,GAAc,CAC5B,KACE,IACC,EAAE,uBAAuB,MAAM,EAAK,EACnC,EAAE,gBAAgB,MAAM,EAAK,EAC7B,EAAE,iBAAiB,MAAM,EAAK,EAC9B,EAAE,qBAAqB,MAAM,EAAK,EAClC,CACE,wBACA,iBACA,kBACA,sBACD,CAAC,SAAS,EAAK,KAAK,GAEvB,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,EAAsB,EAAiB,MAAM,cAAc,CACjE,GAAI,CAAC,EAAqB,OAC1B,IAAM,EAAoB,EAAoB,GAE9C,GAAI,EAAE,iBAAiB,MAAM,EAAa,MACnC,IAAM,KAAQ,EAAa,WAC9B,GAAI,EAAE,SAAS,MAAM,EAAK,EAAI,EAAE,eAAe,MAAM,EAAK,CAAE,CAC1D,IAAI,EAAW,GAUf,GARI,EAAE,WAAW,MAAM,EAAK,IAAI,CAAE,EAAW,EAAK,IAAI,MAEpD,EAAE,QAAQ,MAAM,EAAK,IA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AAS,MAAM,EAAK,EAAI,EAAE,eAAe,MAAM,EAAK,CAAE,CAC1D,IAAI,EAAW,GAKf,OAJI,EAAE,WAAW,MAAM,EAAK,IAAI,CAAE,EAAW,EAAK,IAAI,KAC7C,EAAE,cAAc,MAAM,EAAK,IAAI,CAAE,EAAW,EAAK,IAAI,MACrD,EAAE,QAAQ,MAAM,EAAK,IAAI,GAAE,EAAW,OAAO,EAAK,IAAI,MAAM,EAE9D,CAAC,CAAC,MAAO,UAAW,GAAG,EAAmB,CAAC,SAAS,EAAS,CAEtE,MAAO,IACP,CAGF,EAAO,MAAM,EAAK,CAChB,UAAU,EAAM,CACd,IAAM,EAAO,EAAK,MAEf,EAAE,uBAAuB,MAAM,EAAK,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
|
+
{"version":3,"file":"transformJSFile.cjs","names":["NodeType","babelTsParser"],"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":"0RAOA,MAAM,EAAI,EAAO,MAAM,SACjB,E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AAC,MAAO,UAAW,GAAG,EAAmB,CAAC,SAAS,EAAS,CAEtE,MAAO,IACP,CAGF,EAAO,MAAM,EAAK,CAChB,UAAU,EAAM,CACd,IAAM,EAAO,EAAK,MAEf,EAAE,uBAAuB,MAAM,EAAK,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,3 +1,3 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`);let t=require(`recast`);t=e.t(t);const n=t.types.builders,r=t.types.namedTypes,i=e=>typeof e==`object`&&!!e&&!Array.isArray(e),a=(e,t)=>t===null?r.Literal.check(e)&&e.value===null:typeof t==`string`||typeof t==`number`||typeof t==`boolean`?(r.Literal.check(e)||r.StringLiteral.check(e)||r.NumericLiteral.check(e)||r.BooleanLiteral.check(e))&&e.value===t:!1,o=(e,t)=>e.properties.find(e=>!!((r.Property.check(e)||r.ObjectProperty.check(e))&&(r.Identifier.check(e.key)&&e.key.name===t||r.StringLiteral.check(e.key)&&e.key.value===t||r.Literal.check(e.key)&&e.key.value===t))),s=e=>e===null?n.literal(null):typeof e==`string`||typeof e==`number`||typeof e==`boolean`?n.literal(e):Array.isArray(e)?n.arrayExpression(e.map(e=>s(e))):i(e)?n.objectExpression(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>n.property(`init`,n.stringLiteral(e),s(t)))):n.literal(null),c=(e,t)=>{for(let[l,u]of Object.entries(t)){if(u===void 0)continue;let t=o(e,l);t?.comments&&t.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)}),i(u)?t&&r.ObjectExpression.check(t.value)?c(t.value,u):t?r.Literal.check(t.value)&&t.value.value===u||(t.value=s(u)):e.properties.push(n.property(`init`,n.stringLiteral(l),s(u))):t?a(t.value,u)||(t.value=s(u)):e.properties.push(n.property(`init`,n.stringLiteral(l),s(u)))}},l=(e,n,i)=>{let a=`const _config = ${e.trim()||`{}`};`,o;try{o=t.parse(a)}catch{return JSON.stringify(i?n.content:n,null,2)}let s=o.program.body[0],l;if(r.VariableDeclaration.check(s)&&s.declarations.length>0&&r.VariableDeclarator.check(s.declarations[0])&&r.ObjectExpression.check(s.declarations[0].init)&&(l=s.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 n=l.properties[t];if(r.Property.check(n)||r.ObjectProperty.check(n)){let i=``;r.Identifier.check(n.key)?i=n.key.name:r.StringLiteral.check(n.key)?i=n.key.value:r.Literal.check(n.key)&&(i=String(n.key.value)),[`key`,`content`,...e].includes(i)&&l.properties.splice(t,1)}}}c(l,i?n.content:n);let u=t.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
2
|
`),p};exports.transformJSONFile=l;
|
|
3
3
|
//# sourceMappingURL=transformJSONFile.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformJSONFile.cjs","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 finalO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,GAAG,MAG1C,EAAY,CACd,IAAM,EAAqB,CACzB,KACA,SACA,SACA,OACA,QACA,cACA,OACA,UACA,WACA,4BACA,UACD,CAGD,IAAK,IAAI,EAAI,EAAc,WAAW,OAAS,EAAG,GAAK,EAAG,IAAK,CAC7D,IAAM,EAAO,EAAc,WAAW,GACtC,GAAI,EAAE,SAAS,MAAM,EAAK,EAAI,EAAE,eAAe,MAAM,EAAK,CAAE,CAC1D,IAAI,EAAW,GACX,EAAE,WAAW,MAAM,EAAK,IAAI,CAAE,EAAW,EAAK,IAAI,KAC7C,EAAE,cAAc,MAAM,EAAK,IAAI,CAAE,EAAW,EAAK,IAAI,MACrD,EAAE,QAAQ,MAAM,EAAK,IAAI,GAAE,EAAW,OAAO,EAAK,IAAI,MAAM,EAEjE,CAAC,MAAO,UAAW,GAAG,EAAmB,CAAC,SAAS,EAAS,EAC9D,EAAc,WAAW,OAAO,EAAG,EAAE,GAO7C,EACE,EACA,EAAc,EAAW,QAAkC,EAC5D,CAGD,IAAM,EAAc,EAAO,MAAM,EAAK,CACpC,SAAU,EACV,MAAO,SACP,cAAe,GAChB,CAAC,CAAC,KAGG,EAAa,EAAY,QAAQ,IAAI,CACrC,EAAW,EAAY,YAAY,IAAI,CACzC,EAAc,EAAY,UAAU,EAAY,EAAW,EAAE,CAWjE,MARA,GAAc,EAAY,QACxB,0CACA,UACD,CAGD,EAAc,EAAY,QAAQ,cAAe;EAAK,CAE/C"}
|
|
1
|
+
{"version":3,"file":"transformJSONFile.cjs","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":"6IAGA,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,KA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EAAS,EAC9D,EAAc,WAAW,OAAO,EAAG,EAAE,GAO7C,EACE,EACA,EAAc,EAAW,QAAkC,EAC5D,CAGD,IAAM,EAAc,EAAO,MAAM,EAAK,CACpC,SAAU,EACV,MAAO,SACP,cAAe,GAChB,CAAC,CAAC,KAGG,EAAa,EAAY,QAAQ,IAAI,CACrC,EAAW,EAAY,YAAY,IAAI,CACzC,EAAc,EAAY,UAAU,EAAY,EAAW,EAAE,CAWjE,MARA,GAAc,EAAY,QACxB,0CACA,UACD,CAGD,EAAc,EAAY,QAAQ,cAAe;EAAK,CAE/C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../chunk-Bmb41Sf3.cjs`);const e=require(`../utils/getFormatFromExtension.cjs`),t=require(`../detectFormatCommand.cjs`),n=require(`./processContentDeclarationContent.cjs`),r=require(`./transformJSONFile.cjs`),i=require(`./writeJSFile.cjs`);let a=require(`node:fs/promises`),o=require(`node:path`),s=require(`@intlayer/config/client`),c=require(`@intlayer/unmerged-dictionaries-entry`),l=require(`node:fs`),u=require(`@intlayer/core/plugins`),d=require(`node:child_process`),f=require(`node:util`);const p=async(t,r,i)=>{let a=await n.processContentDeclarationContent(t),s=a.content;t.locale?s=(0,u.getPerLocaleDictionary)(a,t.locale).content:i&&(s=(0,u.getFilteredLocalesDictionary)(a,i).content);let c={...t,content:s};for await(let e of r.plugins??[])if(e.formatOutput){let t=await e.formatOutput?.({dictionary:c,configuration:r});t&&(c=t)}if(!(c.content&&c.key))return c;let l={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:s};return e.getFormatFromExtension(t.filePath?(0,o.extname)(t.filePath):`.json`)===`json`&&c.content&&c.key&&(l={$schema:`https://intlayer.org/schema.json`,...l}),l},m={newDictionariesPath:`intlayer-dictionaries`},h=async(e,t,n)=>{let{system:r,compiler:i}=t,{baseDir:a}=r,l=i?.noMetadata??s.DefaultValues.Compiler.COMPILER_NO_METADATA,{newDictionariesPath:u,localeList:d}={...m,...n},h=(0,o.join)(a,u),_=(0,c.getUnmergedDictionaries)(t)[e.key]?.find(t=>t.localId===e.localId),v=await p(e,t,d);if(_?.filePath){let n=(0,f.isDeepStrictEqual)(_,e),r=(0,o.resolve)(t.system.baseDir,_.filePath);return n?{status:`up-to-date`,path:r}:(await g(r,v,t,l),{status:`updated`,path:r})}if(e.filePath){let n=(0,o.resolve)(t.system.baseDir,e.filePath);return await g(n,v,t,l),{status:`created`,path:n}}let y=(0,o.join)(h,`${e.key}.content.json`);return await g(y,v,t,l),{status:`imported`,path:y}},g=async(e,n,s,c)=>{await(0,a.mkdir)((0,o.dirname)(e),{recursive:!0});let u=(0,o.extname)(e);if([`.json`,`.jsonc`,`.json5`].includes(u)){let i=`{}`;if((0,l.existsSync)(e))try{i=await(0,a.readFile)(e,`utf-8`)}catch{}let u=r.transformJSONFile(i,n,c),f=s.system?.tempDir;f&&await(0,a.mkdir)(f,{recursive:!0});let p=`${(0,o.basename)(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,m=f?(0,o.join)(f,p):`${e}.${p}`;try{await(0,a.writeFile)(m,u,`utf-8`),await(0,a.rename)(m,e)}catch(e){try{await(0,a.rm)(m,{force:!0})}catch{}throw e}let h=t.detectFormatCommand(s);if(h)try{(0,d.execSync)(h.replace(`{{file}}`,e),{stdio:`inherit`,cwd:s.system.baseDir})}catch(e){console.error(e)}return}await i.writeJSFile(e,n,s,c);try{await(0,a.rm)((0,o.join)(s.system.cacheDir,`intlayer-prepared.lock`),{recursive:!0})}catch{}};exports.writeContentDeclaration=h;
|
|
2
2
|
//# sourceMappingURL=writeContentDeclaration.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","DefaultValues","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata =\n compiler?.noMetadata ?? DefaultValues.Compiler.COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":"wkBAyBA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG,CAIH,IAAM,EACJ,MAAMA,EAAAA,iCAAiC,EAAW,CAEhD,EAAU,EAAoB,QAM9B,EAAW,OACb,GAAA,EAAA,EAAA,wBACE,EACA,EAAW,OACZ,CAAC,QACO,IACT,GAAA,EAAA,EAAA,8BACE,EACA,EACD,CAAC,SAGJ,IAAI,EAA0B,CAC5B,GAAG,EACH,UACD,CAMD,UAAW,IAAM,KAAU,EAAc,SAAW,EAAE,CACpD,GAAI,EAAO,aAAc,CACvB,IAAM,EAAkB,MAAM,EAAO,eAAe,CAClD,WAAY,EACZ,gBACD,CAAC,CAEE,IACF,EAAqB,GAQ3B,GAAI,EAFF,EAAmB,SAAW,EAAmB,KAE1B,OAAO,EAEhC,IAAI,EAAqB,CACvB,IAAK,EAAW,IAChB,GAAI,EAAW,GACf,MAAO,EAAW,MAClB,YAAa,EAAW,YACxB,KAAM,EAAW,KACjB,OAAQ,EAAW,OACnB,KAAM,EAAW,KACjB,OAAQ,EAAW,OACnB,SAAU,EAAW,SACrB,WAAY,EAAW,WACvB,QAAS,EAAW,QACpB,UACD,CAqBD,OAbeC,EAAAA,uBAFb,EAAW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processContentDeclarationContent","getFormatFromExtension","DefaultValues","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata =\n compiler?.noMetadata ?? DefaultValues.Compiler.COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":"4jBAyBA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG,CAIH,IAAM,EACJ,MAAMA,EAAAA,iCAAiC,EAAW,CAEhD,EAAU,EAAoB,QAM9B,EAAW,OACb,GAAA,EAAA,EAAA,wBACE,EACA,EAAW,OACZ,CAAC,QACO,IACT,GAAA,EAAA,EAAA,8BACE,EACA,EACD,CAAC,SAGJ,IAAI,EAA0B,CAC5B,GAAG,EACH,UACD,CAMD,UAAW,IAAM,KAAU,EAAc,SAAW,EAAE,CACpD,GAAI,EAAO,aAAc,CACvB,IAAM,EAAkB,MAAM,EAAO,eAAe,CAClD,WAAY,EACZ,gBACD,CAAC,CAEE,IACF,EAAqB,GAQ3B,GAAI,EAFF,EAAmB,SAAW,EAAmB,KAE1B,OAAO,EAEhC,IAAI,EAAqB,CACvB,IAAK,EAAW,IAChB,GAAI,EAAW,GACf,MAAO,EAAW,MAClB,YAAa,EAAW,YACxB,KAAM,EAAW,KACjB,OAAQ,EAAW,OACnB,KAAM,EAAW,KACjB,OAAQ,EAAW,OACnB,SAAU,EAAW,SACrB,WAAY,EAAW,WACvB,QAAS,EAAW,QACpB,UACD,CAqBD,OAbeC,EAAAA,uBAFb,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object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../chunk-Bmb41Sf3.cjs`);const e=require(`../utils/getFormatFromExtension.cjs`),t=require(`./transformJSFile.cjs`),n=require(`../detectFormatCommand.cjs`),r=require(`../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs`);let i=require(`node:fs/promises`),a=require(`node:path`),o=require(`@intlayer/config/logger`),s=require(`node:fs`),c=require(`node:child_process`);const l=async(l,u,d,f)=>{let p={...d.dictionary,...u},m=(0,o.getAppLogger)(d);if(!(0,s.existsSync)(l)){let t=e.getFormatFromExtension((0,a.extname)(l));m(`File does not exist, creating it`,{isVerbose:!0});let n=await r.getContentDeclarationFileTemplate(p.key,t,Object.fromEntries(Object.entries({id:f?void 0:p.id,locale:f?void 0:p.locale,filled:f?void 0:p.filled,fill:f?void 0:p.fill,description:f?void 0:p.description,title:f?void 0:p.title,tags:f?void 0:p.tags,version:f?void 0:p.version,priority:f?void 0:p.priority,importMode:f?void 0:p.importMode}).filter(([,e])=>e!==void 0)),f),o=d.system?.tempDir;o&&await(0,i.mkdir)(o,{recursive:!0});let s=`${(0,a.basename)(l)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,c=o?(0,a.join)(o,s):`${l}.${s}`;try{await(0,i.writeFile)(c,n,`utf-8`),await(0,i.rename)(c,l)}catch(e){try{await(0,i.rm)(c,{force:!0})}catch{}throw e}}let h=await(0,i.readFile)(l,`utf-8`);if(h===``){let t=e.getFormatFromExtension((0,a.extname)(l));h=await r.getContentDeclarationFileTemplate(p.key,t,{},f)}let g=await t.transformJSFile(h,u,u.locale,f),_=d.system?.tempDir;_&&await(0,i.mkdir)(_,{recursive:!0});let v=`${(0,a.basename)(l)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,y=_?(0,a.join)(_,v):`${l}.${v}`;try{await(0,i.writeFile)(y,g,`utf-8`),await(0,i.rename)(y,l),(0,o.logger)(`Successfully updated ${l}`,{level:`info`,isVerbose:!0})}catch(e){try{await(0,i.rm)(y,{force:!0})}catch{}let t=e;throw(0,o.logger)(`Failed to write updated file: ${l}`,{level:`error`}),Error(`Failed to write updated file ${l}: ${t.message}`)}let b=n.detectFormatCommand(d);if(b)try{(0,c.execSync)(b.replace(`{{file}}`,l),{stdio:`inherit`,cwd:d.system.baseDir})}catch(e){console.error(e)}};exports.writeJSFile=l;
|
|
2
2
|
//# sourceMappingURL=writeJSFile.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeJSFile.cjs","names":["getFormatFromExtension","getContentDeclarationFileTemplate","transformJSFile","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeJSFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, extname, join } from 'node:path';\nimport { getAppLogger, logger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport { getContentDeclarationFileTemplate } from '../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { transformJSFile } from './transformJSFile';\n\n/**\n * Updates a JavaScript/TypeScript file based on the provided JSON instructions.\n * It targets a specific dictionary object within the file (identified by its 'key' property)\n * and updates its 'content' entries. Currently, it focuses on modifying arguments\n * of 't' (translation) function calls.\n */\nexport const writeJSFile = async (\n filePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n const mergedDictionary = {\n ...configuration.dictionary,\n ...dictionary,\n };\n\n const appLogger = getAppLogger(configuration);\n\n // Check if the file exist\n if (!existsSync(filePath)) {\n const fileExtension = extname(filePath) as Extension;\n\n const format = getFormatFromExtension(fileExtension);\n\n appLogger('File does not exist, creating it', {\n isVerbose: true,\n });\n const template = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n // Filter out undefined values\n Object.fromEntries(\n Object.entries({\n id: noMetadata ? undefined : mergedDictionary.id,\n locale: noMetadata ? undefined : mergedDictionary.locale,\n filled: noMetadata ? undefined : mergedDictionary.filled,\n fill: noMetadata ? undefined : mergedDictionary.fill,\n description: noMetadata ? undefined : mergedDictionary.description,\n title: noMetadata ? undefined : mergedDictionary.title,\n tags: noMetadata ? undefined : mergedDictionary.tags,\n version: noMetadata ? undefined : mergedDictionary.version,\n priority: noMetadata ? undefined : mergedDictionary.priority,\n importMode: noMetadata ? undefined : mergedDictionary.importMode,\n }).filter(([, value]) => value !== undefined)\n ),\n noMetadata\n );\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, template, 'utf-8');\n await rename(tempPath, filePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n }\n\n let fileContent = await readFile(filePath, 'utf-8');\n\n if (fileContent === '') {\n const format = getFormatFromExtension(extname(filePath) as Extension);\n\n fileContent = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n {},\n noMetadata\n );\n }\n\n const finalCode = await transformJSFile(\n fileContent,\n dictionary,\n dictionary.locale as any,\n noMetadata\n );\n\n // Write the modified code back to the file\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, finalCode, 'utf-8');\n await rename(tempPath, filePath);\n logger(`Successfully updated ${filePath}`, {\n level: 'info',\n isVerbose: true,\n });\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n const err = error as Error;\n logger(`Failed to write updated file: ${filePath}`, {\n level: 'error',\n });\n throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"writeJSFile.cjs","names":["getFormatFromExtension","getContentDeclarationFileTemplate","transformJSFile","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeJSFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, extname, join } from 'node:path';\nimport { getAppLogger, logger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport { getContentDeclarationFileTemplate } from '../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { transformJSFile } from './transformJSFile';\n\n/**\n * Updates a JavaScript/TypeScript file based on the provided JSON instructions.\n * It targets a specific dictionary object within the file (identified by its 'key' property)\n * and updates its 'content' entries. Currently, it focuses on modifying arguments\n * of 't' (translation) function calls.\n */\nexport const writeJSFile = async (\n filePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n const mergedDictionary = {\n ...configuration.dictionary,\n ...dictionary,\n };\n\n const appLogger = getAppLogger(configuration);\n\n // Check if the file exist\n if (!existsSync(filePath)) {\n const fileExtension = extname(filePath) as Extension;\n\n const format = getFormatFromExtension(fileExtension);\n\n appLogger('File does not exist, creating it', {\n isVerbose: true,\n });\n const template = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n // Filter out undefined values\n Object.fromEntries(\n Object.entries({\n id: noMetadata ? undefined : mergedDictionary.id,\n locale: noMetadata ? undefined : mergedDictionary.locale,\n filled: noMetadata ? undefined : mergedDictionary.filled,\n fill: noMetadata ? undefined : mergedDictionary.fill,\n description: noMetadata ? undefined : mergedDictionary.description,\n title: noMetadata ? undefined : mergedDictionary.title,\n tags: noMetadata ? undefined : mergedDictionary.tags,\n version: noMetadata ? undefined : mergedDictionary.version,\n priority: noMetadata ? undefined : mergedDictionary.priority,\n importMode: noMetadata ? undefined : mergedDictionary.importMode,\n }).filter(([, value]) => value !== undefined)\n ),\n noMetadata\n );\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, template, 'utf-8');\n await rename(tempPath, filePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n }\n\n let fileContent = await readFile(filePath, 'utf-8');\n\n if (fileContent === '') {\n const format = getFormatFromExtension(extname(filePath) as Extension);\n\n fileContent = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n {},\n noMetadata\n );\n }\n\n const finalCode = await transformJSFile(\n fileContent,\n dictionary,\n dictionary.locale as any,\n noMetadata\n );\n\n // Write the modified code back to the file\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, finalCode, 'utf-8');\n await rename(tempPath, filePath);\n logger(`Successfully updated ${filePath}`, {\n level: 'info',\n isVerbose: true,\n });\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n const err = error as Error;\n logger(`Failed to write updated file: ${filePath}`, {\n level: 'error',\n });\n throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":"idAqBA,MAAa,EAAc,MACzB,EACA,EACA,EACA,IACkB,CAClB,IAAM,EAAmB,CACvB,GAAG,EAAc,WACjB,GAAG,EACJ,CAEK,GAAA,EAAA,EAAA,cAAyB,EAAc,CAG7C,GAAI,EAAA,EAAA,EAAA,YAAY,EAAS,CAAE,CAGzB,IAAM,EAASA,EAAAA,wBAAAA,EAAAA,EAAAA,SAFe,EAAS,CAEa,CAEpD,EAAU,mCAAoC,CAC5C,UAAW,GACZ,CAAC,CACF,IAAM,EAAW,MAAMC,EAAAA,kCACrB,EAAiB,IACjB,EAEA,OAAO,YACL,OAAO,QAAQ,CACb,GAAI,EAAa,IAAA,GAAY,EAAiB,GAC9C,OAAQ,EAAa,IAAA,GAAY,EAAiB,OAClD,OAAQ,EAAa,IAAA,GAAY,EAAiB,OAClD,KAAM,EAAa,IAAA,GAAY,EAAiB,KAChD,YAAa,EAAa,IAAA,GAAY,EAAiB,YACvD,MAAO,EAAa,IAAA,GAAY,EAAiB,MACjD,KAAM,EAAa,IAAA,GAAY,EAAiB,KAChD,QAAS,EAAa,IAAA,GAAY,EAAiB,QACnD,SAAU,EAAa,IAAA,GAAY,EAAiB,SACpD,WAAY,EAAa,IAAA,GAAY,EAAiB,WACvD,CAAC,CAAC,QAAQ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QAAa,EAAU,EAAS,EAChC,EAAA,EAAA,QAAO,wBAAwB,IAAY,CACzC,MAAO,OACP,UAAW,GACZ,CAAC,OACK,EAAO,CACd,GAAI,CACF,MAAA,EAAA,EAAA,IAAS,EAAU,CAAE,MAAO,GAAM,CAAC,MAC7B,EAGR,IAAM,EAAM,EAIZ,MAHA,EAAA,EAAA,QAAO,iCAAiC,IAAY,CAClD,MAAO,QACR,CAAC,CACQ,MAAM,gCAAgC,EAAS,IAAI,EAAI,UAAU,CAG7E,IAAM,EAAgBC,EAAAA,oBAAoB,EAAc,CAExD,GAAI,EACF,GAAI,EACF,EAAA,EAAA,UAAS,EAAc,QAAQ,WAAY,EAAS,CAAE,CACpD,MAAO,UACP,IAAK,EAAc,OAAO,QAC3B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./chunk-Bmb41Sf3.cjs`);let e=require(`node:fs/promises`),t=require(`node:path`),n=require(`node:crypto`),r=require(`node:fs`);const i=new Set;process.on(`exit`,()=>{for(let e of i)try{(0,r.rmSync)(e,{force:!0})}catch{}});const a=e=>new Promise(t=>{let i=(0,n.createHash)(`sha256`),a=(0,r.createReadStream)(e);a.on(`data`,e=>i.update(e)),a.on(`end`,()=>t(i.digest(`hex`))),a.on(`error`,()=>t(null))}),o=async(r,o,{encoding:s=`utf8`,tempDir:c}={})=>{if((0,n.createHash)(`sha256`).update(o,s).digest(`hex`)===await a(r))return!1;c&&await(0,e.mkdir)(c,{recursive:!0});let l=`${(0,t.basename)(r)}.${Date.now()}-${(0,n.randomBytes)(4).toString(`hex`)}.tmp`,u=c?(0,t.join)(c,l):`${r}.${l}`;i.add(u);try{let t;try{t=(await(0,e.stat)(r)).mode}catch{}await(0,e.writeFile)(u,o,{encoding:s}),t!==void 0&&await(0,e.chmod)(u,t),await(0,e.rename)(u,r)}catch(t){try{await(0,e.rm)(u,{force:!0})}catch{}throw t}finally{i.delete(u)}return!0};exports.writeFileIfChanged=o;
|
|
2
2
|
//# sourceMappingURL=writeFileIfChanged.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeFileIfChanged.cjs","names":[],"sources":["../../src/writeFileIfChanged.ts"],"sourcesContent":["import { createHash, randomBytes } from 'node:crypto';\nimport { createReadStream, rmSync } from 'node:fs';\nimport { chmod, mkdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\n\nconst activeTempFiles = new Set<string>();\n\n// Synchronous cleanup on process exit\nprocess.on('exit', () => {\n for (const file of activeTempFiles) {\n try {\n rmSync(file, { force: true });\n } catch {}\n }\n});\n\n// Helper to hash existing file via stream\nconst getFileHash = (path: string): Promise<string | null> => {\n return new Promise((resolve) => {\n const hash = createHash('sha256');\n const stream = createReadStream(path);\n stream.on('data', (chunk) => hash.update(chunk));\n stream.on('end', () => resolve(hash.digest('hex')));\n stream.on('error', () => resolve(null));\n });\n};\n\nexport const writeFileIfChanged = async (\n path: string,\n data: string,\n {\n encoding = 'utf8',\n tempDir,\n }: { encoding?: BufferEncoding; tempDir?: string } = {}\n): Promise<boolean> => {\n const newDataHash = createHash('sha256').update(data, encoding).digest('hex');\n const existingHash = await getFileHash(path);\n\n if (newDataHash === existingHash) {\n return false;\n }\n\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(path)}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${path}.${tempFileName}`;\n activeTempFiles.add(tempPath);\n\n try {\n let mode: number | undefined;\n try {\n mode = (await stat(path)).mode;\n } catch {}\n\n await writeFile(tempPath, data, { encoding });\n\n if (mode !== undefined) {\n await chmod(tempPath, mode);\n }\n\n await rename(tempPath, path);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {}\n throw error;\n } finally {\n activeTempFiles.delete(tempPath);\n }\n\n return true;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"writeFileIfChanged.cjs","names":[],"sources":["../../src/writeFileIfChanged.ts"],"sourcesContent":["import { createHash, randomBytes } from 'node:crypto';\nimport { createReadStream, rmSync } from 'node:fs';\nimport { chmod, mkdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\n\nconst activeTempFiles = new Set<string>();\n\n// Synchronous cleanup on process exit\nprocess.on('exit', () => {\n for (const file of activeTempFiles) {\n try {\n rmSync(file, { force: true });\n } catch {}\n }\n});\n\n// Helper to hash existing file via stream\nconst getFileHash = (path: string): Promise<string | null> => {\n return new Promise((resolve) => {\n const hash = createHash('sha256');\n const stream = createReadStream(path);\n stream.on('data', (chunk) => hash.update(chunk));\n stream.on('end', () => resolve(hash.digest('hex')));\n stream.on('error', () => resolve(null));\n });\n};\n\nexport const writeFileIfChanged = async (\n path: string,\n data: string,\n {\n encoding = 'utf8',\n tempDir,\n }: { encoding?: BufferEncoding; tempDir?: string } = {}\n): Promise<boolean> => {\n const newDataHash = createHash('sha256').update(data, encoding).digest('hex');\n const existingHash = await getFileHash(path);\n\n if (newDataHash === existingHash) {\n return false;\n }\n\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(path)}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${path}.${tempFileName}`;\n activeTempFiles.add(tempPath);\n\n try {\n let mode: number | undefined;\n try {\n mode = (await stat(path)).mode;\n } catch {}\n\n await writeFile(tempPath, data, { encoding });\n\n if (mode !== undefined) {\n await chmod(tempPath, mode);\n }\n\n await rename(tempPath, path);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {}\n throw error;\n } finally {\n activeTempFiles.delete(tempPath);\n }\n\n return true;\n};\n"],"mappings":"0M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AAE,MAAO,GAAM,CAAC,MAC7B,EACR,MAAM,SACE,CACR,EAAgB,OAAO,EAAS,CAGlC,MAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{basename as e,dirname as t,join as n,relative as r,resolve as i,sep as a}from"node:path";import{existsSync as o,readFileSync as s}from"node:fs";import{fileURLToPath as c}from"node:url";const l=()=>{try{return t(c(import.meta.url))}catch{return typeof __dirname<`u`?__dirname:process.cwd()}},u=t=>{let n=t;for(let t=0;t<12;t++){if(e(n)===`dist`)return n;let t=i(n,`..`);if(t===n)break;n=t}return null},d=e=>{if(!e)return null;try{if(e.startsWith(`file://`))return c(e)}catch{}return e},f=()=>{let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error();Error.captureStackTrace(e,f);let n=e.stack||[],r=e=>e.includes(`${a}_virtual${a}`)||e.includes(`/_virtual/`);for(let e of n){let n=d(typeof e.getFileName==`function`?e.getFileName():null);if(n&&!(n.includes(`node:internal`)||n.includes(`${a}internal${a}modules${a}`))&&!r(n))return t(n)}for(let e of n){let n=d(typeof e.getFileName==`function`?e.getFileName():null);if(n)return t(n)}}catch{}finally{Error.prepareStackTrace=e}return l()},p=(e,t=`utf8`)=>{let a=l(),c=u(a)??i(a,`..`,`..`,`dist`),d=n(c,`assets`),p=[],m=r(c,f()).split(`\\`).join(`/`).replace(/^(?:dist\/)?(?:esm|cjs)\//,``).replace(/^_virtual\//,``);if(e.startsWith(`./`)||e.startsWith(`../`)){let n=i(d,m,e);if(p.push(n),o(n))return s(n,t)}let h=n(d,e);if(p.push(h),o(h))return s(h,t);if(m){let r=n(d,m,e);if(p.push(r),o(r))return s(r,t)}let g=[`readAsset: file not found.`,`Searched:`,...p.map(e=>`- ${e}`)].join(`
|
|
2
|
-
`);throw Error(g)};export{p as
|
|
2
|
+
`);throw Error(g)};export{p as t};
|
package/dist/esm/build.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{generateDictionaryListContent as e}from"./createDictionaryEntryPoint/generateDictionaryListContent.mjs";import{getBuiltDictionariesPath as t}from"./createDictionaryEntryPoint/getBuiltDictionariesPath.mjs";import{getBuiltDynamicDictionariesPath as n}from"./createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs";import{getBuiltFetchDictionariesPath as r}from"./createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs";import{getBuiltRemoteDictionariesPath as i}from"./createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs";import{getBuiltUnmergedDictionariesPath as a}from"./createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs";import{createDictionaryEntryPoint as o}from"./createDictionaryEntryPoint/createDictionaryEntryPoint.mjs";import{buildDictionary as s}from"./buildIntlayerDictionary/buildIntlayerDictionary.mjs";import{createModuleAugmentation as c,getTypeName as l}from"./createType/createModuleAugmentation.mjs";import{createTypes as u,generateTypeScriptType as d}from"./createType/createType.mjs";import{processContentDeclaration as f}from"./buildIntlayerDictionary/processContentDeclaration.mjs";import{ensureIntlayerBundle as p,formatLocalDictionaries as m,loadContentDeclaration as h,loadContentDeclarations as g}from"./loadDictionaries/loadContentDeclaration.mjs";import{loadLocalDictionaries as _}from"./loadDictionaries/loadLocalDictionaries.mjs";import{formatDictionaries as v,formatDictionariesOutput as y,formatDictionary as b,formatDictionaryOutput as x}from"./formatDictionary.mjs";import{formatDistantDictionaries as S,loadRemoteDictionaries as C}from"./loadDictionaries/loadRemoteDictionaries.mjs";import{loadDictionaries as w}from"./loadDictionaries/loadDictionaries.mjs";import{cleanOutputDir as T}from"./cleanOutputDir.mjs";import{isCachedConfigurationUpToDate as E,writeConfiguration as D}from"./writeConfiguration/index.mjs";import{prepareIntlayer as O}from"./prepareIntlayer.mjs";import{detectExportedComponentName as k}from"./writeContentDeclaration/detectExportedComponentName.mjs";import{transformJSFile as A}from"./writeContentDeclaration/transformJSFile.mjs";import{writeJSFile as j}from"./writeContentDeclaration/writeJSFile.mjs";import{writeContentDeclaration as M}from"./writeContentDeclaration/writeContentDeclaration.mjs";export{s as buildDictionary,T as cleanOutputDir,o as createDictionaryEntryPoint,c as createModuleAugmentation,u as createTypes,k as detectExportedComponentName,p as ensureIntlayerBundle,v as formatDictionaries,y as formatDictionariesOutput,b as formatDictionary,x as formatDictionaryOutput,S as formatDistantDictionaries,m as formatLocalDictionaries,e as generateDictionaryListContent,d as generateTypeScriptType,t as getBuiltDictionariesPath,n as getBuiltDynamicDictionariesPath,r as getBuiltFetchDictionariesPath,i as getBuiltRemoteDictionariesPath,a as getBuiltUnmergedDictionariesPath,l as getTypeName,E as isCachedConfigurationUpToDate,h as loadContentDeclaration,g as loadContentDeclarations,w as loadDictionaries,_ as loadLocalDictionaries,C as loadRemoteDictionaries,O as prepareIntlayer,f as processContentDeclaration,A as transformJSFile,D as writeConfiguration,M as writeContentDeclaration,j as writeJSFile};
|
|
1
|
+
import{generateDictionaryListContent as e}from"./createDictionaryEntryPoint/generateDictionaryListContent.mjs";import{getBuiltDictionariesPath as t}from"./createDictionaryEntryPoint/getBuiltDictionariesPath.mjs";import{getBuiltDynamicDictionariesPath as n}from"./createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs";import{getBuiltFetchDictionariesPath as r}from"./createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs";import{getBuiltRemoteDictionariesPath as i}from"./createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs";import{getBuiltUnmergedDictionariesPath as a}from"./createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs";import{createDictionaryEntryPoint as o}from"./createDictionaryEntryPoint/createDictionaryEntryPoint.mjs";import{buildDictionary as s}from"./buildIntlayerDictionary/buildIntlayerDictionary.mjs";import{createModuleAugmentation as c,getTypeName as l}from"./createType/createModuleAugmentation.mjs";import{createTypes as u,generateTypeScriptType as d}from"./createType/createType.mjs";import{processContentDeclaration as f}from"./buildIntlayerDictionary/processContentDeclaration.mjs";import{ensureIntlayerBundle as p,formatLocalDictionaries as m,loadContentDeclaration as h,loadContentDeclarations as g}from"./loadDictionaries/loadContentDeclaration.mjs";import{loadLocalDictionaries as _}from"./loadDictionaries/loadLocalDictionaries.mjs";import{formatDictionaries as v,formatDictionariesOutput as y,formatDictionary as b,formatDictionaryOutput as x}from"./formatDictionary.mjs";import{formatDistantDictionaries as S,loadRemoteDictionaries as C}from"./loadDictionaries/loadRemoteDictionaries.mjs";import{loadDictionaries as w}from"./loadDictionaries/loadDictionaries.mjs";import{cleanOutputDir as T}from"./cleanOutputDir.mjs";import{isCachedConfigurationUpToDate as E,writeConfiguration as D}from"./writeConfiguration/index.mjs";import{prepareIntlayer as O}from"./prepareIntlayer.mjs";import{detectExportedComponentName as k}from"./writeContentDeclaration/detectExportedComponentName.mjs";import{transformJSFile as A}from"./writeContentDeclaration/transformJSFile.mjs";import{writeJSFile as j}from"./writeContentDeclaration/writeJSFile.mjs";import{writeContentDeclaration as M}from"./writeContentDeclaration/writeContentDeclaration.mjs";import"./writeContentDeclaration/index.mjs";import"./buildIntlayerDictionary/index.mjs";export{s as buildDictionary,T as cleanOutputDir,o as createDictionaryEntryPoint,c as createModuleAugmentation,u as createTypes,k as detectExportedComponentName,p as ensureIntlayerBundle,v as formatDictionaries,y as formatDictionariesOutput,b as formatDictionary,x as formatDictionaryOutput,S as formatDistantDictionaries,m as formatLocalDictionaries,e as generateDictionaryListContent,d as generateTypeScriptType,t as getBuiltDictionariesPath,n as getBuiltDynamicDictionariesPath,r as getBuiltFetchDictionariesPath,i as getBuiltRemoteDictionariesPath,a as getBuiltUnmergedDictionariesPath,l as getTypeName,E as isCachedConfigurationUpToDate,h as loadContentDeclaration,g as loadContentDeclarations,w as loadDictionaries,_ as loadLocalDictionaries,C as loadRemoteDictionaries,O as prepareIntlayer,f as processContentDeclaration,A as transformJSFile,D as writeConfiguration,M as writeContentDeclaration,j as writeJSFile};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});export{e as
|
|
1
|
+
var e=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});export{e as t};
|
package/dist/esm/cli.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{listProjects as e}from"./listProjects.mjs";import{listDictionaries as t,listDictionariesWithStats as n}from"./listDictionariesPath.mjs";import{detectExportedComponentName as r}from"./writeContentDeclaration/detectExportedComponentName.mjs";import{transformJSFile as i}from"./writeContentDeclaration/transformJSFile.mjs";import{detectFormatCommand as a}from"./detectFormatCommand.mjs";import{getContentDeclarationFileTemplate as o}from"./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs";import{writeJSFile as s}from"./writeContentDeclaration/writeJSFile.mjs";import{writeContentDeclaration as c}from"./writeContentDeclaration/writeContentDeclaration.mjs";import{initIntlayer as l}from"./init/index.mjs";import{PLATFORMS as u,PLATFORMS_METADATA as d,SKILLS as f,SKILLS_METADATA as p,getInitialSkills as m,installSkills as h}from"./installSkills/index.mjs";import{installMCP as g}from"./installMCP/installMCP.mjs";import{listGitFiles as _,listGitLines as v}from"./listGitFiles.mjs";import{logConfigDetails as y}from"./logConfigDetails.mjs";export{u as PLATFORMS,d as PLATFORMS_METADATA,f as SKILLS,p as SKILLS_METADATA,r as detectExportedComponentName,a as detectFormatCommand,o as getContentDeclarationFileTemplate,m as getInitialSkills,l as initIntlayer,g as installMCP,h as installSkills,t as listDictionaries,n as listDictionariesWithStats,_ as listGitFiles,v as listGitLines,e as listProjects,y as logConfigDetails,i as transformJSFile,c as writeContentDeclaration,s as writeJSFile};
|
|
1
|
+
import{listProjects as e}from"./listProjects.mjs";import{listDictionaries as t,listDictionariesWithStats as n}from"./listDictionariesPath.mjs";import{detectExportedComponentName as r}from"./writeContentDeclaration/detectExportedComponentName.mjs";import{transformJSFile as i}from"./writeContentDeclaration/transformJSFile.mjs";import{detectFormatCommand as a}from"./detectFormatCommand.mjs";import{getContentDeclarationFileTemplate as o}from"./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs";import{writeJSFile as s}from"./writeContentDeclaration/writeJSFile.mjs";import{writeContentDeclaration as c}from"./writeContentDeclaration/writeContentDeclaration.mjs";import"./writeContentDeclaration/index.mjs";import"./getContentDeclarationFileTemplate/index.mjs";import"./_utils_asset-4w8dPH9r.mjs";import{initIntlayer as l}from"./init/index.mjs";import{PLATFORMS as u,PLATFORMS_METADATA as d,SKILLS as f,SKILLS_METADATA as p,getInitialSkills as m,installSkills as h}from"./installSkills/index.mjs";import{installMCP as g}from"./installMCP/installMCP.mjs";import{listGitFiles as _,listGitLines as v}from"./listGitFiles.mjs";import{logConfigDetails as y}from"./logConfigDetails.mjs";export{u as PLATFORMS,d as PLATFORMS_METADATA,f as SKILLS,p as SKILLS_METADATA,r as detectExportedComponentName,a as detectFormatCommand,o as getContentDeclarationFileTemplate,m as getInitialSkills,l as initIntlayer,g as installMCP,h as installSkills,t as listDictionaries,n as listDictionariesWithStats,_ as listGitFiles,v as listGitLines,e as listProjects,y as logConfigDetails,i as transformJSFile,c as writeContentDeclaration,s as writeJSFile};
|
package/dist/esm/init/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{initConfig as e}from"../initConfig/index.mjs";import{updateNextConfig as t,updateViteConfig as n}from"./utils/configManipulation.mjs";import{ensureDirectory as r,exists as i,readFileFromRoot as a,writeFileToRoot as o}from"./utils/fileSystem.mjs";import{parseJSONWithComments as s}from"./utils/jsonParser.mjs";import{findTsConfigFiles as c}from"./utils/tsConfig.mjs";import{join as l}from"node:path";import{ANSIColors as u,colorize as d,colorizePath as f,logger as p,v as m,x as h}from"@intlayer/config/logger";import{getConfiguration as g}from"@intlayer/config/node";import{getAlias as _}from"@intlayer/config/utils";const v={NextJS:`https://intlayer.org/doc/environment/nextjs.md`,NextJS_15:`https://intlayer.org/doc/environment/nextjs/15.md`,NextJS_14:`https://intlayer.org/doc/environment/nextjs/14.md`,CRA:`https://intlayer.org/doc/environment/create-react-app.md`,Astro:`https://intlayer.org/doc/environment/astro.md`,ViteAndReact:`https://intlayer.org/doc/environment/vite-and-react.md`,ViteAndReact_ReactRouterV7:`https://intlayer.org/doc/environment/vite-and-react/react-router-v7.md`,ViteAndReact_ReactRouterV7_FSRoutes:`https://intlayer.org/doc/environment/vite-and-react/react-router-v7-fs-routes.md`,ViteAndVue:`https://intlayer.org/doc/environment/vite-and-vue.md`,ViteAndSolid:`https://intlayer.org/doc/environment/vite-and-solid.md`,ViteAndSvelte:`https://intlayer.org/doc/environment/vite-and-svelte.md`,ViteAndPreact:`https://intlayer.org/doc/environment/vite-and-preact.md`,TanStackRouter:`https://intlayer.org/doc/environment/tanstack.md`,NuxtAndVue:`https://intlayer.org/doc/environment/nuxt-and-vue.md`,Angular:`https://intlayer.org/doc/environment/angular.md`,SvelteKit:`https://intlayer.org/doc/environment/sveltekit.md`,ReactNativeAndExpo:`https://intlayer.org/doc/environment/react-native-and-expo.md`,Lynx:`https://intlayer.org/doc/environment/lynx-and-react.md`,Express:`https://intlayer.org/doc/environment/express.md`,NestJS:`https://intlayer.org/doc/environment/nestjs.md`,Fastify:`https://intlayer.org/doc/environment/fastify.md`,Default:`https://intlayer.org/doc/get-started`,NextIntl:`https://intlayer.org/blog/intlayer-with-next-intl.md`,ReactI18Next:`https://intlayer.org/blog/intlayer-with-react-i18next.md`,ReactIntl:`https://intlayer.org/blog/intlayer-with-react-intl.md`,NextI18Next:`https://intlayer.org/blog/intlayer-with-next-i18next.md`,VueI18n:`https://intlayer.org/blog/intlayer-with-vue-i18n.md`},y=e=>{let t={...e.dependencies,...e.devDependencies},n=(e,t)=>!e||typeof e!=`string`?!1:RegExp(`^[\\^~]?${t}(?:\\.|$)`).test(e);if(t[`@lynx-js/react`]||t[`@lynx-js/core`])return v.Lynx;if(t[`react-native`]||t.expo)return v.ReactNativeAndExpo;if(t.next){let e=t.next;return n(e,14)?v.NextJS_14:n(e,15)?v.NextJS_15:v.NextJS}if(t.nuxt)return v.NuxtAndVue;if(t.astro)return v.Astro;if(t[`@sveltejs/kit`])return v.SvelteKit;if(t[`@tanstack/react-router`])return v.TanStackRouter;let r=t[`react-router`];if(r&&typeof r==`string`){if(t[`@react-router/fs-routes`])return v.ViteAndReact_ReactRouterV7_FSRoutes;if(n(r,7))return v.ViteAndReact_ReactRouterV7}return t.vite?t.vue?v.ViteAndVue:t[`solid-js`]?v.ViteAndSolid:t.svelte?v.ViteAndSvelte:t.preact?v.ViteAndPreact:v.ViteAndReact:t[`react-scripts`]?v.CRA:t[`@angular/core`]?v.Angular:t[`@nestjs/core`]?v.NestJS:t.express?v.Express:t.fastify?v.Fastify:t[`next-intl`]?v.NextIntl:t[`react-i18next`]||t.i18next?v.ReactI18Next:t[`react-intl`]?v.ReactIntl:t[`next-i18next`]?v.NextI18Next:t[`vue-i18n`]?v.VueI18n:v.Default},b=async v=>{p(d(`Checking Intlayer configuration...`,u.CYAN));let b=`package.json`;await i(v,b)||(p(`${h} No ${f(`package.json`)} found. Please run this script from the project root.`,{level:`error`}),process.exit(1));let x=await a(v,b),S;try{S=JSON.parse(x)}catch{p(`${h} Could not parse ${f(`package.json`)}.`,{level:`error`}),process.exit(1)}let C=y(S),w=`.gitignore`;if(await i(v,w)){let e=await a(v,w);e.includes(`intlayer`)?p(`${m} ${f(w)} already includes .intlayer`):(await o(v,w,`${e}\n# Intlayer\n.intlayer\n`),p(`${m} Added ${f(`.intlayer`)} to ${f(w)}`))}let T=`.vscode`,E=l(T,`extensions.json`),D=`intlayer.intlayer-vs-code-extension`;try{let e={recommendations:[]};await i(v,E)?e=s(await a(v,E)):await r(v,T),e.recommendations||=[],e.recommendations.includes(D)?p(`${m} ${f(E)} already includes ${d(D,u.MAGENTA)}`):(e.recommendations.push(D),await o(v,E,JSON.stringify(e,null,2)),p(`${m} Added ${d(D,u.MAGENTA)} to ${f(E)}`))}catch{p(`${h} Could not update ${f(E)}. You may need to add ${d(D,u.MAGENTA)} manually.`,{level:`warn`})}let O=await c(v),k=!1;for(let e of O)if(await i(v,e)){k=!0;try{let t=s(await a(v,e)),n=`.intlayer/**/*.ts`,r=!1;t.include&&(Array.isArray(t.include)&&!t.include.some(e=>e.includes(`.intlayer`))?(t.include.push(n),r=!0):t.include.includes(n)&&p(`${m} ${f(e)} already includes intlayer types`)),r&&(await o(v,e,JSON.stringify(t,null,2)),p(`${m} Updated ${f(e)} to include intlayer types`))}catch{p(`${h} Could not parse or update ${f(e)}. You may need to add ${f(`.intlayer/types/**/*.ts`)} manually.`,{level:`warn`})}}await e(k?`intlayer.config.ts`:`intlayer.config.mjs`,v);let A=!1;for(let e of[`vite.config.ts`,`vite.config.js`,`vite.config.mjs`])if(await i(v,e)){A=!0;let t=await a(v,e);t.includes(`vite-intlayer`)||(await o(v,e,n(t,e.split(`.`).pop())),p(`${m} Updated ${f(e)} to include Intlayer plugin`));break}let j=[`next.config.js`,`next.config.mjs`,`next.config.ts`],M=!1;for(let e of j)if(await i(v,e)){M=!0,A=!0;let n=await a(v,e);n.includes(`next-intlayer`)||(await o(v,e,t(n,e.split(`.`).pop())),p(`${m} Updated ${f(e)} to include Intlayer plugin`));break}if(M){let e=S.dependencies?.next||S.devDependencies?.next;if(e&&((e,t)=>{if(!e||typeof e!=`string`)return!1;let n=e.match(/^[^\d]*(\d+)/);return n?parseInt(n[1],10)>=t:!1})(e,16)){let e=S.scripts?.dev,t=`intlayer watch --with 'bun run --bun next dev'`;e&&e!==t&&e.includes(`next dev`)&&(S.scripts.dev=t,await o(v,b,JSON.stringify(S,null,2)),p(`${m} Updated ${f(`package.json`)} dev script for Next.js >= 16`))}}for(let e of[`webpack.config.js`,`webpack.config.ts`,`webpack.config.mjs`,`webpack.config.cjs`])if(await i(v,e)){A=!0,p(`${m} Found ${f(e)}. Make sure to configure aliases manually or use the Intlayer Webpack plugin.`);break}if(!A){let e=_({configuration:g({baseDir:v})});if(k&&O.length>0){let t=O.find(e=>e===`tsconfig.json`)||O[0],n=s(await a(v,t));n.compilerOptions??={},n.compilerOptions.paths??={};let r=!1;Object.entries(e).forEach(([e,t])=>{n.compilerOptions.paths[e]||(n.compilerOptions.paths[e]=[t],r=!0)}),r&&(await o(v,t,JSON.stringify(n,null,2)),p(`${m} Updated ${f(t)} to include Intlayer aliases`))}else{let t=`jsconfig.json`;if(await i(v,t)){let n=s(await a(v,t));n.compilerOptions??={},n.compilerOptions.paths??={};let r=!1;Object.entries(e).forEach(([e,t])=>{n.compilerOptions.paths[e]||(n.compilerOptions.paths[e]=[t],r=!0)}),r&&(await o(v,t,JSON.stringify(n,null,2)),p(`${m} Updated ${f(t)} to include Intlayer aliases`))}else{S.imports??={};let t=!1;Object.entries(e).forEach(([e,n])=>{let r=e.replace(`@`,`#`),i=n.startsWith(`.`)?n:`./${n}`;S.imports[r]||(S.imports[r]=i,t=!0)}),t&&(await o(v,b,JSON.stringify(S,null,2)),p(`${m} Updated ${f(b)} to include Intlayer imports`))}}}p(`${m} ${d(`Intlayer init setup complete.`,u.GREEN)}`),p([d(`Next →`,u.MAGENTA),d(`Follow the instructions in the documentation to complete the setup:`,u.GREY_LIGHT),f(C)])};export{b as initIntlayer};
|
|
1
|
+
import"../_utils_asset-4w8dPH9r.mjs";import{initConfig as e}from"../initConfig/index.mjs";import{updateNextConfig as t,updateViteConfig as n}from"./utils/configManipulation.mjs";import{ensureDirectory as r,exists as i,readFileFromRoot as a,writeFileToRoot as o}from"./utils/fileSystem.mjs";import{parseJSONWithComments as s}from"./utils/jsonParser.mjs";import{findTsConfigFiles as c}from"./utils/tsConfig.mjs";import{join as l}from"node:path";import{ANSIColors as u,colorize as d,colorizePath as f,logger as p,v as m,x as h}from"@intlayer/config/logger";import{getConfiguration as g}from"@intlayer/config/node";import{getAlias as _}from"@intlayer/config/utils";const v={NextJS:`https://intlayer.org/doc/environment/nextjs.md`,NextJS_15:`https://intlayer.org/doc/environment/nextjs/15.md`,NextJS_14:`https://intlayer.org/doc/environment/nextjs/14.md`,CRA:`https://intlayer.org/doc/environment/create-react-app.md`,Astro:`https://intlayer.org/doc/environment/astro.md`,ViteAndReact:`https://intlayer.org/doc/environment/vite-and-react.md`,ViteAndReact_ReactRouterV7:`https://intlayer.org/doc/environment/vite-and-react/react-router-v7.md`,ViteAndReact_ReactRouterV7_FSRoutes:`https://intlayer.org/doc/environment/vite-and-react/react-router-v7-fs-routes.md`,ViteAndVue:`https://intlayer.org/doc/environment/vite-and-vue.md`,ViteAndSolid:`https://intlayer.org/doc/environment/vite-and-solid.md`,ViteAndSvelte:`https://intlayer.org/doc/environment/vite-and-svelte.md`,ViteAndPreact:`https://intlayer.org/doc/environment/vite-and-preact.md`,TanStackRouter:`https://intlayer.org/doc/environment/tanstack.md`,NuxtAndVue:`https://intlayer.org/doc/environment/nuxt-and-vue.md`,Angular:`https://intlayer.org/doc/environment/angular.md`,SvelteKit:`https://intlayer.org/doc/environment/sveltekit.md`,ReactNativeAndExpo:`https://intlayer.org/doc/environment/react-native-and-expo.md`,Lynx:`https://intlayer.org/doc/environment/lynx-and-react.md`,Express:`https://intlayer.org/doc/environment/express.md`,NestJS:`https://intlayer.org/doc/environment/nestjs.md`,Fastify:`https://intlayer.org/doc/environment/fastify.md`,Default:`https://intlayer.org/doc/get-started`,NextIntl:`https://intlayer.org/blog/intlayer-with-next-intl.md`,ReactI18Next:`https://intlayer.org/blog/intlayer-with-react-i18next.md`,ReactIntl:`https://intlayer.org/blog/intlayer-with-react-intl.md`,NextI18Next:`https://intlayer.org/blog/intlayer-with-next-i18next.md`,VueI18n:`https://intlayer.org/blog/intlayer-with-vue-i18n.md`},y=e=>{let t={...e.dependencies,...e.devDependencies},n=(e,t)=>!e||typeof e!=`string`?!1:RegExp(`^[\\^~]?${t}(?:\\.|$)`).test(e);if(t[`@lynx-js/react`]||t[`@lynx-js/core`])return v.Lynx;if(t[`react-native`]||t.expo)return v.ReactNativeAndExpo;if(t.next){let e=t.next;return n(e,14)?v.NextJS_14:n(e,15)?v.NextJS_15:v.NextJS}if(t.nuxt)return v.NuxtAndVue;if(t.astro)return v.Astro;if(t[`@sveltejs/kit`])return v.SvelteKit;if(t[`@tanstack/react-router`])return v.TanStackRouter;let r=t[`react-router`];if(r&&typeof r==`string`){if(t[`@react-router/fs-routes`])return v.ViteAndReact_ReactRouterV7_FSRoutes;if(n(r,7))return v.ViteAndReact_ReactRouterV7}return t.vite?t.vue?v.ViteAndVue:t[`solid-js`]?v.ViteAndSolid:t.svelte?v.ViteAndSvelte:t.preact?v.ViteAndPreact:v.ViteAndReact:t[`react-scripts`]?v.CRA:t[`@angular/core`]?v.Angular:t[`@nestjs/core`]?v.NestJS:t.express?v.Express:t.fastify?v.Fastify:t[`next-intl`]?v.NextIntl:t[`react-i18next`]||t.i18next?v.ReactI18Next:t[`react-intl`]?v.ReactIntl:t[`next-i18next`]?v.NextI18Next:t[`vue-i18n`]?v.VueI18n:v.Default},b=async v=>{p(d(`Checking Intlayer configuration...`,u.CYAN));let b=`package.json`;await i(v,b)||(p(`${h} No ${f(`package.json`)} found. Please run this script from the project root.`,{level:`error`}),process.exit(1));let x=await a(v,b),S;try{S=JSON.parse(x)}catch{p(`${h} Could not parse ${f(`package.json`)}.`,{level:`error`}),process.exit(1)}let C=y(S),w=`.gitignore`;if(await i(v,w)){let e=await a(v,w);e.includes(`intlayer`)?p(`${m} ${f(w)} already includes .intlayer`):(await o(v,w,`${e}\n# Intlayer\n.intlayer\n`),p(`${m} Added ${f(`.intlayer`)} to ${f(w)}`))}let T=`.vscode`,E=l(T,`extensions.json`),D=`intlayer.intlayer-vs-code-extension`;try{let e={recommendations:[]};await i(v,E)?e=s(await a(v,E)):await r(v,T),e.recommendations||=[],e.recommendations.includes(D)?p(`${m} ${f(E)} already includes ${d(D,u.MAGENTA)}`):(e.recommendations.push(D),await o(v,E,JSON.stringify(e,null,2)),p(`${m} Added ${d(D,u.MAGENTA)} to ${f(E)}`))}catch{p(`${h} Could not update ${f(E)}. You may need to add ${d(D,u.MAGENTA)} manually.`,{level:`warn`})}let O=await c(v),k=!1;for(let e of O)if(await i(v,e)){k=!0;try{let t=s(await a(v,e)),n=`.intlayer/**/*.ts`,r=!1;t.include&&(Array.isArray(t.include)&&!t.include.some(e=>e.includes(`.intlayer`))?(t.include.push(n),r=!0):t.include.includes(n)&&p(`${m} ${f(e)} already includes intlayer types`)),r&&(await o(v,e,JSON.stringify(t,null,2)),p(`${m} Updated ${f(e)} to include intlayer types`))}catch{p(`${h} Could not parse or update ${f(e)}. You may need to add ${f(`.intlayer/types/**/*.ts`)} manually.`,{level:`warn`})}}await e(k?`intlayer.config.ts`:`intlayer.config.mjs`,v);let A=!1;for(let e of[`vite.config.ts`,`vite.config.js`,`vite.config.mjs`])if(await i(v,e)){A=!0;let t=await a(v,e);t.includes(`vite-intlayer`)||(await o(v,e,n(t,e.split(`.`).pop())),p(`${m} Updated ${f(e)} to include Intlayer plugin`));break}let j=[`next.config.js`,`next.config.mjs`,`next.config.ts`],M=!1;for(let e of j)if(await i(v,e)){M=!0,A=!0;let n=await a(v,e);n.includes(`next-intlayer`)||(await o(v,e,t(n,e.split(`.`).pop())),p(`${m} Updated ${f(e)} to include Intlayer plugin`));break}if(M){let e=S.dependencies?.next||S.devDependencies?.next;if(e&&((e,t)=>{if(!e||typeof e!=`string`)return!1;let n=e.match(/^[^\d]*(\d+)/);return n?parseInt(n[1],10)>=t:!1})(e,16)){let e=S.scripts?.dev,t=`intlayer watch --with 'bun run --bun next dev'`;e&&e!==t&&e.includes(`next dev`)&&(S.scripts.dev=t,await o(v,b,JSON.stringify(S,null,2)),p(`${m} Updated ${f(`package.json`)} dev script for Next.js >= 16`))}}for(let e of[`webpack.config.js`,`webpack.config.ts`,`webpack.config.mjs`,`webpack.config.cjs`])if(await i(v,e)){A=!0,p(`${m} Found ${f(e)}. Make sure to configure aliases manually or use the Intlayer Webpack plugin.`);break}if(!A){let e=_({configuration:g({baseDir:v})});if(k&&O.length>0){let t=O.find(e=>e===`tsconfig.json`)||O[0],n=s(await a(v,t));n.compilerOptions??={},n.compilerOptions.paths??={};let r=!1;Object.entries(e).forEach(([e,t])=>{n.compilerOptions.paths[e]||(n.compilerOptions.paths[e]=[t],r=!0)}),r&&(await o(v,t,JSON.stringify(n,null,2)),p(`${m} Updated ${f(t)} to include Intlayer aliases`))}else{let t=`jsconfig.json`;if(await i(v,t)){let n=s(await a(v,t));n.compilerOptions??={},n.compilerOptions.paths??={};let r=!1;Object.entries(e).forEach(([e,t])=>{n.compilerOptions.paths[e]||(n.compilerOptions.paths[e]=[t],r=!0)}),r&&(await o(v,t,JSON.stringify(n,null,2)),p(`${m} Updated ${f(t)} to include Intlayer aliases`))}else{S.imports??={};let t=!1;Object.entries(e).forEach(([e,n])=>{let r=e.replace(`@`,`#`),i=n.startsWith(`.`)?n:`./${n}`;S.imports[r]||(S.imports[r]=i,t=!0)}),t&&(await o(v,b,JSON.stringify(S,null,2)),p(`${m} Updated ${f(b)} to include Intlayer imports`))}}}p(`${m} ${d(`Intlayer init setup complete.`,u.GREEN)}`),p([d(`Next →`,u.MAGENTA),d(`Follow the instructions in the documentation to complete the setup:`,u.GREY_LIGHT),f(C)])};export{b as initIntlayer};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|