|
1 |
| -import { join, dirname, isAbsolute } from 'path'; |
| 1 | +import { join, dirname, relative, resolve } from 'path'; |
2 | 2 | import { chalk, fs, globby, json5, logger } from '@modern-js/utils';
|
3 | 3 | import MagicString from 'magic-string';
|
| 4 | +import { createMatchPath, loadConfig } from '@modern-js/utils/tsconfig-paths'; |
| 5 | +import { ts } from '@ast-grep/napi'; |
4 | 6 | import type {
|
5 | 7 | ITsconfig,
|
6 | 8 | GeneratorDtsConfig,
|
7 | 9 | BuildType,
|
8 | 10 | TsTarget,
|
9 | 11 | } from '../types';
|
| 12 | +import { normalizeSlashes } from './builder'; |
| 13 | + |
| 14 | +type MatchModule = { |
| 15 | + name?: string; |
| 16 | + start: number; |
| 17 | + end: number; |
| 18 | +}[]; |
10 | 19 |
|
11 | 20 | export const getProjectTsconfig = async (
|
12 | 21 | tsconfigPath: string,
|
@@ -43,66 +52,114 @@ export const getTscBinPath = async (appDirectory: string) => {
|
43 | 52 | return tscBinFile;
|
44 | 53 | };
|
45 | 54 |
|
46 |
| -export const resolveAlias = async (config: GeneratorDtsConfig) => { |
47 |
| - const { userTsconfig, distPath, tsconfigPath } = config; |
48 |
| - const { transformDtsAlias } = await import('./tspath'); |
49 |
| - const dtsFilenames = await globby('**/*.d.ts', { |
| 55 | +export const processDtsFilesAfterTsc = async (config: GeneratorDtsConfig) => { |
| 56 | + const { distPath, tsconfigPath, userTsconfig, dtsExtension, banner, footer } = |
| 57 | + config; |
| 58 | + const dtsFilesPath = await globby('**/*.d.ts', { |
50 | 59 | absolute: true,
|
51 | 60 | cwd: distPath,
|
52 | 61 | });
|
53 |
| - const userBaseUrl = userTsconfig.compilerOptions?.baseUrl; |
54 |
| - const baseUrl = isAbsolute(userBaseUrl || '.') |
55 |
| - ? userBaseUrl! |
56 |
| - : join(dirname(tsconfigPath), userBaseUrl || '.'); |
57 |
| - const result = transformDtsAlias({ |
58 |
| - filenames: dtsFilenames, |
59 |
| - baseUrl, |
60 |
| - paths: userTsconfig.compilerOptions?.paths ?? {}, |
61 |
| - }); |
62 |
| - return result; |
63 |
| -}; |
64 | 62 |
|
65 |
| -export const writeDtsFiles = async ( |
66 |
| - config: GeneratorDtsConfig, |
67 |
| - result: { path: string; content: string }[], |
68 |
| -) => { |
69 |
| - const { dtsExtension } = config; |
70 |
| - // write to dist |
| 63 | + /** |
| 64 | + * get matchPath func to support tsconfig paths |
| 65 | + */ |
| 66 | + const result = loadConfig(tsconfigPath); |
| 67 | + if (result.resultType === 'failed') { |
| 68 | + logger.error(result.message); |
| 69 | + return; |
| 70 | + } |
| 71 | + const { absoluteBaseUrl, paths, mainFields, addMatchAll } = result; |
| 72 | + const matchPath = createMatchPath( |
| 73 | + absoluteBaseUrl, |
| 74 | + paths, |
| 75 | + mainFields, |
| 76 | + addMatchAll, |
| 77 | + ); |
| 78 | + |
| 79 | + /** |
| 80 | + * `export $VAR from` is invalid, so we need `{$$$VAR}`, `*` and `* as $VAR` |
| 81 | + * But `import $VAR from` is valid. |
| 82 | + */ |
| 83 | + const Pattern = [ |
| 84 | + `import $VAR from '$MATCH'`, |
| 85 | + `import $VAR from "$MATCH"`, |
| 86 | + `export {$$$VAR} from '$MATCH'`, |
| 87 | + `export {$$$VAR} from "$MATCH"`, |
| 88 | + `export * from '$MATCH'`, |
| 89 | + `export * from "$MATCH"`, |
| 90 | + `export * as $VAR from '$MATCH'`, |
| 91 | + `export * as $VAR from "$MATCH"`, |
| 92 | + `import('$MATCH')`, |
| 93 | + `import("$MATCH")`, |
| 94 | + ]; |
| 95 | + |
71 | 96 | await Promise.all(
|
72 |
| - result.map(({ path, content }) => { |
73 |
| - const filepath = |
| 97 | + dtsFilesPath.map(filePath => { |
| 98 | + const code = fs.readFileSync(filePath, 'utf8'); |
| 99 | + let matchModule: MatchModule = []; |
| 100 | + try { |
| 101 | + const sgNode = ts.parse(code).root(); |
| 102 | + matchModule = Pattern.map(p => sgNode.findAll(p)) |
| 103 | + .flat() |
| 104 | + .map(node => { |
| 105 | + const matchNode = node.getMatch('MATCH')!; |
| 106 | + return { |
| 107 | + name: matchNode.text(), |
| 108 | + start: matchNode.range().start.index, |
| 109 | + end: matchNode.range().end.index, |
| 110 | + }; |
| 111 | + }); |
| 112 | + } catch (e) { |
| 113 | + logger.error('[parse error]', e); |
| 114 | + } |
| 115 | + const str: MagicString = new MagicString(code); |
| 116 | + |
| 117 | + const originalFilePath = resolve( |
| 118 | + absoluteBaseUrl, |
| 119 | + userTsconfig?.compilerOptions?.rootDir || 'src', |
| 120 | + relative(distPath, filePath), |
| 121 | + ); |
| 122 | + |
| 123 | + matchModule.forEach(module => { |
| 124 | + if (!module.name) { |
| 125 | + return; |
| 126 | + } |
| 127 | + const { start, end, name } = module; |
| 128 | + const absoluteImportPath = matchPath(name); |
| 129 | + if (absoluteImportPath) { |
| 130 | + const relativePath = relative( |
| 131 | + dirname(originalFilePath), |
| 132 | + absoluteImportPath, |
| 133 | + ); |
| 134 | + const relativeImportPath = normalizeSlashes( |
| 135 | + relativePath.startsWith('..') ? relativePath : `./${relativePath}`, |
| 136 | + ); |
| 137 | + str.overwrite(start, end, relativeImportPath); |
| 138 | + } |
| 139 | + }); |
| 140 | + |
| 141 | + // add banner and footer |
| 142 | + banner && str.prepend(`${banner}\n`); |
| 143 | + footer && str.append(`\n${footer}\n`); |
| 144 | + |
| 145 | + // rewrite dts file |
| 146 | + const content = str.toString(); |
| 147 | + const finalPath = |
74 | 148 | // We confirm that users will not mix ts and c(m)ts files in their projects.
|
75 | 149 | // If a mix is required, please configure separate buildConfig to handle different inputs.
|
76 | 150 | // So we don't replace .d.(c|m)ts that generated by tsc directly, this can confirm that
|
77 | 151 | // users can use c(m)ts directly rather than enable autoExtension, in this condition,
|
78 | 152 | // users need to set esbuild out-extensions like { '.js': '.mjs' }
|
79 |
| - path.replace(/\.d\.ts/, dtsExtension); |
80 |
| - fs.ensureFileSync(filepath); |
| 153 | + filePath.replace(/\.d\.ts/, dtsExtension); |
81 | 154 | return fs.writeFile(
|
82 | 155 | // only replace .d.ts, if tsc generate .d.m(c)ts, keep.
|
83 |
| - filepath, |
| 156 | + finalPath, |
84 | 157 | content,
|
85 | 158 | );
|
86 | 159 | }),
|
87 | 160 | );
|
88 | 161 | };
|
89 | 162 |
|
90 |
| -export const addBannerAndFooter = ( |
91 |
| - result: { path: string; content: string }[], |
92 |
| - banner?: string, |
93 |
| - footer?: string, |
94 |
| -) => { |
95 |
| - return result.map(({ path, content }) => { |
96 |
| - const ms = new MagicString(content); |
97 |
| - banner && ms.prepend(`${banner}\n`); |
98 |
| - footer && ms.append(`\n${footer}\n`); |
99 |
| - return { |
100 |
| - path, |
101 |
| - content: ms.toString(), |
102 |
| - }; |
103 |
| - }); |
104 |
| -}; |
105 |
| - |
106 | 163 | export const printOrThrowDtsErrors = async (
|
107 | 164 | error: unknown,
|
108 | 165 | options: { abortOnError?: boolean; buildType: BuildType },
|
|
0 commit comments