This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

3
node_modules/metro-resolver/README.md generated vendored Normal file
View File

@ -0,0 +1,3 @@
# metro-resolver
🚇 [Metro](https://facebook.github.io/metro/) resolution logic

18
node_modules/metro-resolver/package.json generated vendored Normal file
View File

@ -0,0 +1,18 @@
{
"version": "0.59.0",
"name": "metro-resolver",
"description": "🚇 Metro resolution logic",
"main": "src",
"repository": {
"type": "git",
"url": "git@github.com:facebook/metro.git"
},
"scripts": {
"prepare-release": "test -d build && rm -rf src.real && mv src src.real && mv build src",
"cleanup-release": "test ! -e build && mv src build && mv src.real src"
},
"dependencies": {
"absolute-path": "^0.0.0"
},
"license": "MIT"
}

4
node_modules/metro-resolver/rn-babelrc.json generated vendored Normal file
View File

@ -0,0 +1,4 @@
{
"presets": [ "metro-react-native-babel-preset" ],
"plugins": []
}

View File

@ -0,0 +1,30 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict
* @format
*/
"use strict";
const path = require("path");
class FailedToResolveNameError extends Error {
constructor(dirPaths, extraPaths) {
const displayDirPaths = dirPaths.concat(extraPaths);
const hint = displayDirPaths.length ? " or in these directories:" : "";
super(
`Module does not exist in the Haste module map${hint}\n` +
displayDirPaths
.map(dirPath => ` ${path.dirname(dirPath)}\n`)
.join(", ") +
"\n"
);
this.dirPaths = dirPaths;
this.extraPaths = extraPaths;
}
}
module.exports = FailedToResolveNameError;

View File

@ -0,0 +1,38 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
const path = require('path');
class FailedToResolveNameError extends Error {
dirPaths: $ReadOnlyArray<string>;
extraPaths: $ReadOnlyArray<string>;
constructor(
dirPaths: $ReadOnlyArray<string>,
extraPaths: $ReadOnlyArray<string>,
) {
const displayDirPaths = dirPaths.concat(extraPaths);
const hint = displayDirPaths.length ? ' or in these directories:' : '';
super(
`Module does not exist in the Haste module map${hint}\n` +
displayDirPaths
.map(dirPath => ` ${path.dirname(dirPath)}\n`)
.join(', ') +
'\n',
);
this.dirPaths = dirPaths;
this.extraPaths = extraPaths;
}
}
module.exports = FailedToResolveNameError;

View File

@ -0,0 +1,25 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict
* @format
*/
"use strict";
const formatFileCandidates = require("./formatFileCandidates");
class FailedToResolvePathError extends Error {
constructor(candidates) {
super(
"The module could not be resolved because none of these files exist:\n\n" +
` * ${formatFileCandidates(candidates.file)}\n` +
` * ${formatFileCandidates(candidates.dir)}`
);
this.candidates = candidates;
}
}
module.exports = FailedToResolvePathError;

View File

@ -0,0 +1,30 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
const formatFileCandidates = require('./formatFileCandidates');
import type {FileAndDirCandidates} from './types';
class FailedToResolvePathError extends Error {
candidates: FileAndDirCandidates;
constructor(candidates: FileAndDirCandidates) {
super(
'The module could not be resolved because none of these files exist:\n\n' +
` * ${formatFileCandidates(candidates.file)}\n` +
` * ${formatFileCandidates(candidates.dir)}`,
);
this.candidates = candidates;
}
}
module.exports = FailedToResolvePathError;

47
node_modules/metro-resolver/src/InvalidPackageError.js generated vendored Normal file
View File

@ -0,0 +1,47 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict
* @format
*/
"use strict";
const formatFileCandidates = require("./formatFileCandidates");
class InvalidPackageError extends Error {
/**
* The file candidates we tried to find to resolve the `main` field of the
* package. Ex. `/js/foo/beep(.js|.json)?` if `main` is specifying `./beep`
* as the entry point.
*/
/**
* The 'index' file candidates we tried to find to resolve the `main` field of
* the package. Ex. `/js/foo/beep/index(.js|.json)?` if `main` is specifying
* `./beep` as the entry point.
*/
/**
* The module path prefix we where trying to resolve. For example './beep'.
*/
/**
* Full path the package we were trying to resolve.
* Ex. `/js/foo/package.json`.
*/
constructor(opts) {
super(
`The package \`${opts.packageJsonPath}\` is invalid because it ` +
"specifies a `main` module field that could not be resolved (" +
`\`${opts.mainPrefixPath}\`. None of these files exist:\n\n` +
` * ${formatFileCandidates(opts.fileCandidates)}\n` +
` * ${formatFileCandidates(opts.indexCandidates)}`
);
Object.assign(this, opts);
}
}
module.exports = InvalidPackageError;

View File

@ -0,0 +1,57 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
const formatFileCandidates = require('./formatFileCandidates');
import type {FileCandidates} from './types';
class InvalidPackageError extends Error {
/**
* The file candidates we tried to find to resolve the `main` field of the
* package. Ex. `/js/foo/beep(.js|.json)?` if `main` is specifying `./beep`
* as the entry point.
*/
fileCandidates: FileCandidates;
/**
* The 'index' file candidates we tried to find to resolve the `main` field of
* the package. Ex. `/js/foo/beep/index(.js|.json)?` if `main` is specifying
* `./beep` as the entry point.
*/
indexCandidates: FileCandidates;
/**
* The module path prefix we where trying to resolve. For example './beep'.
*/
mainPrefixPath: string;
/**
* Full path the package we were trying to resolve.
* Ex. `/js/foo/package.json`.
*/
packageJsonPath: string;
constructor(opts: {|
+fileCandidates: FileCandidates,
+indexCandidates: FileCandidates,
+mainPrefixPath: string,
+packageJsonPath: string,
|}) {
super(
`The package \`${opts.packageJsonPath}\` is invalid because it ` +
'specifies a `main` module field that could not be resolved (' +
`\`${opts.mainPrefixPath}\`. None of these files exist:\n\n` +
` * ${formatFileCandidates(opts.fileCandidates)}\n` +
` * ${formatFileCandidates(opts.indexCandidates)}`,
);
Object.assign(this, opts);
}
}
module.exports = InvalidPackageError;

View File

@ -0,0 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict
* @format
*/
"use strict";
function formatFileCandidates(candidates) {
if (candidates.type === "asset") {
return candidates.name;
}
return `${candidates.filePathPrefix}(${candidates.candidateExts
.filter(Boolean)
.join("|")})`;
}
module.exports = formatFileCandidates;

View File

@ -0,0 +1,24 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
import type {FileCandidates} from './types';
function formatFileCandidates(candidates: FileCandidates): string {
if (candidates.type === 'asset') {
return candidates.name;
}
return `${candidates.filePathPrefix}(${candidates.candidateExts
.filter(Boolean)
.join('|')})`;
}
module.exports = formatFileCandidates;

19
node_modules/metro-resolver/src/index.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
const Resolver = {
FailedToResolveNameError: require("./FailedToResolveNameError"),
FailedToResolvePathError: require("./FailedToResolvePathError"),
formatFileCandidates: require("./formatFileCandidates"),
InvalidPackageError: require("./InvalidPackageError"),
resolve: require("./resolve")
};
module.exports = Resolver;

35
node_modules/metro-resolver/src/index.js.flow generated vendored Normal file
View File

@ -0,0 +1,35 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
export type {
AssetFileResolution,
CustomResolver,
DoesFileExist,
FileAndDirCandidates,
FileCandidates,
FileResolution,
IsAssetFile,
ResolutionContext,
Resolution,
ResolveAsset,
Result,
} from './types';
const Resolver = {
FailedToResolveNameError: require('./FailedToResolveNameError'),
FailedToResolvePathError: require('./FailedToResolvePathError'),
formatFileCandidates: require('./formatFileCandidates'),
InvalidPackageError: require('./InvalidPackageError'),
resolve: require('./resolve'),
};
module.exports = Resolver;

520
node_modules/metro-resolver/src/resolve.js generated vendored Normal file
View File

@ -0,0 +1,520 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
"use strict";
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const FailedToResolveNameError = require("./FailedToResolveNameError");
const FailedToResolvePathError = require("./FailedToResolvePathError");
const InvalidPackageError = require("./InvalidPackageError");
const formatFileCandidates = require("./formatFileCandidates");
const isAbsolutePath = require("absolute-path");
const path = require("path");
function resolve(context, moduleName, platform) {
const resolveRequest = context.resolveRequest;
if (
!resolveRequest &&
(isRelativeImport(moduleName) || isAbsolutePath(moduleName))
) {
return resolveModulePath(context, moduleName, platform);
}
const realModuleName = context.redirectModulePath(moduleName); // exclude
if (realModuleName === false) {
return {
type: "empty"
};
}
const originModulePath = context.originModulePath;
const isDirectImport =
isRelativeImport(realModuleName) || isAbsolutePath(realModuleName); // We disable the direct file loading to let the custom resolvers deal with it
if (!resolveRequest && 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);
} // The Haste resolution must occur before the custom resolver because we want
// to allow overriding imports. It could be part of the custom resolver, but
// that's not the case right now.
if (context.allowHaste && !isDirectImport) {
const normalizedName = normalizePath(realModuleName);
const result = resolveHasteName(context, normalizedName, platform);
if (result.type === "resolved") {
return result.resolution;
}
}
if (resolveRequest) {
try {
const resolution = resolveRequest(
context,
realModuleName,
platform,
moduleName
);
if (resolution) {
return resolution;
}
} catch (error) {}
}
const dirPaths = [];
for (
let currDir = path.dirname(originModulePath);
currDir !== "." && currDir !== path.parse(originModulePath).root;
currDir = path.dirname(currDir)
) {
const searchPath = path.join(currDir, "node_modules");
dirPaths.push(path.join(searchPath, realModuleName));
}
const extraPaths = [];
const extraNodeModules = context.extraNodeModules;
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 = dirPaths.concat(extraPaths);
for (let i = 0; i < allDirPaths.length; ++i) {
const realModuleName = context.redirectModulePath(allDirPaths[i]);
const result = resolveFileOrDir(context, realModuleName, platform);
if (result.type === "resolved") {
return result.resolution;
}
}
throw new FailedToResolveNameError(dirPaths, 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, toModuleName, platform) {
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, moduleName, platform) {
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.candidates;
const opts = {
moduleName,
packageName,
pathInModule,
candidates
};
throw new MissingFileInHastePackageError(opts);
}
class MissingFileInHastePackageError extends Error {
constructor(opts) {
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, potentialModulePath, platform) {
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 = resolveDir(context, potentialModulePath, platform);
if (dirResult.type === "resolved") {
return dirResult;
}
return failedFor({
file: fileResult.candidates,
dir: dirResult.candidates
});
}
/**
* Try to resolve a potential path as if it was a directory-based module.
* Either this is a directory that contains a package, or that the directory
* contains an index file. If it fails to resolve these options, it returns
* `null` and fills the array of `candidates` that were tried.
*
* For example we could try to resolve `/foo/bar`, that would eventually
* resolve to `/foo/bar/lib/index.ios.js` if we're on platform iOS and that
* `bar` contains a package which entry point is `./lib/index` (or `./lib`).
*/
function resolveDir(context, potentialDirPath, platform) {
const packageJsonPath = path.join(potentialDirPath, "package.json");
if (context.doesFileExist(packageJsonPath)) {
const resolution = resolvePackage(context, packageJsonPath, platform);
return {
resolution,
type: "resolved"
};
}
return resolveFile(context, potentialDirPath, "index", platform);
}
/**
* Resolve the main module of a package that we know exist. The resolution
* itself cannot fail because we already resolved the path to the package.
* If the `main` of the package is invalid, this is not a resolution failure,
* this means the package is invalid, and should purposefully stop the
* resolution process altogether.
*/
function resolvePackage(context, packageJsonPath, platform) {
const mainPrefixPath = context.getPackageMainPath(packageJsonPath);
const dirPath = path.dirname(mainPrefixPath);
const prefixName = path.basename(mainPrefixPath);
const fileResult = resolveFile(context, dirPath, prefixName, platform);
if (fileResult.type === "resolved") {
return fileResult.resolution;
}
const indexResult = resolveFile(context, mainPrefixPath, "index", platform);
if (indexResult.type === "resolved") {
return indexResult.resolution;
}
throw new InvalidPackageError({
packageJsonPath,
mainPrefixPath,
indexCandidates: indexResult.candidates,
fileCandidates: fileResult.candidates
});
}
/**
* 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, dirPath, fileName, platform) {
const isAssetFile = context.isAssetFile,
resolveAsset = context.resolveAsset;
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 = [];
const filePathPrefix = path.join(dirPath, fileName);
const sfContext = _objectSpread({}, context, {
candidateExts,
filePathPrefix
});
const filePath = resolveSourceFile(sfContext, platform);
if (filePath != null) {
return resolvedAs({
type: "sourceFile",
filePath
});
}
return failedFor({
type: "sourceFile",
filePathPrefix,
candidateExts
});
}
/**
* 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.
*/
function resolveSourceFile(context, platform) {
let filePath = resolveSourceFileForAllExts(context, "");
if (filePath) {
return filePath;
}
const sourceExts = context.sourceExts;
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.
*/
function resolveSourceFileForAllExts(context, sourceExt, platform) {
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, extension) {
const filePath = `${context.filePathPrefix}${extension}`;
if (context.doesFileExist(filePath)) {
return filePath;
}
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) {
if (path.sep !== "\\") {
return modulePath;
}
return path.resolve(modulePath);
}
function isRelativeImport(filePath) {
return /^[.][.]?(?:[/]|$)/.test(filePath);
}
function normalizePath(modulePath) {
if (path.sep === "/") {
modulePath = path.normalize(modulePath);
} else if (path.posix) {
modulePath = path.posix.normalize(modulePath);
}
return modulePath.replace(/\/$/, "");
}
function resolvedAs(resolution) {
return {
type: "resolved",
resolution
};
}
function failedFor(candidates) {
return {
type: "failed",
candidates
};
}
function mapResult(result, mapper) {
if (result.type === "failed") {
return result;
}
return {
type: "resolved",
resolution: mapper(result.resolution)
};
}
module.exports = resolve;

481
node_modules/metro-resolver/src/resolve.js.flow generated vendored Normal file
View File

@ -0,0 +1,481 @@
/**
* Copyright (c) Facebook, Inc. and its 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
*/
'use strict';
const FailedToResolveNameError = require('./FailedToResolveNameError');
const FailedToResolvePathError = require('./FailedToResolvePathError');
const InvalidPackageError = require('./InvalidPackageError');
const formatFileCandidates = require('./formatFileCandidates');
const isAbsolutePath = require('absolute-path');
const path = require('path');
import type {
DoesFileExist,
FileAndDirCandidates,
FileCandidates,
FileContext,
FileOrDirContext,
FileResolution,
HasteContext,
ModulePathContext,
ResolutionContext,
Resolution,
Result,
} from './types';
function resolve(
context: ResolutionContext,
moduleName: string,
platform: string | null,
): Resolution {
const resolveRequest = context.resolveRequest;
if (
!resolveRequest &&
(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);
// We disable the direct file loading to let the custom resolvers deal with it
if (!resolveRequest && 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);
}
// The Haste resolution must occur before the custom resolver because we want
// to allow overriding imports. It could be part of the custom resolver, but
// that's not the case right now.
if (context.allowHaste && !isDirectImport) {
const normalizedName = normalizePath(realModuleName);
const result = resolveHasteName(context, normalizedName, platform);
if (result.type === 'resolved') {
return result.resolution;
}
}
if (resolveRequest) {
try {
const resolution = resolveRequest(
context,
realModuleName,
platform,
moduleName,
);
if (resolution) {
return resolution;
}
} catch (error) {}
}
const dirPaths = [];
for (
let currDir = path.dirname(originModulePath);
currDir !== '.' && currDir !== path.parse(originModulePath).root;
currDir = path.dirname(currDir)
) {
const searchPath = path.join(currDir, 'node_modules');
dirPaths.push(path.join(searchPath, realModuleName));
}
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 = dirPaths.concat(extraPaths);
for (let i = 0; i < allDirPaths.length; ++i) {
const realModuleName = context.redirectModulePath(allDirPaths[i]);
const result = resolveFileOrDir(context, realModuleName, platform);
if (result.type === 'resolved') {
return result.resolution;
}
}
throw new FailedToResolveNameError(dirPaths, 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: ModulePathContext,
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: HasteContext,
moduleName: string,
platform: string | null,
): Result<FileResolution, 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: FileOrDirContext,
potentialModulePath: string,
platform: string | null,
): Result<FileResolution, 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 = resolveDir(context, potentialModulePath, platform);
if (dirResult.type === 'resolved') {
return dirResult;
}
return failedFor({file: fileResult.candidates, dir: dirResult.candidates});
}
/**
* Try to resolve a potential path as if it was a directory-based module.
* Either this is a directory that contains a package, or that the directory
* contains an index file. If it fails to resolve these options, it returns
* `null` and fills the array of `candidates` that were tried.
*
* For example we could try to resolve `/foo/bar`, that would eventually
* resolve to `/foo/bar/lib/index.ios.js` if we're on platform iOS and that
* `bar` contains a package which entry point is `./lib/index` (or `./lib`).
*/
function resolveDir(
context: FileOrDirContext,
potentialDirPath: string,
platform: string | null,
): Result<FileResolution, FileCandidates> {
const packageJsonPath = path.join(potentialDirPath, 'package.json');
if (context.doesFileExist(packageJsonPath)) {
const resolution = resolvePackage(context, packageJsonPath, platform);
return {resolution, type: 'resolved'};
}
return resolveFile(context, potentialDirPath, 'index', platform);
}
/**
* Resolve the main module of a package that we know exist. The resolution
* itself cannot fail because we already resolved the path to the package.
* If the `main` of the package is invalid, this is not a resolution failure,
* this means the package is invalid, and should purposefully stop the
* resolution process altogether.
*/
function resolvePackage(
context: FileOrDirContext,
packageJsonPath: string,
platform: string | null,
): FileResolution {
const mainPrefixPath = context.getPackageMainPath(packageJsonPath);
const dirPath = path.dirname(mainPrefixPath);
const prefixName = path.basename(mainPrefixPath);
const fileResult = resolveFile(context, dirPath, prefixName, platform);
if (fileResult.type === 'resolved') {
return fileResult.resolution;
}
const indexResult = resolveFile(context, mainPrefixPath, 'index', platform);
if (indexResult.type === 'resolved') {
return indexResult.resolution;
}
throw new InvalidPackageError({
packageJsonPath,
mainPrefixPath,
indexCandidates: indexResult.candidates,
fileCandidates: fileResult.candidates,
});
}
/**
* 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: FileContext,
dirPath: string,
fileName: string,
platform: string | null,
): Result<FileResolution, 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 = [];
const filePathPrefix = path.join(dirPath, fileName);
const sfContext = {...context, candidateExts, filePathPrefix};
const filePath = resolveSourceFile(sfContext, platform);
if (filePath != null) {
return resolvedAs({type: 'sourceFile', filePath});
}
return failedFor({type: 'sourceFile', filePathPrefix, candidateExts});
}
type SourceFileContext = SourceFileForAllExtsContext & {
+sourceExts: $ReadOnlyArray<string>,
...
};
/**
* 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.
*/
function resolveSourceFile(
context: SourceFileContext,
platform: ?string,
): ?string {
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;
}
type SourceFileForAllExtsContext = SourceFileForExtContext & {
+preferNativePlatform: boolean,
...
};
/**
* 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.
*/
function resolveSourceFileForAllExts(
context: SourceFileForAllExtsContext,
sourceExt: string,
platform: ?string,
): ?string {
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;
}
type SourceFileForExtContext = {
+candidateExts: Array<string>,
+doesFileExist: DoesFileExist,
+filePathPrefix: string,
...
};
/**
* 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: SourceFileForExtContext,
extension: string,
): ?string {
const filePath = `${context.filePathPrefix}${extension}`;
if (context.doesFileExist(filePath)) {
return filePath;
}
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) {
if (path.sep !== '\\') {
return modulePath;
}
return path.resolve(modulePath);
}
function isRelativeImport(filePath: string) {
return /^[.][.]?(?:[/]|$)/.test(filePath);
}
function normalizePath(modulePath) {
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;

10
node_modules/metro-resolver/src/types.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict
* @format
*/
"use strict";

126
node_modules/metro-resolver/src/types.js.flow generated vendored Normal file
View File

@ -0,0 +1,126 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
export type Result<+TResolution, +TCandidates> =
| {|+type: 'resolved', +resolution: TResolution|}
| {|+type: 'failed', +candidates: TCandidates|};
export type Resolution = FileResolution | {|+type: 'empty'|};
export type AssetFileResolution = $ReadOnlyArray<string>;
export type FileResolution =
| {|+type: 'sourceFile', +filePath: string|}
| {|+type: 'assetFiles', +filePaths: AssetFileResolution|};
export type FileAndDirCandidates = {|
+dir: FileCandidates,
+file: FileCandidates,
|};
/**
* This is a way to describe what files we tried to look for when resolving
* a module name as file. This is mainly used for error reporting, so that
* we can explain why we cannot resolve a module.
*/
export type FileCandidates =
// We only tried to resolve a specific asset.
| {|+type: 'asset', +name: string|}
// We attempted to resolve a name as being a source file (ex. JavaScript,
// JSON...), in which case there can be several extensions we tried, for
// example `/js/foo.ios.js`, `/js/foo.js`, etc. for a single prefix '/js/foo'.
| {|
+type: 'sourceFile',
filePathPrefix: string,
+candidateExts: $ReadOnlyArray<string>,
|};
/**
* Check existence of a single file.
*/
export type DoesFileExist = (filePath: string) => boolean;
export type IsAssetFile = (fileName: string) => boolean;
/**
* Given a directory path and the base asset name, return a list of all the
* asset file names that match the given base name in that directory. Return
* null if there's no such named asset. `platform` is used to identify
* platform-specific assets, ex. `foo.ios.js` instead of a generic `foo.js`.
*/
export type ResolveAsset = (
dirPath: string,
assetName: string,
extension: string,
) => ?$ReadOnlyArray<string>;
export type FileContext = {
+doesFileExist: DoesFileExist,
+isAssetFile: IsAssetFile,
+preferNativePlatform: boolean,
+redirectModulePath: (modulePath: string) => string | false,
+resolveAsset: ResolveAsset,
+sourceExts: $ReadOnlyArray<string>,
...
};
export type FileOrDirContext = FileContext & {
/**
* This should return the path of the "main" module of the specified
* `package.json` file, after post-processing: for example, applying the
* 'browser' field if necessary.
*
* FIXME: move the post-processing here. Right now it is
* located in `node-haste/Package.js`, and fully duplicated in
* `ModuleGraph/node-haste/Package.js` (!)
*/
+getPackageMainPath: (packageJsonPath: string) => string,
...
};
export type HasteContext = FileOrDirContext & {
/**
* Given a name, this should return the full path to the file that provides
* a Haste module of that name. Ex. for `Foo` it may return `/smth/Foo.js`.
*/
+resolveHasteModule: (name: string) => ?string,
/**
* Given a name, this should return the full path to the package manifest that
* provides a Haste package of that name. Ex. for `Foo` it may return
* `/smth/Foo/package.json`.
*/
+resolveHastePackage: (name: string) => ?string,
...
};
export type ModulePathContext = FileOrDirContext & {
/**
* Full path of the module that is requiring or importing the module to be
* resolved.
*/
+originModulePath: string,
...
};
export type ResolutionContext = ModulePathContext &
HasteContext & {
allowHaste: boolean,
extraNodeModules: ?{[string]: string, ...},
originModulePath: string,
resolveRequest?: ?CustomResolver,
...
};
export type CustomResolver = (
ResolutionContext,
string,
string | null,
string | null,
) => Resolution;