@intlayer/engine 9.3.0 → 9.3.2
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/README.md +24 -24
- package/dist/assets/initConfig/templates/cjs.txt +1 -1
- package/dist/assets/initConfig/templates/mjs.txt +1 -1
- package/dist/assets/initConfig/templates/ts.txt +1 -1
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -2
- package/dist/cjs/_virtual/_utils_asset.cjs +2 -1
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs +2 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs +2 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeNestedDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs +4 -2
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs.map +1 -1
- package/dist/cjs/cleanOutputDir.cjs.map +1 -1
- package/dist/cjs/cleanRemovedContentDeclaration.cjs +7 -4
- package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
- package/dist/cjs/cli.cjs +2 -0
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs +5 -3
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createType/createModuleAugmentation.cjs +2 -1
- package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
- package/dist/cjs/createType/createType.cjs.map +1 -1
- package/dist/cjs/detectFormatCommand.cjs.map +1 -1
- package/dist/cjs/docReview/alignBlocks.cjs +1 -1
- package/dist/cjs/docReview/alignBlocks.cjs.map +1 -1
- package/dist/cjs/docReview/computeSimilarity.cjs +0 -1
- package/dist/cjs/docReview/computeSimilarity.cjs.map +1 -1
- package/dist/cjs/docReview/mapChangedLinesToBlocks.cjs +0 -1
- package/dist/cjs/docReview/mapChangedLinesToBlocks.cjs.map +1 -1
- package/dist/cjs/docReview/normalizeBlock.cjs +0 -1
- package/dist/cjs/docReview/normalizeBlock.cjs.map +1 -1
- package/dist/cjs/docReview/planActions.cjs +0 -1
- package/dist/cjs/docReview/planActions.cjs.map +1 -1
- package/dist/cjs/docReview/rebuildDocument.cjs +0 -1
- package/dist/cjs/docReview/rebuildDocument.cjs.map +1 -1
- package/dist/cjs/docReview/reviewReport.cjs +2 -1
- package/dist/cjs/docReview/reviewReport.cjs.map +1 -1
- package/dist/cjs/docReview/segmentDocument.cjs +0 -1
- package/dist/cjs/docReview/segmentDocument.cjs.map +1 -1
- package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
- package/dist/cjs/formatDictionary.cjs.map +1 -1
- package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs.map +1 -1
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs +4 -2
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileChange.cjs +6 -2
- package/dist/cjs/handleContentDeclarationFileChange.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileMoved.cjs.map +1 -1
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs +4 -2
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/init/cms.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/detect.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/index.cjs +1 -3
- package/dist/cjs/init/frameworkSetup/nextAppRouter/index.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/restructure.cjs +2 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/restructure.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/templates.cjs +0 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/templates.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/detect.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/index.cjs +3 -5
- package/dist/cjs/init/frameworkSetup/tanstackStart/index.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/restructure.cjs +2 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/restructure.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/templates.cjs +18 -12
- package/dist/cjs/init/frameworkSetup/tanstackStart/templates.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/transforms.cjs +57 -14
- package/dist/cjs/init/frameworkSetup/tanstackStart/transforms.cjs.map +1 -1
- package/dist/cjs/init/index.cjs +124 -45
- package/dist/cjs/init/index.cjs.map +1 -1
- package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
- package/dist/cjs/init/utils/fileSystem.cjs +3 -1
- package/dist/cjs/init/utils/fileSystem.cjs.map +1 -1
- package/dist/cjs/init/utils/githubActions.cjs.map +1 -1
- package/dist/cjs/init/utils/index.cjs +3 -0
- package/dist/cjs/init/utils/jsonParser.cjs +0 -1
- package/dist/cjs/init/utils/jsonParser.cjs.map +1 -1
- package/dist/cjs/init/utils/nextCompilerBabel.cjs.map +1 -1
- package/dist/cjs/init/utils/packageManager.cjs +105 -7
- package/dist/cjs/init/utils/packageManager.cjs.map +1 -1
- package/dist/cjs/init/utils/tsConfig.cjs.map +1 -1
- package/dist/cjs/init/utils/version.cjs +0 -1
- package/dist/cjs/init/utils/version.cjs.map +1 -1
- package/dist/cjs/initConfig/index.cjs +12 -8
- package/dist/cjs/initConfig/index.cjs.map +1 -1
- package/dist/cjs/installSkills/index.cjs.map +1 -1
- package/dist/cjs/listDictionariesPath.cjs +6 -5
- package/dist/cjs/listDictionariesPath.cjs.map +1 -1
- package/dist/cjs/listGitFiles.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs +2 -1
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs +2 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +8 -5
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadMarkdownContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadYamlContentDeclaration.cjs +2 -1
- package/dist/cjs/loadDictionaries/loadYamlContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/log.cjs +10 -6
- package/dist/cjs/loadDictionaries/log.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs.map +1 -1
- package/dist/cjs/logConfigDetails.cjs +4 -3
- package/dist/cjs/logConfigDetails.cjs.map +1 -1
- package/dist/cjs/prepareIntlayer.cjs +5 -3
- package/dist/cjs/prepareIntlayer.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/applyMask.cjs +0 -1
- package/dist/cjs/reduceDictionaryContent/applyMask.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs +2 -1
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs.map +1 -1
- package/dist/cjs/scan/calculateScore.cjs +0 -1
- package/dist/cjs/scan/calculateScore.cjs.map +1 -1
- package/dist/cjs/scan/checks.cjs +1 -1
- package/dist/cjs/scan/checks.cjs.map +1 -1
- package/dist/cjs/scan/parseHtml.cjs +0 -1
- package/dist/cjs/scan/parseHtml.cjs.map +1 -1
- package/dist/cjs/scan/scanWebsite.cjs.map +1 -1
- package/dist/cjs/syncPluginKit/createFileAdapter.cjs +2 -1
- package/dist/cjs/syncPluginKit/createFileAdapter.cjs.map +1 -1
- package/dist/cjs/syncPluginKit/createSyncPlugin.cjs +4 -1
- package/dist/cjs/syncPluginKit/createSyncPlugin.cjs.map +1 -1
- package/dist/cjs/syncPluginKit/extractKeyAndLocaleFromPath.cjs +0 -1
- package/dist/cjs/syncPluginKit/extractKeyAndLocaleFromPath.cjs.map +1 -1
- package/dist/cjs/syncPluginKit/filePathPatternHelpers.cjs +0 -1
- package/dist/cjs/syncPluginKit/filePathPatternHelpers.cjs.map +1 -1
- package/dist/cjs/utils/autoDecorateContent.cjs.map +1 -1
- package/dist/cjs/utils/babelParser.cjs.map +1 -1
- package/dist/cjs/utils/buildComponentFilesList.cjs.map +1 -1
- package/dist/cjs/utils/buildFilesList.cjs.map +1 -1
- package/dist/cjs/utils/chunkArray.cjs +0 -1
- package/dist/cjs/utils/chunkArray.cjs.map +1 -1
- package/dist/cjs/utils/formatter.cjs.map +1 -1
- package/dist/cjs/utils/getContentExtension.cjs +1 -4
- package/dist/cjs/utils/getContentExtension.cjs.map +1 -1
- package/dist/cjs/utils/getFormatFromExtension.cjs +0 -1
- package/dist/cjs/utils/getFormatFromExtension.cjs.map +1 -1
- package/dist/cjs/utils/getPathHash.cjs +0 -1
- package/dist/cjs/utils/getPathHash.cjs.map +1 -1
- package/dist/cjs/utils/mergeChunks.cjs +0 -1
- package/dist/cjs/utils/mergeChunks.cjs.map +1 -1
- package/dist/cjs/utils/pLimit.cjs +0 -1
- package/dist/cjs/utils/pLimit.cjs.map +1 -1
- package/dist/cjs/utils/readDictionariesFromDisk.cjs.map +1 -1
- package/dist/cjs/utils/reduceObjectFormat.cjs +0 -1
- package/dist/cjs/utils/reduceObjectFormat.cjs.map +1 -1
- package/dist/cjs/utils/resolveObjectPromises.cjs +0 -1
- package/dist/cjs/utils/resolveObjectPromises.cjs.map +1 -1
- package/dist/cjs/utils/resolveRelativePath.cjs +4 -1
- package/dist/cjs/utils/resolveRelativePath.cjs.map +1 -1
- package/dist/cjs/utils/runOnce.cjs +2 -2
- package/dist/cjs/utils/runOnce.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/bin.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/bootstrap.cjs +0 -1
- package/dist/cjs/utils/runParallel/bootstrap.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/spawnPosix.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/spawnWin32.cjs.map +1 -1
- package/dist/cjs/utils/sortAlphabetically.cjs +0 -1
- package/dist/cjs/utils/sortAlphabetically.cjs.map +1 -1
- package/dist/cjs/utils/splitTextByLine.cjs +0 -1
- package/dist/cjs/utils/splitTextByLine.cjs.map +1 -1
- package/dist/cjs/utils/verifyIdenticObjectFormat.cjs +0 -1
- package/dist/cjs/utils/verifyIdenticObjectFormat.cjs.map +1 -1
- package/dist/cjs/watcher.cjs +4 -2
- package/dist/cjs/watcher.cjs.map +1 -1
- package/dist/cjs/writeConfiguration/index.cjs +2 -1
- package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs +0 -1
- package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs +26 -23
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs +6 -5
- package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +9 -3
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +2 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs +2 -1
- package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeYamlFile.cjs +4 -2
- package/dist/cjs/writeContentDeclaration/writeYamlFile.cjs.map +1 -1
- package/dist/cjs/writeFileIfChanged.cjs.map +1 -1
- package/dist/esm/_virtual/_utils_asset.mjs +2 -1
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs +2 -1
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs +2 -1
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs +4 -2
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs.map +1 -1
- package/dist/esm/cleanRemovedContentDeclaration.mjs +7 -4
- package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
- package/dist/esm/cli.mjs +2 -2
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs +5 -3
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs.map +1 -1
- package/dist/esm/createType/createModuleAugmentation.mjs +2 -1
- package/dist/esm/createType/createModuleAugmentation.mjs.map +1 -1
- package/dist/esm/docReview/alignBlocks.mjs +1 -1
- package/dist/esm/docReview/alignBlocks.mjs.map +1 -1
- package/dist/esm/docReview/reviewReport.mjs +2 -1
- package/dist/esm/docReview/reviewReport.mjs.map +1 -1
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs +4 -2
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/handleContentDeclarationFileChange.mjs +6 -2
- package/dist/esm/handleContentDeclarationFileChange.mjs.map +1 -1
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs +4 -2
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/nextAppRouter/index.mjs +1 -3
- package/dist/esm/init/frameworkSetup/nextAppRouter/index.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/nextAppRouter/restructure.mjs +2 -1
- package/dist/esm/init/frameworkSetup/nextAppRouter/restructure.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/index.mjs +4 -6
- package/dist/esm/init/frameworkSetup/tanstackStart/index.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/restructure.mjs +2 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/restructure.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/templates.mjs +17 -10
- package/dist/esm/init/frameworkSetup/tanstackStart/templates.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/transforms.mjs +58 -15
- package/dist/esm/init/frameworkSetup/tanstackStart/transforms.mjs.map +1 -1
- package/dist/esm/init/index.mjs +125 -46
- package/dist/esm/init/index.mjs.map +1 -1
- package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
- package/dist/esm/init/utils/fileSystem.mjs +3 -1
- package/dist/esm/init/utils/fileSystem.mjs.map +1 -1
- package/dist/esm/init/utils/index.mjs +2 -2
- package/dist/esm/init/utils/packageManager.mjs +103 -8
- package/dist/esm/init/utils/packageManager.mjs.map +1 -1
- package/dist/esm/initConfig/index.mjs +12 -8
- package/dist/esm/initConfig/index.mjs.map +1 -1
- package/dist/esm/listDictionariesPath.mjs +6 -5
- package/dist/esm/listDictionariesPath.mjs.map +1 -1
- package/dist/esm/listProjects.mjs +2 -1
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs +2 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs +8 -5
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadYamlContentDeclaration.mjs +2 -1
- package/dist/esm/loadDictionaries/loadYamlContentDeclaration.mjs.map +1 -1
- package/dist/esm/loadDictionaries/log.mjs +10 -6
- package/dist/esm/loadDictionaries/log.mjs.map +1 -1
- package/dist/esm/logConfigDetails.mjs +4 -3
- package/dist/esm/logConfigDetails.mjs.map +1 -1
- package/dist/esm/prepareIntlayer.mjs +5 -3
- package/dist/esm/prepareIntlayer.mjs.map +1 -1
- package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs +2 -1
- package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs.map +1 -1
- package/dist/esm/scan/checks.mjs +1 -1
- package/dist/esm/scan/checks.mjs.map +1 -1
- package/dist/esm/syncPluginKit/createFileAdapter.mjs +2 -1
- package/dist/esm/syncPluginKit/createFileAdapter.mjs.map +1 -1
- package/dist/esm/syncPluginKit/createSyncPlugin.mjs +4 -1
- package/dist/esm/syncPluginKit/createSyncPlugin.mjs.map +1 -1
- package/dist/esm/utils/babelParser.mjs.map +1 -1
- package/dist/esm/utils/getContentExtension.mjs +1 -3
- package/dist/esm/utils/getContentExtension.mjs.map +1 -1
- package/dist/esm/utils/resolveRelativePath.mjs +4 -1
- package/dist/esm/utils/resolveRelativePath.mjs.map +1 -1
- package/dist/esm/utils/runOnce.mjs +2 -2
- package/dist/esm/utils/runOnce.mjs.map +1 -1
- package/dist/esm/watcher.mjs +4 -2
- package/dist/esm/watcher.mjs.map +1 -1
- package/dist/esm/writeConfiguration/index.mjs +2 -1
- package/dist/esm/writeConfiguration/index.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/transformJSFile.mjs +26 -23
- package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/transformJSONFile.mjs +6 -5
- package/dist/esm/writeContentDeclaration/transformJSONFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +9 -3
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs +2 -1
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs +2 -1
- package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeYamlFile.mjs +4 -2
- package/dist/esm/writeContentDeclaration/writeYamlFile.mjs.map +1 -1
- package/dist/types/cli.d.ts +2 -2
- package/dist/types/init/frameworkSetup/tanstackStart/templates.d.ts +9 -4
- package/dist/types/init/frameworkSetup/tanstackStart/templates.d.ts.map +1 -1
- package/dist/types/init/frameworkSetup/tanstackStart/transforms.d.ts +6 -2
- package/dist/types/init/frameworkSetup/tanstackStart/transforms.d.ts.map +1 -1
- package/dist/types/init/index.d.ts +2 -7
- package/dist/types/init/index.d.ts.map +1 -1
- package/dist/types/init/utils/index.d.ts +2 -2
- package/dist/types/init/utils/packageManager.d.ts +39 -6
- package/dist/types/init/utils/packageManager.d.ts.map +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"restructure.cjs","names":["sep","babelTsParser"],"sources":["../../../../../src/init/frameworkSetup/nextAppRouter/restructure.ts"],"sourcesContent":["import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport fg from 'fast-glob';\nimport * as recast from 'recast';\nimport { babelTsParser } from '../../../utils/babelParser';\n\nconst { namedTypes: n } = recast.types;\n\n/** Source file extensions whose relative imports must be rewritten after a move. */\nconst SCRIPT_GLOB = '**/*.{ts,tsx,js,jsx,mjs,cjs}';\n\n/** Strips a known script extension from a file name, e.g. `page.tsx` -> `page`. */\nconst stripScriptExtension = (fileName: string): string =>\n fileName.replace(/\\.(tsx|ts|jsx|js|mjs|cjs)$/, '');\n\n/**\n * Detects whether a top-level App Router entry is already a locale segment, in\n * any of the Next.js dynamic-segment forms:\n * - `[locale]` — required segment (prefix every locale),\n * - `[...locale]` / `[[...locale]]` — catch-all / optional catch-all segments.\n *\n * Used to skip the restructure when the project is already locale-aware, so an\n * existing locale segment is never nested under a freshly created `[locale]`.\n */\nexport const isLocaleSegment = (entryName: string): boolean =>\n /^\\[\\[?\\.{0,3}locale\\]\\]?$/.test(entryName);\n\n/**\n * Top-level App Router entries that must stay at the app root and never be\n * moved under `[locale]`:\n * - `api/` route handlers (not locale-prefixed),\n * - global stylesheets,\n * - metadata/asset file conventions (favicon, icon, sitemap, robots, manifest…),\n * - `global-error` and `not-found` boundaries (kept as root fallbacks).\n *\n * Everything else (`page`, `loading`, `error`, `template`, `default`, the root\n * `layout`, and nested route folders) is moved so it becomes locale-aware.\n */\nexport const shouldKeepAppEntryAtRoot = (entryName: string): boolean => {\n if (entryName === 'api') return true;\n if (entryName.toLowerCase().endsWith('.css')) return true;\n if (entryName === 'favicon.ico') return true;\n\n const base = stripScriptExtension(entryName);\n const keepExactBases = new Set([\n 'not-found',\n 'global-error',\n 'sitemap',\n 'robots',\n 'manifest',\n ]);\n if (keepExactBases.has(base)) return true;\n\n // Image metadata conventions: favicon, icon, apple-icon, opengraph-image,\n // twitter-image — optionally suffixed (e.g. `icon1`, `opengraph-image-alt`).\n const imageConventionPrefixes = [\n 'favicon',\n 'icon',\n 'apple-icon',\n 'opengraph-image',\n 'twitter-image',\n ];\n if (imageConventionPrefixes.some((prefix) => base.startsWith(prefix))) {\n return true;\n }\n\n return false;\n};\n\ntype RewriteContext = {\n appDirAbs: string;\n localeDirAbs: string;\n movedTopLevelNames: string[];\n};\n\n/**\n * Maps an import target's pre-move absolute path to its post-move absolute path.\n * Targets that live inside a moved top-level entry are relocated under\n * `[locale]`; targets that stayed at the app root or live outside the app\n * directory are returned unchanged.\n */\nconst mapTargetPath = (\n oldTargetAbs: string,\n { appDirAbs, localeDirAbs, movedTopLevelNames }: RewriteContext\n): string => {\n const relFromApp = relative(appDirAbs, oldTargetAbs);\n\n // Outside the app directory (e.g. `../components/...`) — never moved.\n if (relFromApp.startsWith('..') || isAbsolute(relFromApp)) {\n return oldTargetAbs;\n }\n\n const firstSegment = relFromApp.split(sep)[0] ?? '';\n const isMoved = movedTopLevelNames.some(\n (name) =>\n name === firstSegment || stripScriptExtension(name) === firstSegment\n );\n\n if (!isMoved) return oldTargetAbs;\n\n return join(localeDirAbs, relFromApp);\n};\n\n/**\n * Rewrites relative import/export/`import()`/`require()` specifiers in a file\n * that has moved from `oldAbs` to `newAbs`, so they keep resolving to the same\n * modules after the move. Non-relative specifiers (bare packages, `@/` aliases)\n * are left untouched. Returns the original code unchanged when nothing matched.\n */\nexport const rewriteRelativeImports = (\n code: string,\n oldAbs: string,\n newAbs: string,\n context: RewriteContext\n): string => {\n // babel-ts handles TypeScript *and* JSX (App Router files are `.tsx`).\n const ast = recast.parse(code, { parser: babelTsParser });\n\n let changed = false;\n\n const rewriteSource = (sourceNode: any): void => {\n if (!sourceNode || !n.StringLiteral.check(sourceNode)) return;\n const specifier = sourceNode.value;\n if (typeof specifier !== 'string' || !specifier.startsWith('.')) return;\n\n const oldTargetAbs = resolve(dirname(oldAbs), specifier);\n const newTargetAbs = mapTargetPath(oldTargetAbs, context);\n\n let newSpecifier = relative(dirname(newAbs), newTargetAbs)\n .split(sep)\n .join('/');\n if (!newSpecifier.startsWith('.')) {\n newSpecifier = `./${newSpecifier}`;\n }\n\n if (newSpecifier !== specifier) {\n sourceNode.value = newSpecifier;\n changed = true;\n }\n };\n\n recast.visit(ast, {\n visitImportDeclaration(path) {\n rewriteSource(path.node.source);\n return false;\n },\n visitExportAllDeclaration(path) {\n rewriteSource(path.node.source);\n return false;\n },\n visitExportNamedDeclaration(path) {\n if (path.node.source) rewriteSource(path.node.source);\n return false;\n },\n visitCallExpression(path) {\n const { callee, arguments: args } = path.node;\n const isDynamicImport = callee.type === 'Import';\n const isRequire = n.Identifier.check(callee) && callee.name === 'require';\n if ((isDynamicImport || isRequire) && args.length > 0) {\n rewriteSource(args[0]);\n }\n this.traverse(path);\n },\n });\n\n if (!changed) return code;\n return recast.print(ast).code;\n};\n\n/** Outcome of an attempted `[locale]` restructure. */\nexport type RestructureResult =\n | { status: 'already-structured'; localeSegment: string }\n | { status: 'nothing-to-move' }\n | { status: 'moved'; movedEntries: string[] };\n\n/**\n * Moves the routable App Router entries of `appDir` under a new `[locale]`\n * segment and rewrites relative imports in the moved files. Idempotent: it is a\n * no-op when the app is already locale-aware in any prefix mode (see\n * {@link isLocaleSegment}), which is reported via `localeSegment`. Root-only\n * files (see {@link shouldKeepAppEntryAtRoot}) are left in place.\n */\nexport const restructureAppIntoLocale = async (\n rootDir: string,\n appDir: string\n): Promise<RestructureResult> => {\n const appDirAbs = join(rootDir, appDir);\n const localeDirAbs = join(appDirAbs, '[locale]');\n\n const entries = await readdir(appDirAbs, { withFileTypes: true });\n\n // Skip when the app is already locale-aware in any prefix mode — a fresh\n // `[locale]`, or an existing `[...locale]` / `[[...locale]]` catch-all segment.\n const existingLocaleSegment = entries.find((entry) =>\n isLocaleSegment(entry.name)\n );\n if (existingLocaleSegment) {\n return {\n status: 'already-structured',\n localeSegment: existingLocaleSegment.name,\n };\n }\n\n const movedTopLevelNames = entries\n .map((entry) => entry.name)\n .filter((name) => !shouldKeepAppEntryAtRoot(name));\n\n if (movedTopLevelNames.length === 0) {\n return { status: 'nothing-to-move' };\n }\n\n await mkdir(localeDirAbs, { recursive: true });\n\n for (const name of movedTopLevelNames) {\n await rename(join(appDirAbs, name), join(localeDirAbs, name));\n }\n\n const movedFiles = await fg(SCRIPT_GLOB, {\n cwd: localeDirAbs,\n absolute: true,\n onlyFiles: true,\n });\n\n const rewriteContext: RewriteContext = {\n appDirAbs,\n localeDirAbs,\n movedTopLevelNames,\n };\n\n for (const newAbs of movedFiles) {\n const relFromLocale = relative(localeDirAbs, newAbs);\n const oldAbs = join(appDirAbs, relFromLocale);\n const code = await readFile(newAbs, 'utf8');\n const rewritten = rewriteRelativeImports(\n code,\n oldAbs,\n newAbs,\n rewriteContext\n );\n if (rewritten !== code) {\n await writeFile(newAbs, rewritten, 'utf8');\n }\n }\n\n return { status: 'moved', movedEntries: movedTopLevelNames };\n};\n"],"mappings":";;;;;;;;;;;AAMA,MAAM,EAAE,YAAY,MAAM,OAAO;;AAGjC,MAAM,cAAc;;AAGpB,MAAM,wBAAwB,aAC5B,SAAS,QAAQ,8BAA8B,EAAE;;;;;;;;;;AAWnD,MAAa,mBAAmB,cAC9B,4BAA4B,KAAK,SAAS;;;;;;;;;;;;AAa5C,MAAa,4BAA4B,cAA+B;CACtE,IAAI,cAAc,OAAO,OAAO;CAChC,IAAI,UAAU,YAAY,CAAC,CAAC,SAAS,MAAM,GAAG,OAAO;CACrD,IAAI,cAAc,eAAe,OAAO;CAExC,MAAM,OAAO,qBAAqB,SAAS;CAQ3C,qBAAI,IAPuB,IAAI;EAC7B;EACA;EACA;EACA;EACA;CACF,CACiB,EAAC,CAAC,IAAI,IAAI,GAAG,OAAO;CAWrC,IAAI;EANF;EACA;EACA;EACA;EACA;CAEwB,CAAC,CAAC,MAAM,WAAW,KAAK,WAAW,MAAM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EA,OAAO;EAAE,QAAQ;EAAS,cAAc;CAAmB;AAC7D"}
|
|
1
|
+
{"version":3,"file":"restructure.cjs","names":["relative","isAbsolute","sep","join","babelTsParser","resolve","dirname","readdir","mkdir","rename","fg","readFile","writeFile"],"sources":["../../../../../src/init/frameworkSetup/nextAppRouter/restructure.ts"],"sourcesContent":["import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport fg from 'fast-glob';\nimport * as recast from 'recast';\nimport { babelTsParser } from '../../../utils/babelParser';\n\nconst { namedTypes: n } = recast.types;\n\n/** Source file extensions whose relative imports must be rewritten after a move. */\nconst SCRIPT_GLOB = '**/*.{ts,tsx,js,jsx,mjs,cjs}';\n\n/** Strips a known script extension from a file name, e.g. `page.tsx` -> `page`. */\nconst stripScriptExtension = (fileName: string): string =>\n fileName.replace(/\\.(tsx|ts|jsx|js|mjs|cjs)$/, '');\n\n/**\n * Detects whether a top-level App Router entry is already a locale segment, in\n * any of the Next.js dynamic-segment forms:\n * - `[locale]` — required segment (prefix every locale),\n * - `[...locale]` / `[[...locale]]` — catch-all / optional catch-all segments.\n *\n * Used to skip the restructure when the project is already locale-aware, so an\n * existing locale segment is never nested under a freshly created `[locale]`.\n */\nexport const isLocaleSegment = (entryName: string): boolean =>\n /^\\[\\[?\\.{0,3}locale\\]\\]?$/.test(entryName);\n\n/**\n * Top-level App Router entries that must stay at the app root and never be\n * moved under `[locale]`:\n * - `api/` route handlers (not locale-prefixed),\n * - global stylesheets,\n * - metadata/asset file conventions (favicon, icon, sitemap, robots, manifest…),\n * - `global-error` and `not-found` boundaries (kept as root fallbacks).\n *\n * Everything else (`page`, `loading`, `error`, `template`, `default`, the root\n * `layout`, and nested route folders) is moved so it becomes locale-aware.\n */\nexport const shouldKeepAppEntryAtRoot = (entryName: string): boolean => {\n if (entryName === 'api') return true;\n if (entryName.toLowerCase().endsWith('.css')) return true;\n if (entryName === 'favicon.ico') return true;\n\n const base = stripScriptExtension(entryName);\n const keepExactBases = new Set([\n 'not-found',\n 'global-error',\n 'sitemap',\n 'robots',\n 'manifest',\n ]);\n if (keepExactBases.has(base)) return true;\n\n // Image metadata conventions: favicon, icon, apple-icon, opengraph-image,\n // twitter-image — optionally suffixed (e.g. `icon1`, `opengraph-image-alt`).\n const imageConventionPrefixes = [\n 'favicon',\n 'icon',\n 'apple-icon',\n 'opengraph-image',\n 'twitter-image',\n ];\n if (imageConventionPrefixes.some((prefix) => base.startsWith(prefix))) {\n return true;\n }\n\n return false;\n};\n\ntype RewriteContext = {\n appDirAbs: string;\n localeDirAbs: string;\n movedTopLevelNames: string[];\n};\n\n/**\n * Maps an import target's pre-move absolute path to its post-move absolute path.\n * Targets that live inside a moved top-level entry are relocated under\n * `[locale]`; targets that stayed at the app root or live outside the app\n * directory are returned unchanged.\n */\nconst mapTargetPath = (\n oldTargetAbs: string,\n { appDirAbs, localeDirAbs, movedTopLevelNames }: RewriteContext\n): string => {\n const relFromApp = relative(appDirAbs, oldTargetAbs);\n\n // Outside the app directory (e.g. `../components/...`) — never moved.\n if (relFromApp.startsWith('..') || isAbsolute(relFromApp)) {\n return oldTargetAbs;\n }\n\n const firstSegment = relFromApp.split(sep)[0] ?? '';\n const isMoved = movedTopLevelNames.some(\n (name) =>\n name === firstSegment || stripScriptExtension(name) === firstSegment\n );\n\n if (!isMoved) return oldTargetAbs;\n\n return join(localeDirAbs, relFromApp);\n};\n\n/**\n * Rewrites relative import/export/`import()`/`require()` specifiers in a file\n * that has moved from `oldAbs` to `newAbs`, so they keep resolving to the same\n * modules after the move. Non-relative specifiers (bare packages, `@/` aliases)\n * are left untouched. Returns the original code unchanged when nothing matched.\n */\nexport const rewriteRelativeImports = (\n code: string,\n oldAbs: string,\n newAbs: string,\n context: RewriteContext\n): string => {\n // babel-ts handles TypeScript *and* JSX (App Router files are `.tsx`).\n const ast = recast.parse(code, { parser: babelTsParser });\n\n let changed = false;\n\n const rewriteSource = (sourceNode: any): void => {\n if (!sourceNode || !n.StringLiteral.check(sourceNode)) return;\n const specifier = sourceNode.value;\n if (typeof specifier !== 'string' || !specifier.startsWith('.')) return;\n\n const oldTargetAbs = resolve(dirname(oldAbs), specifier);\n const newTargetAbs = mapTargetPath(oldTargetAbs, context);\n\n let newSpecifier = relative(dirname(newAbs), newTargetAbs)\n .split(sep)\n .join('/');\n if (!newSpecifier.startsWith('.')) {\n newSpecifier = `./${newSpecifier}`;\n }\n\n if (newSpecifier !== specifier) {\n sourceNode.value = newSpecifier;\n changed = true;\n }\n };\n\n recast.visit(ast, {\n visitImportDeclaration(path) {\n rewriteSource(path.node.source);\n return false;\n },\n visitExportAllDeclaration(path) {\n rewriteSource(path.node.source);\n return false;\n },\n visitExportNamedDeclaration(path) {\n if (path.node.source) rewriteSource(path.node.source);\n return false;\n },\n visitCallExpression(path) {\n const { callee, arguments: args } = path.node;\n const isDynamicImport = callee.type === 'Import';\n const isRequire = n.Identifier.check(callee) && callee.name === 'require';\n if ((isDynamicImport || isRequire) && args.length > 0) {\n rewriteSource(args[0]);\n }\n this.traverse(path);\n },\n });\n\n if (!changed) return code;\n return recast.print(ast).code;\n};\n\n/** Outcome of an attempted `[locale]` restructure. */\nexport type RestructureResult =\n | { status: 'already-structured'; localeSegment: string }\n | { status: 'nothing-to-move' }\n | { status: 'moved'; movedEntries: string[] };\n\n/**\n * Moves the routable App Router entries of `appDir` under a new `[locale]`\n * segment and rewrites relative imports in the moved files. Idempotent: it is a\n * no-op when the app is already locale-aware in any prefix mode (see\n * {@link isLocaleSegment}), which is reported via `localeSegment`. Root-only\n * files (see {@link shouldKeepAppEntryAtRoot}) are left in place.\n */\nexport const restructureAppIntoLocale = async (\n rootDir: string,\n appDir: string\n): Promise<RestructureResult> => {\n const appDirAbs = join(rootDir, appDir);\n const localeDirAbs = join(appDirAbs, '[locale]');\n\n const entries = await readdir(appDirAbs, { withFileTypes: true });\n\n // Skip when the app is already locale-aware in any prefix mode — a fresh\n // `[locale]`, or an existing `[...locale]` / `[[...locale]]` catch-all segment.\n const existingLocaleSegment = entries.find((entry) =>\n isLocaleSegment(entry.name)\n );\n if (existingLocaleSegment) {\n return {\n status: 'already-structured',\n localeSegment: existingLocaleSegment.name,\n };\n }\n\n const movedTopLevelNames = entries\n .map((entry) => entry.name)\n .filter((name) => !shouldKeepAppEntryAtRoot(name));\n\n if (movedTopLevelNames.length === 0) {\n return { status: 'nothing-to-move' };\n }\n\n await mkdir(localeDirAbs, { recursive: true });\n\n for (const name of movedTopLevelNames) {\n await rename(join(appDirAbs, name), join(localeDirAbs, name));\n }\n\n const movedFiles = await fg(SCRIPT_GLOB, {\n cwd: localeDirAbs,\n absolute: true,\n onlyFiles: true,\n });\n\n const rewriteContext: RewriteContext = {\n appDirAbs,\n localeDirAbs,\n movedTopLevelNames,\n };\n\n for (const newAbs of movedFiles) {\n const relFromLocale = relative(localeDirAbs, newAbs);\n const oldAbs = join(appDirAbs, relFromLocale);\n const code = await readFile(newAbs, 'utf8');\n const rewritten = rewriteRelativeImports(\n code,\n oldAbs,\n newAbs,\n rewriteContext\n );\n if (rewritten !== code) {\n await writeFile(newAbs, rewritten, 'utf8');\n }\n }\n\n return { status: 'moved', movedEntries: movedTopLevelNames };\n};\n"],"mappings":";;;;;;;;;;;AAMA,MAAM,EAAE,YAAY,MAAM,OAAO;;AAGjC,MAAM,cAAc;;AAGpB,MAAM,wBAAwB,aAC5B,SAAS,QAAQ,8BAA8B,EAAE;;;;;;;;;;AAWnD,MAAa,mBAAmB,cAC9B,4BAA4B,KAAK,SAAS;;;;;;;;;;;;AAa5C,MAAa,4BAA4B,cAA+B;CACtE,IAAI,cAAc,OAAO,OAAO;CAChC,IAAI,UAAU,YAAY,CAAC,CAAC,SAAS,MAAM,GAAG,OAAO;CACrD,IAAI,cAAc,eAAe,OAAO;CAExC,MAAM,OAAO,qBAAqB,SAAS;CAQ3C,qBAAI,IAPuB,IAAI;EAC7B;EACA;EACA;EACA;EACA;CACF,CACiB,EAAC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ACA;CACF;CAEA,KAAK,MAAM,UAAU,YAAY;EAC/B,MAAM,oBAAgBV,oBAAS,cAAc,MAAM;EACnD,MAAM,aAASG,gBAAK,WAAW,aAAa;EAC5C,MAAM,OAAO,UAAMQ,2BAAS,QAAQ,MAAM;EAC1C,MAAM,YAAY,uBAChB,MACA,QACA,QACA,cACF;EACA,IAAI,cAAc,MAChB,UAAMC,4BAAU,QAAQ,WAAW,MAAM;CAE7C;CAEA,OAAO;EAAE,QAAQ;EAAS,cAAc;CAAmB;AAC7D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.cjs","names":[],"sources":["../../../../../src/init/frameworkSetup/nextAppRouter/templates.ts"],"sourcesContent":["/**\n * File templates for a fresh Next.js App Router integration. These are only\n * written when the target file does not exist (or, for the locale layout/page,\n * when the app is effectively empty) — they never overwrite user code.\n */\n\n/** Next.js >= 16 locale-detection proxy (`src/proxy.ts`). */\nexport const PROXY_TEMPLATE = `export { intlayerProxy as proxy } from \"next-intlayer/proxy\";\n\nexport const config = {\n matcher:\n \"/((?!api|static|assets|robots|sitemap|sw|service-worker|manifest|.*\\\\\\\\..*|_next).*)\",\n};\n`;\n\n/** Next.js < 16 locale-detection middleware (`src/middleware.ts`). */\nexport const MIDDLEWARE_TEMPLATE = `export { intlayerMiddleware as middleware } from \"next-intlayer/middleware\";\n\nexport const config = {\n matcher:\n \"/((?!api|static|assets|robots|sitemap|sw|service-worker|manifest|.*\\\\\\\\..*|_next).*)\",\n};\n`;\n\n/** Minimal pass-through root layout (`app/layout.tsx`), lets `[locale]/layout` own `<html>`. */\nexport const ROOT_LAYOUT_TEMPLATE_TS = `import type { PropsWithChildren, FC } from \"react\";\n\nconst RootLayout: FC<PropsWithChildren> = ({ children }) => <>{children}</>;\n\nexport default RootLayout;\n`;\n\nexport const ROOT_LAYOUT_TEMPLATE_JS = `const RootLayout = ({ children }) => <>{children}</>;\n\nexport default RootLayout;\n`;\n\n/** Locale layout (`app/[locale]/layout.tsx`) providing `<html>` + client provider. */\nexport const LOCALE_LAYOUT_TEMPLATE_TS = `import { type NextLayoutIntlayer, IntlayerClientProvider } from \"next-intlayer\";\nimport { getHTMLTextDir } from \"intlayer\";\n\nexport { generateStaticParams } from \"next-intlayer\";\n\nconst LocaleLayout: NextLayoutIntlayer = async ({ children, params }) => {\n const { locale } = await params;\n\n return (\n <html lang={locale} dir={getHTMLTextDir(locale)}>\n <body>\n <IntlayerClientProvider locale={locale}>\n {children}\n </IntlayerClientProvider>\n </body>\n </html>\n );\n};\n\nexport default LocaleLayout;\n`;\n\nexport const LOCALE_LAYOUT_TEMPLATE_JS = `import { IntlayerClientProvider } from \"next-intlayer\";\nimport { getHTMLTextDir } from \"intlayer\";\n\nexport { generateStaticParams } from \"next-intlayer\";\n\nconst LocaleLayout = async ({ children, params }) => {\n const { locale } = await params;\n\n return (\n <html lang={locale} dir={getHTMLTextDir(locale)}>\n <body>\n <IntlayerClientProvider locale={locale}>\n {children}\n </IntlayerClientProvider>\n </body>\n </html>\n );\n};\n\nexport default LocaleLayout;\n`;\n\n/**\n * Locale home page (`app/[locale]/page.tsx`). Self-contained starter that does\n * not depend on an example content declaration — add Intlayer content (a\n * `*.content.ts` file consumed via `useIntlayer`) as the next step.\n */\nexport const LOCALE_PAGE_TEMPLATE_TS = `import { type NextPageIntlayer } from \"next-intlayer\";\n\nconst Page: NextPageIntlayer = async ({ params }) => {\n const { locale } = await params;\n\n return (\n <main>\n <h1>{locale}</h1>\n <p>Get started by editing this page.</p>\n </main>\n );\n};\n\nexport default Page;\n`;\n\nexport const LOCALE_PAGE_TEMPLATE_JS = `const Page = async ({ params }) => {\n const { locale } = await params;\n\n return (\n <main>\n <h1>{locale}</h1>\n <p>Get started by editing this page.</p>\n </main>\n );\n};\n\nexport default Page;\n`;\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"templates.cjs","names":[],"sources":["../../../../../src/init/frameworkSetup/nextAppRouter/templates.ts"],"sourcesContent":["/**\n * File templates for a fresh Next.js App Router integration. These are only\n * written when the target file does not exist (or, for the locale layout/page,\n * when the app is effectively empty) — they never overwrite user code.\n */\n\n/** Next.js >= 16 locale-detection proxy (`src/proxy.ts`). */\nexport const PROXY_TEMPLATE = `export { intlayerProxy as proxy } from \"next-intlayer/proxy\";\n\nexport const config = {\n matcher:\n \"/((?!api|static|assets|robots|sitemap|sw|service-worker|manifest|.*\\\\\\\\..*|_next).*)\",\n};\n`;\n\n/** Next.js < 16 locale-detection middleware (`src/middleware.ts`). */\nexport const MIDDLEWARE_TEMPLATE = `export { intlayerMiddleware as middleware } from \"next-intlayer/middleware\";\n\nexport const config = {\n matcher:\n \"/((?!api|static|assets|robots|sitemap|sw|service-worker|manifest|.*\\\\\\\\..*|_next).*)\",\n};\n`;\n\n/** Minimal pass-through root layout (`app/layout.tsx`), lets `[locale]/layout` own `<html>`. */\nexport const ROOT_LAYOUT_TEMPLATE_TS = `import type { PropsWithChildren, FC } from \"react\";\n\nconst RootLayout: FC<PropsWithChildren> = ({ children }) => <>{children}</>;\n\nexport default RootLayout;\n`;\n\nexport const ROOT_LAYOUT_TEMPLATE_JS = `const RootLayout = ({ children }) => <>{children}</>;\n\nexport default RootLayout;\n`;\n\n/** Locale layout (`app/[locale]/layout.tsx`) providing `<html>` + client provider. */\nexport const LOCALE_LAYOUT_TEMPLATE_TS = `import { type NextLayoutIntlayer, IntlayerClientProvider } from \"next-intlayer\";\nimport { getHTMLTextDir } from \"intlayer\";\n\nexport { generateStaticParams } from \"next-intlayer\";\n\nconst LocaleLayout: NextLayoutIntlayer = async ({ children, params }) => {\n const { locale } = await params;\n\n return (\n <html lang={locale} dir={getHTMLTextDir(locale)}>\n <body>\n <IntlayerClientProvider locale={locale}>\n {children}\n </IntlayerClientProvider>\n </body>\n </html>\n );\n};\n\nexport default LocaleLayout;\n`;\n\nexport const LOCALE_LAYOUT_TEMPLATE_JS = `import { IntlayerClientProvider } from \"next-intlayer\";\nimport { getHTMLTextDir } from \"intlayer\";\n\nexport { generateStaticParams } from \"next-intlayer\";\n\nconst LocaleLayout = async ({ children, params }) => {\n const { locale } = await params;\n\n return (\n <html lang={locale} dir={getHTMLTextDir(locale)}>\n <body>\n <IntlayerClientProvider locale={locale}>\n {children}\n </IntlayerClientProvider>\n </body>\n </html>\n );\n};\n\nexport default LocaleLayout;\n`;\n\n/**\n * Locale home page (`app/[locale]/page.tsx`). Self-contained starter that does\n * not depend on an example content declaration — add Intlayer content (a\n * `*.content.ts` file consumed via `useIntlayer`) as the next step.\n */\nexport const LOCALE_PAGE_TEMPLATE_TS = `import { type NextPageIntlayer } from \"next-intlayer\";\n\nconst Page: NextPageIntlayer = async ({ params }) => {\n const { locale } = await params;\n\n return (\n <main>\n <h1>{locale}</h1>\n <p>Get started by editing this page.</p>\n </main>\n );\n};\n\nexport default Page;\n`;\n\nexport const LOCALE_PAGE_TEMPLATE_JS = `const Page = async ({ params }) => {\n const { locale } = await params;\n\n return (\n <main>\n <h1>{locale}</h1>\n <p>Get started by editing this page.</p>\n </main>\n );\n};\n\nexport default Page;\n`;\n"],"mappings":";;;;;;;;AAOA,MAAa,iBAAiB;;;;;;;;AAS9B,MAAa,sBAAsB;;;;;;;;AASnC,MAAa,0BAA0B;;;;;;AAOvC,MAAa,0BAA0B;;;;;AAMvC,MAAa,4BAA4B;;;;;;;;;;;;;;;;;;;;;AAsBzC,MAAa,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BzC,MAAa,0BAA0B;;;;;;;;;;;;;;;AAgBvC,MAAa,0BAA0B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"detect.cjs","names":["exists"],"sources":["../../../../../src/init/frameworkSetup/tanstackStart/detect.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { exists } from '../../utils/fileSystem';\n\n/** Location of the TanStack Router file-based routes directory. */\nexport type TanStackRoutesInfo = {\n /** Routes directory relative to the root, e.g. `src/routes` or `routes`. */\n routesDir: string;\n /** `src` when the project uses a `src/` directory, otherwise `''`. */\n srcDir: string;\n};\n\n/**\n * Detects the TanStack Router routes directory, preferring `src/routes` over\n * `routes`. Returns `null` when neither exists.\n */\nexport const detectTanStackRoutesDir = async (\n rootDir: string\n): Promise<TanStackRoutesInfo | null> => {\n if (await exists(rootDir, join('src', 'routes'))) {\n return { routesDir: join('src', 'routes'), srcDir: 'src' };\n }\n if (await exists(rootDir, 'routes')) {\n return { routesDir: 'routes', srcDir: '' };\n }\n return null;\n};\n\n/**\n * Returns true when the project depends on TanStack Start (`@tanstack/react-start`)\n * or, failing that, on `@tanstack/react-router` (file-based routing).\n */\nexport const hasTanStackStartDeps = (\n allDeps: Record<string, string>\n): boolean =>\n Boolean(\n allDeps['@tanstack/react-start'] || allDeps['@tanstack/react-router']\n );\n"],"mappings":";;;;;;;;;AAeA,MAAa,0BAA0B,OACrC,YACuC;CACvC,IAAI,MAAMA,qCAAO,
|
|
1
|
+
{"version":3,"file":"detect.cjs","names":["exists","join"],"sources":["../../../../../src/init/frameworkSetup/tanstackStart/detect.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { exists } from '../../utils/fileSystem';\n\n/** Location of the TanStack Router file-based routes directory. */\nexport type TanStackRoutesInfo = {\n /** Routes directory relative to the root, e.g. `src/routes` or `routes`. */\n routesDir: string;\n /** `src` when the project uses a `src/` directory, otherwise `''`. */\n srcDir: string;\n};\n\n/**\n * Detects the TanStack Router routes directory, preferring `src/routes` over\n * `routes`. Returns `null` when neither exists.\n */\nexport const detectTanStackRoutesDir = async (\n rootDir: string\n): Promise<TanStackRoutesInfo | null> => {\n if (await exists(rootDir, join('src', 'routes'))) {\n return { routesDir: join('src', 'routes'), srcDir: 'src' };\n }\n if (await exists(rootDir, 'routes')) {\n return { routesDir: 'routes', srcDir: '' };\n }\n return null;\n};\n\n/**\n * Returns true when the project depends on TanStack Start (`@tanstack/react-start`)\n * or, failing that, on `@tanstack/react-router` (file-based routing).\n */\nexport const hasTanStackStartDeps = (\n allDeps: Record<string, string>\n): boolean =>\n Boolean(\n allDeps['@tanstack/react-start'] || allDeps['@tanstack/react-router']\n );\n"],"mappings":";;;;;;;;;AAeA,MAAa,0BAA0B,OACrC,YACuC;CACvC,IAAI,MAAMA,qCAAO,aAASC,gBAAK,OAAO,QAAQ,CAAC,GAC7C,OAAO;EAAE,eAAWA,gBAAK,OAAO,QAAQ;EAAG,QAAQ;CAAM;CAE3D,IAAI,MAAMD,qCAAO,SAAS,QAAQ,GAChC,OAAO;EAAE,WAAW;EAAU,QAAQ;CAAG;CAE3C,OAAO;AACT;;;;;AAMA,MAAa,wBACX,YAEA,QACE,QAAQ,4BAA4B,QAAQ,yBAC9C"}
|
|
@@ -21,9 +21,7 @@ const logTransformOutcome = (filePath, result) => {
|
|
|
21
21
|
case "already":
|
|
22
22
|
(0, _intlayer_config_logger.logger)(`${_intlayer_config_logger.v} ${(0, _intlayer_config_logger.colorizePath)(filePath)} already wraps the Intlayer provider`);
|
|
23
23
|
break;
|
|
24
|
-
case "skipped":
|
|
25
|
-
(0, _intlayer_config_logger.logger)(`${_intlayer_config_logger.x} Could not safely add the Intlayer provider to ${(0, _intlayer_config_logger.colorizePath)(filePath)} — please wrap the document's {children} with <IntlayerProvider locale={locale}> manually.`, { level: "warn" });
|
|
26
|
-
break;
|
|
24
|
+
case "skipped": (0, _intlayer_config_logger.logger)(`${_intlayer_config_logger.x} Could not safely add the Intlayer provider to ${(0, _intlayer_config_logger.colorizePath)(filePath)} — please wrap the document's {children} with <IntlayerProvider locale={locale}> manually.`, { level: "warn" });
|
|
27
25
|
}
|
|
28
26
|
};
|
|
29
27
|
/** Transforms an existing file in place, writing it back only when changed. */
|
|
@@ -66,8 +64,8 @@ const tanStackStartAdapter = {
|
|
|
66
64
|
await require_init_utils_fileSystem.ensureDirectory(rootDir, localeDir);
|
|
67
65
|
await createIfMissing(rootDir, (0, node_path.join)(localeDir, `route.${scriptExtension}`), require_init_frameworkSetup_tanstackStart_templates.buildLocaleRouteTemplate(activeLocaleSegment), "locale route");
|
|
68
66
|
const existingRoot = await require_init_frameworkSetup_nextAppRouter_detect.findAppFile(rootDir, routesDir, "__root");
|
|
69
|
-
if (existingRoot) await transformExistingFile(rootDir, existingRoot, require_init_frameworkSetup_tanstackStart_transforms.wrapRootWithProvider);
|
|
70
|
-
else await createIfMissing(rootDir, (0, node_path.join)(routesDir, `__root.${scriptExtension}`), useTypeScript ? require_init_frameworkSetup_tanstackStart_templates.
|
|
67
|
+
if (existingRoot) await transformExistingFile(rootDir, existingRoot, (code) => require_init_frameworkSetup_tanstackStart_transforms.wrapRootWithProvider(code, activeLocaleSegment));
|
|
68
|
+
else await createIfMissing(rootDir, (0, node_path.join)(routesDir, `__root.${scriptExtension}`), useTypeScript ? require_init_frameworkSetup_tanstackStart_templates.buildRootTemplateTs(activeLocaleSegment) : require_init_frameworkSetup_tanstackStart_templates.buildRootTemplateJs(activeLocaleSegment), "root document");
|
|
71
69
|
}
|
|
72
70
|
};
|
|
73
71
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["v","x","readFileFromRoot","writeFileToRoot","exists","hasTanStackStartDeps","detectTanStackRoutesDir","getLocaleSegment","ANSIColors","restructureRoutesIntoLocale","ensureDirectory","buildLocaleRouteTemplate","findAppFile","wrapRootWithProvider","
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["v","colorizePath","x","readFileFromRoot","writeFileToRoot","exists","hasTanStackStartDeps","detectTanStackRoutesDir","getLocaleSegment","colorize","ANSIColors","restructureRoutesIntoLocale","join","ensureDirectory","buildLocaleRouteTemplate","findAppFile","wrapRootWithProvider","buildRootTemplateTs","buildRootTemplateJs"],"sources":["../../../../../src/init/frameworkSetup/tanstackStart/index.ts"],"sourcesContent":["import { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, logger, v, x } from '@intlayer/config/logger';\nimport {\n ensureDirectory,\n exists,\n readFileFromRoot,\n writeFileToRoot,\n} from '../../utils/fileSystem';\nimport { findAppFile } from '../nextAppRouter/detect';\nimport type { FrameworkAdapter, FrameworkSetupContext } from '../types';\nimport { detectTanStackRoutesDir, hasTanStackStartDeps } from './detect';\nimport { getLocaleSegment, restructureRoutesIntoLocale } from './restructure';\nimport {\n buildLocaleRouteTemplate,\n buildRootTemplateJs,\n buildRootTemplateTs,\n} from './templates';\nimport { type TransformResult, wrapRootWithProvider } from './transforms';\n\n/** Logs the outcome of the root-document provider-wrap transform. */\nconst logTransformOutcome = (\n filePath: string,\n result: TransformResult\n): void => {\n switch (result.status) {\n case 'wrapped':\n logger(`${v} Added Intlayer provider to ${colorizePath(filePath)}`);\n break;\n case 'already':\n logger(\n `${v} ${colorizePath(filePath)} already wraps the Intlayer provider`\n );\n break;\n case 'skipped':\n logger(\n `${x} Could not safely add the Intlayer provider to ${colorizePath(filePath)} — please wrap the document's {children} with <IntlayerProvider locale={locale}> manually.`,\n { level: 'warn' }\n );\n break;\n }\n};\n\n/** Transforms an existing file in place, writing it back only when changed. */\nconst transformExistingFile = async (\n rootDir: string,\n filePath: string,\n transform: (code: string) => TransformResult\n): Promise<void> => {\n const code = await readFileFromRoot(rootDir, filePath);\n const result = transform(code);\n if (result.status === 'wrapped') {\n await writeFileToRoot(rootDir, filePath, result.code);\n }\n logTransformOutcome(filePath, result);\n};\n\n/** Creates a file from a template only when it does not already exist. */\nconst createIfMissing = async (\n rootDir: string,\n filePath: string,\n content: string,\n description: string\n): Promise<boolean> => {\n if (await exists(rootDir, filePath)) return false;\n await writeFileToRoot(rootDir, filePath, content);\n logger(`${v} Created ${description} ${colorizePath(filePath)}`);\n return true;\n};\n\n/**\n * TanStack Start adapter. Restructures the file-based routes under a `{-$locale}`\n * segment, scaffolds the locale segment route, and wraps the root document with\n * the Intlayer provider — all idempotently and without overwriting user code it\n * cannot confidently transform.\n */\nexport const tanStackStartAdapter: FrameworkAdapter = {\n name: 'TanStack Start',\n\n detect: async ({ rootDir, allDeps }) => {\n if (!hasTanStackStartDeps(allDeps)) return false;\n return (await detectTanStackRoutesDir(rootDir)) !== null;\n },\n\n setup: async ({\n rootDir,\n useTypeScript,\n routingMode,\n }: FrameworkSetupContext) => {\n const routesInfo = await detectTanStackRoutesDir(rootDir);\n if (!routesInfo) return;\n\n const { routesDir } = routesInfo;\n const scriptExtension = useTypeScript ? 'tsx' : 'jsx';\n\n // `prefix-all` needs the required `$locale` segment; every other mode uses\n // the optional `{-$locale}` segment so the default locale stays prefix-free.\n const targetLocaleSegment = getLocaleSegment(routingMode);\n\n logger(\n colorize('Setting up TanStack Start integration...', ANSIColors.CYAN)\n );\n\n // 1. Move routable route entries under the locale segment (idempotent).\n const restructureResult = await restructureRoutesIntoLocale(\n rootDir,\n routesDir,\n targetLocaleSegment\n );\n if (restructureResult.status === 'moved') {\n logger(\n `${v} Restructured routes under ${colorizePath(join(routesDir, targetLocaleSegment))}: ${restructureResult.movedEntries\n .map((entry) => colorize(entry, ANSIColors.MAGENTA))\n .join(', ')}`\n );\n } else if (restructureResult.status === 'already-structured') {\n logger(\n `${v} ${colorizePath(join(routesDir, restructureResult.localeSegment))} already exists, skipping restructure`\n );\n }\n\n // Scaffold the locale route for the segment actually in use: a pre-existing\n // segment (e.g. a prefix-all `$locale` the user already set up) wins over the\n // target, so we never create a second, conflicting locale segment.\n const activeLocaleSegment =\n restructureResult.status === 'already-structured'\n ? restructureResult.localeSegment\n : targetLocaleSegment;\n\n const localeDir = join(routesDir, activeLocaleSegment);\n await ensureDirectory(rootDir, localeDir);\n\n // 2. Locale segment route (`<segment>/route.tsx`) — create when absent.\n await createIfMissing(\n rootDir,\n join(localeDir, `route.${scriptExtension}`),\n buildLocaleRouteTemplate(activeLocaleSegment),\n 'locale route'\n );\n\n // 3. Root document — transform an existing `__root`, else scaffold one.\n const existingRoot = await findAppFile(rootDir, routesDir, '__root');\n if (existingRoot) {\n await transformExistingFile(rootDir, existingRoot, (code) =>\n wrapRootWithProvider(code, activeLocaleSegment)\n );\n } else {\n await createIfMissing(\n rootDir,\n join(routesDir, `__root.${scriptExtension}`),\n useTypeScript\n ? buildRootTemplateTs(activeLocaleSegment)\n : buildRootTemplateJs(activeLocaleSegment),\n 'root document'\n );\n }\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,MAAM,uBACJ,UACA,WACS;CACT,QAAQ,OAAO,QAAf;EACE,KAAK;GACH,oCAAO,GAAGA,0BAAE,kCAA8BC,sCAAa,QAAQ,GAAG;GAClE;EACF,KAAK;GACH,oCACE,GAAGD,0BAAE,OAAGC,sCAAa,QAAQ,EAAE,qCACjC;GACA;EACF,KAAK,WACH,oCACE,GAAGC,0BAAE,qDAAiDD,sCAAa,QAAQ,EAAE,6FAC7E,EAAE,OAAO,OAAO,CAClB;CAEJ;AACF;;AAGA,MAAM,wBAAwB,OAC5B,SACA,UACA,cACkB;CAElB,MAAM,SAAS,UAAU,MADNE,+CAAiB,SAAS,QAAQ,CACxB;CAC7B,IAAI,OAAO,WAAW,WACpB,MAAMC,8CAAgB,SAAS,UAAU,OAAO,IAAI;CAEtD,oBAAoB,UAAU,MAAM;AACtC;;AAGA,MAAM,kBAAkB,OACtB,SACA,UACA,SACA,gBACqB;CACrB,IAAI,MAAMC,qCAAO,SAAS,QAAQ,GAAG,OAAO;CAC5C,MAAMD,8CAAgB,SAAS,UAAU,OAAO;CAChD,oCAAO,GAAGJ,0BAAE,WAAW,YAAY,OAAGC,sCAAa,QAAQ,GAAG;CAC9D,OAAO;AACT;;;;;;;AAQA,MAAa,uBAAyC;CACpD,MAAM;CAEN,QAAQ,OAAO,EAAE,SAAS,cAAc;EACtC,IAAI,CAACK,sEAAqB,OAAO,GAAG,OAAO;EAC3C,OAAQ,MAAMC,yEAAwB,OAAO,MAAO;CACtD;CAEA,OAAO,OAAO,EACZ,SACA,eACA,kBAC2B;EAC3B,MAAM,aAAa,MAAMA,yEAAwB,OAAO;EACxD,IAAI,CAAC,YAAY;EAEjB,MAAM,EAAE,cAAc;EACtB,MAAM,kBAAkB,gBAAgB,QAAQ;EAIhD,MAAM,sBAAsBC,uEAAiB,WAAW;EAExD,wCACEC,kCAAS,4CAA4CC,wBAAW,IAAI,CACtE;EAGA,MAAM,oBAAoB,MAAMC,kFAC9B,SACA,WACA,mBACF;EACA,IAAI,kBAAkB,WAAW,SAC/B,oCACE,GAAGX,0BAAE,iCAA6BC,0CAAaW,gBAAK,WAAW,mBAAmB,CAAC,EAAE,IAAI,kBAAkB,aACxG,KAAK,cAAUH,kCAAS,OAAOC,wBAAW,OAAO,CAAC,CAAC,CACnD,KAAK,IAAI,GACd;OACK,IAAI,kBAAkB,WAAW,sBACtC,oCACE,GAAGV,0BAAE,OAAGC,0CAAaW,gBAAK,WAAW,kBAAkB,aAAa,CAAC,EAAE,sCACzE;EAMF,MAAM,sBACJ,kBAAkB,WAAW,uBACzB,kBAAkB,gBAClB;EAEN,MAAM,gBAAYA,gBAAK,WAAW,mBAAmB;EACrD,MAAMC,8CAAgB,SAAS,SAAS;EAGxC,MAAM,gBACJ,aACAD,gBAAK,WAAW,SAAS,iBAAiB,GAC1CE,6EAAyB,mBAAmB,GAC5C,cACF;EAGA,MAAM,eAAe,MAAMC,6DAAY,SAAS,WAAW,QAAQ;EACnE,IAAI,cACF,MAAM,sBAAsB,SAAS,eAAe,SAClDC,0EAAqB,MAAM,mBAAmB,CAChD;OAEA,MAAM,gBACJ,aACAJ,gBAAK,WAAW,UAAU,iBAAiB,GAC3C,gBACIK,wEAAoB,mBAAmB,IACvCC,wEAAoB,mBAAmB,GAC3C,eACF;CAEJ;AACF"}
|
|
@@ -95,7 +95,8 @@ const restructureRoutesIntoLocale = async (rootDir, routesDir, localeSegment = L
|
|
|
95
95
|
movedTopLevelNames
|
|
96
96
|
};
|
|
97
97
|
for (const newAbs of movedFiles) {
|
|
98
|
-
const
|
|
98
|
+
const relFromLocale = (0, node_path.relative)(localeDirAbs, newAbs);
|
|
99
|
+
const oldAbs = (0, node_path.join)(routesDirAbs, relFromLocale);
|
|
99
100
|
const code = await (0, node_fs_promises.readFile)(newAbs, "utf8");
|
|
100
101
|
const rewritten = require_init_frameworkSetup_nextAppRouter_restructure.rewriteRelativeImports(code, oldAbs, newAbs, rewriteContext);
|
|
101
102
|
if (rewritten !== code) await (0, node_fs_promises.writeFile)(newAbs, rewritten, "utf8");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"restructure.cjs","names":["rewriteRelativeImports"],"sources":["../../../../../src/init/frameworkSetup/tanstackStart/restructure.ts"],"sourcesContent":["import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport fg from 'fast-glob';\nimport type { RoutingMode } from '../../utils/configManipulation';\nimport { rewriteRelativeImports } from '../nextAppRouter/restructure';\n\n/** Source file extensions whose relative imports must be rewritten after a move. */\nconst SCRIPT_GLOB = '**/*.{ts,tsx,js,jsx,mjs,cjs}';\n\n/**\n * The optional TanStack Router locale segment directory (`{-$locale}` param),\n * used by every routing mode except `prefix-all` so the default locale stays\n * prefix-free.\n */\nexport const LOCALE_SEGMENT = '{-$locale}';\n\n/**\n * The required TanStack Router locale segment directory (`$locale` param), used\n * by `prefix-all` routing where every URL — including the default locale — is\n * prefixed.\n */\nexport const PREFIX_ALL_LOCALE_SEGMENT = '$locale';\n\n/**\n * Picks the locale segment directory for the project's routing mode. `prefix-all`\n * requires the mandatory `$locale` param so the default locale is also prefixed;\n * all other modes use the optional `{-$locale}` param so the default locale stays\n * prefix-free.\n */\nexport const getLocaleSegment = (routingMode: RoutingMode): string =>\n routingMode === 'prefix-all' ? PREFIX_ALL_LOCALE_SEGMENT : LOCALE_SEGMENT;\n\n/**\n * Detects whether a top-level route entry is already a locale segment, in any of\n * the TanStack Router param forms:\n * - `{-$locale}` — optional param (prefix every locale except the default),\n * - `$locale` / `{$locale}` — required param (prefix **all** locales).\n *\n * Used to skip the restructure when the project is already locale-aware, so an\n * existing prefix-all `$locale` directory is never nested under a freshly created\n * `{-$locale}` (which would produce `{-$locale}/$locale`).\n */\nexport const isLocaleSegment = (entryName: string): boolean =>\n /^(\\{-?\\$locale\\}|\\$locale)$/.test(entryName);\n\n/** Strips a known script extension from a file name, e.g. `index.tsx` -> `index`. */\nconst stripScriptExtension = (fileName: string): string =>\n fileName.replace(/\\.(tsx|ts|jsx|js|mjs|cjs)$/, '');\n\n/**\n * Routes-directory entries that must stay at the root and never be moved under\n * `{-$locale}`:\n * - `__root` (the root route document),\n * - `routeTree.gen` (generated route tree),\n * - `api` (server / API routes — these are not locale-prefixed),\n * - TanStack-ignored entries prefixed with `-` (e.g. `-components`, `-utils`),\n * - stylesheets.\n *\n * Everything else (route files and nested route folders) is moved so it becomes\n * locale-aware.\n */\nexport const shouldKeepRouteAtRoot = (entryName: string): boolean => {\n if (entryName.startsWith('-')) return true;\n if (entryName.toLowerCase().endsWith('.css')) return true;\n\n const base = stripScriptExtension(entryName);\n const keepExactBases = new Set(['__root', 'routeTree.gen', 'api']);\n return keepExactBases.has(base);\n};\n\n/** Outcome of an attempted `{-$locale}` restructure. */\nexport type RestructureResult =\n | { status: 'already-structured'; localeSegment: string }\n | { status: 'nothing-to-move' }\n | { status: 'moved'; movedEntries: string[] };\n\n/**\n * Moves the routable entries of `routesDir` under a new `localeSegment` directory\n * (the optional `{-$locale}` by default, or the required `$locale` for\n * `prefix-all`) and rewrites relative imports in the moved files. Idempotent: a\n * no-op when the routes are already locale-aware in any prefix mode (see\n * {@link isLocaleSegment}), which is reported via `localeSegment`. Root-only\n * files (see {@link shouldKeepRouteAtRoot}) are left in place.\n */\nexport const restructureRoutesIntoLocale = async (\n rootDir: string,\n routesDir: string,\n localeSegment: string = LOCALE_SEGMENT\n): Promise<RestructureResult> => {\n const routesDirAbs = join(rootDir, routesDir);\n const localeDirAbs = join(routesDirAbs, localeSegment);\n\n const entries = await readdir(routesDirAbs, { withFileTypes: true });\n\n // Skip when the routes are already locale-aware in any prefix mode — a fresh\n // `{-$locale}`, or an existing `$locale` / `{$locale}` (prefix-all) segment.\n const existingLocaleSegment = entries.find((entry) =>\n isLocaleSegment(entry.name)\n );\n if (existingLocaleSegment) {\n return {\n status: 'already-structured',\n localeSegment: existingLocaleSegment.name,\n };\n }\n\n const movedTopLevelNames = entries\n .map((entry) => entry.name)\n .filter((name) => !shouldKeepRouteAtRoot(name));\n\n if (movedTopLevelNames.length === 0) {\n return { status: 'nothing-to-move' };\n }\n\n await mkdir(localeDirAbs, { recursive: true });\n\n for (const name of movedTopLevelNames) {\n await rename(join(routesDirAbs, name), join(localeDirAbs, name));\n }\n\n const movedFiles = await fg(SCRIPT_GLOB, {\n cwd: localeDirAbs,\n absolute: true,\n onlyFiles: true,\n });\n\n const rewriteContext = {\n appDirAbs: routesDirAbs,\n localeDirAbs,\n movedTopLevelNames,\n };\n\n for (const newAbs of movedFiles) {\n const relFromLocale = relative(localeDirAbs, newAbs);\n const oldAbs = join(routesDirAbs, relFromLocale);\n const code = await readFile(newAbs, 'utf8');\n const rewritten = rewriteRelativeImports(\n code,\n oldAbs,\n newAbs,\n rewriteContext\n );\n if (rewritten !== code) {\n await writeFile(newAbs, rewritten, 'utf8');\n }\n }\n\n return { status: 'moved', movedEntries: movedTopLevelNames };\n};\n"],"mappings":";;;;;;;;;;AAOA,MAAM,cAAc;;;;;;AAOpB,MAAa,iBAAiB;;;;;;AAO9B,MAAa,4BAA4B;;;;;;;AAQzC,MAAa,oBAAoB,gBAC/B,gBAAgB,eAAe,4BAA4B;;;;;;;;;;;AAY7D,MAAa,mBAAmB,cAC9B,8BAA8B,KAAK,SAAS;;AAG9C,MAAM,wBAAwB,aAC5B,SAAS,QAAQ,8BAA8B,EAAE;;;;;;;;;;;;;AAcnD,MAAa,yBAAyB,cAA+B;CACnE,IAAI,UAAU,WAAW,GAAG,GAAG,OAAO;CACtC,IAAI,UAAU,YAAY,CAAC,CAAC,SAAS,MAAM,GAAG,OAAO;CAErD,MAAM,OAAO,qBAAqB,SAAS;CAE3C,wBAAO,IADoB,IAAI;EAAC;EAAU;EAAiB;CAAK,CAC5C,EAAC,CAAC,IAAI,IAAI;AAChC;;;;;;;;;AAgBA,MAAa,8BAA8B,OACzC,SACA,WACA,gBAAwB,mBACO;CAC/B,MAAM,
|
|
1
|
+
{"version":3,"file":"restructure.cjs","names":["join","readdir","mkdir","rename","fg","relative","readFile","rewriteRelativeImports","writeFile"],"sources":["../../../../../src/init/frameworkSetup/tanstackStart/restructure.ts"],"sourcesContent":["import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport fg from 'fast-glob';\nimport type { RoutingMode } from '../../utils/configManipulation';\nimport { rewriteRelativeImports } from '../nextAppRouter/restructure';\n\n/** Source file extensions whose relative imports must be rewritten after a move. */\nconst SCRIPT_GLOB = '**/*.{ts,tsx,js,jsx,mjs,cjs}';\n\n/**\n * The optional TanStack Router locale segment directory (`{-$locale}` param),\n * used by every routing mode except `prefix-all` so the default locale stays\n * prefix-free.\n */\nexport const LOCALE_SEGMENT = '{-$locale}';\n\n/**\n * The required TanStack Router locale segment directory (`$locale` param), used\n * by `prefix-all` routing where every URL — including the default locale — is\n * prefixed.\n */\nexport const PREFIX_ALL_LOCALE_SEGMENT = '$locale';\n\n/**\n * Picks the locale segment directory for the project's routing mode. `prefix-all`\n * requires the mandatory `$locale` param so the default locale is also prefixed;\n * all other modes use the optional `{-$locale}` param so the default locale stays\n * prefix-free.\n */\nexport const getLocaleSegment = (routingMode: RoutingMode): string =>\n routingMode === 'prefix-all' ? PREFIX_ALL_LOCALE_SEGMENT : LOCALE_SEGMENT;\n\n/**\n * Detects whether a top-level route entry is already a locale segment, in any of\n * the TanStack Router param forms:\n * - `{-$locale}` — optional param (prefix every locale except the default),\n * - `$locale` / `{$locale}` — required param (prefix **all** locales).\n *\n * Used to skip the restructure when the project is already locale-aware, so an\n * existing prefix-all `$locale` directory is never nested under a freshly created\n * `{-$locale}` (which would produce `{-$locale}/$locale`).\n */\nexport const isLocaleSegment = (entryName: string): boolean =>\n /^(\\{-?\\$locale\\}|\\$locale)$/.test(entryName);\n\n/** Strips a known script extension from a file name, e.g. `index.tsx` -> `index`. */\nconst stripScriptExtension = (fileName: string): string =>\n fileName.replace(/\\.(tsx|ts|jsx|js|mjs|cjs)$/, '');\n\n/**\n * Routes-directory entries that must stay at the root and never be moved under\n * `{-$locale}`:\n * - `__root` (the root route document),\n * - `routeTree.gen` (generated route tree),\n * - `api` (server / API routes — these are not locale-prefixed),\n * - TanStack-ignored entries prefixed with `-` (e.g. `-components`, `-utils`),\n * - stylesheets.\n *\n * Everything else (route files and nested route folders) is moved so it becomes\n * locale-aware.\n */\nexport const shouldKeepRouteAtRoot = (entryName: string): boolean => {\n if (entryName.startsWith('-')) return true;\n if (entryName.toLowerCase().endsWith('.css')) return true;\n\n const base = stripScriptExtension(entryName);\n const keepExactBases = new Set(['__root', 'routeTree.gen', 'api']);\n return keepExactBases.has(base);\n};\n\n/** Outcome of an attempted `{-$locale}` restructure. */\nexport type RestructureResult =\n | { status: 'already-structured'; localeSegment: string }\n | { status: 'nothing-to-move' }\n | { status: 'moved'; movedEntries: string[] };\n\n/**\n * Moves the routable entries of `routesDir` under a new `localeSegment` directory\n * (the optional `{-$locale}` by default, or the required `$locale` for\n * `prefix-all`) and rewrites relative imports in the moved files. Idempotent: a\n * no-op when the routes are already locale-aware in any prefix mode (see\n * {@link isLocaleSegment}), which is reported via `localeSegment`. Root-only\n * files (see {@link shouldKeepRouteAtRoot}) are left in place.\n */\nexport const restructureRoutesIntoLocale = async (\n rootDir: string,\n routesDir: string,\n localeSegment: string = LOCALE_SEGMENT\n): Promise<RestructureResult> => {\n const routesDirAbs = join(rootDir, routesDir);\n const localeDirAbs = join(routesDirAbs, localeSegment);\n\n const entries = await readdir(routesDirAbs, { withFileTypes: true });\n\n // Skip when the routes are already locale-aware in any prefix mode — a fresh\n // `{-$locale}`, or an existing `$locale` / `{$locale}` (prefix-all) segment.\n const existingLocaleSegment = entries.find((entry) =>\n isLocaleSegment(entry.name)\n );\n if (existingLocaleSegment) {\n return {\n status: 'already-structured',\n localeSegment: existingLocaleSegment.name,\n };\n }\n\n const movedTopLevelNames = entries\n .map((entry) => entry.name)\n .filter((name) => !shouldKeepRouteAtRoot(name));\n\n if (movedTopLevelNames.length === 0) {\n return { status: 'nothing-to-move' };\n }\n\n await mkdir(localeDirAbs, { recursive: true });\n\n for (const name of movedTopLevelNames) {\n await rename(join(routesDirAbs, name), join(localeDirAbs, name));\n }\n\n const movedFiles = await fg(SCRIPT_GLOB, {\n cwd: localeDirAbs,\n absolute: true,\n onlyFiles: true,\n });\n\n const rewriteContext = {\n appDirAbs: routesDirAbs,\n localeDirAbs,\n movedTopLevelNames,\n };\n\n for (const newAbs of movedFiles) {\n const relFromLocale = relative(localeDirAbs, newAbs);\n const oldAbs = join(routesDirAbs, relFromLocale);\n const code = await readFile(newAbs, 'utf8');\n const rewritten = rewriteRelativeImports(\n code,\n oldAbs,\n newAbs,\n rewriteContext\n );\n if (rewritten !== code) {\n await writeFile(newAbs, rewritten, 'utf8');\n }\n }\n\n return { status: 'moved', movedEntries: movedTopLevelNames };\n};\n"],"mappings":";;;;;;;;;;AAOA,MAAM,cAAc;;;;;;AAOpB,MAAa,iBAAiB;;;;;;AAO9B,MAAa,4BAA4B;;;;;;;AAQzC,MAAa,oBAAoB,gBAC/B,gBAAgB,eAAe,4BAA4B;;;;;;;;;;;AAY7D,MAAa,mBAAmB,cAC9B,8BAA8B,KAAK,SAAS;;AAG9C,MAAM,wBAAwB,aAC5B,SAAS,QAAQ,8BAA8B,EAAE;;;;;;;;;;;;;AAcnD,MAAa,yBAAyB,cAA+B;CACnE,IAAI,UAAU,WAAW,GAAG,GAAG,OAAO;CACtC,IAAI,UAAU,YAAY,CAAC,CAAC,SAAS,MAAM,GAAG,OAAO;CAErD,MAAM,OAAO,qBAAqB,SAAS;CAE3C,wBAAO,IADoB,IAAI;EAAC;EAAU;EAAiB;CAAK,CAC5C,EAAC,CAAC,IAAI,IAAI;AAChC;;;;;;;;;AAgBA,MAAa,8BAA8B,OACz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
* File templates for a fresh TanStack Start integration. These are only written
|
|
@@ -35,25 +34,30 @@ export const Route = createFileRoute("/${localeSegment}")({
|
|
|
35
34
|
`;
|
|
36
35
|
/**
|
|
37
36
|
* Root route document (`routes/__root.tsx`) providing `<html>` + the Intlayer
|
|
38
|
-
* provider, with the locale read from the
|
|
37
|
+
* provider, with the locale read from the locale segment route params.
|
|
38
|
+
*
|
|
39
|
+
* The route is reached through `getRouteApi(<route id>)` rather than by
|
|
40
|
+
* importing `<segment>/route`, so the root never imports a child route module —
|
|
41
|
+
* the recommended way to consume another route's typed hooks.
|
|
39
42
|
*/
|
|
40
|
-
const
|
|
43
|
+
const buildRootTemplateTs = (localeSegment) => `import {
|
|
41
44
|
createRootRoute,
|
|
45
|
+
getRouteApi,
|
|
42
46
|
HeadContent,
|
|
43
47
|
Scripts,
|
|
44
|
-
useParams,
|
|
45
48
|
} from "@tanstack/react-router";
|
|
46
49
|
import { defaultLocale, getHTMLTextDir } from "intlayer";
|
|
47
50
|
import type { ReactNode } from "react";
|
|
48
51
|
import { IntlayerProvider } from "react-intlayer";
|
|
49
52
|
|
|
53
|
+
const localeRoute = getRouteApi("/${localeSegment}");
|
|
54
|
+
|
|
50
55
|
export const Route = createRootRoute({
|
|
51
56
|
shellComponent: RootDocument,
|
|
52
57
|
});
|
|
53
58
|
|
|
54
59
|
function RootDocument({ children }: { children: ReactNode }) {
|
|
55
|
-
const
|
|
56
|
-
const locale = params.locale ?? defaultLocale;
|
|
60
|
+
const { locale = defaultLocale } = localeRoute.useParams();
|
|
57
61
|
|
|
58
62
|
return (
|
|
59
63
|
<html dir={getHTMLTextDir(locale)} lang={locale}>
|
|
@@ -68,22 +72,24 @@ function RootDocument({ children }: { children: ReactNode }) {
|
|
|
68
72
|
);
|
|
69
73
|
}
|
|
70
74
|
`;
|
|
71
|
-
|
|
75
|
+
/** JavaScript counterpart of {@link buildRootTemplateTs}. */
|
|
76
|
+
const buildRootTemplateJs = (localeSegment) => `import {
|
|
72
77
|
createRootRoute,
|
|
78
|
+
getRouteApi,
|
|
73
79
|
HeadContent,
|
|
74
80
|
Scripts,
|
|
75
|
-
useParams,
|
|
76
81
|
} from "@tanstack/react-router";
|
|
77
82
|
import { defaultLocale, getHTMLTextDir } from "intlayer";
|
|
78
83
|
import { IntlayerProvider } from "react-intlayer";
|
|
79
84
|
|
|
85
|
+
const localeRoute = getRouteApi("/${localeSegment}");
|
|
86
|
+
|
|
80
87
|
export const Route = createRootRoute({
|
|
81
88
|
shellComponent: RootDocument,
|
|
82
89
|
});
|
|
83
90
|
|
|
84
91
|
function RootDocument({ children }) {
|
|
85
|
-
const
|
|
86
|
-
const locale = params.locale ?? defaultLocale;
|
|
92
|
+
const { locale = defaultLocale } = localeRoute.useParams();
|
|
87
93
|
|
|
88
94
|
return (
|
|
89
95
|
<html dir={getHTMLTextDir(locale)} lang={locale}>
|
|
@@ -100,7 +106,7 @@ function RootDocument({ children }) {
|
|
|
100
106
|
`;
|
|
101
107
|
|
|
102
108
|
//#endregion
|
|
103
|
-
exports.ROOT_TEMPLATE_JS = ROOT_TEMPLATE_JS;
|
|
104
|
-
exports.ROOT_TEMPLATE_TS = ROOT_TEMPLATE_TS;
|
|
105
109
|
exports.buildLocaleRouteTemplate = buildLocaleRouteTemplate;
|
|
110
|
+
exports.buildRootTemplateJs = buildRootTemplateJs;
|
|
111
|
+
exports.buildRootTemplateTs = buildRootTemplateTs;
|
|
106
112
|
//# sourceMappingURL=templates.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.cjs","names":[],"sources":["../../../../../src/init/frameworkSetup/tanstackStart/templates.ts"],"sourcesContent":["/**\n * File templates for a fresh TanStack Start integration. These are only written\n * when the target file does not exist — they never overwrite user code.\n */\n\n/**\n * Builds the locale segment route (`routes/<localeSegment>/route.tsx`) for the\n * given segment. The optional `{-$locale}` param makes the default locale\n * prefix-free, while the required `$locale` param (`prefix-all`) prefixes every\n * locale; in both cases `validatePrefix` redirects unknown prefixes to a valid\n * one. Identical for TypeScript and JavaScript projects.\n */\nexport const buildLocaleRouteTemplate = (\n localeSegment: string\n): string => `import { createFileRoute, Outlet, redirect } from \"@tanstack/react-router\";\nimport { validatePrefix } from \"intlayer\";\n\nexport const Route = createFileRoute(\"/${localeSegment}\")({\n beforeLoad: ({ params }) => {\n // beforeLoad runs on both client and server, so resolve the locale from the\n // route params rather than from request headers.\n const { isValid, localePrefix } = validatePrefix(params.locale);\n\n // A valid (or absent, i.e. default) locale prefix is fine as-is.\n if (isValid) return;\n\n // Otherwise redirect to the same route with a valid locale prefix.\n throw redirect({\n params: { locale: localePrefix },\n to: \"/${localeSegment}\",\n });\n },\n component: Outlet,\n});\n`;\n\n/**\n * Root route document (`routes/__root.tsx`) providing `<html>` + the Intlayer\n * provider, with the locale read from the
|
|
1
|
+
{"version":3,"file":"templates.cjs","names":[],"sources":["../../../../../src/init/frameworkSetup/tanstackStart/templates.ts"],"sourcesContent":["/**\n * File templates for a fresh TanStack Start integration. These are only written\n * when the target file does not exist — they never overwrite user code.\n */\n\n/**\n * Builds the locale segment route (`routes/<localeSegment>/route.tsx`) for the\n * given segment. The optional `{-$locale}` param makes the default locale\n * prefix-free, while the required `$locale` param (`prefix-all`) prefixes every\n * locale; in both cases `validatePrefix` redirects unknown prefixes to a valid\n * one. Identical for TypeScript and JavaScript projects.\n */\nexport const buildLocaleRouteTemplate = (\n localeSegment: string\n): string => `import { createFileRoute, Outlet, redirect } from \"@tanstack/react-router\";\nimport { validatePrefix } from \"intlayer\";\n\nexport const Route = createFileRoute(\"/${localeSegment}\")({\n beforeLoad: ({ params }) => {\n // beforeLoad runs on both client and server, so resolve the locale from the\n // route params rather than from request headers.\n const { isValid, localePrefix } = validatePrefix(params.locale);\n\n // A valid (or absent, i.e. default) locale prefix is fine as-is.\n if (isValid) return;\n\n // Otherwise redirect to the same route with a valid locale prefix.\n throw redirect({\n params: { locale: localePrefix },\n to: \"/${localeSegment}\",\n });\n },\n component: Outlet,\n});\n`;\n\n/**\n * Root route document (`routes/__root.tsx`) providing `<html>` + the Intlayer\n * provider, with the locale read from the locale segment route params.\n *\n * The route is reached through `getRouteApi(<route id>)` rather than by\n * importing `<segment>/route`, so the root never imports a child route module —\n * the recommended way to consume another route's typed hooks.\n */\nexport const buildRootTemplateTs = (localeSegment: string): string => `import {\n createRootRoute,\n getRouteApi,\n HeadContent,\n Scripts,\n} from \"@tanstack/react-router\";\nimport { defaultLocale, getHTMLTextDir } from \"intlayer\";\nimport type { ReactNode } from \"react\";\nimport { IntlayerProvider } from \"react-intlayer\";\n\nconst localeRoute = getRouteApi(\"/${localeSegment}\");\n\nexport const Route = createRootRoute({\n shellComponent: RootDocument,\n});\n\nfunction RootDocument({ children }: { children: ReactNode }) {\n const { locale = defaultLocale } = localeRoute.useParams();\n\n return (\n <html dir={getHTMLTextDir(locale)} lang={locale}>\n <head>\n <HeadContent />\n </head>\n <body>\n <IntlayerProvider locale={locale}>{children}</IntlayerProvider>\n <Scripts />\n </body>\n </html>\n );\n}\n`;\n\n/** JavaScript counterpart of {@link buildRootTemplateTs}. */\nexport const buildRootTemplateJs = (localeSegment: string): string => `import {\n createRootRoute,\n getRouteApi,\n HeadContent,\n Scripts,\n} from \"@tanstack/react-router\";\nimport { defaultLocale, getHTMLTextDir } from \"intlayer\";\nimport { IntlayerProvider } from \"react-intlayer\";\n\nconst localeRoute = getRouteApi(\"/${localeSegment}\");\n\nexport const Route = createRootRoute({\n shellComponent: RootDocument,\n});\n\nfunction RootDocument({ children }) {\n const { locale = defaultLocale } = localeRoute.useParams();\n\n return (\n <html dir={getHTMLTextDir(locale)} lang={locale}>\n <head>\n <HeadContent />\n </head>\n <body>\n <IntlayerProvider locale={locale}>{children}</IntlayerProvider>\n <Scripts />\n </body>\n </html>\n );\n}\n`;\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,4BACX,kBACW;;;yCAG4B,cAAc;;;;;;;;;;;;cAYzC,cAAc;;;;;;;;;;;;;;AAe5B,MAAa,uBAAuB,kBAAkC;;;;;;;;;;oCAUlC,cAAc;;;;;;;;;;;;;;;;;;;;;;;AAwBlD,MAAa,uBAAuB,kBAAkC;;;;;;;;;oCASlC,cAAc"}
|
|
@@ -7,6 +7,8 @@ recast = require_runtime.__toESM(recast);
|
|
|
7
7
|
|
|
8
8
|
//#region src/init/frameworkSetup/tanstackStart/transforms.ts
|
|
9
9
|
const { builders: b, namedTypes: n } = recast.types;
|
|
10
|
+
/** Module-scope identifier bound to the locale route's typed API. */
|
|
11
|
+
const LOCALE_ROUTE_API_VARIABLE = "localeRoute";
|
|
10
12
|
/** babel-ts parser handles TypeScript *and* JSX. */
|
|
11
13
|
const parseTsx = (code) => recast.parse(code, { parser: require_utils_babelParser.babelTsParser });
|
|
12
14
|
/**
|
|
@@ -51,27 +53,59 @@ const patternBindsName = (node, name) => {
|
|
|
51
53
|
}
|
|
52
54
|
};
|
|
53
55
|
/**
|
|
54
|
-
* Inserts `const locale =
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
56
|
+
* Inserts `const { locale = defaultLocale } = localeRoute.useParams();` once, at
|
|
57
|
+
* the top of the function body. The destructuring form binds only `locale`, so
|
|
58
|
+
* it can never collide with a `params` variable the document already declares.
|
|
59
|
+
* Expression-bodied arrow functions are first converted to a block so the
|
|
60
|
+
* declaration has somewhere to live.
|
|
59
61
|
*
|
|
60
62
|
* No-ops when `locale` is already bound in the function — whether as a simple
|
|
61
63
|
* identifier, through a destructuring pattern (e.g.
|
|
62
|
-
* `const { locale = defaultLocale } = useLoaderData()`), or as a function
|
|
64
|
+
* `const { locale = defaultLocale } = Route.useLoaderData()`), or as a function
|
|
63
65
|
* parameter — so the injected declaration never collides with one the document
|
|
64
66
|
* already provides (which would produce an
|
|
65
67
|
* `Identifier 'locale' has already been declared` parse error).
|
|
68
|
+
*
|
|
69
|
+
* @returns `true` when the declaration was injected, `false` when the document
|
|
70
|
+
* already binds `locale` itself. Callers use this to skip the imports and the
|
|
71
|
+
* route API declaration the injected statement would have needed.
|
|
66
72
|
*/
|
|
67
73
|
const ensureLocaleFromParams = (funcNode) => {
|
|
68
74
|
if (funcNode.body?.type !== "BlockStatement") funcNode.body = b.blockStatement([b.returnStatement(funcNode.body)]);
|
|
69
75
|
const declaredInBody = funcNode.body.body.some((stmt) => stmt.type === "VariableDeclaration" && stmt.declarations.some((d) => patternBindsName(d.id, "locale")));
|
|
70
76
|
const declaredInParams = (funcNode.params ?? []).some((param) => patternBindsName(param, "locale"));
|
|
71
|
-
if (declaredInBody || declaredInParams) return;
|
|
72
|
-
const statement = parseTsx(
|
|
77
|
+
if (declaredInBody || declaredInParams) return false;
|
|
78
|
+
const statement = parseTsx(`const { locale = defaultLocale } = ${LOCALE_ROUTE_API_VARIABLE}.useParams();`).program.body[0];
|
|
73
79
|
funcNode.body.body.unshift(statement);
|
|
80
|
+
return true;
|
|
74
81
|
};
|
|
82
|
+
/**
|
|
83
|
+
* Ensures the module-scope `const localeRoute = getRouteApi("/<segment>");`
|
|
84
|
+
* declaration the injected locale statement reads from, inserted right after the
|
|
85
|
+
* import block.
|
|
86
|
+
*
|
|
87
|
+
* Referencing the locale route by id keeps the root document free of an import
|
|
88
|
+
* of `<segment>/route` — importing a child route module from `__root` is
|
|
89
|
+
* discouraged, since the generated route tree already imports the root.
|
|
90
|
+
*
|
|
91
|
+
* No-ops when `localeRoute` is already bound at module scope, reusing that
|
|
92
|
+
* binding rather than redeclaring it (which would be a parse error).
|
|
93
|
+
*
|
|
94
|
+
* @returns `true` when the declaration was inserted, `false` when an existing
|
|
95
|
+
* binding was reused.
|
|
96
|
+
*/
|
|
97
|
+
const ensureLocaleRouteApi = (ast, localeSegment) => {
|
|
98
|
+
if (require_init_utils_astImports.isModuleScopeBinding(ast, LOCALE_ROUTE_API_VARIABLE)) return false;
|
|
99
|
+
const declaration = parseTsx(`const ${LOCALE_ROUTE_API_VARIABLE} = getRouteApi("/${localeSegment}");`).program.body[0];
|
|
100
|
+
ast.program.body.splice(require_init_utils_astImports.firstInsertIndex(ast), 0, declaration);
|
|
101
|
+
return true;
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Puts a blank line between the import block and the inserted route API
|
|
105
|
+
* declaration — recast prints a spliced statement flush against the preceding
|
|
106
|
+
* line, which reads as part of the imports.
|
|
107
|
+
*/
|
|
108
|
+
const separateRouteApiDeclaration = (printedCode) => printedCode.replace(new RegExp(`([^\\n])\\n(const ${LOCALE_ROUTE_API_VARIABLE} = getRouteApi\\()`), "$1\n\n$2");
|
|
75
109
|
/** Sets `lang={locale}` and `dir={getHTMLTextDir(locale)}` on the first `<html>` element. */
|
|
76
110
|
const setHtmlLangAndDir = (ast) => {
|
|
77
111
|
recast.visit(ast, { visitJSXOpeningElement(path) {
|
|
@@ -92,12 +126,16 @@ const setHtmlLangAndDir = (ast) => {
|
|
|
92
126
|
};
|
|
93
127
|
/**
|
|
94
128
|
* Wraps the `{children}` of a TanStack Start root document with
|
|
95
|
-
* `IntlayerProvider`, deriving the locale from the
|
|
129
|
+
* `IntlayerProvider`, deriving the locale from the locale segment route params.
|
|
96
130
|
* Safe and idempotent: bails (returns the original code) when the provider is
|
|
97
131
|
* already present, when no `<html>` document function is found, or when there is
|
|
98
132
|
* no `{children}` placeholder to wrap.
|
|
133
|
+
*
|
|
134
|
+
* @param code Source of the project's `__root` document.
|
|
135
|
+
* @param localeSegment Locale segment directory in use — `{-$locale}` for every
|
|
136
|
+
* routing mode but `prefix-all`, which uses the required `$locale`.
|
|
99
137
|
*/
|
|
100
|
-
const wrapRootWithProvider = (code) => {
|
|
138
|
+
const wrapRootWithProvider = (code, localeSegment) => {
|
|
101
139
|
const ast = parseTsx(code);
|
|
102
140
|
if (code.includes("IntlayerProvider")) return {
|
|
103
141
|
code,
|
|
@@ -125,14 +163,19 @@ const wrapRootWithProvider = (code) => {
|
|
|
125
163
|
code,
|
|
126
164
|
status: "skipped"
|
|
127
165
|
};
|
|
166
|
+
const injectedLocaleDeclaration = ensureLocaleFromParams(funcNode);
|
|
128
167
|
require_init_utils_astImports.ensureNamedImport(ast, "IntlayerProvider", "react-intlayer");
|
|
129
|
-
|
|
130
|
-
|
|
168
|
+
let insertedRouteApi = false;
|
|
169
|
+
if (injectedLocaleDeclaration) {
|
|
170
|
+
require_init_utils_astImports.ensureNamedImport(ast, "getRouteApi", "@tanstack/react-router");
|
|
171
|
+
require_init_utils_astImports.ensureNamedImport(ast, "defaultLocale", "intlayer");
|
|
172
|
+
insertedRouteApi = ensureLocaleRouteApi(ast, localeSegment);
|
|
173
|
+
}
|
|
131
174
|
require_init_utils_astImports.ensureNamedImport(ast, "getHTMLTextDir", "intlayer");
|
|
132
|
-
ensureLocaleFromParams(funcNode);
|
|
133
175
|
setHtmlLangAndDir(ast);
|
|
176
|
+
const printedCode = recast.print(ast).code;
|
|
134
177
|
return {
|
|
135
|
-
code:
|
|
178
|
+
code: insertedRouteApi ? separateRouteApiDeclaration(printedCode) : printedCode,
|
|
136
179
|
status: "wrapped"
|
|
137
180
|
};
|
|
138
181
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transforms.cjs","names":["babelTsParser"],"sources":["../../../../../src/init/frameworkSetup/tanstackStart/transforms.ts"],"sourcesContent":["import * as recast from 'recast';\nimport { babelTsParser } from '../../../utils/babelParser';\nimport { ensureNamedImport } from '../../utils/astImports';\n\nconst { builders: b, namedTypes: n } = recast.types;\n\n/** babel-ts parser handles TypeScript *and* JSX. */\nconst parseTsx = (code: string): any =>\n recast.parse(code, { parser: babelTsParser });\n\n/** Result of a source transform. `code` is unchanged for any non-`wrapped` status. */\nexport type TransformResult = {\n code: string;\n status: 'wrapped' | 'already' | 'skipped';\n};\n\n/**\n * Finds the single function that returns the `<html>` document element. Returns\n * `null` when there is no such function, or more than one (ambiguous).\n */\nconst findHtmlDocumentFunction = (ast: any): any => {\n const found = new Set<any>();\n\n recast.visit(ast, {\n visitJSXOpeningElement(path) {\n const node = path.node;\n if (node.name?.type === 'JSXIdentifier' && node.name.name === 'html') {\n // Walk up to the nearest enclosing function node.\n let current = path.parentPath;\n while (current) {\n const value = current.value;\n if (\n value &&\n (n.FunctionDeclaration.check(value) ||\n n.FunctionExpression.check(value) ||\n n.ArrowFunctionExpression.check(value))\n ) {\n found.add(value);\n break;\n }\n current = current.parentPath;\n }\n }\n this.traverse(path);\n },\n });\n\n return found.size === 1 ? [...found][0] : null;\n};\n\n/**\n * Whether the binding pattern `node` introduces a variable named `name`.\n * Recurses through destructuring patterns so all of `const locale`,\n * `const { locale } = …`, `const { locale = fallback } = …`,\n * `const { foo: locale } = …`, `const [locale] = …` and `...locale` are\n * detected — not just a bare identifier.\n */\nconst patternBindsName = (node: any, name: string): boolean => {\n if (!node) return false;\n switch (node.type) {\n case 'Identifier':\n return node.name === name;\n case 'AssignmentPattern':\n // `locale = fallback`\n return patternBindsName(node.left, name);\n case 'RestElement':\n // `...locale`\n return patternBindsName(node.argument, name);\n case 'ArrayPattern':\n return node.elements.some((element: any) =>\n patternBindsName(element, name)\n );\n case 'ObjectPattern':\n return node.properties.some((property: any) =>\n property.type === 'RestElement'\n ? patternBindsName(property.argument, name)\n : // The *value* is the binding target (`{ foo: locale }` binds `locale`).\n patternBindsName(property.value, name)\n );\n default:\n return false;\n }\n};\n\n/**\n * Inserts `const locale = …` once, at the top of the function body. A single\n * self-contained statement is used (rather than an intermediate `params` const)\n * so it can never collide with a `params` variable the document already\n * declares. Expression-bodied arrow functions are first converted to a block so\n * the declaration has somewhere to live.\n *\n * No-ops when `locale` is already bound in the function — whether as a simple\n * identifier, through a destructuring pattern (e.g.\n * `const { locale = defaultLocale } = useLoaderData()`), or as a function\n * parameter — so the injected declaration never collides with one the document\n * already provides (which would produce an\n * `Identifier 'locale' has already been declared` parse error).\n */\nconst ensureLocaleFromParams = (funcNode: any): void => {\n if (funcNode.body?.type !== 'BlockStatement') {\n funcNode.body = b.blockStatement([b.returnStatement(funcNode.body)]);\n }\n\n const declaredInBody = funcNode.body.body.some(\n (stmt: any) =>\n stmt.type === 'VariableDeclaration' &&\n stmt.declarations.some((d: any) => patternBindsName(d.id, 'locale'))\n );\n const declaredInParams = (funcNode.params ?? []).some((param: any) =>\n patternBindsName(param, 'locale')\n );\n if (declaredInBody || declaredInParams) return;\n\n const statement = parseTsx(\n 'const locale = useParams({ strict: false }).locale ?? defaultLocale;'\n ).program.body[0];\n funcNode.body.body.unshift(statement);\n};\n\n/** Sets `lang={locale}` and `dir={getHTMLTextDir(locale)}` on the first `<html>` element. */\nconst setHtmlLangAndDir = (ast: any): void => {\n recast.visit(ast, {\n visitJSXOpeningElement(path) {\n const node = path.node;\n if (node.name?.type !== 'JSXIdentifier' || node.name.name !== 'html') {\n this.traverse(path);\n return;\n }\n\n const upsertAttribute = (name: string, value: any): void => {\n const existing = node.attributes?.find(\n (attr: any) =>\n attr.type === 'JSXAttribute' && attr.name?.name === name\n ) as any;\n if (existing) {\n existing.value = value;\n } else {\n node.attributes?.push(b.jsxAttribute(b.jsxIdentifier(name), value));\n }\n };\n\n upsertAttribute('lang', b.jsxExpressionContainer(b.identifier('locale')));\n upsertAttribute(\n 'dir',\n b.jsxExpressionContainer(\n b.callExpression(b.identifier('getHTMLTextDir'), [\n b.identifier('locale'),\n ])\n )\n );\n return false;\n },\n });\n};\n\n/**\n * Wraps the `{children}` of a TanStack Start root document with\n * `IntlayerProvider`, deriving the locale from the `{-$locale}` route param.\n * Safe and idempotent: bails (returns the original code) when the provider is\n * already present, when no `<html>` document function is found, or when there is\n * no `{children}` placeholder to wrap.\n */\nexport const wrapRootWithProvider = (code: string): TransformResult => {\n const ast = parseTsx(code);\n\n if (code.includes('IntlayerProvider')) return { code, status: 'already' };\n\n const funcNode = findHtmlDocumentFunction(ast);\n if (!funcNode) return { code, status: 'skipped' };\n\n let wrapped = false;\n recast.visit(funcNode, {\n visitJSXExpressionContainer(path) {\n if (wrapped) return false;\n const expression = path.node.expression;\n if (expression?.type === 'Identifier' && expression.name === 'children') {\n const template = parseTsx(\n 'const __wrap = <IntlayerProvider locale={locale}>{__child__}</IntlayerProvider>;'\n );\n const providerElement = template.program.body[0].declarations[0].init;\n providerElement.children = [path.node];\n path.replace(providerElement);\n wrapped = true;\n return false;\n }\n this.traverse(path);\n },\n });\n\n if (!wrapped) return { code, status: 'skipped' };\n\n ensureNamedImport(ast, 'IntlayerProvider', 'react-intlayer');\n ensureNamedImport(ast, 'useParams', '@tanstack/react-router');\n ensureNamedImport(ast, 'defaultLocale', 'intlayer');\n ensureNamedImport(ast, 'getHTMLTextDir', 'intlayer');\n ensureLocaleFromParams(funcNode);\n setHtmlLangAndDir(ast);\n\n return { code: recast.print(ast).code, status: 'wrapped' };\n};\n"],"mappings":";;;;;;;;AAIA,MAAM,EAAE,UAAU,GAAG,YAAY,MAAM,OAAO;;AAG9C,MAAM,YAAY,SAChB,OAAO,MAAM,MAAM,EAAE,QAAQA,wCAAc,CAAC;;;;;AAY9C,MAAM,4BAA4B,QAAkB;CAClD,MAAM,wBAAQ,IAAI,IAAS;CAE3B,OAAO,MAAM,KAAK,EAChB,uBAAuB,MAAM;EAC3B,MAAM,OAAO,KAAK;EAClB,IAAI,KAAK,MAAM,SAAS,mBAAmB,KAAK,KAAK,SAAS,QAAQ;GAEpE,IAAI,UAAU,KAAK;GACnB,OAAO,SAAS;IACd,MAAM,QAAQ,QAAQ;IACtB,IACE,UACC,EAAE,oBAAoB,MAAM,KAAK,KAChC,EAAE,mBAAmB,MAAM,KAAK,KAChC,EAAE,wBAAwB,MAAM,KAAK,IACvC;KACA,MAAM,IAAI,KAAK;KACf;IACF;IACA,UAAU,QAAQ;GACpB;EACF;EACA,KAAK,SAAS,IAAI;CACpB,EACF,CAAC;CAED,OAAO,MAAM,SAAS,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK;AAC5C;;;;;;;;AASA,MAAM,oBAAoB,MAAW,SAA0B;CAC7D,IAAI,CAAC,MAAM,OAAO;CAClB,QAAQ,KAAK,MAAb;EACE,KAA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"file":"transforms.cjs","names":["babelTsParser","isModuleScopeBinding","firstInsertIndex"],"sources":["../../../../../src/init/frameworkSetup/tanstackStart/transforms.ts"],"sourcesContent":["import * as recast from 'recast';\nimport { babelTsParser } from '../../../utils/babelParser';\nimport {\n ensureNamedImport,\n firstInsertIndex,\n isModuleScopeBinding,\n} from '../../utils/astImports';\n\nconst { builders: b, namedTypes: n } = recast.types;\n\n/** Module-scope identifier bound to the locale route's typed API. */\nconst LOCALE_ROUTE_API_VARIABLE = 'localeRoute';\n\n/** babel-ts parser handles TypeScript *and* JSX. */\nconst parseTsx = (code: string): any =>\n recast.parse(code, { parser: babelTsParser });\n\n/** Result of a source transform. `code` is unchanged for any non-`wrapped` status. */\nexport type TransformResult = {\n code: string;\n status: 'wrapped' | 'already' | 'skipped';\n};\n\n/**\n * Finds the single function that returns the `<html>` document element. Returns\n * `null` when there is no such function, or more than one (ambiguous).\n */\nconst findHtmlDocumentFunction = (ast: any): any => {\n const found = new Set<any>();\n\n recast.visit(ast, {\n visitJSXOpeningElement(path) {\n const node = path.node;\n if (node.name?.type === 'JSXIdentifier' && node.name.name === 'html') {\n // Walk up to the nearest enclosing function node.\n let current = path.parentPath;\n while (current) {\n const value = current.value;\n if (\n value &&\n (n.FunctionDeclaration.check(value) ||\n n.FunctionExpression.check(value) ||\n n.ArrowFunctionExpression.check(value))\n ) {\n found.add(value);\n break;\n }\n current = current.parentPath;\n }\n }\n this.traverse(path);\n },\n });\n\n return found.size === 1 ? [...found][0] : null;\n};\n\n/**\n * Whether the binding pattern `node` introduces a variable named `name`.\n * Recurses through destructuring patterns so all of `const locale`,\n * `const { locale } = …`, `const { locale = fallback } = …`,\n * `const { foo: locale } = …`, `const [locale] = …` and `...locale` are\n * detected — not just a bare identifier.\n */\nconst patternBindsName = (node: any, name: string): boolean => {\n if (!node) return false;\n switch (node.type) {\n case 'Identifier':\n return node.name === name;\n case 'AssignmentPattern':\n // `locale = fallback`\n return patternBindsName(node.left, name);\n case 'RestElement':\n // `...locale`\n return patternBindsName(node.argument, name);\n case 'ArrayPattern':\n return node.elements.some((element: any) =>\n patternBindsName(element, name)\n );\n case 'ObjectPattern':\n return node.properties.some((property: any) =>\n property.type === 'RestElement'\n ? patternBindsName(property.argument, name)\n : // The *value* is the binding target (`{ foo: locale }` binds `locale`).\n patternBindsName(property.value, name)\n );\n default:\n return false;\n }\n};\n\n/**\n * Inserts `const { locale = defaultLocale } = localeRoute.useParams();` once, at\n * the top of the function body. The destructuring form binds only `locale`, so\n * it can never collide with a `params` variable the document already declares.\n * Expression-bodied arrow functions are first converted to a block so the\n * declaration has somewhere to live.\n *\n * No-ops when `locale` is already bound in the function — whether as a simple\n * identifier, through a destructuring pattern (e.g.\n * `const { locale = defaultLocale } = Route.useLoaderData()`), or as a function\n * parameter — so the injected declaration never collides with one the document\n * already provides (which would produce an\n * `Identifier 'locale' has already been declared` parse error).\n *\n * @returns `true` when the declaration was injected, `false` when the document\n * already binds `locale` itself. Callers use this to skip the imports and the\n * route API declaration the injected statement would have needed.\n */\nconst ensureLocaleFromParams = (funcNode: any): boolean => {\n if (funcNode.body?.type !== 'BlockStatement') {\n funcNode.body = b.blockStatement([b.returnStatement(funcNode.body)]);\n }\n\n const declaredInBody = funcNode.body.body.some(\n (stmt: any) =>\n stmt.type === 'VariableDeclaration' &&\n stmt.declarations.some((d: any) => patternBindsName(d.id, 'locale'))\n );\n const declaredInParams = (funcNode.params ?? []).some((param: any) =>\n patternBindsName(param, 'locale')\n );\n if (declaredInBody || declaredInParams) return false;\n\n const statement = parseTsx(\n `const { locale = defaultLocale } = ${LOCALE_ROUTE_API_VARIABLE}.useParams();`\n ).program.body[0];\n funcNode.body.body.unshift(statement);\n return true;\n};\n\n/**\n * Ensures the module-scope `const localeRoute = getRouteApi(\"/<segment>\");`\n * declaration the injected locale statement reads from, inserted right after the\n * import block.\n *\n * Referencing the locale route by id keeps the root document free of an import\n * of `<segment>/route` — importing a child route module from `__root` is\n * discouraged, since the generated route tree already imports the root.\n *\n * No-ops when `localeRoute` is already bound at module scope, reusing that\n * binding rather than redeclaring it (which would be a parse error).\n *\n * @returns `true` when the declaration was inserted, `false` when an existing\n * binding was reused.\n */\nconst ensureLocaleRouteApi = (ast: any, localeSegment: string): boolean => {\n if (isModuleScopeBinding(ast, LOCALE_ROUTE_API_VARIABLE)) return false;\n\n const declaration = parseTsx(\n `const ${LOCALE_ROUTE_API_VARIABLE} = getRouteApi(\"/${localeSegment}\");`\n ).program.body[0];\n ast.program.body.splice(firstInsertIndex(ast), 0, declaration);\n return true;\n};\n\n/**\n * Puts a blank line between the import block and the inserted route API\n * declaration — recast prints a spliced statement flush against the preceding\n * line, which reads as part of the imports.\n */\nconst separateRouteApiDeclaration = (printedCode: string): string =>\n printedCode.replace(\n new RegExp(\n `([^\\\\n])\\\\n(const ${LOCALE_ROUTE_API_VARIABLE} = getRouteApi\\\\()`\n ),\n '$1\\n\\n$2'\n );\n\n/** Sets `lang={locale}` and `dir={getHTMLTextDir(locale)}` on the first `<html>` element. */\nconst setHtmlLangAndDir = (ast: any): void => {\n recast.visit(ast, {\n visitJSXOpeningElement(path) {\n const node = path.node;\n if (node.name?.type !== 'JSXIdentifier' || node.name.name !== 'html') {\n this.traverse(path);\n return;\n }\n\n const upsertAttribute = (name: string, value: any): void => {\n const existing = node.attributes?.find(\n (attr: any) =>\n attr.type === 'JSXAttribute' && attr.name?.name === name\n ) as any;\n if (existing) {\n existing.value = value;\n } else {\n node.attributes?.push(b.jsxAttribute(b.jsxIdentifier(name), value));\n }\n };\n\n upsertAttribute('lang', b.jsxExpressionContainer(b.identifier('locale')));\n upsertAttribute(\n 'dir',\n b.jsxExpressionContainer(\n b.callExpression(b.identifier('getHTMLTextDir'), [\n b.identifier('locale'),\n ])\n )\n );\n return false;\n },\n });\n};\n\n/**\n * Wraps the `{children}` of a TanStack Start root document with\n * `IntlayerProvider`, deriving the locale from the locale segment route params.\n * Safe and idempotent: bails (returns the original code) when the provider is\n * already present, when no `<html>` document function is found, or when there is\n * no `{children}` placeholder to wrap.\n *\n * @param code Source of the project's `__root` document.\n * @param localeSegment Locale segment directory in use — `{-$locale}` for every\n * routing mode but `prefix-all`, which uses the required `$locale`.\n */\nexport const wrapRootWithProvider = (\n code: string,\n localeSegment: string\n): TransformResult => {\n const ast = parseTsx(code);\n\n if (code.includes('IntlayerProvider')) return { code, status: 'already' };\n\n const funcNode = findHtmlDocumentFunction(ast);\n if (!funcNode) return { code, status: 'skipped' };\n\n let wrapped = false;\n recast.visit(funcNode, {\n visitJSXExpressionContainer(path) {\n if (wrapped) return false;\n const expression = path.node.expression;\n if (expression?.type === 'Identifier' && expression.name === 'children') {\n const template = parseTsx(\n 'const __wrap = <IntlayerProvider locale={locale}>{__child__}</IntlayerProvider>;'\n );\n const providerElement = template.program.body[0].declarations[0].init;\n providerElement.children = [path.node];\n path.replace(providerElement);\n wrapped = true;\n return false;\n }\n this.traverse(path);\n },\n });\n\n if (!wrapped) return { code, status: 'skipped' };\n\n const injectedLocaleDeclaration = ensureLocaleFromParams(funcNode);\n\n ensureNamedImport(ast, 'IntlayerProvider', 'react-intlayer');\n // Only needed by the injected declaration: a document that already derives its\n // own `locale` must not be given unused imports or a stray route API const.\n let insertedRouteApi = false;\n if (injectedLocaleDeclaration) {\n ensureNamedImport(ast, 'getRouteApi', '@tanstack/react-router');\n ensureNamedImport(ast, 'defaultLocale', 'intlayer');\n insertedRouteApi = ensureLocaleRouteApi(ast, localeSegment);\n }\n ensureNamedImport(ast, 'getHTMLTextDir', 'intlayer');\n setHtmlLangAndDir(ast);\n\n const printedCode = recast.print(ast).code;\n\n return {\n code: insertedRouteApi\n ? separateRouteApiDeclaration(printedCode)\n : printedCode,\n status: 'wrapped',\n };\n};\n"],"mappings":";;;;;;;;AAQA,MAAM,EAAE,UAAU,GAAG,YAAY,MAAM,OAAO;;AAG9C,MAAM,4BAA4B;;AAGlC,MAAM,YAAY,SAChB,OAAO,MAAM,MAAM,EAAE,QAAQA,wCAAc,CAAC;;;;;A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