/
NodeResolverBase.js
210 lines (182 loc) Β· 5.37 KB
/
NodeResolverBase.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
// @flow
import type {
PackageJSON,
FileCreateInvalidation,
FilePath,
DependencySpecifier,
} from '@parcel/types';
import type {FileSystem} from '@parcel/fs';
import type {ResolveResult} from './types';
// $FlowFixMe
import Module from 'module';
import path from 'path';
import invariant from 'assert';
import {normalizeSeparators} from '@parcel/utils';
const builtins = {pnpapi: true};
for (let builtin of Module.builtinModules) {
builtins[builtin] = true;
}
export type ModuleInfo = {|
moduleName: string,
subPath: ?string,
moduleDir: FilePath,
filePath: FilePath,
code?: string,
|};
export type ResolverContext = {|
invalidateOnFileCreate: Array<FileCreateInvalidation>,
invalidateOnFileChange: Set<FilePath>,
|};
const NODE_MODULES = `${path.sep}node_modules${path.sep}`;
export class NodeResolverBase<T> {
fs: FileSystem;
extensions: Array<string>;
packageCache: Map<string, PackageJSON>;
projectRoot: FilePath;
constructor(
fs: FileSystem,
projectRoot: FilePath,
extensions?: Array<string>,
) {
this.fs = fs;
this.projectRoot = projectRoot;
this.extensions =
extensions ||
// $FlowFixMe[prop-missing]
Object.keys(Module._extensions);
this.packageCache = new Map();
}
resolve(id: DependencySpecifier, from: FilePath): T {
throw new Error(`Could not resolve "${id}" from "${from}"`);
}
expandFile(file: FilePath): Array<FilePath> {
// Expand extensions and aliases
let res = [];
for (let ext of this.extensions) {
let f = file + ext;
res.push(f);
}
if (path.extname(file)) {
res.unshift(file);
} else {
res.push(file);
}
return res;
}
getPackageEntries(dir: FilePath, pkg: PackageJSON): Array<string> {
let main = pkg.main;
if (
(process.env.PARCEL_BUILD_ENV !== 'production' ||
process.env.PARCEL_SELF_BUILD) &&
typeof pkg.name === 'string' &&
typeof pkg.source === 'string' &&
pkg.name.startsWith('@parcel/') &&
pkg.name !== '@parcel/watcher'
) {
main = pkg.source;
}
return [main]
.filter(entry => typeof entry === 'string')
.map(main => {
// Default to index file if no main field find
if (!main || main === '.' || main === './') {
main = 'index';
}
invariant(typeof main === 'string');
return path.resolve(dir, main);
});
}
getModuleParts(name: string): [FilePath, ?string] {
name = path.normalize(name);
let splitOn = name.indexOf(path.sep);
if (name.charAt(0) === '@') {
splitOn = name.indexOf(path.sep, splitOn + 1);
}
if (splitOn < 0) {
return [normalizeSeparators(name), undefined];
} else {
return [
normalizeSeparators(name.substring(0, splitOn)),
name.substring(splitOn + 1) || undefined,
];
}
}
isBuiltin(name: DependencySpecifier): boolean {
return !!(builtins[name] || name.startsWith('node:'));
}
findNodeModulePath(
id: DependencySpecifier,
sourceFile: FilePath,
ctx: ResolverContext,
): ?ResolveResult | ?ModuleInfo {
if (this.isBuiltin(id)) {
return {
resolved: id,
invalidateOnFileChange: new Set(),
invalidateOnFileCreate: [],
};
}
let [moduleName, subPath] = this.getModuleParts(id);
let dir = path.dirname(sourceFile);
let moduleDir = this.fs.findNodeModule(moduleName, dir);
ctx.invalidateOnFileCreate.push({
fileName: `node_modules/${moduleName}`,
aboveFilePath: sourceFile,
});
if (!moduleDir && process.versions.pnp != null) {
try {
// $FlowFixMe[prop-missing]
let pnp = Module.findPnpApi(dir + '/');
moduleDir = pnp.resolveToUnqualified(
moduleName +
// retain slash in `require('assert/')` to force loading builtin from npm
(id[moduleName.length] === '/' ? '/' : ''),
dir + '/',
);
// Invalidate whenever the .pnp.js file changes.
ctx.invalidateOnFileChange.add(
pnp.resolveToUnqualified('pnpapi', null),
);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
}
}
if (moduleDir) {
return {
moduleName,
subPath,
moduleDir: moduleDir,
filePath: subPath ? path.join(moduleDir, subPath) : moduleDir,
};
}
return null;
}
getNodeModulesPackagePath(sourceFile: FilePath): ?FilePath {
// If the file is in node_modules, we can find the package.json in the root of the package
// by slicing from the start of the string until 1-2 path segments after node_modules.
let index = sourceFile.lastIndexOf(NODE_MODULES);
if (index >= 0) {
index += NODE_MODULES.length;
// If a scoped path, add an extra path segment.
if (sourceFile[index] === '@') {
index = sourceFile.indexOf(path.sep, index) + 1;
}
index = sourceFile.indexOf(path.sep, index);
return path.join(
sourceFile.slice(0, index >= 0 ? index : undefined),
'package.json',
);
}
}
invalidate(filePath: FilePath) {
// Invalidate the package.jsons above `filePath`
let dir = path.dirname(filePath);
let {root} = path.parse(dir);
while (dir !== root && path.basename(dir) !== 'node_modules') {
this.packageCache.delete(path.join(dir, 'package.json'));
dir = path.dirname(dir);
}
}
}