@intlayer/chokidar 8.1.2 → 8.1.3
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/assets/installSkills/skills/angular.md +3 -0
- package/dist/assets/installSkills/skills/astro.md +3 -0
- package/dist/assets/installSkills/skills/cli.md +7 -4
- package/dist/assets/installSkills/skills/config.md +3 -0
- package/dist/assets/installSkills/skills/content.md +3 -0
- package/dist/assets/installSkills/skills/next_js.md +3 -0
- package/dist/assets/installSkills/skills/preact.md +3 -2
- package/dist/assets/installSkills/skills/react.md +3 -0
- package/dist/assets/installSkills/skills/solid.md +3 -0
- package/dist/assets/installSkills/skills/svelte.md +3 -0
- package/dist/assets/installSkills/skills/usage.md +2 -0
- package/dist/assets/installSkills/skills/vue.md +3 -0
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -29
- package/dist/cjs/_virtual/_utils_asset.cjs +2 -98
- package/dist/cjs/build.cjs +1 -51
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs +1 -53
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/index.cjs +1 -6
- package/dist/cjs/buildIntlayerDictionary/processContentDeclaration.cjs +1 -26
- package/dist/cjs/buildIntlayerDictionary/processContentDeclaration.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs +4 -78
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs +4 -62
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs +1 -46
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs +1 -50
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs +1 -59
- package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs.map +1 -1
- package/dist/cjs/cleanOutputDir.cjs +1 -30
- package/dist/cjs/cleanOutputDir.cjs.map +1 -1
- package/dist/cjs/cleanRemovedContentDeclaration.cjs +1 -96
- package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
- package/dist/cjs/cli.cjs +1 -21
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs +1 -70
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs +7 -41
- package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs +1 -23
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs +1 -24
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs +1 -24
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs +1 -23
- package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs +1 -23
- package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/index.cjs +1 -16
- package/dist/cjs/createType/createModuleAugmentation.cjs +9 -110
- package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
- package/dist/cjs/createType/createType.cjs +1 -29
- package/dist/cjs/createType/createType.cjs.map +1 -1
- package/dist/cjs/createType/index.cjs +1 -8
- package/dist/cjs/fetchDistantDictionaries.cjs +1 -50
- package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs +1 -49
- package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
- package/dist/cjs/formatDictionary.cjs +1 -49
- package/dist/cjs/formatDictionary.cjs.map +1 -1
- package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs +1 -39
- package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs.map +1 -1
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs +1 -34
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileChange.cjs +1 -49
- package/dist/cjs/handleContentDeclarationFileChange.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileMoved.cjs +1 -24
- package/dist/cjs/handleContentDeclarationFileMoved.cjs.map +1 -1
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs +1 -37
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -131
- package/dist/cjs/init/index.cjs +1 -242
- package/dist/cjs/init/index.cjs.map +1 -1
- package/dist/cjs/init/utils/configManipulation.cjs +1 -164
- package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
- package/dist/cjs/init/utils/fileSystem.cjs +1 -30
- package/dist/cjs/init/utils/fileSystem.cjs.map +1 -1
- package/dist/cjs/init/utils/index.cjs +1 -13
- package/dist/cjs/init/utils/jsonParser.cjs +3 -42
- package/dist/cjs/init/utils/jsonParser.cjs.map +1 -1
- package/dist/cjs/init/utils/tsConfig.cjs +1 -18
- package/dist/cjs/init/utils/tsConfig.cjs.map +1 -1
- package/dist/cjs/initConfig/index.cjs +1 -38
- package/dist/cjs/initConfig/index.cjs.map +1 -1
- package/dist/cjs/installSkills/index.cjs +1 -172
- package/dist/cjs/installSkills/index.cjs.map +1 -1
- package/dist/cjs/listDictionariesPath.cjs +1 -41
- package/dist/cjs/listDictionariesPath.cjs.map +1 -1
- package/dist/cjs/listGitFiles.cjs +5 -95
- package/dist/cjs/listGitFiles.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs +1 -47
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs +1 -66
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/index.cjs +1 -12
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +2 -72
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs +1 -125
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs +1 -28
- package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs +1 -61
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/log.cjs +3 -135
- package/dist/cjs/loadDictionaries/log.cjs.map +1 -1
- package/dist/cjs/prepareIntlayer.cjs +1 -95
- package/dist/cjs/prepareIntlayer.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/applyMask.cjs +1 -30
- package/dist/cjs/reduceDictionaryContent/applyMask.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs +1 -12
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs.map +1 -1
- package/dist/cjs/transformFiles/extractDictionaryKey.cjs +1 -16
- package/dist/cjs/transformFiles/extractDictionaryKey.cjs.map +1 -1
- package/dist/cjs/transformFiles/index.cjs +1 -10
- package/dist/cjs/transformFiles/transformFiles.cjs +1 -251
- package/dist/cjs/transformFiles/transformFiles.cjs.map +1 -1
- package/dist/cjs/utils/autoDecorateContent.cjs +1 -87
- package/dist/cjs/utils/autoDecorateContent.cjs.map +1 -1
- package/dist/cjs/utils/buildFilesList.cjs +1 -50
- package/dist/cjs/utils/buildFilesList.cjs.map +1 -1
- package/dist/cjs/utils/chunkJSON.cjs +1 -336
- package/dist/cjs/utils/chunkJSON.cjs.map +1 -1
- package/dist/cjs/utils/formatter.cjs +1 -16
- package/dist/cjs/utils/formatter.cjs.map +1 -1
- package/dist/cjs/utils/getChunk.cjs +1 -34
- package/dist/cjs/utils/getChunk.cjs.map +1 -1
- package/dist/cjs/utils/getComponentTransformPattern.cjs +1 -48
- package/dist/cjs/utils/getComponentTransformPattern.cjs.map +1 -1
- package/dist/cjs/utils/getFileHash.cjs +1 -12
- package/dist/cjs/utils/getFileHash.cjs.map +1 -1
- package/dist/cjs/utils/getFormatFromExtension.cjs +1 -31
- package/dist/cjs/utils/getFormatFromExtension.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +1 -46
- package/dist/cjs/utils/pLimit.cjs +1 -128
- package/dist/cjs/utils/pLimit.cjs.map +1 -1
- package/dist/cjs/utils/parallelize.cjs +1 -11
- package/dist/cjs/utils/parallelize.cjs.map +1 -1
- package/dist/cjs/utils/parallelizeGlobal.cjs +1 -29
- package/dist/cjs/utils/parallelizeGlobal.cjs.map +1 -1
- package/dist/cjs/utils/reduceObjectFormat.cjs +1 -31
- package/dist/cjs/utils/reduceObjectFormat.cjs.map +1 -1
- package/dist/cjs/utils/resolveObjectPromises.cjs +1 -21
- package/dist/cjs/utils/resolveObjectPromises.cjs.map +1 -1
- package/dist/cjs/utils/runOnce.cjs +1 -95
- package/dist/cjs/utils/runOnce.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/bin.cjs +1 -54
- package/dist/cjs/utils/runParallel/bin.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/bootstrap.cjs +1 -24
- package/dist/cjs/utils/runParallel/bootstrap.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/index.cjs +1 -110
- package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/pidTree.cjs +1 -145
- package/dist/cjs/utils/runParallel/pidTree.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/ps.cjs +1 -49
- package/dist/cjs/utils/runParallel/ps.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/runTask.cjs +1 -154
- package/dist/cjs/utils/runParallel/runTask.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/spawnPosix.cjs +1 -59
- package/dist/cjs/utils/runParallel/spawnPosix.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/spawnWin32.cjs +1 -43
- package/dist/cjs/utils/runParallel/spawnWin32.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/wmic.cjs +1 -52
- package/dist/cjs/utils/runParallel/wmic.cjs.map +1 -1
- package/dist/cjs/utils/sortAlphabetically.cjs +1 -7
- package/dist/cjs/utils/sortAlphabetically.cjs.map +1 -1
- package/dist/cjs/utils/splitTextByLine.cjs +1 -11
- package/dist/cjs/utils/splitTextByLine.cjs.map +1 -1
- package/dist/cjs/utils/verifyIdenticObjectFormat.cjs +1 -60
- package/dist/cjs/utils/verifyIdenticObjectFormat.cjs.map +1 -1
- package/dist/cjs/watcher.cjs +1 -95
- package/dist/cjs/watcher.cjs.map +1 -1
- package/dist/cjs/writeConfiguration/index.cjs +1 -34
- package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs +1 -28
- package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/detectFormatCommand.cjs +1 -31
- package/dist/cjs/writeContentDeclaration/detectFormatCommand.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/index.cjs +1 -12
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs +1 -93
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs +2 -1775
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs +1 -77
- package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +1 -123
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +1 -71
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
- package/dist/cjs/writeFileIfChanged.cjs +1 -12
- package/dist/cjs/writeFileIfChanged.cjs.map +1 -1
- package/dist/cjs/writeJsonIfChanged.cjs +1 -17
- package/dist/cjs/writeJsonIfChanged.cjs.map +1 -1
- package/dist/esm/_virtual/_rolldown/runtime.mjs +1 -8
- package/dist/esm/_virtual/_utils_asset.mjs +2 -97
- package/dist/esm/build.mjs +1 -24
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs +1 -51
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/index.mjs +1 -4
- package/dist/esm/buildIntlayerDictionary/processContentDeclaration.mjs +1 -24
- package/dist/esm/buildIntlayerDictionary/processContentDeclaration.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs +4 -75
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeFetchDictionary.mjs +4 -59
- package/dist/esm/buildIntlayerDictionary/writeFetchDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs +1 -44
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs +1 -48
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeUnmergedDictionary.mjs +1 -56
- package/dist/esm/buildIntlayerDictionary/writeUnmergedDictionary.mjs.map +1 -1
- package/dist/esm/cleanOutputDir.mjs +1 -28
- package/dist/esm/cleanOutputDir.mjs.map +1 -1
- package/dist/esm/cleanRemovedContentDeclaration.mjs +1 -93
- package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
- package/dist/esm/cli.mjs +1 -8
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs +1 -68
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs +7 -39
- package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs +1 -20
- package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs +1 -21
- package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs +1 -21
- package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs +1 -20
- package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs +1 -20
- package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/index.mjs +1 -9
- package/dist/esm/createType/createModuleAugmentation.mjs +9 -106
- package/dist/esm/createType/createModuleAugmentation.mjs.map +1 -1
- package/dist/esm/createType/createType.mjs +1 -26
- package/dist/esm/createType/createType.mjs.map +1 -1
- package/dist/esm/createType/index.mjs +1 -4
- package/dist/esm/fetchDistantDictionaries.mjs +1 -48
- package/dist/esm/fetchDistantDictionaries.mjs.map +1 -1
- package/dist/esm/filterInvalidDictionaries.mjs +1 -46
- package/dist/esm/filterInvalidDictionaries.mjs.map +1 -1
- package/dist/esm/formatDictionary.mjs +1 -44
- package/dist/esm/formatDictionary.mjs.map +1 -1
- package/dist/esm/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs +1 -37
- package/dist/esm/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs.map +1 -1
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs +1 -32
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/handleContentDeclarationFileChange.mjs +1 -47
- package/dist/esm/handleContentDeclarationFileChange.mjs.map +1 -1
- package/dist/esm/handleContentDeclarationFileMoved.mjs +1 -22
- package/dist/esm/handleContentDeclarationFileMoved.mjs.map +1 -1
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs +1 -35
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/index.mjs +1 -57
- package/dist/esm/init/index.mjs +1 -240
- package/dist/esm/init/index.mjs.map +1 -1
- package/dist/esm/init/utils/configManipulation.mjs +1 -161
- package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
- package/dist/esm/init/utils/fileSystem.mjs +1 -26
- package/dist/esm/init/utils/fileSystem.mjs.map +1 -1
- package/dist/esm/init/utils/index.mjs +1 -6
- package/dist/esm/init/utils/jsonParser.mjs +3 -40
- package/dist/esm/init/utils/jsonParser.mjs.map +1 -1
- package/dist/esm/init/utils/tsConfig.mjs +1 -16
- package/dist/esm/init/utils/tsConfig.mjs.map +1 -1
- package/dist/esm/initConfig/index.mjs +1 -36
- package/dist/esm/initConfig/index.mjs.map +1 -1
- package/dist/esm/installSkills/index.mjs +1 -167
- package/dist/esm/installSkills/index.mjs.map +1 -1
- package/dist/esm/listDictionariesPath.mjs +1 -37
- package/dist/esm/listDictionariesPath.mjs.map +1 -1
- package/dist/esm/listGitFiles.mjs +5 -90
- package/dist/esm/listGitFiles.mjs.map +1 -1
- package/dist/esm/listProjects.mjs +1 -43
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs +1 -65
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
- package/dist/esm/loadDictionaries/index.mjs +1 -6
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs +2 -69
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadDictionaries.mjs +1 -123
- package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs +1 -26
- package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs +1 -58
- package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/log.mjs +3 -132
- package/dist/esm/loadDictionaries/log.mjs.map +1 -1
- package/dist/esm/prepareIntlayer.mjs +1 -92
- package/dist/esm/prepareIntlayer.mjs.map +1 -1
- package/dist/esm/reduceDictionaryContent/applyMask.mjs +1 -28
- package/dist/esm/reduceDictionaryContent/applyMask.mjs.map +1 -1
- package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs +1 -10
- package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs.map +1 -1
- package/dist/esm/transformFiles/extractDictionaryKey.mjs +1 -14
- package/dist/esm/transformFiles/extractDictionaryKey.mjs.map +1 -1
- package/dist/esm/transformFiles/index.mjs +1 -4
- package/dist/esm/transformFiles/transformFiles.mjs +1 -244
- package/dist/esm/transformFiles/transformFiles.mjs.map +1 -1
- package/dist/esm/utils/autoDecorateContent.mjs +1 -85
- package/dist/esm/utils/autoDecorateContent.mjs.map +1 -1
- package/dist/esm/utils/buildFilesList.mjs +1 -47
- package/dist/esm/utils/buildFilesList.mjs.map +1 -1
- package/dist/esm/utils/chunkJSON.mjs +1 -333
- package/dist/esm/utils/chunkJSON.mjs.map +1 -1
- package/dist/esm/utils/formatter.mjs +1 -12
- package/dist/esm/utils/formatter.mjs.map +1 -1
- package/dist/esm/utils/getChunk.mjs +1 -33
- package/dist/esm/utils/getChunk.mjs.map +1 -1
- package/dist/esm/utils/getComponentTransformPattern.mjs +1 -44
- package/dist/esm/utils/getComponentTransformPattern.mjs.map +1 -1
- package/dist/esm/utils/getFileHash.mjs +1 -9
- package/dist/esm/utils/getFileHash.mjs.map +1 -1
- package/dist/esm/utils/getFormatFromExtension.mjs +1 -28
- package/dist/esm/utils/getFormatFromExtension.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +1 -20
- package/dist/esm/utils/pLimit.mjs +1 -125
- package/dist/esm/utils/pLimit.mjs.map +1 -1
- package/dist/esm/utils/parallelize.mjs +1 -10
- package/dist/esm/utils/parallelize.mjs.map +1 -1
- package/dist/esm/utils/parallelizeGlobal.mjs +1 -26
- package/dist/esm/utils/parallelizeGlobal.mjs.map +1 -1
- package/dist/esm/utils/reduceObjectFormat.mjs +1 -29
- package/dist/esm/utils/reduceObjectFormat.mjs.map +1 -1
- package/dist/esm/utils/resolveObjectPromises.mjs +1 -19
- package/dist/esm/utils/resolveObjectPromises.mjs.map +1 -1
- package/dist/esm/utils/runOnce.mjs +1 -92
- package/dist/esm/utils/runOnce.mjs.map +1 -1
- package/dist/esm/utils/runParallel/bin.mjs +1 -52
- package/dist/esm/utils/runParallel/bin.mjs.map +1 -1
- package/dist/esm/utils/runParallel/bootstrap.mjs +1 -22
- package/dist/esm/utils/runParallel/bootstrap.mjs.map +1 -1
- package/dist/esm/utils/runParallel/index.mjs +1 -108
- package/dist/esm/utils/runParallel/index.mjs.map +1 -1
- package/dist/esm/utils/runParallel/pidTree.mjs +1 -142
- package/dist/esm/utils/runParallel/pidTree.mjs.map +1 -1
- package/dist/esm/utils/runParallel/ps.mjs +1 -46
- package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
- package/dist/esm/utils/runParallel/runTask.mjs +1 -152
- package/dist/esm/utils/runParallel/runTask.mjs.map +1 -1
- package/dist/esm/utils/runParallel/spawnPosix.mjs +1 -57
- package/dist/esm/utils/runParallel/spawnPosix.mjs.map +1 -1
- package/dist/esm/utils/runParallel/spawnWin32.mjs +1 -41
- package/dist/esm/utils/runParallel/spawnWin32.mjs.map +1 -1
- package/dist/esm/utils/runParallel/wmic.mjs +1 -49
- package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
- package/dist/esm/utils/sortAlphabetically.mjs +1 -5
- package/dist/esm/utils/sortAlphabetically.mjs.map +1 -1
- package/dist/esm/utils/splitTextByLine.mjs +1 -9
- package/dist/esm/utils/splitTextByLine.mjs.map +1 -1
- package/dist/esm/utils/verifyIdenticObjectFormat.mjs +1 -58
- package/dist/esm/utils/verifyIdenticObjectFormat.mjs.map +1 -1
- package/dist/esm/watcher.mjs +1 -92
- package/dist/esm/watcher.mjs.map +1 -1
- package/dist/esm/writeConfiguration/index.mjs +1 -31
- package/dist/esm/writeConfiguration/index.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/detectExportedComponentName.mjs +1 -26
- package/dist/esm/writeContentDeclaration/detectExportedComponentName.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/detectFormatCommand.mjs +1 -29
- package/dist/esm/writeContentDeclaration/detectFormatCommand.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/index.mjs +1 -7
- package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs +1 -91
- package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/transformJSFile.mjs +2 -1773
- package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/transformJSONFile.mjs +1 -75
- package/dist/esm/writeContentDeclaration/transformJSONFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +1 -121
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs +1 -69
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -1
- package/dist/esm/writeFileIfChanged.mjs +1 -10
- package/dist/esm/writeFileIfChanged.mjs.map +1 -1
- package/dist/esm/writeJsonIfChanged.mjs +1 -16
- package/dist/esm/writeJsonIfChanged.mjs.map +1 -1
- package/dist/types/build.d.ts +3 -1
- package/dist/types/buildIntlayerDictionary/buildIntlayerDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeDynamicDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeFetchDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeMergedDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeRemoteDictionary.d.ts.map +1 -1
- package/dist/types/createDictionaryEntryPoint/generateDictionaryListContent.d.ts.map +1 -1
- package/dist/types/fetchDistantDictionaries.d.ts.map +1 -1
- package/dist/types/index.d.ts +16 -24
- package/dist/types/initConfig/index.d.ts +1 -1
- package/dist/types/initConfig/index.d.ts.map +1 -1
- package/dist/types/listGitFiles.d.ts.map +1 -1
- package/dist/types/loadDictionaries/getIntlayerBundle.d.ts.map +1 -1
- package/dist/types/loadDictionaries/loadContentDeclaration.d.ts.map +1 -1
- package/dist/types/prepareIntlayer.d.ts.map +1 -1
- package/dist/types/transformFiles/transformFiles.d.ts +1 -1
- package/dist/types/transformFiles/transformFiles.d.ts.map +1 -1
- package/dist/types/utils/formatter.d.ts +1 -1
- package/dist/types/watcher.d.ts +1 -1
- package/dist/types/writeContentDeclaration/processContentDeclarationContent.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/transformJSFile.d.ts.map +1 -1
- package/package.json +10 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformFiles.mjs","names":[],"sources":["../../../src/transformFiles/transformFiles.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path';\nimport {\n ANSIColors,\n camelCaseToKebabCase,\n colorizePath,\n type GetConfigurationOptions,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\nimport { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';\nimport { writeContentDeclaration } from '../writeContentDeclaration';\nimport { detectFormatCommand } from '../writeContentDeclaration/detectFormatCommand';\nimport { extractDictionaryKey } from './extractDictionaryKey';\n\n// ==========================================\n// Shared Utilities (exported for reuse in babel plugin)\n// ==========================================\n\n/**\n * Attributes that should be extracted for localization\n */\nexport const ATTRIBUTES_TO_EXTRACT = [\n 'title',\n 'placeholder',\n 'alt',\n 'aria-label',\n 'label',\n];\n\n/**\n * Default function to determine if a string should be extracted for localization\n */\nexport const shouldExtract = (text: string): boolean => {\n const trimmed = text.trim();\n if (!trimmed) return false;\n if (!trimmed.includes(' ')) return false;\n // Starts with Capital letter\n if (!/^[A-Z]/.test(trimmed)) return false;\n // Filter out template logic identifiers (simple check)\n if (trimmed.startsWith('{') || trimmed.startsWith('v-')) return false;\n return true;\n};\n\n/**\n * Generate a unique key from text for use as a dictionary key\n */\nexport const generateKey = (\n text: string,\n existingKeys: Set<string>\n): string => {\n const maxWords = 5;\n let key = text\n .replace(/\\s+/g, ' ')\n .replace(/_+/g, ' ')\n .replace(/-+/g, ' ')\n .replace(/[^a-zA-Z0-9 ]/g, '')\n .trim()\n .split(' ')\n .filter(Boolean)\n .slice(0, maxWords)\n .map((word, index) =>\n index === 0\n ? word.toLowerCase()\n : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()\n )\n .join('');\n\n if (!key) key = 'content';\n if (existingKeys.has(key)) {\n let i = 1;\n while (existingKeys.has(`${key}${i}`)) i++;\n key = `${key}${i}`;\n }\n return key;\n};\n\n/**\n * Translation node structure used in multilingual dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\n};\n\nconst writeContentHelper = async (\n extractedContent: Record<string, string>,\n componentKey: string,\n filePath: string,\n configuration: IntlayerConfig,\n outputDir?: string\n) => {\n const { defaultLocale } = configuration.internationalization;\n const { baseDir, fileExtensions } = configuration.content;\n\n const isPerLocaleFile = configuration?.dictionary?.locale;\n\n const dirName = outputDir ? resolve(outputDir) : dirname(filePath);\n const ext = extname(filePath);\n const baseName = basename(filePath, ext);\n const contentBaseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);\n\n const contentFilePath = join(\n dirName,\n `${contentBaseName}.${fileExtensions[0]}`\n );\n const relativeContentFilePath = relative(baseDir, contentFilePath);\n\n let dictionary: Dictionary;\n\n if (isPerLocaleFile) {\n // Per-locale format: simple string content with locale property\n dictionary = {\n key: componentKey,\n content: extractedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n } else {\n // Multilingual format: content wrapped in translation nodes, no locale property\n const multilingualContent: Record<string, TranslationNode> = {};\n for (const [key, value] of Object.entries(extractedContent)) {\n multilingualContent[key] = {\n nodeType: 'translation',\n translation: {\n [defaultLocale]: value,\n },\n };\n }\n\n dictionary = {\n key: componentKey,\n content: multilingualContent,\n filePath: relativeContentFilePath,\n };\n }\n\n const relativeDir = relative(baseDir, dirName);\n await writeContentDeclaration(dictionary, configuration, {\n newDictionariesPath: relativeDir,\n });\n\n return contentFilePath;\n};\n\ntype TsReplacement = {\n node: Node;\n key: string;\n type: 'jsx-text' | 'jsx-attribute' | 'string-literal';\n};\n\nconst extractTsContent = (\n sourceFile: SourceFile,\n existingKeys: Set<string>\n): {\n extractedContent: Record<string, string>;\n replacements: TsReplacement[];\n} => {\n const extractedContent: Record<string, string> = {};\n const replacements: TsReplacement[] = [];\n\n sourceFile.forEachDescendant((node) => {\n // 1. JSX Text\n if (Node.isJsxText(node)) {\n const text = node.getText();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.replace(/\\s+/g, ' ').trim();\n replacements.push({ node, key, type: 'jsx-text' });\n }\n }\n\n // 2. JSX Attributes\n else if (Node.isJsxAttribute(node)) {\n const name = node.getNameNode().getText();\n if (ATTRIBUTES_TO_EXTRACT.includes(name)) {\n const initializer = node.getInitializer();\n if (Node.isStringLiteral(initializer)) {\n const text = initializer.getLiteralValue();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'jsx-attribute' });\n }\n }\n }\n }\n\n // 3. String Literals (Variables, Arrays, etc.)\n else if (Node.isStringLiteral(node)) {\n const text = node.getLiteralValue();\n if (shouldExtract(text)) {\n const parent = node.getParent();\n\n // Skip if inside ImportDeclaration\n if (\n parent?.getKindName() === 'ImportDeclaration' ||\n parent?.getKindName() === 'ImportSpecifier' ||\n parent?.getKindName() === 'ModuleSpecifier'\n ) {\n return;\n }\n\n // Skip if it's a JSX Attribute value (handled above)\n if (Node.isJsxAttribute(parent)) return;\n\n // Skip console.log\n if (Node.isCallExpression(parent)) {\n const expression = parent.getExpression();\n if (expression.getText().includes('console.log')) return;\n }\n\n // Skip Object Keys: { key: \"value\" } -> \"key\" is PropertyAssignment name if not computed\n if (Node.isPropertyAssignment(parent)) {\n if (parent.getNameNode() === node) return; // It's the key\n }\n\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'string-literal' });\n }\n }\n });\n\n return { extractedContent, replacements };\n};\n\n// ==========================================\n// React (TS-Morph) Strategy\n// ==========================================\n\nconst processTsxFile = async (\n filePath: string,\n componentKey: string,\n packageName: PackageName,\n project: Project,\n save: boolean = true\n) => {\n let sourceFile: SourceFile;\n try {\n sourceFile = project.addSourceFileAtPath(filePath);\n } catch {\n sourceFile = project.getSourceFileOrThrow(filePath);\n }\n\n const isSolid = packageName === 'solid-intlayer';\n\n const existingKeys = new Set<string>();\n const { extractedContent, replacements } = extractTsContent(\n sourceFile,\n existingKeys\n );\n\n if (Object.keys(extractedContent).length === 0) return null;\n\n for (const { node, key, type } of replacements) {\n const contentAccess = isSolid ? `content().${key}` : `content.${key}`;\n\n if (type === 'jsx-text' && Node.isJsxText(node)) {\n node.replaceWithText(`{${contentAccess}}`);\n } else if (type === 'jsx-attribute' && Node.isJsxAttribute(node)) {\n node.setInitializer(`{${contentAccess}.value}`);\n } else if (type === 'string-literal' && Node.isStringLiteral(node)) {\n // For React/JS variables, we usually want the value\n node.replaceWithText(`${contentAccess}.value`);\n }\n }\n\n // Inject hook\n const importDecl = sourceFile.getImportDeclaration(\n (d) => d.getModuleSpecifierValue() === packageName\n );\n if (!importDecl) {\n sourceFile.addImportDeclaration({\n namedImports: ['useIntlayer'],\n moduleSpecifier: packageName,\n });\n } else if (\n !importDecl.getNamedImports().some((n) => n.getName() === 'useIntlayer')\n ) {\n importDecl.addNamedImport('useIntlayer');\n }\n\n // Insert hook at start of component\n sourceFile.getFunctions().forEach((f) => {\n f.getBody()\n ?.asKind(SyntaxKind.Block)\n ?.insertStatements(0, `const content = useIntlayer(\"${componentKey}\");`);\n });\n\n // Also handle const/arrow components\n sourceFile.getVariableDeclarations().forEach((v) => {\n const init = v.getInitializer();\n if (Node.isArrowFunction(init) || Node.isFunctionExpression(init)) {\n const body = init.getBody();\n if (Node.isBlock(body)) {\n // Heuristic: check if it returns JSX or uses hooks\n if (\n body.getText().includes('return') ||\n body.getText().includes('use')\n ) {\n body.insertStatements(\n 0,\n `const content = useIntlayer(\"${componentKey}\");`\n );\n }\n }\n }\n });\n\n if (save) {\n await sourceFile.save();\n }\n return extractedContent;\n};\n\n// ==========================================\n// 5. Main Dispatcher\n// ==========================================\n\nexport type PackageName =\n | 'next-intlayer'\n | 'react-intlayer'\n | 'vue-intlayer'\n | 'svelte-intlayer'\n | 'preact-intlayer'\n | 'solid-intlayer'\n | 'angular-intlayer'\n | 'express-intlayer';\n\nexport type ExtractIntlayerOptions = {\n configOptions?: GetConfigurationOptions;\n outputDir?: string;\n codeOnly?: boolean;\n declarationOnly?: boolean;\n};\n\nexport const extractIntlayer = async (\n filePath: string,\n packageName: PackageName,\n options?: ExtractIntlayerOptions,\n project?: Project\n) => {\n const saveComponent = !options?.declarationOnly;\n const writeContent = !options?.codeOnly;\n\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n const { baseDir } = configuration.content;\n\n // Setup Project for TS/React files if needed\n const _project =\n project || new Project({ skipAddingFilesFromTsConfig: true });\n\n const baseName = extractDictionaryKey(\n filePath,\n (await fs.readFile(filePath)).toString()\n );\n const componentKey = camelCaseToKebabCase(baseName);\n const ext = extname(filePath);\n\n let extractedContent: Record<string, string> | null = null;\n\n if (ext === '.vue') {\n try {\n const { processVueFile } = await import('@intlayer/vue-transformer');\n extractedContent = await processVueFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/vue-transformer', ANSIColors.YELLOW)} to process Vue files.`\n );\n }\n throw error;\n }\n } else if (ext === '.svelte') {\n try {\n const { processSvelteFile } = (await import(\n '@intlayer/svelte-transformer'\n )) as any;\n extractedContent = await processSvelteFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/svelte-transformer', ANSIColors.YELLOW)} to process Svelte files.`\n );\n }\n throw error;\n }\n } else if (['.tsx', '.jsx', '.ts', '.js'].includes(ext)) {\n extractedContent = await processTsxFile(\n filePath,\n componentKey,\n packageName,\n _project,\n saveComponent\n );\n }\n\n if (!extractedContent) {\n appLogger(`No extractable text found in ${baseName}`);\n return;\n }\n\n // Shared Write Logic\n if (writeContent) {\n const contentFilePath = await writeContentHelper(\n extractedContent,\n componentKey,\n filePath,\n configuration,\n options?.outputDir\n );\n\n const relativeContentFilePath = relative(\n configuration.content.baseDir,\n contentFilePath\n );\n appLogger(`Created content file: ${colorizePath(relativeContentFilePath)}`);\n }\n\n // Optional: Format\n if (saveComponent) {\n try {\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'ignore', // Silent\n cwd: baseDir,\n });\n }\n } catch {\n // Ignore format errors\n }\n\n appLogger(\n `Updated component: ${colorizePath(relative(baseDir, filePath))}`\n );\n }\n};\n\nexport const transformFiles = async (\n filePaths: string[],\n packageName: PackageName,\n options?: ExtractIntlayerOptions\n) => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n });\n\n for (const filePath of filePaths) {\n try {\n await extractIntlayer(filePath, packageName, options, project);\n } catch (error) {\n appLogger(`Failed to transform ${filePath}: ${(error as Error).message}`);\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;AAwBA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACD;;;;AAKD,MAAa,iBAAiB,SAA0B;CACtD,MAAM,UAAU,KAAK,MAAM;AAC3B,KAAI,CAAC,QAAS,QAAO;AACrB,KAAI,CAAC,QAAQ,SAAS,IAAI,CAAE,QAAO;AAEnC,KAAI,CAAC,SAAS,KAAK,QAAQ,CAAE,QAAO;AAEpC,KAAI,QAAQ,WAAW,IAAI,IAAI,QAAQ,WAAW,KAAK,CAAE,QAAO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AAI;EACF,MAAM,EAAE,sBAAuB,MAAM,OACnC;AAEF,qBAAmB,MAAM,kBACvB,UACA,cACA,aACA;GACE;GACA;GACA;GACD,EACD,cACD;UACM,OAAY;AACnB,MACE,MAAM,SAAS,0BACf,MAAM,SAAS,SAAS,qBAAqB,CAE7C,OAAM,IAAI,MACR,kBAAkB,aAAa,gCAAgC,WAAW,OAAO,CAAC,2BACnF;AAEH,QAAM;;UAEC;EAAC;EAAQ;EAAQ;EAAO;EAAM,CAAC,SAAS,IAAI,CACrD,oBAAmB,MAAM,eACvB,UACA,cACA,aACA,UACA,cACD;AAGH,KAAI,CAAC,kBAAkB;AACrB,YAAU,gCAAgC,WAAW;AACrD;;AAIF,KAAI,cAAc;EAChB,MAAM,kBAAkB,MAAM,mBAC5B,kBACA,cACA,UACA,eACA,SAAS,UACV;AAMD,YAAU,yBAAyB,aAJH,SAC9B,cAAc,QAAQ,SACtB,gBACD,CACuE,GAAG;;AAI7E,KAAI,eAAe;AACjB,MAAI;GACF,MAAM,gBAAgB,oBAAoB,cAAc;AACxD,OAAI,cACF,UAAS,cAAc,QAAQ,YAAY,SAAS,EAAE;IACpD,OAAO;IACP,KAAK;IACN,CAAC;UAEE;AAIR,YACE,sBAAsB,aAAa,SAAS,SAAS,SAAS,CAAC,GAChE;;;AAIL,MAAa,iBAAiB,OAC5B,WACA,aACA,YACG;CAEH,MAAM,YAAY,aADI,iBAAiB,SAAS,cAAc,CACjB;CAE7C,MAAM,UAAU,IAAI,QAAQ,EAC1B,6BAA6B,MAC9B,CAAC;AAEF,MAAK,MAAM,YAAY,UACrB,KAAI;AACF,QAAM,gBAAgB,UAAU,aAAa,SAAS,QAAQ;UACvD,OAAO;AACd,YAAU,uBAAuB,SAAS,IAAK,MAAgB,UAAU"}
|
|
1
|
+
{"version":3,"file":"transformFiles.mjs","names":[],"sources":["../../../src/transformFiles/transformFiles.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path';\nimport {\n ANSIColors,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { camelCaseToKebabCase } from '@intlayer/config/utils';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\nimport { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';\nimport { writeContentDeclaration } from '../writeContentDeclaration';\nimport { detectFormatCommand } from '../writeContentDeclaration/detectFormatCommand';\nimport { extractDictionaryKey } from './extractDictionaryKey';\n\n// ==========================================\n// Shared Utilities (exported for reuse in babel plugin)\n// ==========================================\n\n/**\n * Attributes that should be extracted for localization\n */\nexport const ATTRIBUTES_TO_EXTRACT = [\n 'title',\n 'placeholder',\n 'alt',\n 'aria-label',\n 'label',\n];\n\n/**\n * Default function to determine if a string should be extracted for localization\n */\nexport const shouldExtract = (text: string): boolean => {\n const trimmed = text.trim();\n if (!trimmed) return false;\n if (!trimmed.includes(' ')) return false;\n // Starts with Capital letter\n if (!/^[A-Z]/.test(trimmed)) return false;\n // Filter out template logic identifiers (simple check)\n if (trimmed.startsWith('{') || trimmed.startsWith('v-')) return false;\n return true;\n};\n\n/**\n * Generate a unique key from text for use as a dictionary key\n */\nexport const generateKey = (\n text: string,\n existingKeys: Set<string>\n): string => {\n const maxWords = 5;\n let key = text\n .replace(/\\s+/g, ' ')\n .replace(/_+/g, ' ')\n .replace(/-+/g, ' ')\n .replace(/[^a-zA-Z0-9 ]/g, '')\n .trim()\n .split(' ')\n .filter(Boolean)\n .slice(0, maxWords)\n .map((word, index) =>\n index === 0\n ? word.toLowerCase()\n : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()\n )\n .join('');\n\n if (!key) key = 'content';\n if (existingKeys.has(key)) {\n let i = 1;\n while (existingKeys.has(`${key}${i}`)) i++;\n key = `${key}${i}`;\n }\n return key;\n};\n\n/**\n * Translation node structure used in multilingual dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\n};\n\nconst writeContentHelper = async (\n extractedContent: Record<string, string>,\n componentKey: string,\n filePath: string,\n configuration: IntlayerConfig,\n outputDir?: string\n) => {\n const { defaultLocale } = configuration.internationalization;\n const { baseDir, fileExtensions } = configuration.content;\n\n const isPerLocaleFile = configuration?.dictionary?.locale;\n\n const dirName = outputDir ? resolve(outputDir) : dirname(filePath);\n const ext = extname(filePath);\n const baseName = basename(filePath, ext);\n const contentBaseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);\n\n const contentFilePath = join(\n dirName,\n `${contentBaseName}.${fileExtensions[0]}`\n );\n const relativeContentFilePath = relative(baseDir, contentFilePath);\n\n let dictionary: Dictionary;\n\n if (isPerLocaleFile) {\n // Per-locale format: simple string content with locale property\n dictionary = {\n key: componentKey,\n content: extractedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n } else {\n // Multilingual format: content wrapped in translation nodes, no locale property\n const multilingualContent: Record<string, TranslationNode> = {};\n for (const [key, value] of Object.entries(extractedContent)) {\n multilingualContent[key] = {\n nodeType: 'translation',\n translation: {\n [defaultLocale]: value,\n },\n };\n }\n\n dictionary = {\n key: componentKey,\n content: multilingualContent,\n filePath: relativeContentFilePath,\n };\n }\n\n const relativeDir = relative(baseDir, dirName);\n await writeContentDeclaration(dictionary, configuration, {\n newDictionariesPath: relativeDir,\n });\n\n return contentFilePath;\n};\n\ntype TsReplacement = {\n node: Node;\n key: string;\n type: 'jsx-text' | 'jsx-attribute' | 'string-literal';\n};\n\nconst extractTsContent = (\n sourceFile: SourceFile,\n existingKeys: Set<string>\n): {\n extractedContent: Record<string, string>;\n replacements: TsReplacement[];\n} => {\n const extractedContent: Record<string, string> = {};\n const replacements: TsReplacement[] = [];\n\n sourceFile.forEachDescendant((node) => {\n // 1. JSX Text\n if (Node.isJsxText(node)) {\n const text = node.getText();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.replace(/\\s+/g, ' ').trim();\n replacements.push({ node, key, type: 'jsx-text' });\n }\n }\n\n // 2. JSX Attributes\n else if (Node.isJsxAttribute(node)) {\n const name = node.getNameNode().getText();\n if (ATTRIBUTES_TO_EXTRACT.includes(name)) {\n const initializer = node.getInitializer();\n if (Node.isStringLiteral(initializer)) {\n const text = initializer.getLiteralValue();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'jsx-attribute' });\n }\n }\n }\n }\n\n // 3. String Literals (Variables, Arrays, etc.)\n else if (Node.isStringLiteral(node)) {\n const text = node.getLiteralValue();\n if (shouldExtract(text)) {\n const parent = node.getParent();\n\n // Skip if inside ImportDeclaration\n if (\n parent?.getKindName() === 'ImportDeclaration' ||\n parent?.getKindName() === 'ImportSpecifier' ||\n parent?.getKindName() === 'ModuleSpecifier'\n ) {\n return;\n }\n\n // Skip if it's a JSX Attribute value (handled above)\n if (Node.isJsxAttribute(parent)) return;\n\n // Skip console.log\n if (Node.isCallExpression(parent)) {\n const expression = parent.getExpression();\n if (expression.getText().includes('console.log')) return;\n }\n\n // Skip Object Keys: { key: \"value\" } -> \"key\" is PropertyAssignment name if not computed\n if (Node.isPropertyAssignment(parent)) {\n if (parent.getNameNode() === node) return; // It's the key\n }\n\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'string-literal' });\n }\n }\n });\n\n return { extractedContent, replacements };\n};\n\n// ==========================================\n// React (TS-Morph) Strategy\n// ==========================================\n\nconst processTsxFile = async (\n filePath: string,\n componentKey: string,\n packageName: PackageName,\n project: Project,\n save: boolean = true\n) => {\n let sourceFile: SourceFile;\n try {\n sourceFile = project.addSourceFileAtPath(filePath);\n } catch {\n sourceFile = project.getSourceFileOrThrow(filePath);\n }\n\n const isSolid = packageName === 'solid-intlayer';\n\n const existingKeys = new Set<string>();\n const { extractedContent, replacements } = extractTsContent(\n sourceFile,\n existingKeys\n );\n\n if (Object.keys(extractedContent).length === 0) return null;\n\n for (const { node, key, type } of replacements) {\n const contentAccess = isSolid ? `content().${key}` : `content.${key}`;\n\n if (type === 'jsx-text' && Node.isJsxText(node)) {\n node.replaceWithText(`{${contentAccess}}`);\n } else if (type === 'jsx-attribute' && Node.isJsxAttribute(node)) {\n node.setInitializer(`{${contentAccess}.value}`);\n } else if (type === 'string-literal' && Node.isStringLiteral(node)) {\n // For React/JS variables, we usually want the value\n node.replaceWithText(`${contentAccess}.value`);\n }\n }\n\n // Inject hook\n const importDecl = sourceFile.getImportDeclaration(\n (d) => d.getModuleSpecifierValue() === packageName\n );\n if (!importDecl) {\n sourceFile.addImportDeclaration({\n namedImports: ['useIntlayer'],\n moduleSpecifier: packageName,\n });\n } else if (\n !importDecl.getNamedImports().some((n) => n.getName() === 'useIntlayer')\n ) {\n importDecl.addNamedImport('useIntlayer');\n }\n\n // Insert hook at start of component\n sourceFile.getFunctions().forEach((f) => {\n f.getBody()\n ?.asKind(SyntaxKind.Block)\n ?.insertStatements(0, `const content = useIntlayer(\"${componentKey}\");`);\n });\n\n // Also handle const/arrow components\n sourceFile.getVariableDeclarations().forEach((v) => {\n const init = v.getInitializer();\n if (Node.isArrowFunction(init) || Node.isFunctionExpression(init)) {\n const body = init.getBody();\n if (Node.isBlock(body)) {\n // Heuristic: check if it returns JSX or uses hooks\n if (\n body.getText().includes('return') ||\n body.getText().includes('use')\n ) {\n body.insertStatements(\n 0,\n `const content = useIntlayer(\"${componentKey}\");`\n );\n }\n }\n }\n });\n\n if (save) {\n await sourceFile.save();\n }\n return extractedContent;\n};\n\n// ==========================================\n// 5. Main Dispatcher\n// ==========================================\n\nexport type PackageName =\n | 'next-intlayer'\n | 'react-intlayer'\n | 'vue-intlayer'\n | 'svelte-intlayer'\n | 'preact-intlayer'\n | 'solid-intlayer'\n | 'angular-intlayer'\n | 'express-intlayer';\n\nexport type ExtractIntlayerOptions = {\n configOptions?: GetConfigurationOptions;\n outputDir?: string;\n codeOnly?: boolean;\n declarationOnly?: boolean;\n};\n\nexport const extractIntlayer = async (\n filePath: string,\n packageName: PackageName,\n options?: ExtractIntlayerOptions,\n project?: Project\n) => {\n const saveComponent = !options?.declarationOnly;\n const writeContent = !options?.codeOnly;\n\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n const { baseDir } = configuration.content;\n\n // Setup Project for TS/React files if needed\n const _project =\n project || new Project({ skipAddingFilesFromTsConfig: true });\n\n const baseName = extractDictionaryKey(\n filePath,\n (await fs.readFile(filePath)).toString()\n );\n const componentKey = camelCaseToKebabCase(baseName);\n const ext = extname(filePath);\n\n let extractedContent: Record<string, string> | null = null;\n\n if (ext === '.vue') {\n try {\n const { processVueFile } = await import('@intlayer/vue-transformer');\n extractedContent = await processVueFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/vue-transformer', ANSIColors.YELLOW)} to process Vue files.`\n );\n }\n throw error;\n }\n } else if (ext === '.svelte') {\n try {\n const { processSvelteFile } = (await import(\n '@intlayer/svelte-transformer'\n )) as any;\n extractedContent = await processSvelteFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/svelte-transformer', ANSIColors.YELLOW)} to process Svelte files.`\n );\n }\n throw error;\n }\n } else if (['.tsx', '.jsx', '.ts', '.js'].includes(ext)) {\n extractedContent = await processTsxFile(\n filePath,\n componentKey,\n packageName,\n _project,\n saveComponent\n );\n }\n\n if (!extractedContent) {\n appLogger(`No extractable text found in ${baseName}`);\n return;\n }\n\n // Shared Write Logic\n if (writeContent) {\n const contentFilePath = await writeContentHelper(\n extractedContent,\n componentKey,\n filePath,\n configuration,\n options?.outputDir\n );\n\n const relativeContentFilePath = relative(\n configuration.content.baseDir,\n contentFilePath\n );\n appLogger(`Created content file: ${colorizePath(relativeContentFilePath)}`);\n }\n\n // Optional: Format\n if (saveComponent) {\n try {\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'ignore', // Silent\n cwd: baseDir,\n });\n }\n } catch {\n // Ignore format errors\n }\n\n appLogger(\n `Updated component: ${colorizePath(relative(baseDir, filePath))}`\n );\n }\n};\n\nexport const transformFiles = async (\n filePaths: string[],\n packageName: PackageName,\n options?: ExtractIntlayerOptions\n) => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n });\n\n for (const filePath of filePaths) {\n try {\n await extractIntlayer(filePath, packageName, options, project);\n } catch (error) {\n appLogger(`Failed to transform ${filePath}: ${(error as Error).message}`);\n }\n }\n};\n"],"mappings":"2rBA0BA,MAAa,EAAwB,CACnC,QACA,cACA,MACA,aACA,QACD,CAKY,EAAiB,GAA0B,CACtD,IAAM,EAAU,EAAK,MAAM,CAO3B,MADA,EALI,CAAC,GACD,CAAC,EAAQ,SAAS,IAAI,EAEtB,CAAC,SAAS,KAAK,EAAQ,EAEvB,EAAQ,WAAW,IAAI,EAAI,EAAQ,WAAW,KAAK,GAO5C,GACX,EACA,IACW,CAEX,IAAI,EAAM,EACP,QAAQ,OAAQ,IAAI,CACpB,QAAQ,MAAO,IAAI,CACnB,QAAQ,MAAO,IAAI,CACnB,QAAQ,iBAAkB,GAAG,CAC7B,MAAM,CACN,MAAM,IAAI,CACV,OAAO,QAAQ,CACf,MAAM,EATQ,EASI,CAClB,KAAK,EAAM,IACV,IAAU,EACN,EAAK,aAAa,CAClB,EAAK,O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IAAM,EAAgB,EAAoB,EAAc,CACpD,GACF,EAAS,EAAc,QAAQ,WAAY,EAAS,CAAE,CACpD,MAAO,SACP,IAAK,EACN,CAAC,MAEE,EAIR,EACE,sBAAsB,EAAa,EAAS,EAAS,EAAS,CAAC,GAChE,GAIQ,EAAiB,MAC5B,EACA,EACA,IACG,CAEH,IAAM,EAAY,EADI,EAAiB,GAAS,cAAc,CACjB,CAEvC,EAAU,IAAI,EAAQ,CAC1B,4BAA6B,GAC9B,CAAC,CAEF,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,MAAM,EAAgB,EAAU,EAAa,EAAS,EAAQ,OACvD,EAAO,CACd,EAAU,uBAAuB,EAAS,IAAK,EAAgB,UAAU"}
|
|
@@ -1,86 +1,2 @@
|
|
|
1
|
-
import { getInsertionValues
|
|
2
|
-
import { NodeType } from "@intlayer/types";
|
|
3
|
-
|
|
4
|
-
//#region src/utils/autoDecorateContent.ts
|
|
5
|
-
/**
|
|
6
|
-
* Check if a string is a markdown string
|
|
7
|
-
*/
|
|
8
|
-
const isMarkdown = (str) => {
|
|
9
|
-
return [
|
|
10
|
-
/^\s*---/m,
|
|
11
|
-
/^\s*#+\s/m,
|
|
12
|
-
/^\s*[-*+]\s/m,
|
|
13
|
-
/^\s*\d+\.\s/m,
|
|
14
|
-
/^\s*>\s/m,
|
|
15
|
-
/\[.+\]\(.+\)/,
|
|
16
|
-
/!\[.+\]\(.+\)/,
|
|
17
|
-
/`{1,3}.+`{1,3}/,
|
|
18
|
-
/\*\*.+\*\*/,
|
|
19
|
-
/__.+__/,
|
|
20
|
-
/<(https?:\/\/[^\s>]+)>/
|
|
21
|
-
].some((pattern) => pattern.test(str));
|
|
22
|
-
};
|
|
23
|
-
/**
|
|
24
|
-
* Check if a string is an insertion string
|
|
25
|
-
*/
|
|
26
|
-
const isInsertion = (str) => getInsertionValues(str).length > 0;
|
|
27
|
-
/**
|
|
28
|
-
* Check if a string is an HTML/JSX string
|
|
29
|
-
* Matches:
|
|
30
|
-
* - <Tag>
|
|
31
|
-
* - </Tag>
|
|
32
|
-
* - <Tag />
|
|
33
|
-
* - <Tag attribute="value">
|
|
34
|
-
* - <Component.SubComponent>
|
|
35
|
-
*/
|
|
36
|
-
const isHTML = (str) => {
|
|
37
|
-
return /<[a-zA-Z][a-zA-Z0-9\-.]*(\s+[^>]*)?\/?>/.test(str) || /<\/[a-zA-Z][a-zA-Z0-9\-.]*\s*>/.test(str);
|
|
38
|
-
};
|
|
39
|
-
const leafNodeTypes = [
|
|
40
|
-
NodeType.HTML,
|
|
41
|
-
NodeType.Markdown,
|
|
42
|
-
NodeType.Insertion,
|
|
43
|
-
NodeType.File,
|
|
44
|
-
NodeType.ReactNode,
|
|
45
|
-
NodeType.Text,
|
|
46
|
-
NodeType.Number,
|
|
47
|
-
NodeType.Boolean,
|
|
48
|
-
NodeType.Null,
|
|
49
|
-
NodeType.Unknown
|
|
50
|
-
];
|
|
51
|
-
/**
|
|
52
|
-
* Automatically decorate content strings with md() or insert() if they match
|
|
53
|
-
*/
|
|
54
|
-
const autoDecorateContent = (content, options = true) => {
|
|
55
|
-
if (options === false) return content;
|
|
56
|
-
const { markdown = true, html: htmlOption = true, insertion = true } = typeof options === "object" ? options : {};
|
|
57
|
-
if (typeof content === "string") {
|
|
58
|
-
if (markdown && isMarkdown(content)) return {
|
|
59
|
-
...md(content),
|
|
60
|
-
metadata: getMarkdownMetadata(content)
|
|
61
|
-
};
|
|
62
|
-
if (htmlOption && isHTML(content)) return html(content);
|
|
63
|
-
if (insertion && isInsertion(content)) return insert(content);
|
|
64
|
-
return content;
|
|
65
|
-
}
|
|
66
|
-
if (Array.isArray(content)) return content.map((item) => autoDecorateContent(item, options));
|
|
67
|
-
if (content && typeof content === "object") {
|
|
68
|
-
if ("nodeType" in content) {
|
|
69
|
-
const nodeType = content.nodeType;
|
|
70
|
-
if (leafNodeTypes.includes(nodeType)) return content;
|
|
71
|
-
if (nodeType in content) return {
|
|
72
|
-
...content,
|
|
73
|
-
[nodeType]: autoDecorateContent(content[nodeType], options)
|
|
74
|
-
};
|
|
75
|
-
return content;
|
|
76
|
-
}
|
|
77
|
-
const result = {};
|
|
78
|
-
for (const key of Object.keys(content)) result[key] = autoDecorateContent(content[key], options);
|
|
79
|
-
return result;
|
|
80
|
-
}
|
|
81
|
-
return content;
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
//#endregion
|
|
85
|
-
export { autoDecorateContent };
|
|
1
|
+
import{NodeType as e}from"@intlayer/types";import{getMarkdownMetadata as t}from"@intlayer/core/markdown";import{getInsertionValues as n,html as r,insert as i,md as a}from"@intlayer/core/transpiler";const o=e=>[/^\s*---/m,/^\s*#+\s/m,/^\s*[-*+]\s/m,/^\s*\d+\.\s/m,/^\s*>\s/m,/\[.+\]\(.+\)/,/!\[.+\]\(.+\)/,/`{1,3}.+`{1,3}/,/\*\*.+\*\*/,/__.+__/,/<(https?:\/\/[^\s>]+)>/].some(t=>t.test(e)),s=e=>n(e).length>0,c=e=>/<[a-zA-Z][a-zA-Z0-9\-.]*(\s+[^>]*)?\/?>/.test(e)||/<\/[a-zA-Z][a-zA-Z0-9\-.]*\s*>/.test(e),l=[e.HTML,e.Markdown,e.Insertion,e.File,e.ReactNode,e.Text,e.Number,e.Boolean,e.Null,e.Unknown],u=(e,n=!0)=>{if(n===!1)return e;let{markdown:d=!0,html:f=!0,insertion:p=!0}=typeof n==`object`?n:{};if(typeof e==`string`)return d&&o(e)?{...a(e),metadata:t(e)}:f&&c(e)?r(e):p&&s(e)?i(e):e;if(Array.isArray(e))return e.map(e=>u(e,n));if(e&&typeof e==`object`){if(`nodeType`in e){let t=e.nodeType;return l.includes(t)?e:t in e?{...e,[t]:u(e[t],n)}:e}let t={};for(let r of Object.keys(e))t[r]=u(e[r],n);return t}return e};export{u as autoDecorateContent};
|
|
86
2
|
//# sourceMappingURL=autoDecorateContent.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autoDecorateContent.mjs","names":[],"sources":["../../../src/utils/autoDecorateContent.ts"],"sourcesContent":["import {\n getInsertionValues,\n
|
|
1
|
+
{"version":3,"file":"autoDecorateContent.mjs","names":[],"sources":["../../../src/utils/autoDecorateContent.ts"],"sourcesContent":["import { getMarkdownMetadata } from '@intlayer/core/markdown';\nimport {\n getInsertionValues,\n html,\n insert,\n md,\n} from '@intlayer/core/transpiler';\nimport { NodeType } from '@intlayer/types';\n\n/**\n * Check if a string is a markdown string\n */\nconst isMarkdown = (str: string): boolean => {\n // Check for common markdown indicators\n const patterns = [\n /^\\s*---/m, // Front Matter\n /^\\s*#+\\s/m, // Headers: # Title\n /^\\s*[-*+]\\s/m, // Unordered lists: - Item or * Item\n /^\\s*\\d+\\.\\s/m, // Ordered lists: 1. Item\n /^\\s*>\\s/m, // Blockquotes: > Quote\n /\\[.+\\]\\(.+\\)/, // Links: [text](url)\n /!\\[.+\\]\\(.+\\)/, // Images: \n /`{1,3}.+`{1,3}/, // Code blocks or inline code: `code` or ```code```\n /\\*\\*.+\\*\\*/, // Bold: **text**\n /__.+__/, // Bold: __text__\n /<(https?:\\/\\/[^\\s>]+)>/, // Autolinks: <http://...>\n ];\n\n return patterns.some((pattern) => pattern.test(str));\n};\n\n/**\n * Check if a string is an insertion string\n */\nconst isInsertion = (str: string): boolean =>\n getInsertionValues(str).length > 0;\n\n/**\n * Check if a string is an HTML/JSX string\n * Matches:\n * - <Tag>\n * - </Tag>\n * - <Tag />\n * - <Tag attribute=\"value\">\n * - <Component.SubComponent>\n */\nconst isHTML = (str: string): boolean => {\n // 1. Matches opening or self-closing tags: <Tag ... > or <Tag ... />\n // - Must start with < followed by a letter (to avoid math comparisons like a < b)\n // - Allows alphanumeric, hyphens, and dots (for Namespaced components) in tag name\n // - Allows attributes until the closing >\n const openTagRegex = /<[a-zA-Z][a-zA-Z0-9\\-.]*(\\s+[^>]*)?\\/?>/;\n\n // 2. Matches closing tags: </Tag>\n const closeTagRegex = /<\\/[a-zA-Z][a-zA-Z0-9\\-.]*\\s*>/;\n\n return openTagRegex.test(str) || closeTagRegex.test(str);\n};\n\nconst leafNodeTypes: string[] = [\n NodeType.HTML,\n NodeType.Markdown,\n NodeType.Insertion,\n NodeType.File,\n NodeType.ReactNode,\n NodeType.Text,\n NodeType.Number,\n NodeType.Boolean,\n NodeType.Null,\n NodeType.Unknown,\n];\n\ntype AutoTransformationOptions = {\n markdown?: boolean;\n html?: boolean;\n insertion?: boolean;\n};\n\n/**\n * Automatically decorate content strings with md() or insert() if they match\n */\nexport const autoDecorateContent = (\n content: any,\n options: boolean | AutoTransformationOptions = true\n): any => {\n if (options === false) {\n return content;\n }\n\n const {\n markdown = true,\n html: htmlOption = true,\n insertion = true,\n } = typeof options === 'object' ? options : {};\n\n if (typeof content === 'string') {\n if (markdown && isMarkdown(content)) {\n const markdownNode = md(content);\n\n return {\n ...markdownNode,\n metadata: getMarkdownMetadata(content),\n };\n }\n\n if (htmlOption && isHTML(content)) {\n return html(content);\n }\n\n if (insertion && isInsertion(content)) {\n return insert(content);\n }\n\n return content;\n }\n\n if (Array.isArray(content)) {\n return content.map((item) => autoDecorateContent(item, options));\n }\n\n if (content && typeof content === 'object') {\n // If it's already a decorated node (has nodeType)\n if ('nodeType' in content) {\n const nodeType = content.nodeType;\n\n // If it's a leaf node type, don't re-decorate its content\n if (leafNodeTypes.includes(nodeType)) {\n return content;\n }\n\n // If it's a container node type (like translation, enumeration, etc.), recurse into its content field\n if (nodeType in content) {\n return {\n ...content,\n [nodeType]: autoDecorateContent(content[nodeType], options),\n };\n }\n\n return content;\n }\n\n // Plain object, recurse into all keys\n const result: Record<string, any> = {};\n for (const key of Object.keys(content)) {\n result[key] = autoDecorateContent(content[key], options);\n }\n return result;\n }\n\n return content;\n};\n"],"mappings":"sMAYA,MAAM,EAAc,GAED,CACf,WACA,YACA,eACA,eACA,WACA,eACA,gBACA,iBACA,aACA,SACA,yBACD,CAEe,KAAM,GAAY,EAAQ,KAAK,EAAI,CAAC,CAMhD,EAAe,GACnB,EAAmB,EAAI,CAAC,OAAS,EAW7B,EAAU,GAKO,0CAKD,KAAK,EAAI,EAFP,iCAEyB,KAAK,EAAI,CAGpD,EAA0B,CAC9B,EAAS,KACT,EAAS,SACT,EAAS,UACT,EAAS,KACT,EAAS,UACT,EAAS,KACT,EAAS,OACT,EAAS,QACT,EAAS,KACT,EAAS,QACV,CAWY,GACX,EACA,EAA+C,KACvC,CACR,GAAI,IAAY,GACd,OAAO,EAGT,GAAM,CACJ,WAAW,GACX,KAAM,EAAa,GACnB,YAAY,IACV,OAAO,GAAY,SAAW,EAAU,EAAE,CAE9C,GAAI,OAAO,GAAY,SAkBrB,OAjBI,GAAY,EAAW,EAAQ,CAG1B,CACL,GAHmB,EAAG,EAAQ,CAI9B,SAAU,EAAoB,EAAQ,CACvC,CAGC,GAAc,EAAO,EAAQ,CACxB,EAAK,EAAQ,CAGlB,GAAa,EAAY,EAAQ,CAC5B,EAAO,EAAQ,CAGjB,EAGT,GAAI,MAAM,QAAQ,EAAQ,CACxB,OAAO,EAAQ,IAAK,GAAS,EAAoB,EAAM,EAAQ,CAAC,CAGlE,GAAI,GAAW,OAAO,GAAY,SAAU,CAE1C,GAAI,aAAc,EAAS,CACzB,IAAM,EAAW,EAAQ,SAezB,OAZI,EAAc,SAAS,EAAS,CAC3B,EAIL,KAAY,EACP,CACL,GAAG,GACF,GAAW,EAAoB,EAAQ,GAAW,EAAQ,CAC5D,CAGI,EAIT,IAAM,EAA8B,EAAE,CACtC,IAAK,IAAM,KAAO,OAAO,KAAK,EAAQ,CACpC,EAAO,GAAO,EAAoB,EAAQ,GAAM,EAAQ,CAE1D,OAAO,EAGT,OAAO"}
|
|
@@ -1,48 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
import fg from "fast-glob";
|
|
3
|
-
|
|
4
|
-
//#region src/utils/buildFilesList.ts
|
|
5
|
-
/**
|
|
6
|
-
* Normalizes a pattern value to an array
|
|
7
|
-
*/
|
|
8
|
-
const normalizeToArray = (value) => {
|
|
9
|
-
return Array.isArray(value) ? value : [value];
|
|
10
|
-
};
|
|
11
|
-
/**
|
|
12
|
-
* Builds a list of files matching the given patterns.
|
|
13
|
-
*
|
|
14
|
-
* This utility consolidates the file listing logic used across multiple compilers
|
|
15
|
-
* (Vue, Svelte, Vite) to avoid code duplication.
|
|
16
|
-
*
|
|
17
|
-
* @param options - Configuration options for building the file list
|
|
18
|
-
* @returns Array of absolute file paths matching the patterns
|
|
19
|
-
*
|
|
20
|
-
* @example
|
|
21
|
-
* // Basic usage
|
|
22
|
-
* const files = buildFilesList({
|
|
23
|
-
* transformPattern: 'src/**\/*.{ts,tsx}',
|
|
24
|
-
* excludePattern: ['**\/node_modules;\/**'],
|
|
25
|
-
* baseDir: '/path/to/project',
|
|
26
|
-
* });
|
|
27
|
-
*
|
|
28
|
-
* @example
|
|
29
|
-
* // With framework extension (Vue)
|
|
30
|
-
* const files = buildFilesList({
|
|
31
|
-
* transformPattern: 'src/**\/*.{ts,tsx}',
|
|
32
|
-
* excludePattern: ['**\/node_modules\/**'],
|
|
33
|
-
* baseDir: '/path/to/project',
|
|
34
|
-
* });
|
|
35
|
-
*/
|
|
36
|
-
const buildFilesList = (options) => {
|
|
37
|
-
const { transformPattern, excludePattern, baseDir } = options;
|
|
38
|
-
const patterns = normalizeToArray(transformPattern);
|
|
39
|
-
const excludePatterns = normalizeToArray(excludePattern);
|
|
40
|
-
return fg.sync(patterns, {
|
|
41
|
-
cwd: baseDir,
|
|
42
|
-
ignore: excludePatterns
|
|
43
|
-
}).map((file) => join(baseDir, file));
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
//#endregion
|
|
47
|
-
export { buildFilesList };
|
|
1
|
+
import{join as e}from"node:path";import t from"fast-glob";const n=e=>Array.isArray(e)?e:[e],r=r=>{let{transformPattern:i,excludePattern:a,baseDir:o}=r,s=n(i),c=n(a);return t.sync(s,{cwd:o,ignore:c}).map(t=>e(o,t))};export{r as buildFilesList};
|
|
48
2
|
//# sourceMappingURL=buildFilesList.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildFilesList.mjs","names":[],"sources":["../../../src/utils/buildFilesList.ts"],"sourcesContent":["import { join } from 'node:path';\nimport fg from 'fast-glob';\n\n/**\n * Options for building the files list\n */\nexport type BuildFilesListOptions = {\n /**\n * Glob patterns to match files\n */\n transformPattern: string | string[];\n /**\n * Glob patterns to exclude files\n */\n excludePattern: string | string[];\n /**\n * Base directory for file resolution\n */\n baseDir: string;\n};\n\n/**\n * Normalizes a pattern value to an array\n */\nconst normalizeToArray = <T>(value: T | T[]): T[] => {\n return Array.isArray(value) ? value : [value];\n};\n\n/**\n * Builds a list of files matching the given patterns.\n *\n * This utility consolidates the file listing logic used across multiple compilers\n * (Vue, Svelte, Vite) to avoid code duplication.\n *\n * @param options - Configuration options for building the file list\n * @returns Array of absolute file paths matching the patterns\n *\n * @example\n * // Basic usage\n * const files = buildFilesList({\n * transformPattern: 'src/**\\/*.{ts,tsx}',\n * excludePattern: ['**\\/node_modules;\\/**'],\n * baseDir: '/path/to/project',\n * });\n *\n * @example\n * // With framework extension (Vue)\n * const files = buildFilesList({\n * transformPattern: 'src/**\\/*.{ts,tsx}',\n * excludePattern: ['**\\/node_modules\\/**'],\n * baseDir: '/path/to/project',\n * });\n */\nexport const buildFilesList = (options: BuildFilesListOptions): string[] => {\n const { transformPattern, excludePattern, baseDir } = options;\n\n const patterns = normalizeToArray(transformPattern);\n const excludePatterns = normalizeToArray(excludePattern);\n\n const files = fg\n .sync(patterns, {\n cwd: baseDir,\n ignore: excludePatterns,\n })\n .map((file) => join(baseDir, file));\n\n return files;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"buildFilesList.mjs","names":[],"sources":["../../../src/utils/buildFilesList.ts"],"sourcesContent":["import { join } from 'node:path';\nimport fg from 'fast-glob';\n\n/**\n * Options for building the files list\n */\nexport type BuildFilesListOptions = {\n /**\n * Glob patterns to match files\n */\n transformPattern: string | string[];\n /**\n * Glob patterns to exclude files\n */\n excludePattern: string | string[];\n /**\n * Base directory for file resolution\n */\n baseDir: string;\n};\n\n/**\n * Normalizes a pattern value to an array\n */\nconst normalizeToArray = <T>(value: T | T[]): T[] => {\n return Array.isArray(value) ? value : [value];\n};\n\n/**\n * Builds a list of files matching the given patterns.\n *\n * This utility consolidates the file listing logic used across multiple compilers\n * (Vue, Svelte, Vite) to avoid code duplication.\n *\n * @param options - Configuration options for building the file list\n * @returns Array of absolute file paths matching the patterns\n *\n * @example\n * // Basic usage\n * const files = buildFilesList({\n * transformPattern: 'src/**\\/*.{ts,tsx}',\n * excludePattern: ['**\\/node_modules;\\/**'],\n * baseDir: '/path/to/project',\n * });\n *\n * @example\n * // With framework extension (Vue)\n * const files = buildFilesList({\n * transformPattern: 'src/**\\/*.{ts,tsx}',\n * excludePattern: ['**\\/node_modules\\/**'],\n * baseDir: '/path/to/project',\n * });\n */\nexport const buildFilesList = (options: BuildFilesListOptions): string[] => {\n const { transformPattern, excludePattern, baseDir } = options;\n\n const patterns = normalizeToArray(transformPattern);\n const excludePatterns = normalizeToArray(excludePattern);\n\n const files = fg\n .sync(patterns, {\n cwd: baseDir,\n ignore: excludePatterns,\n })\n .map((file) => join(baseDir, file));\n\n return files;\n};\n"],"mappings":"0DAwBA,MAAM,EAAuB,GACpB,MAAM,QAAQ,EAAM,CAAG,EAAQ,CAAC,EAAM,CA4BlC,EAAkB,GAA6C,CAC1E,GAAM,CAAE,mBAAkB,iBAAgB,WAAY,EAEhD,EAAW,EAAiB,EAAiB,CAC7C,EAAkB,EAAiB,EAAe,CASxD,OAPc,EACX,KAAK,EAAU,CACd,IAAK,EACL,OAAQ,EACT,CAAC,CACD,IAAK,GAAS,EAAK,EAAS,EAAK,CAAC"}
|
|
@@ -1,334 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
//#region src/utils/chunkJSON.ts
|
|
4
|
-
/**
|
|
5
|
-
* Split & reassemble JSON by character budget.
|
|
6
|
-
* - Measures serialized size using JSON.stringify(..).length (characters).
|
|
7
|
-
* - Ensures each chunk is itself valid JSON.
|
|
8
|
-
* - Very large strings are split into safe pieces using getChunk and re-concatenated on assemble.
|
|
9
|
-
* - Protects against circular structures (JSON can't serialize those anyway).
|
|
10
|
-
*/
|
|
11
|
-
const isObject = (val) => {
|
|
12
|
-
return typeof val === "object" && val !== null && !Array.isArray(val);
|
|
13
|
-
};
|
|
14
|
-
const computeDjb2 = (str) => {
|
|
15
|
-
let hash = 5381;
|
|
16
|
-
for (let i = 0; i < str.length; i++) hash = (hash << 5) + hash ^ str.charCodeAt(i);
|
|
17
|
-
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
18
|
-
};
|
|
19
|
-
const setAtPath = (root, path, value) => {
|
|
20
|
-
let current = root;
|
|
21
|
-
for (let i = 0; i < path.length - 1; i++) {
|
|
22
|
-
const key = path[i];
|
|
23
|
-
const isNextIndex = typeof path[i + 1] === "number";
|
|
24
|
-
if (typeof key === "number") {
|
|
25
|
-
if (!Array.isArray(current)) throw new Error(`Expected array at path segment ${i}`);
|
|
26
|
-
if (current[key] === void 0) current[key] = isNextIndex ? [] : {};
|
|
27
|
-
current = current[key];
|
|
28
|
-
} else {
|
|
29
|
-
if (!isObject(current)) throw new Error(`Expected object at path segment ${i}`);
|
|
30
|
-
if (!(key in current)) current[key] = isNextIndex ? [] : {};
|
|
31
|
-
current = current[key];
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
const last = path[path.length - 1];
|
|
35
|
-
if (typeof last === "number") {
|
|
36
|
-
if (!Array.isArray(current)) throw new Error(`Expected array at final segment`);
|
|
37
|
-
current[last] = value;
|
|
38
|
-
} else {
|
|
39
|
-
if (!isObject(current)) throw new Error(`Expected object at final segment`);
|
|
40
|
-
current[last] = value;
|
|
41
|
-
}
|
|
42
|
-
};
|
|
43
|
-
const pathKey = (path) => {
|
|
44
|
-
return JSON.stringify(path);
|
|
45
|
-
};
|
|
46
|
-
/**
|
|
47
|
-
* Split a string into parts using getChunk with a charLength budget per part.
|
|
48
|
-
*/
|
|
49
|
-
const splitStringByBudget = (str, maxCharsPerPart) => {
|
|
50
|
-
if (maxCharsPerPart <= 0) throw new Error("maxChars must be > 0");
|
|
51
|
-
const output = [];
|
|
52
|
-
let offset = 0;
|
|
53
|
-
while (offset < str.length) {
|
|
54
|
-
const part = getChunk(str, {
|
|
55
|
-
charStart: offset,
|
|
56
|
-
charLength: maxCharsPerPart
|
|
57
|
-
});
|
|
58
|
-
if (!part) break;
|
|
59
|
-
output.push(part);
|
|
60
|
-
offset += part.length;
|
|
61
|
-
}
|
|
62
|
-
return output;
|
|
63
|
-
};
|
|
64
|
-
/**
|
|
65
|
-
* Flatten JSON into patches (leaf writes). Strings too large to fit in a single
|
|
66
|
-
* chunk are yielded as multiple str-append patches.
|
|
67
|
-
*/
|
|
68
|
-
const flattenToPatches = (value, maxCharsPerChunk, path = [], seen = /* @__PURE__ */ new WeakSet()) => {
|
|
69
|
-
const maxStringPiece = Math.max(1, Math.floor((maxCharsPerChunk - 400) * .8));
|
|
70
|
-
const patches = [];
|
|
71
|
-
const walk = (currentValue, currentPath) => {
|
|
72
|
-
if (typeof currentValue === "string") {
|
|
73
|
-
const testPatch = {
|
|
74
|
-
op: "set",
|
|
75
|
-
path: currentPath,
|
|
76
|
-
value: currentValue
|
|
77
|
-
};
|
|
78
|
-
if (JSON.stringify(testPatch).length + 150 <= maxCharsPerChunk) {
|
|
79
|
-
patches.push(testPatch);
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
const parts = splitStringByBudget(currentValue, maxStringPiece);
|
|
83
|
-
patches.push({
|
|
84
|
-
op: "set",
|
|
85
|
-
path: [...currentPath, "__splittedType"],
|
|
86
|
-
value: "string"
|
|
87
|
-
});
|
|
88
|
-
patches.push({
|
|
89
|
-
op: "set",
|
|
90
|
-
path: [...currentPath, "__total"],
|
|
91
|
-
value: parts.length
|
|
92
|
-
});
|
|
93
|
-
for (let i = 0; i < parts.length; i++) patches.push({
|
|
94
|
-
op: "set",
|
|
95
|
-
path: [...currentPath, String(i + 1)],
|
|
96
|
-
value: parts[i]
|
|
97
|
-
});
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
if (currentValue === null || typeof currentValue !== "object") {
|
|
101
|
-
patches.push({
|
|
102
|
-
op: "set",
|
|
103
|
-
path: currentPath,
|
|
104
|
-
value: currentValue
|
|
105
|
-
});
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
if (seen.has(currentValue)) throw new Error("Cannot serialize circular structures to JSON.");
|
|
109
|
-
seen.add(currentValue);
|
|
110
|
-
if (Array.isArray(currentValue)) for (let i = 0; i < currentValue.length; i++) walk(currentValue[i], [...currentPath, i]);
|
|
111
|
-
else for (const key of Object.keys(currentValue)) walk(currentValue[key], [...currentPath, key]);
|
|
112
|
-
seen.delete(currentValue);
|
|
113
|
-
};
|
|
114
|
-
walk(value, path);
|
|
115
|
-
return patches;
|
|
116
|
-
};
|
|
117
|
-
/**
|
|
118
|
-
* Split JSON into chunks constrained by character count of serialized chunk.
|
|
119
|
-
*/
|
|
120
|
-
const chunkJSON = (value, maxChars) => {
|
|
121
|
-
if (!isObject(value) && !Array.isArray(value)) throw new Error("Root must be an object or array.");
|
|
122
|
-
if (maxChars < 500) throw new Error("maxChars is too small. Use at least 500 characters.");
|
|
123
|
-
const rootType = Array.isArray(value) ? "array" : "object";
|
|
124
|
-
let sourceString;
|
|
125
|
-
try {
|
|
126
|
-
sourceString = JSON.stringify(value);
|
|
127
|
-
} catch {
|
|
128
|
-
throw new Error("Cannot serialize circular structures to JSON.");
|
|
129
|
-
}
|
|
130
|
-
const checksum = computeDjb2(sourceString);
|
|
131
|
-
const allPatches = flattenToPatches(value, maxChars);
|
|
132
|
-
const chunks = [];
|
|
133
|
-
let currentChunk = {
|
|
134
|
-
schemaVersion: 1,
|
|
135
|
-
index: 0,
|
|
136
|
-
total: 0,
|
|
137
|
-
rootType,
|
|
138
|
-
checksum,
|
|
139
|
-
entries: []
|
|
140
|
-
};
|
|
141
|
-
const emptyEnvelopeSize = JSON.stringify({
|
|
142
|
-
...currentChunk,
|
|
143
|
-
entries: []
|
|
144
|
-
}).length;
|
|
145
|
-
const tryFlush = () => {
|
|
146
|
-
if (currentChunk.entries.length > 0) {
|
|
147
|
-
chunks.push(currentChunk);
|
|
148
|
-
currentChunk = {
|
|
149
|
-
schemaVersion: 1,
|
|
150
|
-
index: 0,
|
|
151
|
-
total: 0,
|
|
152
|
-
rootType,
|
|
153
|
-
checksum,
|
|
154
|
-
entries: []
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
};
|
|
158
|
-
for (const patch of allPatches) if (emptyEnvelopeSize + JSON.stringify(currentChunk.entries).length + (currentChunk.entries.length ? 1 : 0) + JSON.stringify(patch).length <= maxChars) currentChunk.entries.push(patch);
|
|
159
|
-
else {
|
|
160
|
-
if (currentChunk.entries.length > 0) tryFlush();
|
|
161
|
-
if (emptyEnvelopeSize + JSON.stringify([patch]).length > maxChars) throw new Error("A single entry exceeds maxChars and cannot be split. Reduce entry size or increase maxChars.");
|
|
162
|
-
currentChunk.entries.push(patch);
|
|
163
|
-
}
|
|
164
|
-
tryFlush();
|
|
165
|
-
if (chunks.length === 0) chunks.push({
|
|
166
|
-
schemaVersion: 1,
|
|
167
|
-
index: 0,
|
|
168
|
-
total: 0,
|
|
169
|
-
rootType,
|
|
170
|
-
checksum,
|
|
171
|
-
entries: []
|
|
172
|
-
});
|
|
173
|
-
const totalChunks = chunks.length;
|
|
174
|
-
chunks.forEach((chunk, index) => {
|
|
175
|
-
chunk.index = index;
|
|
176
|
-
chunk.total = totalChunks;
|
|
177
|
-
});
|
|
178
|
-
return chunks;
|
|
179
|
-
};
|
|
180
|
-
/**
|
|
181
|
-
* Reassemble JSON from chunks.
|
|
182
|
-
* - Validates checksums and indices.
|
|
183
|
-
* - Applies 'set' patches and merges string pieces from 'str-append'.
|
|
184
|
-
*/
|
|
185
|
-
/**
|
|
186
|
-
* Reconstruct content from a single chunk without validation.
|
|
187
|
-
* Useful for processing individual chunks in a pipeline where you don't have all chunks yet.
|
|
188
|
-
* Note: This will only reconstruct the partial content contained in this chunk.
|
|
189
|
-
*/
|
|
190
|
-
const reconstructFromSingleChunk = (chunk) => {
|
|
191
|
-
const root = chunk.rootType === "array" ? [] : {};
|
|
192
|
-
for (const entry of chunk.entries) if (entry.op === "set") setAtPath(root, entry.path, entry.value);
|
|
193
|
-
const reconcileSplitNodes = (node) => {
|
|
194
|
-
if (node === null || typeof node !== "object") return node;
|
|
195
|
-
if (Array.isArray(node)) {
|
|
196
|
-
for (let i = 0; i < node.length; i++) node[i] = reconcileSplitNodes(node[i]);
|
|
197
|
-
return node;
|
|
198
|
-
}
|
|
199
|
-
if (node["__splittedType"] === "string") {
|
|
200
|
-
const total = node["__total"];
|
|
201
|
-
if (typeof total !== "number" || total <= 0) return node;
|
|
202
|
-
const parts = [];
|
|
203
|
-
let hasAllParts = true;
|
|
204
|
-
for (let i = 1; i <= total; i++) {
|
|
205
|
-
const piece = node[String(i)];
|
|
206
|
-
if (typeof piece !== "string") {
|
|
207
|
-
hasAllParts = false;
|
|
208
|
-
break;
|
|
209
|
-
}
|
|
210
|
-
parts.push(piece);
|
|
211
|
-
}
|
|
212
|
-
if (hasAllParts) return parts.join("");
|
|
213
|
-
return node;
|
|
214
|
-
}
|
|
215
|
-
if (node["__splittedType"] === "array") {
|
|
216
|
-
const total = node["__total"];
|
|
217
|
-
if (typeof total !== "number" || total < 0) return node;
|
|
218
|
-
const output = [];
|
|
219
|
-
let hasAllParts = true;
|
|
220
|
-
for (let i = 1; i <= total; i++) {
|
|
221
|
-
const slice = node[String(i)];
|
|
222
|
-
if (!Array.isArray(slice)) {
|
|
223
|
-
hasAllParts = false;
|
|
224
|
-
break;
|
|
225
|
-
}
|
|
226
|
-
for (let j = 0; j < slice.length; j++) output.push(reconcileSplitNodes(slice[j]));
|
|
227
|
-
}
|
|
228
|
-
if (hasAllParts) return output;
|
|
229
|
-
return node;
|
|
230
|
-
}
|
|
231
|
-
for (const key of Object.keys(node)) node[key] = reconcileSplitNodes(node[key]);
|
|
232
|
-
return node;
|
|
233
|
-
};
|
|
234
|
-
return reconcileSplitNodes(root);
|
|
235
|
-
};
|
|
236
|
-
const assembleJSON = (chunks) => {
|
|
237
|
-
if (!chunks || chunks.length === 0) throw new Error("No chunks provided.");
|
|
238
|
-
const sorted = [...chunks].sort((a, b) => a.index - b.index);
|
|
239
|
-
const { checksum, rootType } = sorted[0];
|
|
240
|
-
const schemaVersion = 1;
|
|
241
|
-
for (let i = 0; i < sorted.length; i++) {
|
|
242
|
-
const chunk = sorted[i];
|
|
243
|
-
if (chunk.schemaVersion !== schemaVersion) {
|
|
244
|
-
console.error("Unsupported schemaVersion.", {
|
|
245
|
-
cause: chunk,
|
|
246
|
-
schemaVersion
|
|
247
|
-
});
|
|
248
|
-
throw new Error("Unsupported schemaVersion.");
|
|
249
|
-
}
|
|
250
|
-
if (chunk.rootType !== rootType) {
|
|
251
|
-
console.error("Chunks rootType mismatch.", {
|
|
252
|
-
cause: chunk,
|
|
253
|
-
rootType
|
|
254
|
-
});
|
|
255
|
-
throw new Error("Chunks rootType mismatch.");
|
|
256
|
-
}
|
|
257
|
-
if (chunk.checksum !== checksum) {
|
|
258
|
-
console.error("Chunks checksum mismatch (different source objects?).", {
|
|
259
|
-
cause: chunk,
|
|
260
|
-
checksum
|
|
261
|
-
});
|
|
262
|
-
throw new Error("Chunks checksum mismatch (different source objects?).");
|
|
263
|
-
}
|
|
264
|
-
if (chunk.index !== i) {
|
|
265
|
-
console.error("Chunk indices are not contiguous or sorted.", {
|
|
266
|
-
cause: chunk,
|
|
267
|
-
index: chunk.index,
|
|
268
|
-
i
|
|
269
|
-
});
|
|
270
|
-
throw new Error("Chunk indices are not contiguous or sorted.");
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
const root = rootType === "array" ? [] : {};
|
|
274
|
-
const stringParts = /* @__PURE__ */ new Map();
|
|
275
|
-
const applySet = (patch) => setAtPath(root, patch.path, patch.value);
|
|
276
|
-
for (const chunk of sorted) for (const entry of chunk.entries) if (entry.op === "set") applySet(entry);
|
|
277
|
-
else {
|
|
278
|
-
const key = pathKey(entry.path);
|
|
279
|
-
const record = stringParts.get(key) ?? {
|
|
280
|
-
path: entry.path,
|
|
281
|
-
total: entry.total,
|
|
282
|
-
received: []
|
|
283
|
-
};
|
|
284
|
-
if (record.total !== entry.total) throw new Error("Inconsistent string part totals for a path.");
|
|
285
|
-
record.received.push(entry);
|
|
286
|
-
stringParts.set(key, record);
|
|
287
|
-
}
|
|
288
|
-
for (const { path, total, received } of stringParts.values()) {
|
|
289
|
-
if (received.length !== total) throw new Error("Missing string parts for a path; incomplete chunk set.");
|
|
290
|
-
received.sort((a, b) => a.index - b.index);
|
|
291
|
-
setAtPath(root, path, received.map((part) => part.value).join(""));
|
|
292
|
-
}
|
|
293
|
-
const reconcileSplitNodes = (node) => {
|
|
294
|
-
if (node === null || typeof node !== "object") return node;
|
|
295
|
-
if (Array.isArray(node)) {
|
|
296
|
-
for (let i = 0; i < node.length; i++) node[i] = reconcileSplitNodes(node[i]);
|
|
297
|
-
return node;
|
|
298
|
-
}
|
|
299
|
-
if (node["__splittedType"] === "string") {
|
|
300
|
-
const total = node["__total"];
|
|
301
|
-
if (typeof total !== "number" || total <= 0) throw new Error("Invalid split-node total for a path.");
|
|
302
|
-
const parts = [];
|
|
303
|
-
for (let i = 1; i <= total; i++) {
|
|
304
|
-
const piece = node[String(i)];
|
|
305
|
-
if (typeof piece !== "string") throw new Error("Missing string parts for a path; incomplete chunk set.");
|
|
306
|
-
parts.push(piece);
|
|
307
|
-
}
|
|
308
|
-
return parts.join("");
|
|
309
|
-
}
|
|
310
|
-
if (node["__splittedType"] === "array") {
|
|
311
|
-
const total = node["__total"];
|
|
312
|
-
if (typeof total !== "number" || total < 0) throw new Error("Invalid split-node total for a path.");
|
|
313
|
-
const output = [];
|
|
314
|
-
for (let i = 1; i <= total; i++) {
|
|
315
|
-
const slice = node[String(i)];
|
|
316
|
-
if (!Array.isArray(slice)) throw new Error("Missing string parts for a path; incomplete chunk set.");
|
|
317
|
-
for (let j = 0; j < slice.length; j++) output.push(reconcileSplitNodes(slice[j]));
|
|
318
|
-
}
|
|
319
|
-
return output;
|
|
320
|
-
}
|
|
321
|
-
for (const key of Object.keys(node)) node[key] = reconcileSplitNodes(node[key]);
|
|
322
|
-
return node;
|
|
323
|
-
};
|
|
324
|
-
const reconciled = reconcileSplitNodes(root);
|
|
325
|
-
for (let i = 0; i < sorted.length; i++) {
|
|
326
|
-
const chunk = sorted[i];
|
|
327
|
-
if (chunk.total !== sorted.length) throw new Error(`Chunk total does not match provided count. Expected ${sorted.length}, but chunk ${i} has total=${chunk.total}`);
|
|
328
|
-
}
|
|
329
|
-
return reconciled;
|
|
330
|
-
};
|
|
331
|
-
|
|
332
|
-
//#endregion
|
|
333
|
-
export { assembleJSON, chunkJSON, reconstructFromSingleChunk };
|
|
1
|
+
import{getChunk as e}from"./getChunk.mjs";const t=e=>typeof e==`object`&&!!e&&!Array.isArray(e),n=e=>{let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(16).padStart(8,`0`)},r=(e,n,r)=>{let i=e;for(let e=0;e<n.length-1;e++){let r=n[e],a=typeof n[e+1]==`number`;if(typeof r==`number`){if(!Array.isArray(i))throw Error(`Expected array at path segment ${e}`);i[r]===void 0&&(i[r]=a?[]:{}),i=i[r]}else{if(!t(i))throw Error(`Expected object at path segment ${e}`);r in i||(i[r]=a?[]:{}),i=i[r]}}let a=n[n.length-1];if(typeof a==`number`){if(!Array.isArray(i))throw Error(`Expected array at final segment`);i[a]=r}else{if(!t(i))throw Error(`Expected object at final segment`);i[a]=r}},i=e=>JSON.stringify(e),a=(t,n)=>{if(n<=0)throw Error(`maxChars must be > 0`);let r=[],i=0;for(;i<t.length;){let a=e(t,{charStart:i,charLength:n});if(!a)break;r.push(a),i+=a.length}return r},o=(e,t,n=[],r=new WeakSet)=>{let i=Math.max(1,Math.floor((t-400)*.8)),o=[],s=(e,n)=>{if(typeof e==`string`){let r={op:`set`,path:n,value:e};if(JSON.stringify(r).length+150<=t){o.push(r);return}let s=a(e,i);o.push({op:`set`,path:[...n,`__splittedType`],value:`string`}),o.push({op:`set`,path:[...n,`__total`],value:s.length});for(let e=0;e<s.length;e++)o.push({op:`set`,path:[...n,String(e+1)],value:s[e]});return}if(typeof e!=`object`||!e){o.push({op:`set`,path:n,value:e});return}if(r.has(e))throw Error(`Cannot serialize circular structures to JSON.`);if(r.add(e),Array.isArray(e))for(let t=0;t<e.length;t++)s(e[t],[...n,t]);else for(let t of Object.keys(e))s(e[t],[...n,t]);r.delete(e)};return s(e,n),o},s=(e,r)=>{if(!t(e)&&!Array.isArray(e))throw Error(`Root must be an object or array.`);if(r<500)throw Error(`maxChars is too small. Use at least 500 characters.`);let i=Array.isArray(e)?`array`:`object`,a;try{a=JSON.stringify(e)}catch{throw Error(`Cannot serialize circular structures to JSON.`)}let s=n(a),c=o(e,r),l=[],u={schemaVersion:1,index:0,total:0,rootType:i,checksum:s,entries:[]},d=JSON.stringify({...u,entries:[]}).length,f=()=>{u.entries.length>0&&(l.push(u),u={schemaVersion:1,index:0,total:0,rootType:i,checksum:s,entries:[]})};for(let e of c)if(d+JSON.stringify(u.entries).length+(u.entries.length?1:0)+JSON.stringify(e).length<=r)u.entries.push(e);else{if(u.entries.length>0&&f(),d+JSON.stringify([e]).length>r)throw Error(`A single entry exceeds maxChars and cannot be split. Reduce entry size or increase maxChars.`);u.entries.push(e)}f(),l.length===0&&l.push({schemaVersion:1,index:0,total:0,rootType:i,checksum:s,entries:[]});let p=l.length;return l.forEach((e,t)=>{e.index=t,e.total=p}),l},c=e=>{let t=e.rootType===`array`?[]:{};for(let n of e.entries)n.op===`set`&&r(t,n.path,n.value);let n=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){for(let t=0;t<e.length;t++)e[t]=n(e[t]);return e}if(e.__splittedType===`string`){let t=e.__total;if(typeof t!=`number`||t<=0)return e;let n=[],r=!0;for(let i=1;i<=t;i++){let t=e[String(i)];if(typeof t!=`string`){r=!1;break}n.push(t)}return r?n.join(``):e}if(e.__splittedType===`array`){let t=e.__total;if(typeof t!=`number`||t<0)return e;let r=[],i=!0;for(let a=1;a<=t;a++){let t=e[String(a)];if(!Array.isArray(t)){i=!1;break}for(let e=0;e<t.length;e++)r.push(n(t[e]))}return i?r:e}for(let t of Object.keys(e))e[t]=n(e[t]);return e};return n(t)},l=e=>{if(!e||e.length===0)throw Error(`No chunks provided.`);let t=[...e].sort((e,t)=>e.index-t.index),{checksum:n,rootType:a}=t[0];for(let e=0;e<t.length;e++){let r=t[e];if(r.schemaVersion!==1)throw console.error(`Unsupported schemaVersion.`,{cause:r,schemaVersion:1}),Error(`Unsupported schemaVersion.`);if(r.rootType!==a)throw console.error(`Chunks rootType mismatch.`,{cause:r,rootType:a}),Error(`Chunks rootType mismatch.`);if(r.checksum!==n)throw console.error(`Chunks checksum mismatch (different source objects?).`,{cause:r,checksum:n}),Error(`Chunks checksum mismatch (different source objects?).`);if(r.index!==e)throw console.error(`Chunk indices are not contiguous or sorted.`,{cause:r,index:r.index,i:e}),Error(`Chunk indices are not contiguous or sorted.`)}let o=a===`array`?[]:{},s=new Map,c=e=>r(o,e.path,e.value);for(let e of t)for(let t of e.entries)if(t.op===`set`)c(t);else{let e=i(t.path),n=s.get(e)??{path:t.path,total:t.total,received:[]};if(n.total!==t.total)throw Error(`Inconsistent string part totals for a path.`);n.received.push(t),s.set(e,n)}for(let{path:e,total:t,received:n}of s.values()){if(n.length!==t)throw Error(`Missing string parts for a path; incomplete chunk set.`);n.sort((e,t)=>e.index-t.index),r(o,e,n.map(e=>e.value).join(``))}let l=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){for(let t=0;t<e.length;t++)e[t]=l(e[t]);return e}if(e.__splittedType===`string`){let t=e.__total;if(typeof t!=`number`||t<=0)throw Error(`Invalid split-node total for a path.`);let n=[];for(let r=1;r<=t;r++){let t=e[String(r)];if(typeof t!=`string`)throw Error(`Missing string parts for a path; incomplete chunk set.`);n.push(t)}return n.join(``)}if(e.__splittedType===`array`){let t=e.__total;if(typeof t!=`number`||t<0)throw Error(`Invalid split-node total for a path.`);let n=[];for(let r=1;r<=t;r++){let t=e[String(r)];if(!Array.isArray(t))throw Error(`Missing string parts for a path; incomplete chunk set.`);for(let e=0;e<t.length;e++)n.push(l(t[e]))}return n}for(let t of Object.keys(e))e[t]=l(e[t]);return e},u=l(o);for(let e=0;e<t.length;e++){let n=t[e];if(n.total!==t.length)throw Error(`Chunk total does not match provided count. Expected ${t.length}, but chunk ${e} has total=${n.total}`)}return u};export{l as assembleJSON,s as chunkJSON,c as reconstructFromSingleChunk};
|
|
334
2
|
//# sourceMappingURL=chunkJSON.mjs.map
|