chore: add mobile app

This commit is contained in:
2026-02-07 22:33:02 +01:00
parent db34640acc
commit e89384ad4e
29327 changed files with 3886944 additions and 12 deletions
+62
View File
@@ -0,0 +1,62 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import {
BundlerResolution,
TransformResultDependency,
} from '../DeltaBundler/types';
import {ResolverInputOptions} from '../shared/types';
import {EventEmitter} from 'events';
import {ConfigT} from 'metro-config';
export default class DependencyGraph extends EventEmitter {
constructor(
config: ConfigT,
options?: Readonly<{
hasReducedPerformance?: boolean;
watch?: boolean;
}>,
);
ready(): Promise<void>;
/** @deprecated Use the constructor + `ready()` directly */
load(
config: ConfigT,
options?: Readonly<{hasReducedPerformance?: boolean; watch?: boolean}>,
): Promise<DependencyGraph>;
getAllFiles(): string[];
getOrComputeSha1(filename: string): Promise<{sha1: string; content?: Buffer}>;
getWatcher(): EventEmitter;
end(): void;
/** Given a search context, return a list of file paths matching the query. */
matchFilesWithContext(
from: string,
context: Readonly<{
/* Should search for files recursively. */
recursive: boolean;
/* Filter relative paths against a pattern. */
filter: RegExp;
}>,
): string[];
resolveDependency(
from: string,
to: TransformResultDependency,
platform: string | null,
resolverOptions: ResolverInputOptions,
options: {assumeFlatNodeModules: boolean},
): BundlerResolution;
getHasteName(filePath: string): string;
getDependencies(filePath: string): string[];
}
+293
View File
@@ -0,0 +1,293 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _createFileMap = _interopRequireDefault(
require("./DependencyGraph/createFileMap"),
);
var _ModuleResolution = require("./DependencyGraph/ModuleResolution");
var _PackageCache = require("./PackageCache");
var _events = _interopRequireDefault(require("events"));
var _fs = _interopRequireDefault(require("fs"));
var _metroCore = require("metro-core");
var _canonicalize = _interopRequireDefault(
require("metro-core/private/canonicalize"),
);
var _metroFileMap = require("metro-file-map");
var _metroResolver = require("metro-resolver");
var _nullthrows = _interopRequireDefault(require("nullthrows"));
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
const { createActionStartEntry, createActionEndEntry, log } = _metroCore.Logger;
const NULL_PLATFORM = Symbol();
function getOrCreateMap(map, field) {
let subMap = map.get(field);
if (!subMap) {
subMap = new Map();
map.set(field, subMap);
}
return subMap;
}
class DependencyGraph extends _events.default {
#packageCache;
constructor(config, options) {
super();
this._config = config;
const { hasReducedPerformance, watch } = options ?? {};
const initializingMetroLogEntry = log(
createActionStartEntry("Initializing Metro"),
);
config.reporter.update({
type: "dep_graph_loading",
hasReducedPerformance: !!hasReducedPerformance,
});
const fileMap = (0, _createFileMap.default)(config, {
throwOnModuleCollision: false,
watch,
});
fileMap.setMaxListeners(1000);
this._haste = fileMap;
this._haste.on("status", (status) => this._onWatcherStatus(status));
this._initializedPromise = fileMap
.build()
.then(({ fileSystem, hasteMap }) => {
log(createActionEndEntry(initializingMetroLogEntry));
config.reporter.update({
type: "dep_graph_loaded",
});
this._fileSystem = fileSystem;
this._hasteMap = hasteMap;
this._haste.on("change", (changeEvent) =>
this._onHasteChange(changeEvent),
);
this._haste.on("healthCheck", (result) =>
this._onWatcherHealthCheck(result),
);
this._resolutionCache = new Map();
this.#packageCache = this._createPackageCache();
this._createModuleResolver();
});
}
_onWatcherHealthCheck(result) {
this._config.reporter.update({
type: "watcher_health_check_result",
result,
});
}
_onWatcherStatus(status) {
this._config.reporter.update({
type: "watcher_status",
status,
});
}
async ready() {
await this._initializedPromise;
}
static async load(config, options) {
const self = new DependencyGraph(config, options);
await self.ready();
return self;
}
_onHasteChange({ eventsQueue }) {
this._resolutionCache = new Map();
eventsQueue.forEach(({ filePath }) =>
this.#packageCache.invalidate(filePath),
);
this._createModuleResolver();
this.emit("change");
}
_createModuleResolver() {
const fileSystemLookup = (path) => {
const result = this._fileSystem.lookup(path);
if (result.exists) {
return {
exists: true,
realPath: result.realPath,
type: result.type,
};
}
return {
exists: false,
};
};
this._moduleResolver = new _ModuleResolution.ModuleResolver({
assetExts: new Set(this._config.resolver.assetExts),
dirExists: (filePath) => {
try {
return _fs.default.lstatSync(filePath).isDirectory();
} catch (e) {}
return false;
},
disableHierarchicalLookup:
this._config.resolver.disableHierarchicalLookup,
doesFileExist: this._doesFileExist,
emptyModulePath: this._config.resolver.emptyModulePath,
extraNodeModules: this._config.resolver.extraNodeModules,
fileSystemLookup,
getHasteModulePath: (name, platform) =>
this._hasteMap.getModule(name, platform, true),
getHastePackagePath: (name, platform) =>
this._hasteMap.getPackage(name, platform, true),
mainFields: this._config.resolver.resolverMainFields,
nodeModulesPaths: this._config.resolver.nodeModulesPaths,
packageCache: this.#packageCache,
preferNativePlatform: true,
projectRoot: this._config.projectRoot,
reporter: this._config.reporter,
resolveAsset: (dirPath, assetName, extension) => {
const basePath = dirPath + _path.default.sep + assetName;
const assets = [
basePath + extension,
...this._config.resolver.assetResolutions.map(
(resolution) => basePath + "@" + resolution + "x" + extension,
),
]
.map((assetPath) => fileSystemLookup(assetPath).realPath)
.filter(Boolean);
return assets.length ? assets : null;
},
resolveRequest: this._config.resolver.resolveRequest,
sourceExts: this._config.resolver.sourceExts,
unstable_conditionNames: this._config.resolver.unstable_conditionNames,
unstable_conditionsByPlatform:
this._config.resolver.unstable_conditionsByPlatform,
unstable_enablePackageExports:
this._config.resolver.unstable_enablePackageExports,
});
}
_getClosestPackage(absoluteModulePath) {
const result = this._fileSystem.hierarchicalLookup(
absoluteModulePath,
"package.json",
{
breakOnSegment: "node_modules",
invalidatedBy: null,
subpathType: "f",
},
);
return result
? {
packageJsonPath: result.absolutePath,
packageRelativePath: result.containerRelativePath,
}
: null;
}
_createPackageCache() {
return new _PackageCache.PackageCache({
getClosestPackage: (absolutePath) =>
this._getClosestPackage(absolutePath),
});
}
getAllFiles() {
return (0, _nullthrows.default)(this._fileSystem).getAllFiles();
}
async getOrComputeSha1(mixedPath) {
const result = await this._fileSystem.getOrComputeSha1(mixedPath);
if (!result || !result.sha1) {
throw new Error(`Failed to get the SHA-1 for: ${mixedPath}.
Potential causes:
1) The file is not watched. Ensure it is under the configured \`projectRoot\` or \`watchFolders\`.
2) Check \`blockList\` in your metro.config.js and make sure it isn't excluding the file path.
3) The file may have been deleted since it was resolved - try refreshing your app.
4) Otherwise, this is a bug in Metro or the configured resolver - please report it.`);
}
return result;
}
getWatcher() {
return this._haste;
}
async end() {
await this.ready();
await this._haste.end();
}
matchFilesWithContext(from, context) {
return this._fileSystem.matchFiles({
rootDir: from,
recursive: context.recursive,
filter: context.filter,
filterComparePosix: true,
follow: true,
});
}
resolveDependency(
originModulePath,
dependency,
platform,
resolverOptions,
{ assumeFlatNodeModules } = {
assumeFlatNodeModules: false,
},
) {
const to = dependency.name;
const isSensitiveToOriginFolder =
!assumeFlatNodeModules ||
to.includes("/") ||
to === "." ||
to === ".." ||
originModulePath.includes(
_path.default.sep + "node_modules" + _path.default.sep,
);
const resolverOptionsKey =
JSON.stringify(resolverOptions ?? {}, _canonicalize.default) ?? "";
const originKey = isSensitiveToOriginFolder
? _path.default.dirname(originModulePath)
: "";
const targetKey =
to + (dependency.data.isESMImport === true ? "\0esm" : "\0cjs");
const platformKey = platform ?? NULL_PLATFORM;
const mapByResolverOptions = this._resolutionCache;
const mapByOrigin = getOrCreateMap(
mapByResolverOptions,
resolverOptionsKey,
);
const mapByTarget = getOrCreateMap(mapByOrigin, originKey);
const mapByPlatform = getOrCreateMap(mapByTarget, targetKey);
let resolution = mapByPlatform.get(platformKey);
if (!resolution) {
try {
resolution = this._moduleResolver.resolveDependency(
originModulePath,
dependency,
true,
platform,
resolverOptions,
);
} catch (error) {
if (error instanceof _metroFileMap.DuplicateHasteCandidatesError) {
throw new _metroCore.AmbiguousModuleResolutionError(
originModulePath,
error,
);
}
if (error instanceof _metroResolver.InvalidPackageError) {
throw new _metroCore.PackageResolutionError({
packageError: error,
originModulePath,
targetModuleName: to,
});
}
throw error;
}
}
mapByPlatform.set(platformKey, resolution);
return resolution;
}
_doesFileExist = (filePath) => {
return this._fileSystem.exists(filePath);
};
getHasteName(filePath) {
const hasteName = this._fileSystem.getModuleName(filePath);
if (hasteName) {
return hasteName;
}
return _path.default.relative(this._config.projectRoot, filePath);
}
getDependencies(filePath) {
return (0, _nullthrows.default)(this._fileSystem.getDependencies(filePath));
}
}
exports.default = DependencyGraph;
@@ -0,0 +1,396 @@
/**
* 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
*/
import type {
BundlerResolution,
TransformResultDependency,
} from '../DeltaBundler/types';
import type {ResolverInputOptions} from '../shared/types';
import type Package from './Package';
import type {ConfigT} from 'metro-config';
import type MetroFileMap, {
ChangeEvent,
FileSystem,
HasteMap,
HealthCheckResult,
WatcherStatus,
} from 'metro-file-map';
import type {FileSystemLookup} from 'metro-resolver';
import createFileMap from './DependencyGraph/createFileMap';
import {ModuleResolver} from './DependencyGraph/ModuleResolution';
import {PackageCache} from './PackageCache';
import EventEmitter from 'events';
import fs from 'fs';
import {
AmbiguousModuleResolutionError,
Logger,
PackageResolutionError,
} from 'metro-core';
import canonicalize from 'metro-core/private/canonicalize';
import {DuplicateHasteCandidatesError} from 'metro-file-map';
import {InvalidPackageError} from 'metro-resolver';
import nullthrows from 'nullthrows';
import path from 'path';
const {createActionStartEntry, createActionEndEntry, log} = Logger;
const NULL_PLATFORM = Symbol();
function getOrCreateMap<T>(
map: Map<string | symbol, Map<string | symbol, T>>,
field: string,
): Map<string | symbol, T> {
let subMap = map.get(field);
if (!subMap) {
subMap = new Map();
map.set(field, subMap);
}
return subMap;
}
export default class DependencyGraph extends EventEmitter {
_config: ConfigT;
_haste: MetroFileMap;
_fileSystem: FileSystem;
#packageCache: PackageCache;
_hasteMap: HasteMap;
_moduleResolver: ModuleResolver<Package>;
_resolutionCache: Map<
// Custom resolver options
string | symbol,
Map<
// Origin folder
string | symbol,
Map<
// Dependency name
string | symbol,
Map<
// Platform
string | symbol,
BundlerResolution,
>,
>,
>,
>;
_initializedPromise: Promise<void>;
constructor(
config: ConfigT,
options?: {
+hasReducedPerformance?: boolean,
+watch?: boolean,
},
) {
super();
this._config = config;
const {hasReducedPerformance, watch} = options ?? {};
const initializingMetroLogEntry = log(
createActionStartEntry('Initializing Metro'),
);
config.reporter.update({
type: 'dep_graph_loading',
hasReducedPerformance: !!hasReducedPerformance,
});
const fileMap = createFileMap(config, {
throwOnModuleCollision: false,
watch,
});
// We can have a lot of graphs listening to Haste for changes.
// Bump this up to silence the max listeners EventEmitter warning.
fileMap.setMaxListeners(1000);
this._haste = fileMap;
this._haste.on('status', status => this._onWatcherStatus(status));
this._initializedPromise = fileMap
.build()
.then(({fileSystem, hasteMap}) => {
log(createActionEndEntry(initializingMetroLogEntry));
config.reporter.update({type: 'dep_graph_loaded'});
this._fileSystem = fileSystem;
this._hasteMap = hasteMap;
this._haste.on('change', changeEvent =>
this._onHasteChange(changeEvent),
);
this._haste.on('healthCheck', result =>
this._onWatcherHealthCheck(result),
);
this._resolutionCache = new Map();
this.#packageCache = this._createPackageCache();
this._createModuleResolver();
});
}
_onWatcherHealthCheck(result: HealthCheckResult) {
this._config.reporter.update({type: 'watcher_health_check_result', result});
}
_onWatcherStatus(status: WatcherStatus) {
this._config.reporter.update({type: 'watcher_status', status});
}
// Waits for the dependency graph to become ready after initialisation.
// Don't read anything from the graph until this resolves.
async ready(): Promise<void> {
await this._initializedPromise;
}
// Creates the dependency graph and waits for it to become ready.
// @deprecated Use the constructor + ready() directly.
static async load(
config: ConfigT,
options?: {+hasReducedPerformance?: boolean, +watch?: boolean},
): Promise<DependencyGraph> {
const self = new DependencyGraph(config, options);
await self.ready();
return self;
}
_onHasteChange({eventsQueue}: ChangeEvent) {
this._resolutionCache = new Map();
eventsQueue.forEach(({filePath}) =>
this.#packageCache.invalidate(filePath),
);
this._createModuleResolver();
this.emit('change');
}
_createModuleResolver() {
const fileSystemLookup = (path: string): ReturnType<FileSystemLookup> => {
const result = this._fileSystem.lookup(path);
if (result.exists) {
return {
exists: true,
realPath: result.realPath,
type: result.type,
};
}
return {exists: false};
};
this._moduleResolver = new ModuleResolver({
assetExts: new Set(this._config.resolver.assetExts),
dirExists: (filePath: string) => {
try {
return fs.lstatSync(filePath).isDirectory();
} catch (e) {}
return false;
},
disableHierarchicalLookup:
this._config.resolver.disableHierarchicalLookup,
doesFileExist: this._doesFileExist,
emptyModulePath: this._config.resolver.emptyModulePath,
extraNodeModules: this._config.resolver.extraNodeModules,
fileSystemLookup,
getHasteModulePath: (name, platform) =>
this._hasteMap.getModule(name, platform, true),
getHastePackagePath: (name, platform) =>
this._hasteMap.getPackage(name, platform, true),
mainFields: this._config.resolver.resolverMainFields,
nodeModulesPaths: this._config.resolver.nodeModulesPaths,
packageCache: this.#packageCache,
preferNativePlatform: true,
projectRoot: this._config.projectRoot,
reporter: this._config.reporter,
resolveAsset: (dirPath: string, assetName: string, extension: string) => {
const basePath = dirPath + path.sep + assetName;
const assets = [
basePath + extension,
...this._config.resolver.assetResolutions.map(
resolution => basePath + '@' + resolution + 'x' + extension,
),
]
.map(assetPath => fileSystemLookup(assetPath).realPath)
.filter(Boolean);
return assets.length ? assets : null;
},
resolveRequest: this._config.resolver.resolveRequest,
sourceExts: this._config.resolver.sourceExts,
unstable_conditionNames: this._config.resolver.unstable_conditionNames,
unstable_conditionsByPlatform:
this._config.resolver.unstable_conditionsByPlatform,
unstable_enablePackageExports:
this._config.resolver.unstable_enablePackageExports,
});
}
_getClosestPackage(
absoluteModulePath: string,
): ?{packageJsonPath: string, packageRelativePath: string} {
const result = this._fileSystem.hierarchicalLookup(
absoluteModulePath,
'package.json',
{
breakOnSegment: 'node_modules',
invalidatedBy: null,
subpathType: 'f',
},
);
return result
? {
packageJsonPath: result.absolutePath,
packageRelativePath: result.containerRelativePath,
}
: null;
}
_createPackageCache(): PackageCache {
return new PackageCache({
getClosestPackage: absolutePath => this._getClosestPackage(absolutePath),
});
}
getAllFiles(): Array<string> {
return nullthrows(this._fileSystem).getAllFiles();
}
/**
* Used when watcher.unstable_lazySha1 is true
*/
async getOrComputeSha1(
mixedPath: string,
): Promise<{content?: Buffer, sha1: string}> {
const result = await this._fileSystem.getOrComputeSha1(mixedPath);
if (!result || !result.sha1) {
throw new Error(`Failed to get the SHA-1 for: ${mixedPath}.
Potential causes:
1) The file is not watched. Ensure it is under the configured \`projectRoot\` or \`watchFolders\`.
2) Check \`blockList\` in your metro.config.js and make sure it isn't excluding the file path.
3) The file may have been deleted since it was resolved - try refreshing your app.
4) Otherwise, this is a bug in Metro or the configured resolver - please report it.`);
}
return result;
}
getWatcher(): EventEmitter {
return this._haste;
}
async end() {
await this.ready();
await this._haste.end();
}
/** Given a search context, return a list of file paths matching the query. */
matchFilesWithContext(
from: string,
context: $ReadOnly<{
/* Should search for files recursively. */
recursive: boolean,
/* Filter relative paths against a pattern. */
filter: RegExp,
}>,
): Iterable<string> {
return this._fileSystem.matchFiles({
rootDir: from,
recursive: context.recursive,
filter: context.filter,
filterComparePosix: true,
follow: true,
});
}
resolveDependency(
originModulePath: string,
dependency: TransformResultDependency,
platform: string | null,
resolverOptions: ResolverInputOptions,
// TODO: Fold assumeFlatNodeModules into resolverOptions and add to graphId
{assumeFlatNodeModules}: {assumeFlatNodeModules: boolean} = {
assumeFlatNodeModules: false,
},
): BundlerResolution {
const to = dependency.name;
const isSensitiveToOriginFolder =
// Resolution is always relative to the origin folder unless we assume a flat node_modules
!assumeFlatNodeModules ||
// Path requests are resolved relative to the origin folder
to.includes('/') ||
to === '.' ||
to === '..' ||
// Preserve standard assumptions under node_modules
originModulePath.includes(path.sep + 'node_modules' + path.sep);
// Compound key for the resolver cache
const resolverOptionsKey =
JSON.stringify(resolverOptions ?? {}, canonicalize) ?? '';
const originKey = isSensitiveToOriginFolder
? path.dirname(originModulePath)
: '';
const targetKey =
to + (dependency.data.isESMImport === true ? '\0esm' : '\0cjs');
const platformKey = platform ?? NULL_PLATFORM;
// Traverse the resolver cache, which is a tree of maps
const mapByResolverOptions = this._resolutionCache;
const mapByOrigin = getOrCreateMap(
mapByResolverOptions,
resolverOptionsKey,
);
const mapByTarget = getOrCreateMap(mapByOrigin, originKey);
const mapByPlatform = getOrCreateMap(mapByTarget, targetKey);
let resolution: ?BundlerResolution = mapByPlatform.get(platformKey);
if (!resolution) {
try {
resolution = this._moduleResolver.resolveDependency(
originModulePath,
dependency,
true,
platform,
resolverOptions,
);
} catch (error) {
if (error instanceof DuplicateHasteCandidatesError) {
throw new AmbiguousModuleResolutionError(originModulePath, error);
}
if (error instanceof InvalidPackageError) {
throw new PackageResolutionError({
packageError: error,
originModulePath,
targetModuleName: to,
});
}
throw error;
}
}
mapByPlatform.set(platformKey, resolution);
return resolution;
}
_doesFileExist = (filePath: string): boolean => {
return this._fileSystem.exists(filePath);
};
getHasteName(filePath: string): string {
const hasteName = this._fileSystem.getModuleName(filePath);
if (hasteName) {
return hasteName;
}
return path.relative(this._config.projectRoot, filePath);
}
getDependencies(filePath: string): Array<string> {
return nullthrows(this._fileSystem.getDependencies(filePath));
}
}
@@ -0,0 +1,363 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.UnableToResolveError = exports.ModuleResolver = void 0;
var _codeFrame = require("@babel/code-frame");
var _fs = _interopRequireDefault(require("fs"));
var _invariant = _interopRequireDefault(require("invariant"));
var Resolver = _interopRequireWildcard(require("metro-resolver"));
var _createDefaultContext = _interopRequireDefault(
require("metro-resolver/private/createDefaultContext"),
);
var _path = _interopRequireDefault(require("path"));
var _util = _interopRequireDefault(require("util"));
function _getRequireWildcardCache(e) {
if ("function" != typeof WeakMap) return null;
var r = new WeakMap(),
t = new WeakMap();
return (_getRequireWildcardCache = function (e) {
return e ? t : r;
})(e);
}
function _interopRequireWildcard(e, r) {
if (!r && e && e.__esModule) return e;
if (null === e || ("object" != typeof e && "function" != typeof e))
return { default: e };
var t = _getRequireWildcardCache(r);
if (t && t.has(e)) return t.get(e);
var n = { __proto__: null },
a = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var u in e)
if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
var i = a ? Object.getOwnPropertyDescriptor(e, u) : null;
i && (i.get || i.set) ? Object.defineProperty(n, u, i) : (n[u] = e[u]);
}
return ((n.default = e), t && t.set(e, n), n);
}
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
class ModuleResolver {
constructor(options) {
this._options = options;
const { projectRoot } = this._options;
this._projectRootFakeModulePath = _path.default.join(projectRoot, "_");
}
_getEmptyModule() {
let emptyModule = this._cachedEmptyModule;
if (!emptyModule) {
emptyModule = this.resolveDependency(
this._projectRootFakeModulePath,
{
name: this._options.emptyModulePath,
data: {
key: this._options.emptyModulePath,
asyncType: null,
isESMImport: false,
locs: [],
},
},
false,
null,
{
dev: false,
},
);
this._cachedEmptyModule = emptyModule;
}
return emptyModule;
}
resolveDependency(
originModulePath,
dependency,
allowHaste,
platform,
resolverOptions,
) {
const {
assetExts,
disableHierarchicalLookup,
doesFileExist,
extraNodeModules,
fileSystemLookup,
mainFields,
nodeModulesPaths,
preferNativePlatform,
resolveAsset,
resolveRequest,
sourceExts,
unstable_conditionNames,
unstable_conditionsByPlatform,
unstable_enablePackageExports,
} = this._options;
try {
const result = Resolver.resolve(
(0, _createDefaultContext.default)(
{
allowHaste,
assetExts,
dev: resolverOptions.dev,
disableHierarchicalLookup,
doesFileExist,
extraNodeModules,
fileSystemLookup,
isESMImport: dependency.data.isESMImport,
mainFields,
nodeModulesPaths,
preferNativePlatform,
resolveAsset,
resolveRequest,
sourceExts,
unstable_conditionNames,
unstable_conditionsByPlatform,
unstable_enablePackageExports,
unstable_logWarning: this._logWarning,
customResolverOptions: resolverOptions.customResolverOptions ?? {},
originModulePath,
resolveHasteModule: (name) =>
this._options.getHasteModulePath(name, platform),
resolveHastePackage: (name) =>
this._options.getHastePackagePath(name, platform),
getPackage: this._getPackage,
getPackageForModule: (absoluteModulePath) =>
this._getPackageForModule(absoluteModulePath),
},
dependency,
),
dependency.name,
platform,
);
return this._getFileResolvedModule(result);
} catch (error) {
if (error instanceof Resolver.FailedToResolvePathError) {
const { candidates } = error;
throw new UnableToResolveError(
originModulePath,
dependency.name,
"\n\nNone of these files exist:\n" +
[candidates.file, candidates.dir]
.filter(Boolean)
.map(
(candidates) =>
` * ${Resolver.formatFileCandidates(this._removeRoot(candidates))}`,
)
.join("\n"),
{
cause: error,
dependency,
},
);
} else if (error instanceof Resolver.FailedToResolveUnsupportedError) {
throw new UnableToResolveError(
originModulePath,
dependency.name,
error.message,
{
cause: error,
dependency,
},
);
} else if (error instanceof Resolver.FailedToResolveNameError) {
const dirPaths = error.dirPaths;
const extraPaths = error.extraPaths;
const displayDirPaths = dirPaths
.filter((dirPath) => this._options.dirExists(dirPath))
.map((dirPath) =>
_path.default.relative(this._options.projectRoot, dirPath),
)
.concat(extraPaths);
const hint = displayDirPaths.length ? " or in these directories:" : "";
throw new UnableToResolveError(
originModulePath,
dependency.name,
[
`${dependency.name} could not be found within the project${hint || "."}`,
...displayDirPaths.map((dirPath) => ` ${dirPath}`),
].join("\n"),
{
cause: error,
dependency,
},
);
}
throw error;
}
}
_getPackage = (packageJsonPath) => {
try {
return this._options.packageCache.getPackage(packageJsonPath).read();
} catch (e) {}
return null;
};
_getPackageForModule = (absolutePath) => {
let result;
try {
result = this._options.packageCache.getPackageOf(absolutePath);
} catch (e) {}
return result != null
? {
rootPath: _path.default.dirname(result.pkg.path),
packageJson: result.pkg.read(),
packageRelativePath: result.packageRelativePath,
}
: null;
};
_getFileResolvedModule(resolution) {
switch (resolution.type) {
case "sourceFile":
return resolution;
case "assetFiles":
const arbitrary = getArrayLowestItem(resolution.filePaths);
(0, _invariant.default)(arbitrary != null, "invalid asset resolution");
return {
type: "sourceFile",
filePath: arbitrary,
};
case "empty":
return this._getEmptyModule();
default:
resolution.type;
throw new Error("invalid type");
}
}
_logWarning = (message) => {
this._options.reporter.update({
type: "resolver_warning",
message,
});
};
_removeRoot(candidates) {
if (candidates.filePathPrefix) {
candidates.filePathPrefix = _path.default.relative(
this._options.projectRoot,
candidates.filePathPrefix,
);
}
return candidates;
}
}
exports.ModuleResolver = ModuleResolver;
function getArrayLowestItem(a) {
if (a.length === 0) {
return undefined;
}
let lowest = a[0];
for (let i = 1; i < a.length; ++i) {
if (a[i] < lowest) {
lowest = a[i];
}
}
return lowest;
}
class UnableToResolveError extends Error {
type = "UnableToResolveError";
constructor(originModulePath, targetModuleName, message, options) {
super();
this.originModulePath = originModulePath;
this.targetModuleName = targetModuleName;
const codeFrameMessage = this.buildCodeFrameMessage(options?.dependency);
this.message =
_util.default.format(
"Unable to resolve module %s from %s: %s",
targetModuleName,
originModulePath,
message,
) + (codeFrameMessage ? "\n" + codeFrameMessage : "");
this.cause = options?.cause;
}
buildCodeFrameMessage(dependency) {
let file;
try {
file = _fs.default.readFileSync(this.originModulePath, "utf8");
} catch (error) {
if (error.code === "ENOENT" || error.code === "EISDIR") {
return null;
}
throw error;
}
const location = dependency?.data.locs.length
? refineDependencyLocation(
dependency.data.locs[0],
file,
this.targetModuleName,
)
: guessDependencyLocation(file, this.targetModuleName);
return (0, _codeFrame.codeFrameColumns)(
_fs.default.readFileSync(this.originModulePath, "utf8"),
location,
{
forceColor: process.env.NODE_ENV !== "test",
},
);
}
}
exports.UnableToResolveError = UnableToResolveError;
function refineDependencyLocation(loc, fileContents, targetSpecifier) {
const lines = fileContents.split("\n");
for (let line = loc.end.line - 1; line >= loc.start.line - 1; line--) {
const maxColumn =
line === loc.end.line ? loc.end.column + 2 : lines[line].length;
const minColumn = line === loc.start.line ? loc.start.column - 1 : 0;
const lineStr = lines[line];
const lineSlice = lineStr.slice(minColumn, maxColumn);
for (
let offset = lineSlice.lastIndexOf(targetSpecifier);
offset !== -1 && offset > 0 && offset < lineSlice.length - 1;
offset = lineSlice.lastIndexOf(targetSpecifier, offset - 1)
) {
const maybeQuoteBefore = lineSlice[minColumn + offset - 1];
const maybeQuoteAfter =
lineStr[minColumn + offset + targetSpecifier.length];
if (isQuote(maybeQuoteBefore) && maybeQuoteBefore === maybeQuoteAfter) {
return {
start: {
line: line + 1,
column: minColumn + offset + 1,
},
};
}
}
}
if (loc.start.line === loc.end.line) {
return {
start: {
line: loc.start.line,
column: loc.start.column + 1,
},
end: {
line: loc.end.line,
column: loc.end.column + 1,
},
};
}
return {
start: {
line: loc.start.line,
column: loc.start.column + 1,
},
};
}
function guessDependencyLocation(fileContents, targetSpecifier) {
const lines = fileContents.split("\n");
let lineNumber = 0;
let column = -1;
for (let line = 0; line < lines.length; line++) {
const columnLocation = lines[line].lastIndexOf(targetSpecifier);
if (columnLocation >= 0) {
lineNumber = line;
column = columnLocation;
break;
}
}
return {
start: {
column: column + 1,
line: lineNumber + 1,
},
};
}
function isQuote(str) {
return str === '"' || str === "'" || str === "`";
}
@@ -0,0 +1,484 @@
/**
* 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
*/
import type {
BundlerResolution,
TransformResultDependency,
} from '../../DeltaBundler/types';
import type {Reporter} from '../../lib/reporting';
import type {ResolverInputOptions} from '../../shared/types';
import type {
CustomResolver,
DoesFileExist,
FileCandidates,
FileSystemLookup,
Resolution,
ResolveAsset,
} from 'metro-resolver';
import type {PackageForModule, PackageJson} from 'metro-resolver/private/types';
import {codeFrameColumns} from '@babel/code-frame';
import fs from 'fs';
import invariant from 'invariant';
import * as Resolver from 'metro-resolver';
import createDefaultContext from 'metro-resolver/private/createDefaultContext';
import path from 'path';
import util from 'util';
export type DirExistsFn = (filePath: string) => boolean;
export type Packageish = interface {
path: string,
read(): PackageJson,
};
export type Moduleish = interface {
+path: string,
};
export type PackageishCache<TPackage> = interface {
getPackage(
name: string,
platform?: string,
supportsNativePlatform?: boolean,
): TPackage,
getPackageOf(absolutePath: string): ?{
pkg: TPackage,
packageRelativePath: string,
},
};
type Options<TPackage> = $ReadOnly<{
assetExts: $ReadOnlySet<string>,
dirExists: DirExistsFn,
disableHierarchicalLookup: boolean,
doesFileExist: DoesFileExist,
emptyModulePath: string,
extraNodeModules: ?Object,
fileSystemLookup: FileSystemLookup,
getHasteModulePath: (name: string, platform: ?string) => ?string,
getHastePackagePath: (name: string, platform: ?string) => ?string,
mainFields: $ReadOnlyArray<string>,
packageCache: PackageishCache<TPackage>,
nodeModulesPaths: $ReadOnlyArray<string>,
preferNativePlatform: boolean,
projectRoot: string,
reporter: Reporter,
resolveAsset: ResolveAsset,
resolveRequest: ?CustomResolver,
sourceExts: $ReadOnlyArray<string>,
unstable_conditionNames: $ReadOnlyArray<string>,
unstable_conditionsByPlatform: $ReadOnly<{
[platform: string]: $ReadOnlyArray<string>,
}>,
unstable_enablePackageExports: boolean,
}>;
export class ModuleResolver<TPackage: Packageish> {
_options: Options<TPackage>;
// A module representing the project root, used as the origin when resolving `emptyModulePath`.
_projectRootFakeModulePath: string;
// An empty module, the result of resolving `emptyModulePath` from the project root.
_cachedEmptyModule: ?BundlerResolution;
constructor(options: Options<TPackage>) {
this._options = options;
const {projectRoot} = this._options;
this._projectRootFakeModulePath = path.join(projectRoot, '_');
}
_getEmptyModule(): BundlerResolution {
let emptyModule = this._cachedEmptyModule;
if (!emptyModule) {
emptyModule = this.resolveDependency(
this._projectRootFakeModulePath,
{
name: this._options.emptyModulePath,
data: {
key: this._options.emptyModulePath,
asyncType: null,
isESMImport: false,
locs: [],
},
},
false,
null,
/* resolverOptions */ {dev: false},
);
this._cachedEmptyModule = emptyModule;
}
return emptyModule;
}
resolveDependency(
originModulePath: string,
dependency: TransformResultDependency,
allowHaste: boolean,
platform: string | null,
resolverOptions: ResolverInputOptions,
): BundlerResolution {
const {
assetExts,
disableHierarchicalLookup,
doesFileExist,
extraNodeModules,
fileSystemLookup,
mainFields,
nodeModulesPaths,
preferNativePlatform,
resolveAsset,
resolveRequest,
sourceExts,
unstable_conditionNames,
unstable_conditionsByPlatform,
unstable_enablePackageExports,
} = this._options;
try {
const result = Resolver.resolve(
createDefaultContext(
{
allowHaste,
assetExts,
dev: resolverOptions.dev,
disableHierarchicalLookup,
doesFileExist,
extraNodeModules,
fileSystemLookup,
isESMImport: dependency.data.isESMImport,
mainFields,
nodeModulesPaths,
preferNativePlatform,
resolveAsset,
resolveRequest,
sourceExts,
unstable_conditionNames,
unstable_conditionsByPlatform,
unstable_enablePackageExports,
unstable_logWarning: this._logWarning,
customResolverOptions: resolverOptions.customResolverOptions ?? {},
originModulePath,
resolveHasteModule: (name: string) =>
this._options.getHasteModulePath(name, platform),
resolveHastePackage: (name: string) =>
this._options.getHastePackagePath(name, platform),
getPackage: this._getPackage,
getPackageForModule: (absoluteModulePath: string) =>
this._getPackageForModule(absoluteModulePath),
},
dependency,
),
dependency.name,
platform,
);
return this._getFileResolvedModule(result);
} catch (error) {
if (error instanceof Resolver.FailedToResolvePathError) {
const {candidates} = error;
throw new UnableToResolveError(
originModulePath,
dependency.name,
'\n\nNone of these files exist:\n' +
[candidates.file, candidates.dir]
.filter(Boolean)
.map(
candidates =>
` * ${Resolver.formatFileCandidates(
this._removeRoot(candidates),
)}`,
)
.join('\n'),
{
cause: error,
dependency,
},
);
} else if (error instanceof Resolver.FailedToResolveUnsupportedError) {
throw new UnableToResolveError(
originModulePath,
dependency.name,
error.message,
{cause: error, dependency},
);
} else if (error instanceof Resolver.FailedToResolveNameError) {
const dirPaths = error.dirPaths;
const extraPaths = error.extraPaths;
const displayDirPaths = dirPaths
.filter((dirPath: string) => this._options.dirExists(dirPath))
.map(dirPath => path.relative(this._options.projectRoot, dirPath))
.concat(extraPaths);
const hint = displayDirPaths.length ? ' or in these directories:' : '';
throw new UnableToResolveError(
originModulePath,
dependency.name,
[
`${dependency.name} could not be found within the project${
hint || '.'
}`,
...displayDirPaths.map((dirPath: string) => ` ${dirPath}`),
].join('\n'),
{
cause: error,
dependency,
},
);
}
throw error;
}
}
_getPackage = (packageJsonPath: string): ?PackageJson => {
try {
return this._options.packageCache.getPackage(packageJsonPath).read();
} catch (e) {
// Do nothing. The standard module cache does not trigger any error, but
// the ModuleGraph one does, if the module does not exist.
}
return null;
};
_getPackageForModule = (absolutePath: string): ?PackageForModule => {
let result;
try {
result = this._options.packageCache.getPackageOf(absolutePath);
} catch (e) {
// Do nothing. The standard module cache does not trigger any error, but
// the ModuleGraph one does, if the module does not exist.
}
return result != null
? {
rootPath: path.dirname(result.pkg.path),
packageJson: result.pkg.read(),
packageRelativePath: result.packageRelativePath,
}
: null;
};
/**
* TODO: Return Resolution instead of coercing to BundlerResolution here
*/
_getFileResolvedModule(resolution: Resolution): BundlerResolution {
switch (resolution.type) {
case 'sourceFile':
return resolution;
case 'assetFiles':
// FIXME: we should forward ALL the paths/metadata,
// not just an arbitrary item!
const arbitrary = getArrayLowestItem(resolution.filePaths);
invariant(arbitrary != null, 'invalid asset resolution');
return {type: 'sourceFile', filePath: arbitrary};
case 'empty':
return this._getEmptyModule();
default:
(resolution.type: empty);
throw new Error('invalid type');
}
}
_logWarning = (message: string): void => {
this._options.reporter.update({
type: 'resolver_warning',
message,
});
};
_removeRoot(candidates: FileCandidates): FileCandidates {
if (candidates.filePathPrefix) {
candidates.filePathPrefix = path.relative(
this._options.projectRoot,
candidates.filePathPrefix,
);
}
return candidates;
}
}
function getArrayLowestItem(a: $ReadOnlyArray<string>): string | void {
if (a.length === 0) {
return undefined;
}
let lowest = a[0];
for (let i = 1; i < a.length; ++i) {
if (a[i] < lowest) {
lowest = a[i];
}
}
return lowest;
}
// $FlowFixMe[incompatible-type]
export class UnableToResolveError extends Error {
/**
* File path of the module that tried to require a module, ex. `/js/foo.js`.
*/
originModulePath: string;
/**
* The name of the module that was required, no necessarily a path,
* ex. `./bar`, or `invariant`.
*/
targetModuleName: string;
/**
* Original error that causes this error
*/
cause: ?Error;
/**
* Fixed type field in common with other Metro build errors.
*/
+type: 'UnableToResolveError' = 'UnableToResolveError';
constructor(
originModulePath: string,
targetModuleName: string,
message: string,
options?: $ReadOnly<{
dependency?: ?TransformResultDependency,
cause?: Error,
}>,
) {
super();
this.originModulePath = originModulePath;
this.targetModuleName = targetModuleName;
const codeFrameMessage = this.buildCodeFrameMessage(options?.dependency);
this.message =
util.format(
'Unable to resolve module %s from %s: %s',
targetModuleName,
originModulePath,
message,
) + (codeFrameMessage ? '\n' + codeFrameMessage : '');
this.cause = options?.cause;
}
buildCodeFrameMessage(dependency: ?TransformResultDependency): ?string {
let file;
try {
file = fs.readFileSync(this.originModulePath, 'utf8');
} catch (error) {
if (error.code === 'ENOENT' || error.code === 'EISDIR') {
// We're probably dealing with a virtualised file system where
// `this.originModulePath` doesn't actually exist on disk.
// We can't show a code frame, but there's no need to let this I/O
// error shadow the original module resolution error.
return null;
}
throw error;
}
const location = dependency?.data.locs.length
? refineDependencyLocation(
dependency.data.locs[0],
file,
this.targetModuleName,
)
: // TODO: Ultimately we shouldn't ever have to guess the location.
guessDependencyLocation(file, this.targetModuleName);
return codeFrameColumns(
fs.readFileSync(this.originModulePath, 'utf8'),
location,
{forceColor: process.env.NODE_ENV !== 'test'},
);
}
}
// Given a source location for an import declaration or `require()` call (etc),
// return a location for use with @babel/code-frame in the resolution error.
function refineDependencyLocation(
loc: BabelSourceLocation,
fileContents: string,
targetSpecifier: string,
): {
start: {column: number, line: number},
end?: {column: number, line: number},
} {
const lines = fileContents.split('\n');
// If we can find the module name in range of the given loc, surrounded by
// matching quotes, that's likely our specifier. Point to the first column of
// the *last* valid occurrence.
// Note that module names may not always be found in the source code verbatim,
// whether because of escaping or because of exotic dependency APIs.
for (let line = loc.end.line - 1; line >= loc.start.line - 1; line--) {
const maxColumn =
line === loc.end.line ? loc.end.column + 2 : lines[line].length;
const minColumn = line === loc.start.line ? loc.start.column - 1 : 0;
const lineStr = lines[line];
const lineSlice = lineStr.slice(minColumn, maxColumn);
for (
let offset = lineSlice.lastIndexOf(targetSpecifier);
offset !== -1 && // leave room for quotes
offset > 0 &&
offset < lineSlice.length - 1;
offset = lineSlice.lastIndexOf(targetSpecifier, offset - 1)
) {
const maybeQuoteBefore = lineSlice[minColumn + offset - 1];
const maybeQuoteAfter =
lineStr[minColumn + offset + targetSpecifier.length];
if (isQuote(maybeQuoteBefore) && maybeQuoteBefore === maybeQuoteAfter) {
return {
start: {
line: line + 1,
column: minColumn + offset + 1,
},
};
}
}
}
// Otherwise, if this is a single-line loc, return it exactly, as a range.
if (loc.start.line === loc.end.line) {
return {
start: {
line: loc.start.line,
column: loc.start.column + 1,
},
end: {
line: loc.end.line,
column: loc.end.column + 1,
},
};
}
// Otherwise, point to the first column of the loc, to avoid including too
// much unnecessary context.
return {
start: {
line: loc.start.line,
column: loc.start.column + 1,
},
};
}
function guessDependencyLocation(
fileContents: string,
targetSpecifier: string,
) {
const lines = fileContents.split('\n');
let lineNumber = 0;
let column = -1;
for (let line = 0; line < lines.length; line++) {
const columnLocation = lines[line].lastIndexOf(targetSpecifier);
if (columnLocation >= 0) {
lineNumber = line;
column = columnLocation;
break;
}
}
return {
start: {column: column + 1, line: lineNumber + 1},
};
}
function isQuote(str: ?string): boolean {
return str === '"' || str === "'" || str === '`';
}
@@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = createFileMap;
var _ciInfo = _interopRequireDefault(require("ci-info"));
var _metroFileMap = _interopRequireWildcard(require("metro-file-map"));
function _getRequireWildcardCache(e) {
if ("function" != typeof WeakMap) return null;
var r = new WeakMap(),
t = new WeakMap();
return (_getRequireWildcardCache = function (e) {
return e ? t : r;
})(e);
}
function _interopRequireWildcard(e, r) {
if (!r && e && e.__esModule) return e;
if (null === e || ("object" != typeof e && "function" != typeof e))
return { default: e };
var t = _getRequireWildcardCache(r);
if (t && t.has(e)) return t.get(e);
var n = { __proto__: null },
a = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var u in e)
if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
var i = a ? Object.getOwnPropertyDescriptor(e, u) : null;
i && (i.get || i.set) ? Object.defineProperty(n, u, i) : (n[u] = e[u]);
}
return ((n.default = e), t && t.set(e, n), n);
}
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
function getIgnorePattern(config) {
const { blockList, blacklistRE } = config.resolver;
const ignorePattern = blacklistRE || blockList;
if (!ignorePattern) {
return / ^/;
}
const combine = (regexes) =>
new RegExp(
regexes
.map((regex, index) => {
if (regex.flags !== regexes[0].flags) {
throw new Error(
"Cannot combine blockList patterns, because they have different flags:\n" +
" - Pattern 0: " +
regexes[0].toString() +
"\n" +
` - Pattern ${index}: ` +
regexes[index].toString(),
);
}
return "(" + regex.source + ")";
})
.join("|"),
regexes[0]?.flags ?? "",
);
if (Array.isArray(ignorePattern)) {
return combine(ignorePattern);
}
return ignorePattern;
}
function createFileMap(config, options) {
const dependencyExtractor =
options?.extractDependencies === false
? null
: config.resolver.dependencyExtractor;
const computeDependencies = dependencyExtractor != null;
const watch = options?.watch == null ? !_ciInfo.default.isCI : options.watch;
const { enabled: autoSaveEnabled, ...autoSaveOpts } =
config.watcher.unstable_autoSaveCache ?? {};
const autoSave = watch && autoSaveEnabled ? autoSaveOpts : false;
return _metroFileMap.default.create({
cacheManagerFactory:
config?.unstable_fileMapCacheManagerFactory ??
((factoryParams) =>
new _metroFileMap.DiskCacheManager(factoryParams, {
cacheDirectory:
config.fileMapCacheDirectory ?? config.hasteMapCacheDirectory,
cacheFilePrefix: options?.cacheFilePrefix,
autoSave,
})),
perfLoggerFactory: config.unstable_perfLoggerFactory,
computeDependencies,
computeSha1: !config.watcher.unstable_lazySha1,
dependencyExtractor: config.resolver.dependencyExtractor,
enableHastePackages: config?.resolver.enableGlobalPackages,
enableSymlinks: true,
enableWorkerThreads: config.watcher.unstable_workerThreads,
extensions: Array.from(
new Set([
...config.resolver.sourceExts,
...config.resolver.assetExts,
...config.watcher.additionalExts,
]),
),
forceNodeFilesystemAPI: !config.resolver.useWatchman,
hasteImplModulePath: config.resolver.hasteImplModulePath,
healthCheck: config.watcher.healthCheck,
ignorePattern: getIgnorePattern(config),
maxWorkers: config.maxWorkers,
mocksPattern: "",
platforms: [
...config.resolver.platforms,
_metroFileMap.default.H.NATIVE_PLATFORM,
],
retainAllFiles: true,
resetCache: config.resetCache,
rootDir: config.projectRoot,
roots: config.watchFolders,
throwOnModuleCollision: options?.throwOnModuleCollision ?? true,
useWatchman: config.resolver.useWatchman,
watch,
watchmanDeferStates: config.watcher.watchman.deferStates,
});
}
@@ -0,0 +1,115 @@
/**
* 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 strict-local
* @format
* @oncall react_native
*/
import type {ConfigT} from 'metro-config';
import ci from 'ci-info';
import MetroFileMap, {DiskCacheManager} from 'metro-file-map';
function getIgnorePattern(config: ConfigT): RegExp {
// For now we support both options
const {blockList, blacklistRE} = config.resolver;
const ignorePattern = blacklistRE || blockList;
// If neither option has been set, use default pattern
if (!ignorePattern) {
return / ^/;
}
const combine = (regexes: Array<RegExp>) =>
new RegExp(
regexes
.map((regex, index) => {
if (regex.flags !== regexes[0].flags) {
throw new Error(
'Cannot combine blockList patterns, because they have different flags:\n' +
' - Pattern 0: ' +
regexes[0].toString() +
'\n' +
` - Pattern ${index}: ` +
regexes[index].toString(),
);
}
return '(' + regex.source + ')';
})
.join('|'),
regexes[0]?.flags ?? '',
);
// If ignorePattern is an array, merge it into one
if (Array.isArray(ignorePattern)) {
return combine(ignorePattern);
}
return ignorePattern;
}
export default function createFileMap(
config: ConfigT,
options?: $ReadOnly<{
extractDependencies?: boolean,
watch?: boolean,
throwOnModuleCollision?: boolean,
cacheFilePrefix?: string,
}>,
): MetroFileMap {
const dependencyExtractor =
options?.extractDependencies === false
? null
: config.resolver.dependencyExtractor;
const computeDependencies = dependencyExtractor != null;
const watch = options?.watch == null ? !ci.isCI : options.watch;
const {enabled: autoSaveEnabled, ...autoSaveOpts} =
config.watcher.unstable_autoSaveCache ?? {};
const autoSave = watch && autoSaveEnabled ? autoSaveOpts : false;
return MetroFileMap.create({
cacheManagerFactory:
config?.unstable_fileMapCacheManagerFactory ??
(factoryParams =>
new DiskCacheManager(factoryParams, {
cacheDirectory:
config.fileMapCacheDirectory ?? config.hasteMapCacheDirectory,
cacheFilePrefix: options?.cacheFilePrefix,
autoSave,
})),
perfLoggerFactory: config.unstable_perfLoggerFactory,
computeDependencies,
computeSha1: !config.watcher.unstable_lazySha1,
dependencyExtractor: config.resolver.dependencyExtractor,
enableHastePackages: config?.resolver.enableGlobalPackages,
enableSymlinks: true,
enableWorkerThreads: config.watcher.unstable_workerThreads,
extensions: Array.from(
new Set([
...config.resolver.sourceExts,
...config.resolver.assetExts,
...config.watcher.additionalExts,
]),
),
forceNodeFilesystemAPI: !config.resolver.useWatchman,
hasteImplModulePath: config.resolver.hasteImplModulePath,
healthCheck: config.watcher.healthCheck,
ignorePattern: getIgnorePattern(config),
maxWorkers: config.maxWorkers,
mocksPattern: '',
platforms: [...config.resolver.platforms, MetroFileMap.H.NATIVE_PLATFORM],
retainAllFiles: true,
resetCache: config.resetCache,
rootDir: config.projectRoot,
roots: config.watchFolders,
throwOnModuleCollision: options?.throwOnModuleCollision ?? true,
useWatchman: config.resolver.useWatchman,
watch,
watchmanDeferStates: config.watcher.watchman.deferStates,
});
}
+28
View File
@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _fs = _interopRequireDefault(require("fs"));
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
class Package {
constructor({ file }) {
this.path = _path.default.resolve(file);
this._root = _path.default.dirname(this.path);
this._content = null;
}
invalidate() {
this._content = null;
}
read() {
if (this._content == null) {
this._content = JSON.parse(_fs.default.readFileSync(this.path, "utf8"));
}
return this._content;
}
}
exports.default = Package;
+39
View File
@@ -0,0 +1,39 @@
/**
* 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 strict-local
* @format
* @oncall react_native
*/
import type {PackageJson} from 'metro-resolver/private/types';
import fs from 'fs';
import path from 'path';
export default class Package {
path: string;
_root: string;
_content: ?PackageJson;
constructor({file}: {file: string, ...}) {
this.path = path.resolve(file);
this._root = path.dirname(this.path);
this._content = null;
}
invalidate() {
this._content = null;
}
read(): PackageJson {
if (this._content == null) {
this._content = JSON.parse(fs.readFileSync(this.path, 'utf8'));
}
return this._content;
}
}
+82
View File
@@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.PackageCache = void 0;
var _Package = _interopRequireDefault(require("./Package"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
class PackageCache {
constructor(options) {
this._getClosestPackage = options.getClosestPackage;
this._packageCache = Object.create(null);
this._packagePathAndSubpathByModulePath = Object.create(null);
this._modulePathsByPackagePath = Object.create(null);
}
getPackage(filePath) {
if (!this._packageCache[filePath]) {
this._packageCache[filePath] = new _Package.default({
file: filePath,
});
}
return this._packageCache[filePath];
}
getPackageOf(absoluteModulePath) {
let packagePathAndSubpath =
this._packagePathAndSubpathByModulePath[absoluteModulePath];
if (
packagePathAndSubpath &&
this._packageCache[packagePathAndSubpath.packageJsonPath]
) {
return {
pkg: this._packageCache[packagePathAndSubpath.packageJsonPath],
packageRelativePath: packagePathAndSubpath.packageRelativePath,
};
}
packagePathAndSubpath = this._getClosestPackage(absoluteModulePath);
if (!packagePathAndSubpath) {
return null;
}
const packagePath = packagePathAndSubpath.packageJsonPath;
this._packagePathAndSubpathByModulePath[absoluteModulePath] =
packagePathAndSubpath;
const modulePaths =
this._modulePathsByPackagePath[packagePath] ?? new Set();
modulePaths.add(absoluteModulePath);
this._modulePathsByPackagePath[packagePath] = modulePaths;
return {
pkg: this.getPackage(packagePath),
packageRelativePath: packagePathAndSubpath.packageRelativePath,
};
}
invalidate(filePath) {
if (this._packageCache[filePath]) {
this._packageCache[filePath].invalidate();
delete this._packageCache[filePath];
}
const packagePathAndSubpath =
this._packagePathAndSubpathByModulePath[filePath];
if (packagePathAndSubpath) {
const packagePath = packagePathAndSubpath.packageJsonPath;
delete this._packagePathAndSubpathByModulePath[filePath];
const modulePaths = this._modulePathsByPackagePath[packagePath];
if (modulePaths) {
modulePaths.delete(filePath);
if (modulePaths.size === 0) {
delete this._modulePathsByPackagePath[packagePath];
}
}
}
if (this._modulePathsByPackagePath[filePath]) {
const modulePaths = this._modulePathsByPackagePath[filePath];
for (const modulePath of modulePaths) {
delete this._packagePathAndSubpathByModulePath[modulePath];
}
modulePaths.clear();
delete this._modulePathsByPackagePath[filePath];
}
}
}
exports.PackageCache = PackageCache;
+125
View File
@@ -0,0 +1,125 @@
/**
* 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
*/
import Package from './Package';
type GetClosestPackageFn = (absoluteFilePath: string) => ?{
packageJsonPath: string,
packageRelativePath: string,
};
export class PackageCache {
_getClosestPackage: GetClosestPackageFn;
_packageCache: {
[filePath: string]: Package,
__proto__: null,
...
};
// Cache for "closest package.json" queries by module path.
_packagePathAndSubpathByModulePath: {
[filePath: string]: ?{
packageJsonPath: string,
packageRelativePath: string,
},
__proto__: null,
...
};
// The inverse of _packagePathByModulePath.
_modulePathsByPackagePath: {
[filePath: string]: Set<string>,
__proto__: null,
...
};
constructor(options: {getClosestPackage: GetClosestPackageFn, ...}) {
this._getClosestPackage = options.getClosestPackage;
this._packageCache = Object.create(null);
this._packagePathAndSubpathByModulePath = Object.create(null);
this._modulePathsByPackagePath = Object.create(null);
}
getPackage(filePath: string): Package {
if (!this._packageCache[filePath]) {
this._packageCache[filePath] = new Package({
file: filePath,
});
}
return this._packageCache[filePath];
}
getPackageOf(
absoluteModulePath: string,
): ?{pkg: Package, packageRelativePath: string} {
let packagePathAndSubpath =
this._packagePathAndSubpathByModulePath[absoluteModulePath];
if (
packagePathAndSubpath &&
this._packageCache[packagePathAndSubpath.packageJsonPath]
) {
return {
pkg: this._packageCache[packagePathAndSubpath.packageJsonPath],
packageRelativePath: packagePathAndSubpath.packageRelativePath,
};
}
packagePathAndSubpath = this._getClosestPackage(absoluteModulePath);
if (!packagePathAndSubpath) {
return null;
}
const packagePath = packagePathAndSubpath.packageJsonPath;
this._packagePathAndSubpathByModulePath[absoluteModulePath] =
packagePathAndSubpath;
const modulePaths =
this._modulePathsByPackagePath[packagePath] ?? new Set();
modulePaths.add(absoluteModulePath);
this._modulePathsByPackagePath[packagePath] = modulePaths;
return {
pkg: this.getPackage(packagePath),
packageRelativePath: packagePathAndSubpath.packageRelativePath,
};
}
invalidate(filePath: string) {
if (this._packageCache[filePath]) {
this._packageCache[filePath].invalidate();
delete this._packageCache[filePath];
}
const packagePathAndSubpath =
this._packagePathAndSubpathByModulePath[filePath];
if (packagePathAndSubpath) {
// filePath is a module inside a package.
const packagePath = packagePathAndSubpath.packageJsonPath;
delete this._packagePathAndSubpathByModulePath[filePath];
// This change doesn't invalidate any cached "closest package.json"
// queries for the package's other modules. Clean up only this module.
const modulePaths = this._modulePathsByPackagePath[packagePath];
if (modulePaths) {
modulePaths.delete(filePath);
if (modulePaths.size === 0) {
delete this._modulePathsByPackagePath[packagePath];
}
}
}
if (this._modulePathsByPackagePath[filePath]) {
// filePath is a package. This change invalidates all cached "closest
// package.json" queries for modules inside this package.
const modulePaths = this._modulePathsByPackagePath[filePath];
for (const modulePath of modulePaths) {
delete this._packagePathAndSubpathByModulePath[modulePath];
}
modulePaths.clear();
delete this._modulePathsByPackagePath[filePath];
}
}
}
+57
View File
@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.parse = parse;
exports.tryParse = tryParse;
var _parsePlatformFilePath = _interopRequireDefault(
require("./parsePlatformFilePath"),
);
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
const ASSET_BASE_NAME_RE = /(.+?)(@([\d.]+)x)?$/;
function parseBaseName(baseName) {
const match = baseName.match(ASSET_BASE_NAME_RE);
if (!match) {
throw new Error(`invalid asset name: \`${baseName}'`);
}
const rootName = match[1];
if (match[3] != null) {
const resolution = parseFloat(match[3]);
if (!Number.isNaN(resolution)) {
return {
rootName,
resolution,
};
}
}
return {
rootName,
resolution: 1,
};
}
function tryParse(filePath, platforms) {
const result = (0, _parsePlatformFilePath.default)(filePath, platforms);
const { dirPath, baseName, platform, extension } = result;
if (extension == null) {
return null;
}
const { rootName, resolution } = parseBaseName(baseName);
return {
assetName: _path.default.join(dirPath, `${rootName}.${extension}`),
name: rootName,
platform,
resolution,
type: extension,
};
}
function parse(filePath, platforms) {
const result = tryParse(filePath, platforms);
if (result == null) {
throw new Error(`invalid asset file path: ${filePath}`);
}
return result;
}
@@ -0,0 +1,76 @@
/**
* 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 strict
* @format
* @oncall react_native
*/
import parsePlatformFilePath from './parsePlatformFilePath';
import path from 'path';
export type AssetPath = {
assetName: string,
name: string,
platform: ?string,
resolution: number,
type: string,
};
const ASSET_BASE_NAME_RE = /(.+?)(@([\d.]+)x)?$/;
function parseBaseName(baseName: string): {
resolution: number,
rootName: string,
...
} {
const match = baseName.match(ASSET_BASE_NAME_RE);
if (!match) {
throw new Error(`invalid asset name: \`${baseName}'`);
}
const rootName = match[1];
if (match[3] != null) {
const resolution = parseFloat(match[3]);
if (!Number.isNaN(resolution)) {
return {rootName, resolution};
}
}
return {rootName, resolution: 1};
}
/**
* Return `null` if the `filePath` doesn't have a valid extension, required
* to describe the type of an asset.
*/
export function tryParse(
filePath: string,
platforms: $ReadOnlySet<string>,
): ?AssetPath {
const result = parsePlatformFilePath(filePath, platforms);
const {dirPath, baseName, platform, extension} = result;
if (extension == null) {
return null;
}
const {rootName, resolution} = parseBaseName(baseName);
return {
assetName: path.join(dirPath, `${rootName}.${extension}`),
name: rootName,
platform,
resolution,
type: extension,
};
}
export function parse(
filePath: string,
platforms: $ReadOnlySet<string>,
): AssetPath {
const result = tryParse(filePath, platforms);
if (result == null) {
throw new Error(`invalid asset file path: ${filePath}`);
}
return result;
}
@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = parsePlatformFilePath;
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
const PATH_RE = /^(.+?)(\.([^.]+))?\.([^.]+)$/;
function parsePlatformFilePath(filePath, platforms) {
const dirPath = _path.default.dirname(filePath);
const fileName = _path.default.basename(filePath);
const match = fileName.match(PATH_RE);
if (!match) {
return {
dirPath,
baseName: fileName,
platform: null,
extension: null,
};
}
const extension = match[4] || null;
const platform = match[3] || null;
if (platform == null || platforms.has(platform)) {
return {
dirPath,
baseName: match[1],
platform,
extension,
};
}
const baseName = `${match[1]}.${platform}`;
return {
dirPath,
baseName,
platform: null,
extension,
};
}
@@ -0,0 +1,44 @@
/**
* 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 strict
* @format
* @oncall react_native
*/
import path from 'path';
type PlatformFilePathParts = {
dirPath: string,
baseName: string,
platform: ?string,
extension: ?string,
};
const PATH_RE = /^(.+?)(\.([^.]+))?\.([^.]+)$/;
/**
* Extract the components of a file path that can have a platform specifier: Ex.
* `index.ios.js` is specific to the `ios` platform and has the extension `js`.
*/
export default function parsePlatformFilePath(
filePath: string,
platforms: $ReadOnlySet<string>,
): PlatformFilePathParts {
const dirPath = path.dirname(filePath);
const fileName = path.basename(filePath);
const match = fileName.match(PATH_RE);
if (!match) {
return {dirPath, baseName: fileName, platform: null, extension: null};
}
const extension = match[4] || null;
const platform = match[3] || null;
if (platform == null || platforms.has(platform)) {
return {dirPath, baseName: match[1], platform, extension};
}
const baseName = `${match[1]}.${platform}`;
return {dirPath, baseName, platform: null, extension};
}