|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import fs from 'fs-extra'; |
| 3 | +import { createRequire } from 'node:module'; |
| 4 | +import path from 'node:path'; |
| 5 | +import { glob } from 'glob'; |
| 6 | +import ts from 'typescript'; |
| 7 | + |
| 8 | +const require = createRequire(import.meta.url); |
| 9 | + |
| 10 | +/** @type {ts.CompilerOptions} */ |
| 11 | +const tsConfigBase = require(path.resolve(import.meta.dirname, '../packages/module/tsconfig.cjs.json')); |
| 12 | + |
| 13 | +/** @type {ts.CompilerOptions} */ |
| 14 | +const defaultCompilerOptions = { |
| 15 | + target: tsConfigBase.target, |
| 16 | + module: tsConfigBase.module, |
| 17 | + moduleResolution: tsConfigBase.moduleResolution, |
| 18 | + esModuleInterop: tsConfigBase.esModuleInterop, |
| 19 | + allowJs: true, |
| 20 | + strict: false, |
| 21 | + skipLibCheck: true, |
| 22 | + noEmit: true |
| 23 | +}; |
| 24 | + |
| 25 | +/** |
| 26 | + * Map all exports of the given index module to their corresponding dynamic modules. |
| 27 | + * |
| 28 | + * Example: `@patternfly/react-core` package provides ESModules index at `dist/esm/index.js` |
| 29 | + * which exports Alert component related code & types via `dist/esm/components/Alert/index.js` |
| 30 | + * module. |
| 31 | + * |
| 32 | + * Given the example above, this function should return a mapping like so: |
| 33 | + * ```js |
| 34 | + * { |
| 35 | + * Alert: 'dist/dynamic/components/Alert', |
| 36 | + * AlertProps: 'dist/dynamic/components/Alert', |
| 37 | + * AlertContext: 'dist/dynamic/components/Alert', |
| 38 | + * // ... |
| 39 | + * } |
| 40 | + * ``` |
| 41 | + * |
| 42 | + * The above mapping can be used when generating import statements like so: |
| 43 | + * ```ts |
| 44 | + * import { Alert } from '@patternfly/react-core/dist/dynamic/components/Alert'; |
| 45 | + * ``` |
| 46 | + * |
| 47 | + * It may happen that the same export is provided by multiple dynamic modules; |
| 48 | + * in such case, the resolution favors modules with most specific file paths, for example |
| 49 | + * `dist/dynamic/components/Wizard/hooks` is favored over `dist/dynamic/components/Wizard`. |
| 50 | + * |
| 51 | + * Dynamic modules nested under `deprecated` or `next` directories are ignored. |
| 52 | + * |
| 53 | + * If the referenced index module does not exist, an empty object is returned. |
| 54 | + * |
| 55 | + * @param {string} basePath |
| 56 | + * @param {string} indexModule |
| 57 | + * @param {string} resolutionField |
| 58 | + * @param {ts.CompilerOptions} tsCompilerOptions |
| 59 | + * @returns {Record<string, string>} |
| 60 | + */ |
| 61 | +const getDynamicModuleMap = ( |
| 62 | + basePath, |
| 63 | + indexModule = 'dist/esm/index.js', |
| 64 | + resolutionField = 'module', |
| 65 | + tsCompilerOptions = defaultCompilerOptions |
| 66 | +) => { |
| 67 | + if (!path.isAbsolute(basePath)) { |
| 68 | + throw new Error('Package base path must be absolute'); |
| 69 | + } |
| 70 | + |
| 71 | + const indexModulePath = path.resolve(basePath, indexModule); |
| 72 | + |
| 73 | + if (!fs.existsSync(indexModulePath)) { |
| 74 | + return {}; |
| 75 | + } |
| 76 | + |
| 77 | + /** @type {Record<string, string>} */ |
| 78 | + const dynamicModulePathToPkgDir = glob.sync(`${basePath}/dist/dynamic/**/package.json`).reduce((acc, pkgFile) => { |
| 79 | + const pkg = require(pkgFile); |
| 80 | + const pkgModule = pkg[resolutionField]; |
| 81 | + |
| 82 | + if (!pkgModule) { |
| 83 | + throw new Error(`Missing field ${resolutionField} in ${pkgFile}`); |
| 84 | + } |
| 85 | + |
| 86 | + const pkgResolvedPath = path.resolve(path.dirname(pkgFile), pkgModule); |
| 87 | + const pkgRelativePath = path.dirname(path.relative(basePath, pkgFile)); |
| 88 | + |
| 89 | + acc[pkgResolvedPath] = pkgRelativePath; |
| 90 | + |
| 91 | + return acc; |
| 92 | + }, {}); |
| 93 | + |
| 94 | + const dynamicModulePaths = Object.keys(dynamicModulePathToPkgDir); |
| 95 | + const compilerHost = ts.createCompilerHost(tsCompilerOptions); |
| 96 | + const program = ts.createProgram([indexModulePath, ...dynamicModulePaths], tsCompilerOptions, compilerHost); |
| 97 | + const errorDiagnostics = ts.getPreEmitDiagnostics(program).filter((d) => d.category === ts.DiagnosticCategory.Error); |
| 98 | + |
| 99 | + if (errorDiagnostics.length > 0) { |
| 100 | + const { getCanonicalFileName, getCurrentDirectory, getNewLine } = compilerHost; |
| 101 | + |
| 102 | + console.error( |
| 103 | + ts.formatDiagnostics(errorDiagnostics, { |
| 104 | + getCanonicalFileName, |
| 105 | + getCurrentDirectory, |
| 106 | + getNewLine |
| 107 | + }) |
| 108 | + ); |
| 109 | + |
| 110 | + throw new Error(`Detected TypeScript errors while parsing modules at ${basePath}`); |
| 111 | + } |
| 112 | + |
| 113 | + const typeChecker = program.getTypeChecker(); |
| 114 | + |
| 115 | + /** @param {ts.SourceFile} sourceFile */ |
| 116 | + const getExportNames = (sourceFile) => |
| 117 | + typeChecker.getExportsOfModule(typeChecker.getSymbolAtLocation(sourceFile)).map((symbol) => symbol.getName()); |
| 118 | + |
| 119 | + const indexModuleExports = getExportNames(program.getSourceFile(indexModulePath)); |
| 120 | + |
| 121 | + /** @type {Record<string, string[]>} */ |
| 122 | + const dynamicModuleExports = dynamicModulePaths.reduce((acc, modulePath) => { |
| 123 | + acc[modulePath] = getExportNames(program.getSourceFile(modulePath)); |
| 124 | + return acc; |
| 125 | + }, {}); |
| 126 | + |
| 127 | + /** @param {string[]} modulePaths */ |
| 128 | + const getMostSpecificModulePath = (modulePaths) => |
| 129 | + modulePaths.reduce((acc, p) => { |
| 130 | + const pathSpecificity = p.split(path.sep).length; |
| 131 | + const currSpecificity = acc.split(path.sep).length; |
| 132 | + |
| 133 | + if (pathSpecificity > currSpecificity) { |
| 134 | + return p; |
| 135 | + } |
| 136 | + |
| 137 | + if (pathSpecificity === currSpecificity) { |
| 138 | + return !p.endsWith('index.js') && acc.endsWith('index.js') ? p : acc; |
| 139 | + } |
| 140 | + |
| 141 | + return acc; |
| 142 | + }, ''); |
| 143 | + |
| 144 | + return indexModuleExports.reduce((acc, exportName) => { |
| 145 | + const foundModulePaths = Object.keys(dynamicModuleExports).filter((modulePath) => |
| 146 | + dynamicModuleExports[modulePath].includes(exportName) |
| 147 | + ); |
| 148 | + |
| 149 | + const filteredModulePaths = foundModulePaths.filter((modulePath) => { |
| 150 | + const dirNames = path.dirname(modulePath).split(path.sep); |
| 151 | + return !dirNames.includes('deprecated') && !dirNames.includes('next'); |
| 152 | + }); |
| 153 | + |
| 154 | + if (filteredModulePaths.length > 0) { |
| 155 | + acc[exportName] = dynamicModulePathToPkgDir[getMostSpecificModulePath(filteredModulePaths)]; |
| 156 | + } |
| 157 | + |
| 158 | + return acc; |
| 159 | + }, {}); |
| 160 | +}; |
| 161 | + |
| 162 | +export default getDynamicModuleMap; |
0 commit comments