/
resolve.js
521 lines (472 loc) Β· 16.5 KB
/
resolve.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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
* @oncall react_native
*/
'use strict';
import type {
FileAndDirCandidates,
FileCandidates,
Resolution,
ResolutionContext,
Result,
} from './types';
const FailedToResolveNameError = require('./errors/FailedToResolveNameError');
const FailedToResolvePathError = require('./errors/FailedToResolvePathError');
const InvalidPackageError = require('./errors/InvalidPackageError');
const formatFileCandidates = require('./errors/formatFileCandidates');
const {getPackageEntryPoint} = require('./PackageResolve');
const {getPackageEntryPointFromExports} = require('./PackageExportsResolve');
const isAbsolutePath = require('absolute-path');
const path = require('path');
function resolve(
context: ResolutionContext,
moduleName: string,
platform: string | null,
): Resolution {
const resolveRequest = context.resolveRequest;
if (
resolveRequest &&
// Prevent infinite recursion in the trivial case
resolveRequest !== resolve
) {
return resolveRequest(
Object.freeze({...context, resolveRequest: resolve}),
moduleName,
platform,
);
}
if (isRelativeImport(moduleName) || isAbsolutePath(moduleName)) {
return resolveModulePath(context, moduleName, platform);
}
const realModuleName = context.redirectModulePath(moduleName);
// exclude
if (realModuleName === false) {
return {type: 'empty'};
}
const {originModulePath} = context;
const isDirectImport =
isRelativeImport(realModuleName) || isAbsolutePath(realModuleName);
if (isDirectImport) {
// derive absolute path /.../node_modules/originModuleDir/realModuleName
const fromModuleParentIdx =
originModulePath.lastIndexOf('node_modules' + path.sep) + 13;
const originModuleDir = originModulePath.slice(
0,
originModulePath.indexOf(path.sep, fromModuleParentIdx),
);
const absPath = path.join(originModuleDir, realModuleName);
return resolveModulePath(context, absPath, platform);
}
if (context.allowHaste && !isDirectImport) {
const normalizedName = normalizePath(realModuleName);
const result = resolveHasteName(context, normalizedName, platform);
if (result.type === 'resolved') {
return result.resolution;
}
}
const {disableHierarchicalLookup} = context;
const nodeModulesPaths = [];
let next = path.dirname(originModulePath);
if (!disableHierarchicalLookup) {
let candidate;
do {
candidate = next;
nodeModulesPaths.push(path.join(candidate, 'node_modules'));
next = path.dirname(candidate);
} while (candidate !== next);
}
// Fall back to `nodeModulesPaths` after hierarchical lookup, similar to $NODE_PATH
nodeModulesPaths.push(...context.nodeModulesPaths);
const extraPaths = [];
const {extraNodeModules} = context;
if (extraNodeModules) {
let bits = path.normalize(moduleName).split(path.sep);
let packageName;
// Normalize packageName and bits for scoped modules
if (bits.length >= 2 && bits[0].startsWith('@')) {
packageName = bits.slice(0, 2).join('/');
bits = bits.slice(1);
} else {
packageName = bits[0];
}
if (extraNodeModules[packageName]) {
bits[0] = extraNodeModules[packageName];
extraPaths.push(path.join.apply(path, bits));
}
}
const allDirPaths = nodeModulesPaths
.map(nodeModulePath => path.join(nodeModulePath, realModuleName))
.concat(extraPaths);
for (let i = 0; i < allDirPaths.length; ++i) {
const candidate = context.redirectModulePath(allDirPaths[i]);
// $FlowFixMe[incompatible-call]
const result = resolveFileOrDir(context, candidate, platform);
if (result.type === 'resolved') {
return result.resolution;
}
}
throw new FailedToResolveNameError(nodeModulesPaths, extraPaths);
}
/**
* Resolve any kind of module path, whether it's a file or a directory.
* For example we may want to resolve './foobar'. The closest
* `package.json` may define a redirection for this path, for example
* `/smth/lib/foobar`, that may be further resolved to
* `/smth/lib/foobar/index.ios.js`.
*/
function resolveModulePath(
context: ResolutionContext,
toModuleName: string,
platform: string | null,
): Resolution {
const modulePath = isAbsolutePath(toModuleName)
? resolveWindowsPath(toModuleName)
: path.join(path.dirname(context.originModulePath), toModuleName);
const redirectedPath = context.redirectModulePath(modulePath);
if (redirectedPath === false) {
return {type: 'empty'};
}
const result = resolveFileOrDir(context, redirectedPath, platform);
if (result.type === 'resolved') {
return result.resolution;
}
throw new FailedToResolvePathError(result.candidates);
}
/**
* Resolve a module as a Haste module or package. For example we might try to
* resolve `Foo`, that is provided by file `/smth/Foo.js`. Or, in the case of
* a Haste package, it could be `/smth/Foo/index.js`.
*/
function resolveHasteName(
context: ResolutionContext,
moduleName: string,
platform: string | null,
): Result<Resolution, void> {
const modulePath = context.resolveHasteModule(moduleName);
if (modulePath != null) {
return resolvedAs({type: 'sourceFile', filePath: modulePath});
}
let packageName = moduleName;
let packageJsonPath = context.resolveHastePackage(packageName);
while (packageJsonPath == null && packageName && packageName !== '.') {
packageName = path.dirname(packageName);
packageJsonPath = context.resolveHastePackage(packageName);
}
if (packageJsonPath == null) {
return failedFor();
}
const packageDirPath = path.dirname(packageJsonPath);
const pathInModule = moduleName.substring(packageName.length + 1);
const potentialModulePath = path.join(packageDirPath, pathInModule);
const result = resolveFileOrDir(context, potentialModulePath, platform);
if (result.type === 'resolved') {
return result;
}
const {candidates} = result;
const opts = {moduleName, packageName, pathInModule, candidates};
throw new MissingFileInHastePackageError(opts);
}
class MissingFileInHastePackageError extends Error {
candidates: FileAndDirCandidates;
moduleName: string;
packageName: string;
pathInModule: string;
constructor(opts: {
+candidates: FileAndDirCandidates,
+moduleName: string,
+packageName: string,
+pathInModule: string,
}) {
super(
`While resolving module \`${opts.moduleName}\`, ` +
`the Haste package \`${opts.packageName}\` was found. However the ` +
`module \`${opts.pathInModule}\` could not be found within ` +
'the package. Indeed, none of these files exist:\n\n' +
` * \`${formatFileCandidates(opts.candidates.file)}\`\n` +
` * \`${formatFileCandidates(opts.candidates.dir)}\``,
);
Object.assign(this, opts);
}
}
/**
* In the NodeJS-style module resolution scheme we want to check potential
* paths both as directories and as files. For example, `/foo/bar` may resolve
* to `/foo/bar.js` (preferred), but it might also be `/foo/bar/index.js`, or
* even a package directory.
*/
function resolveFileOrDir(
context: ResolutionContext,
potentialModulePath: string,
platform: string | null,
): Result<Resolution, FileAndDirCandidates> {
const dirPath = path.dirname(potentialModulePath);
const fileNameHint = path.basename(potentialModulePath);
const fileResult = resolveFile(context, dirPath, fileNameHint, platform);
if (fileResult.type === 'resolved') {
return fileResult;
}
const dirResult = resolvePackageEntryPoint(
context,
potentialModulePath,
platform,
);
if (dirResult.type === 'resolved') {
return dirResult;
}
return failedFor({file: fileResult.candidates, dir: dirResult.candidates});
}
/**
* Attempt to resolve a module path as an npm package entry point, or resolve as
* a file if no `package.json` file is present.
*
* When `context.unstable_enablePackageExports` is `true`, attempts to resolve
* using the "exports" field if present, based on the [Package Entry Points spec
* ](https://nodejs.org/docs/latest-v19.x/api/packages.html#package-entry-points).
*
* If resolution via "exports" does not return a match, or
* `context.unstable_enablePackageExports` is `false`, will fall back to legacy
* (non-exports) package resolution behaviour based on the ["browser" field spec
* ](https://github.com/defunctzombie/package-browser-field-spec). This method
* of resolution will additionally:
* - Expand source and platform-specific extensions, e.g. `./lib/index` ->
* `./lib/index.ios.js`.
* - Fall back to a child `index.js` file, e.g. `./lib` -> `./lib/index.js`.
*/
function resolvePackageEntryPoint(
context: ResolutionContext,
modulePath: string,
platform: string | null,
): Result<Resolution, FileCandidates> {
const {doesFileExist, unstable_enablePackageExports} = context;
const packageJsonPath = path.join(modulePath, 'package.json');
if (!context.doesFileExist(packageJsonPath)) {
return resolveFile(context, modulePath, 'index', platform);
}
const packageInfo = {
rootPath: path.dirname(packageJsonPath),
packageJson: context.getPackage(packageJsonPath) ?? {},
};
if (unstable_enablePackageExports) {
const packageExportsEntryPoint = getPackageEntryPointFromExports(
context,
packageInfo,
platform,
);
if (packageExportsEntryPoint != null) {
const mainModulePath = path.join(
packageInfo.rootPath,
packageExportsEntryPoint,
);
if (doesFileExist(mainModulePath)) {
return resolvedAs({type: 'sourceFile', filePath: mainModulePath});
}
// TODO(T142200031): Log an invalid package warning if entry point missing
}
}
const mainModulePath = path.join(
packageInfo.rootPath,
getPackageEntryPoint(context, packageInfo, platform),
);
const fileResult = resolveFile(
context,
path.dirname(mainModulePath),
path.basename(mainModulePath),
platform,
);
if (fileResult.type === 'resolved') {
return fileResult;
}
// Fallback: Attempt to resolve any file at <subpath>/index.js
const indexResult = resolveFile(context, mainModulePath, 'index', platform);
if (indexResult.type !== 'resolved') {
throw new InvalidPackageError({
packageJsonPath,
mainModulePath,
fileCandidates: fileResult.candidates,
indexCandidates: indexResult.candidates,
});
}
return indexResult;
}
/**
* Given a file name for a particular directory, return a resolution result
* depending on whether or not we found the corresponding module as a file. For
* example, we might ask for `foo.png`, that resolves to
* `['/js/beep/foo.ios.png']`. Or we may ask for `boop`, that resolves to
* `/js/boop.android.ts`. On the other hand this function does not resolve
* directory-based module names: for example `boop` will not resolve to
* `/js/boop/index.js` (see `_loadAsDir` for that).
*/
function resolveFile(
context: ResolutionContext,
dirPath: string,
fileName: string,
platform: string | null,
): Result<Resolution, FileCandidates> {
const {isAssetFile, resolveAsset} = context;
if (isAssetFile(fileName)) {
const extension = path.extname(fileName);
const basename = path.basename(fileName, extension);
if (!/@\d+(?:\.\d+)?x$/.test(basename)) {
try {
const assets = resolveAsset(dirPath, basename, extension);
if (assets != null) {
return mapResult(resolvedAs(assets), filePaths => ({
type: 'assetFiles',
filePaths,
}));
}
} catch (err) {
if (err.code === 'ENOENT') {
return failedFor({type: 'asset', name: fileName});
}
}
}
return failedFor({type: 'asset', name: fileName});
}
const candidateExts: Array<string> = [];
const filePathPrefix = path.join(dirPath, fileName);
const sfContext = {...context, candidateExts, filePathPrefix};
const sourceFileResolution = resolveSourceFile(sfContext, platform);
if (sourceFileResolution != null) {
if (typeof sourceFileResolution === 'string') {
return resolvedAs({type: 'sourceFile', filePath: sourceFileResolution});
}
return resolvedAs(sourceFileResolution);
}
return failedFor({type: 'sourceFile', filePathPrefix, candidateExts});
}
type SourceFileContext = $ReadOnly<{
...ResolutionContext,
candidateExts: Array<string>,
filePathPrefix: string,
}>;
// Either a full path, or a restricted subset of Resolution.
type SourceFileResolution = ?string | $ReadOnly<{type: 'empty'}>;
/**
* A particular 'base path' can resolve to a number of possibilities depending
* on the context. For example `foo/bar` could resolve to `foo/bar.ios.js`, or
* to `foo/bar.js`. If can also resolve to the bare path `foo/bar` itself, as
* supported by Node.js resolution. On the other hand it doesn't support
* `foo/bar.ios`, for historical reasons.
*
* Return the full path of the resolved module, `null` if no resolution could
* be found, or `{type: 'empty'}` if redirected to an empty module.
*/
function resolveSourceFile(
context: SourceFileContext,
platform: ?string,
): SourceFileResolution {
let filePath = resolveSourceFileForAllExts(context, '');
if (filePath) {
return filePath;
}
const {sourceExts} = context;
for (let i = 0; i < sourceExts.length; i++) {
const ext = `.${sourceExts[i]}`;
filePath = resolveSourceFileForAllExts(context, ext, platform);
if (filePath != null) {
return filePath;
}
}
return null;
}
/**
* For a particular extension, ex. `js`, we want to try a few possibilities,
* such as `foo.ios.js`, `foo.native.js`, and of course `foo.js`. Return the
* full path of the resolved module, `null` if no resolution could be found, or
* `{type: 'empty'}` if redirected to an empty module.
*/
function resolveSourceFileForAllExts(
context: SourceFileContext,
sourceExt: string,
platform: ?string,
): SourceFileResolution {
if (platform != null) {
const ext = `.${platform}${sourceExt}`;
const filePath = resolveSourceFileForExt(context, ext);
if (filePath) {
return filePath;
}
}
if (context.preferNativePlatform) {
const filePath = resolveSourceFileForExt(context, `.native${sourceExt}`);
if (filePath) {
return filePath;
}
}
const filePath = resolveSourceFileForExt(context, sourceExt);
return filePath;
}
/**
* We try to resolve a single possible extension. If it doesn't exist, then
* we make sure to add the extension to a list of candidates for reporting.
*/
function resolveSourceFileForExt(
context: SourceFileContext,
extension: string,
): SourceFileResolution {
const filePath = `${context.filePathPrefix}${extension}`;
const redirectedPath =
// Any redirections for the bare path have already happened
extension !== '' ? context.redirectModulePath(filePath) : filePath;
if (redirectedPath === false) {
return {type: 'empty'};
}
if (context.unstable_getRealPath) {
const maybeRealPath = context.unstable_getRealPath(redirectedPath);
if (maybeRealPath != null) {
return maybeRealPath;
}
} else if (context.doesFileExist(redirectedPath)) {
return redirectedPath;
}
context.candidateExts.push(extension);
return null;
}
// HasteFS stores paths with backslashes on Windows, this ensures the path is in
// the proper format. Will also add drive letter if not present so `/root` will
// resolve to `C:\root`. Noop on other platforms.
function resolveWindowsPath(modulePath: string) {
if (path.sep !== '\\') {
return modulePath;
}
return path.resolve(modulePath);
}
function isRelativeImport(filePath: string) {
return /^[.][.]?(?:[/]|$)/.test(filePath);
}
function normalizePath(modulePath: any | string) {
if (path.sep === '/') {
modulePath = path.normalize(modulePath);
} else if (path.posix) {
modulePath = path.posix.normalize(modulePath);
}
return modulePath.replace(/\/$/, '');
}
function resolvedAs<TResolution, TCandidates>(
resolution: TResolution,
): Result<TResolution, TCandidates> {
return {type: 'resolved', resolution};
}
function failedFor<TResolution, TCandidates>(
candidates: TCandidates,
): Result<TResolution, TCandidates> {
return {type: 'failed', candidates};
}
function mapResult<TResolution, TNewResolution, TCandidates>(
result: Result<TResolution, TCandidates>,
mapper: TResolution => TNewResolution,
): Result<TNewResolution, TCandidates> {
if (result.type === 'failed') {
return result;
}
return {type: 'resolved', resolution: mapper(result.resolution)};
}
module.exports = resolve;