-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
dependencies.ts
259 lines (229 loc) · 7.37 KB
/
dependencies.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import path from 'path';
import slash from 'slash2';
import crypto from 'crypto';
import * as babel from '@babel/core';
import * as types from '@babel/types';
import traverse from '@babel/traverse';
import {
getModuleResolvePkg,
getModuleResolvePath,
getModuleResolveContent,
getHostPkgPath,
getHostModuleResolvePkg,
} from '../../utils/moduleResolver';
import FileCache from '../../utils/cache';
import type { IDemoOpts } from './options';
import { getBabelOptions } from './options';
const cachers = {
file: new FileCache(),
content: new FileCache(),
};
const getContentHash = (content: string) => {
const hash = crypto.createHash('sha256');
hash.update(content);
return hash.digest('hex');
};
interface IAnalyzeCache {
dependencies: {
resolvePath: string;
name: string;
version: string;
css?: string;
peerDeps: { name: string; version: string; css?: string }[];
}[];
files: {
resolvePath: string;
requireStr: string;
filename: string;
}[];
}
export interface IDepAnalyzeResult {
dependencies: Record<
string,
{
version: string;
css?: string;
}
>;
files: Record<string, { import: string; fileAbsPath: string }>;
}
export const LOCAL_DEP_EXT = ['.jsx', '.tsx', '.js', '.ts'];
export const LOCAL_MODULE_EXT = [...LOCAL_DEP_EXT, '.json'];
// local dependency extensions which will be collected
export const PLAIN_TEXT_EXT = [...LOCAL_MODULE_EXT, '.less', '.css', '.scss', '.sass', '.styl'];
export const isHostPackage = (packageName: string) => getHostPkgPath(packageName);
function analyzeDeps(
raw: string,
{
isTSX,
fileAbsPath,
entryAbsPath,
files = {},
}: IDemoOpts & {
entryAbsPath?: string;
files?: IDepAnalyzeResult['files'];
},
): IDepAnalyzeResult {
const cacheKey = fileAbsPath.endsWith('.md')
? `${fileAbsPath}-${getContentHash(raw)}`
: fileAbsPath;
const dependencies: IDepAnalyzeResult['dependencies'] = {};
let cache: IAnalyzeCache = fileAbsPath && cachers.file.get(fileAbsPath);
if (!cache) {
cache = { dependencies: [], files: [] };
// support to pass babel transform result directly
const { ast } = babel.transformSync(
raw,
getBabelOptions({ isTSX, fileAbsPath, transformRuntime: false }),
);
// traverse all require call expression
traverse(ast, {
CallExpression(callPath) {
const callPathNode = callPath.node;
// tranverse all require statement
if (
types.isIdentifier(callPathNode.callee) &&
callPathNode.callee.name === 'require' &&
types.isStringLiteral(callPathNode.arguments[0])
) {
const requireStr = callPathNode.arguments[0].value;
const resolvePath = getModuleResolvePath({
basePath: fileAbsPath,
sourcePath: requireStr,
extensions: LOCAL_MODULE_EXT,
});
const resolvePathParsed = path.parse(resolvePath);
const isHostPkg = isHostPackage(requireStr);
if (resolvePath.includes('node_modules') || isHostPkg) {
// save external deps
const pkg = isHostPkg
? getHostModuleResolvePkg(requireStr)
: getModuleResolvePkg({
basePath: fileAbsPath,
sourcePath: resolvePath,
extensions: LOCAL_MODULE_EXT,
});
const css = getCSSForDep(pkg.name);
const peerDeps: IAnalyzeCache['dependencies'][0]['peerDeps'] = [];
// process peer dependencies from dependency
Object.keys(pkg.peerDependencies || {}).forEach(dep => {
const peerCSS = getCSSForDep(dep);
peerDeps.push({
name: dep,
version: pkg.peerDependencies[dep],
// also collect css file for peerDependencies
css: peerCSS,
});
});
cache.dependencies.push({
resolvePath,
name: pkg.name,
version: pkg.version,
css,
peerDeps,
});
} else if (
// only analysis for valid local file type
PLAIN_TEXT_EXT.includes(resolvePathParsed.ext) &&
// do not collect entry file
resolvePath !== slash(entryAbsPath || '') &&
// to avoid collect alias module
requireStr.startsWith('.')
) {
// save local deps
const filename = slash(path.relative(entryAbsPath || fileAbsPath, resolvePath)).replace(
/(\.\/|\..\/)/g,
'',
);
cache.files.push({
resolvePath,
requireStr,
filename,
});
}
}
},
});
}
// visit all dependencies
cache.dependencies.forEach(item => {
dependencies[item.name] = {
version: item.version,
...(item.css ? { css: item.css } : {}),
};
});
// visit all peer dependencies, to make sure collect 1-level dependency first
cache.dependencies
.reduce((result, item) => result.concat(item.peerDeps), [])
.filter(item => !dependencies[item])
.forEach(item => {
dependencies[item.name] = {
version: item.version,
...(item.css ? { css: item.css } : {}),
};
});
// visit all local files
cache.files
.filter(item => {
// to avoid circular-reference
return !files[item.filename];
})
.forEach(item => {
const ext = path.extname(item.resolvePath);
files[item.filename] = cachers.content.get(item.resolvePath) || {
import: item.requireStr,
fileAbsPath: item.resolvePath,
};
// cache resolve content
cachers.content.add(item.resolvePath, files[item.filename]);
// continue to collect deps for dep
if (LOCAL_DEP_EXT.includes(ext)) {
const content = getModuleResolveContent({
basePath: fileAbsPath,
sourcePath: item.resolvePath,
extensions: LOCAL_DEP_EXT,
});
const result = analyzeDeps(content, {
isTSX: /\.tsx?/.test(ext),
fileAbsPath: item.resolvePath,
entryAbsPath: entryAbsPath || fileAbsPath,
files,
});
Object.assign(files, result.files);
Object.assign(dependencies, result.dependencies);
}
});
// cache analyze result for single demo code
if (fileAbsPath) {
cachers.file.add(fileAbsPath, cache, cacheKey);
}
return { files, dependencies };
}
export function getCSSForDep(dep: string) {
const pkgWithoutGroup = dep.match(/([^\/]+)$/)[1];
const guessFiles = [
// @group/pkg-suffic => pkg-suffix
`${pkgWithoutGroup}`,
// @group/pkg-suffix => pkgsuffix @ant-design/pro-card => card
...(pkgWithoutGroup.includes('-')
? [pkgWithoutGroup.replace(/-/g, ''), pkgWithoutGroup.split('-')[1]]
: []),
// guess normal css files
'main',
'index',
].reduce((files, name) => files.concat([`${name}.css`, `${name}.min.css`]), []);
// detect guess css files
for (let i = 0; i <= guessFiles.length; i += 1) {
const file = guessFiles[i];
try {
// try to resolve CSS file
const guessFilePath = `${dep}/dist/${file}`;
// 判断一下文件是不是存在,不存在 throw 错误没必要加入
require.resolve(guessFilePath);
return guessFilePath;
} catch (err) {
/* nothing */
}
}
}
export default analyzeDeps;