-
Notifications
You must be signed in to change notification settings - Fork 91
/
bare-imports.js
216 lines (188 loc) · 5.61 KB
/
bare-imports.js
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
// This script is called with two command-line arguments: a directory
// to search for module requires, and a comma-delimited list of names
// to ignore in the filesystem traversal. It prints to stdout a list
// of modules that were required, excluding builtins, local modules,
// etc.
const builtinModules = require("module").builtinModules;
const fs = require("fs");
const path = require("path");
const process = require("process");
const util = require("util");
const babelParser = require("./babel-parser");
// Walk filesystem tree rooted at directory in parallel. For each file
// in the tree, invoke callback. Resolve once all callbacks resolve.
// Ignore files and directories whose basenames are keys in ignored.
async function walkTree({ directory, callback, ignored }) {
const dirents = (await util.promisify(fs.readdir)(directory, {
withFileTypes: true
})).filter(d => !ignored[d.name]);
const fromFilesP = Promise.all(
dirents
.filter(d => d.isFile() && d.name.match(/\.[jt]sx?$/))
// Does not follow symlinks.
.map(async d => callback(path.join(directory, d.name)))
);
const fromDirectoriesP = Promise.all(
dirents
.filter(d => d.isDirectory())
.map(d =>
walkTree({ directory: path.join(directory, d.name), callback, ignored })
)
);
const fromFiles = await fromFilesP;
const fromDirectories = await fromDirectoriesP;
fromDirectories.push(fromFiles);
return [].concat.apply([], fromDirectories);
}
// Return list of modules required by code in the given filename, or
// null if there was a parse error.
async function parseFile(filename) {
const code = await util.promisify(fs.readFile)(filename, {
encoding: "utf-8"
});
let ast;
try {
ast = babelParser.parse(code, {
// Maximum permissibility because the bare imports search is
// just to try to help out the user; we don't need the code to
// be totally valid. See
// <https://babeljs.io/docs/en/next/babel-parser.html>.
allowImportExportEverywhere: true,
allowAwaitOutsideFunction: true,
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
allowUndeclaredExports: true,
sourceType: "unambiguous",
plugins: [
"asyncGenerators",
"bigInt",
"classProperties",
"classPrivateProperties",
"classPrivateMethods",
"doExpressions",
"dynamicImport",
"exportDefaultFrom",
"exportNamespaceFrom",
"functionBind",
"functionSent",
"importMeta",
"logicalAssignment",
"nullishCoalescingOperator",
"numericSeparator",
"objectRestSpread",
"optionalCatchBinding",
"optionalChaining",
"partialApplication",
"throwExpressions"
]
});
} catch (err) {
return null;
}
return parseNode(ast);
}
// Return list of modules required by code in the given Babel AST
// node, array, or other object.
function parseNode(node) {
if (Array.isArray(node)) {
return [].concat.apply([], node.map(parseNode));
}
if (typeof node !== "object" || node === null) {
return [];
}
if (
node.type === "ImportDeclaration" &&
node.source.type === "StringLiteral"
) {
return [node.source.value];
}
if (
node.type === "CallExpression" &&
(node.callee.type === "Import" ||
(node.callee.type === "Identifier" && node.callee.name === "require")) &&
node.arguments.length === 1 &&
node.arguments[0].type === "StringLiteral"
) {
return [node.arguments[0].value];
}
return [].concat.apply([], Object.values(node).map(parseNode));
}
// Given list of arguments, do top-level logic and return or throw
// error.
async function commandLine(args) {
if (args.length != 2) {
throw new Error("usage: node bare-imports.js DIRECTORY IGNORED");
}
const [directory, ignoredList] = args;
const ignored = {};
for (const name of ignoredList.split(",")) {
ignored[name] = true;
}
let hadErrors = false;
const modules = {};
await walkTree({
directory,
callback: async filename => {
const foundModules = await parseFile(filename);
if (foundModules === null) {
hadErrors = true;
} else {
for (const module of foundModules) {
modules[module] = true;
}
}
},
ignored
});
const filteredModules = {};
for (let module in modules) {
// Skip modules loaded via plugins; see
// <https://stackoverflow.com/a/34930235/3538165>.
if (module.indexOf("!") != -1) {
continue;
}
// Prevent our code from crashing.
if (module === "") {
continue;
}
// Skip local modules.
if (module[0] === ".") {
continue;
}
// Skip absolute modules.
if (module[0] === "/") {
continue;
}
// Resolve "express/router" into just "express", but
// "@types/express/router" into "@types/express".
if (module[0] === "@") {
module = module
.split("/")
.slice(0, 2)
.join("/");
} else {
module = module.split("/")[0];
}
filteredModules[module] = true;
}
for (const module of builtinModules) {
delete filteredModules[module];
}
console.log(
JSON.stringify({
modules: Object.keys(filteredModules),
success: !hadErrors
})
);
}
// process.argv has only one element in the case that this module is
// loaded via 'require', and at least two if it is run as a script.
if (process.argv.length >= 2) {
commandLine(process.argv.slice(2))
.then(_ => process.exit(0))
.catch(err => {
console.error(err);
process.exit(1);
});
}
module.exports = { parseFile, parseNode };