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
@@ -0,0 +1,24 @@
/**
* 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 type {DuplicatesSet} from '../flow-types';
export class DuplicateHasteCandidatesError extends Error {
hasteName: string;
platform: string | null;
supportsNativePlatform: boolean;
duplicatesSet: DuplicatesSet;
constructor(
name: string,
platform: string,
supportsNativePlatform: boolean,
duplicatesSet: DuplicatesSet,
);
}
+172
View File
@@ -0,0 +1,172 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.FileProcessor = void 0;
var _constants = _interopRequireDefault(require("../constants"));
var _worker = require("../worker");
var _jestWorker = require("jest-worker");
var _path = require("path");
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
const debug = require("debug")("Metro:FileMap");
const NODE_MODULES = _path.sep + "node_modules" + _path.sep;
const MAX_FILES_PER_WORKER = 100;
class FileProcessor {
#dependencyExtractor;
#enableHastePackages;
#hasteImplModulePath;
#enableWorkerThreads;
#maxFilesPerWorker;
#maxWorkers;
#perfLogger;
#workerArgs;
#inBandWorker;
constructor(opts) {
this.#dependencyExtractor = opts.dependencyExtractor;
this.#enableHastePackages = opts.enableHastePackages;
this.#enableWorkerThreads = opts.enableWorkerThreads;
this.#hasteImplModulePath = opts.hasteImplModulePath;
this.#maxFilesPerWorker = opts.maxFilesPerWorker ?? MAX_FILES_PER_WORKER;
this.#maxWorkers = opts.maxWorkers;
this.#workerArgs = {};
this.#inBandWorker = new _worker.Worker(this.#workerArgs);
this.#perfLogger = opts.perfLogger;
}
async processBatch(files, req) {
const errors = [];
const numWorkers = Math.min(
this.#maxWorkers,
Math.ceil(files.length / this.#maxFilesPerWorker),
);
const batchWorker = this.#getBatchWorker(numWorkers);
if (req.maybeReturnContent) {
throw new Error(
"Batch processing does not support returning file contents",
);
}
await Promise.all(
files.map(([absolutePath, fileMetadata]) => {
const maybeWorkerInput = this.#getWorkerInput(
absolutePath,
fileMetadata,
req,
);
if (!maybeWorkerInput) {
return null;
}
return batchWorker
.processFile(maybeWorkerInput)
.then((reply) => processWorkerReply(reply, fileMetadata))
.catch((error) =>
errors.push({
absolutePath,
error: normalizeWorkerError(error),
}),
);
}),
);
await batchWorker.end();
return {
errors,
};
}
processRegularFile(absolutePath, fileMetadata, req) {
const workerInput = this.#getWorkerInput(absolutePath, fileMetadata, req);
return workerInput
? {
content: processWorkerReply(
this.#inBandWorker.processFile(workerInput),
fileMetadata,
),
}
: null;
}
#getWorkerInput(absolutePath, fileMetadata, req) {
const computeSha1 =
req.computeSha1 && fileMetadata[_constants.default.SHA1] == null;
const { computeDependencies, maybeReturnContent } = req;
if (absolutePath.includes(NODE_MODULES)) {
if (computeSha1) {
return {
computeDependencies: false,
computeSha1: true,
dependencyExtractor: null,
enableHastePackages: false,
filePath: absolutePath,
hasteImplModulePath: null,
maybeReturnContent,
};
}
return null;
}
return {
computeDependencies,
computeSha1,
dependencyExtractor: this.#dependencyExtractor,
enableHastePackages: this.#enableHastePackages,
filePath: absolutePath,
hasteImplModulePath: this.#hasteImplModulePath,
maybeReturnContent,
};
}
#getBatchWorker(numWorkers) {
if (numWorkers <= 1) {
return {
processFile: async (message) => this.#inBandWorker.processFile(message),
end: async () => {},
};
}
const workerPath = require.resolve("../worker");
debug(
"Creating worker farm of %d worker %s",
numWorkers,
this.#enableWorkerThreads ? "threads" : "processes",
);
this.#perfLogger?.point("initWorkers_start");
const jestWorker = new _jestWorker.Worker(workerPath, {
exposedMethods: ["processFile"],
maxRetries: 3,
numWorkers,
enableWorkerThreads: this.#enableWorkerThreads,
forkOptions: {
execArgv: [],
},
setupArgs: [this.#workerArgs],
});
this.#perfLogger?.point("initWorkers_end");
this.#perfLogger = null;
return jestWorker;
}
async end() {}
}
exports.FileProcessor = FileProcessor;
function processWorkerReply(metadata, fileMetadata) {
fileMetadata[_constants.default.VISITED] = 1;
const metadataId = metadata.id;
if (metadataId != null) {
fileMetadata[_constants.default.ID] = metadataId;
}
fileMetadata[_constants.default.DEPENDENCIES] = metadata.dependencies
? metadata.dependencies.join(_constants.default.DEPENDENCY_DELIM)
: "";
if (metadata.sha1 != null) {
fileMetadata[_constants.default.SHA1] = metadata.sha1;
}
return metadata.content;
}
function normalizeWorkerError(mixedError) {
if (
mixedError == null ||
typeof mixedError !== "object" ||
mixedError.message == null ||
mixedError.stack == null
) {
const error = new Error(mixedError);
error.stack = "";
return error;
}
return mixedError;
}
@@ -0,0 +1,268 @@
/**
* 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 {
FileMetadata,
PerfLogger,
WorkerMessage,
WorkerMetadata,
WorkerSetupArgs,
} from '../flow-types';
import H from '../constants';
import {Worker} from '../worker';
import {Worker as JestWorker} from 'jest-worker';
import {sep} from 'path';
// eslint-disable-next-line import/no-commonjs
const debug = require('debug')('Metro:FileMap');
type ProcessFileRequest = $ReadOnly<{
/**
* Populate metadata[H.SHA1] with the SHA1 of the file's contents.
*/
computeSha1: boolean,
/**
* Populate metadata[H.DEPENDENCIES] with unresolved dependency specifiers
* using the dependencyExtractor provided to the constructor.
*/
computeDependencies: boolean,
/**
* Only if processing has already required reading the file's contents, return
* the contents as a Buffer - null otherwise. Not supported for batches.
*/
maybeReturnContent: boolean,
}>;
interface AsyncWorker {
+processFile: WorkerMessage => Promise<WorkerMetadata>;
+end: () => Promise<void>;
}
interface MaybeCodedError extends Error {
code?: string;
}
const NODE_MODULES = sep + 'node_modules' + sep;
const MAX_FILES_PER_WORKER = 100;
export class FileProcessor {
#dependencyExtractor: ?string;
#enableHastePackages: boolean;
#hasteImplModulePath: ?string;
#enableWorkerThreads: boolean;
#maxFilesPerWorker: number;
#maxWorkers: number;
#perfLogger: ?PerfLogger;
#workerArgs: WorkerSetupArgs;
#inBandWorker: Worker;
constructor(
opts: $ReadOnly<{
dependencyExtractor: ?string,
enableHastePackages: boolean,
enableWorkerThreads: boolean,
hasteImplModulePath: ?string,
maxFilesPerWorker?: ?number,
maxWorkers: number,
perfLogger: ?PerfLogger,
}>,
) {
this.#dependencyExtractor = opts.dependencyExtractor;
this.#enableHastePackages = opts.enableHastePackages;
this.#enableWorkerThreads = opts.enableWorkerThreads;
this.#hasteImplModulePath = opts.hasteImplModulePath;
this.#maxFilesPerWorker = opts.maxFilesPerWorker ?? MAX_FILES_PER_WORKER;
this.#maxWorkers = opts.maxWorkers;
this.#workerArgs = {};
this.#inBandWorker = new Worker(this.#workerArgs);
this.#perfLogger = opts.perfLogger;
}
async processBatch(
files: $ReadOnlyArray<[string /*absolutePath*/, FileMetadata]>,
req: ProcessFileRequest,
): Promise<{
errors: Array<{
absolutePath: string,
error: MaybeCodedError,
}>,
}> {
const errors = [];
const numWorkers = Math.min(
this.#maxWorkers,
Math.ceil(files.length / this.#maxFilesPerWorker),
);
const batchWorker = this.#getBatchWorker(numWorkers);
if (req.maybeReturnContent) {
throw new Error(
'Batch processing does not support returning file contents',
);
}
await Promise.all(
files.map(([absolutePath, fileMetadata]) => {
const maybeWorkerInput = this.#getWorkerInput(
absolutePath,
fileMetadata,
req,
);
if (!maybeWorkerInput) {
return null;
}
return batchWorker
.processFile(maybeWorkerInput)
.then(reply => processWorkerReply(reply, fileMetadata))
.catch(error =>
errors.push({absolutePath, error: normalizeWorkerError(error)}),
);
}),
);
await batchWorker.end();
return {errors};
}
processRegularFile(
absolutePath: string,
fileMetadata: FileMetadata,
req: ProcessFileRequest,
): ?{content: ?Buffer} {
const workerInput = this.#getWorkerInput(absolutePath, fileMetadata, req);
return workerInput
? {
content: processWorkerReply(
this.#inBandWorker.processFile(workerInput),
fileMetadata,
),
}
: null;
}
#getWorkerInput(
absolutePath: string,
fileMetadata: FileMetadata,
req: ProcessFileRequest,
): ?WorkerMessage {
const computeSha1 = req.computeSha1 && fileMetadata[H.SHA1] == null;
const {computeDependencies, maybeReturnContent} = req;
// Use a cheaper worker configuration for node_modules files, because we
// never care about extracting dependencies, and they may never be Haste
// modules or packages.
//
// Note that we'd only expect node_modules files to reach this point if
// retainAllFiles is true, or they're touched during watch mode.
if (absolutePath.includes(NODE_MODULES)) {
if (computeSha1) {
return {
computeDependencies: false,
computeSha1: true,
dependencyExtractor: null,
enableHastePackages: false,
filePath: absolutePath,
hasteImplModulePath: null,
maybeReturnContent,
};
}
return null;
}
return {
computeDependencies,
computeSha1,
dependencyExtractor: this.#dependencyExtractor,
enableHastePackages: this.#enableHastePackages,
filePath: absolutePath,
hasteImplModulePath: this.#hasteImplModulePath,
maybeReturnContent,
};
}
/**
* Creates workers or parses files and extracts metadata in-process.
*/
#getBatchWorker(numWorkers: number): AsyncWorker {
if (numWorkers <= 1) {
// In-band worker with the same interface as a Jest worker farm
return {
processFile: async message => this.#inBandWorker.processFile(message),
end: async () => {},
};
}
const workerPath = require.resolve('../worker');
debug(
'Creating worker farm of %d worker %s',
numWorkers,
this.#enableWorkerThreads ? 'threads' : 'processes',
);
this.#perfLogger?.point('initWorkers_start');
const jestWorker = new JestWorker<{
processFile: WorkerMessage => Promise<WorkerMetadata>,
}>(workerPath, {
exposedMethods: ['processFile'],
maxRetries: 3,
numWorkers,
enableWorkerThreads: this.#enableWorkerThreads,
forkOptions: {
// Don't pass Node arguments down to workers. In particular, avoid
// unnecessarily registering Babel when we're running Metro from
// source (our worker is plain CommonJS).
execArgv: [],
},
setupArgs: [this.#workerArgs],
});
this.#perfLogger?.point('initWorkers_end');
// Only log worker init once
this.#perfLogger = null;
return jestWorker;
}
async end(): Promise<void> {}
}
function processWorkerReply(
metadata: WorkerMetadata,
fileMetadata: FileMetadata,
) {
fileMetadata[H.VISITED] = 1;
const metadataId = metadata.id;
if (metadataId != null) {
fileMetadata[H.ID] = metadataId;
}
fileMetadata[H.DEPENDENCIES] = metadata.dependencies
? metadata.dependencies.join(H.DEPENDENCY_DELIM)
: '';
if (metadata.sha1 != null) {
fileMetadata[H.SHA1] = metadata.sha1;
}
return metadata.content;
}
function normalizeWorkerError(mixedError: ?Error | string): MaybeCodedError {
if (
mixedError == null ||
typeof mixedError !== 'object' ||
mixedError.message == null ||
mixedError.stack == null
) {
const error = new Error(mixedError);
error.stack = ''; // Remove stack for stack-less errors.
return error;
}
return mixedError;
}
+238
View File
@@ -0,0 +1,238 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.RootPathUtils = void 0;
var _invariant = _interopRequireDefault(require("invariant"));
var path = _interopRequireWildcard(require("path"));
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 };
}
const UP_FRAGMENT_SEP = ".." + path.sep;
const SEP_UP_FRAGMENT = path.sep + "..";
const UP_FRAGMENT_SEP_LENGTH = UP_FRAGMENT_SEP.length;
const CURRENT_FRAGMENT = "." + path.sep;
class RootPathUtils {
#rootDir;
#rootDirnames;
#rootParts;
#rootDepth;
constructor(rootDir) {
this.#rootDir = rootDir;
const rootDirnames = [];
for (
let next = rootDir, previous = null;
previous !== next;
previous = next, next = path.dirname(next)
) {
rootDirnames.push(next);
}
this.#rootDirnames = rootDirnames;
this.#rootParts = rootDir.split(path.sep);
this.#rootDepth = rootDirnames.length - 1;
if (this.#rootDepth === 0) {
this.#rootParts.pop();
}
}
getBasenameOfNthAncestor(n) {
return this.#rootParts[this.#rootParts.length - 1 - n];
}
getParts() {
return this.#rootParts;
}
absoluteToNormal(absolutePath) {
let endOfMatchingPrefix = 0;
let lastMatchingPartIdx = 0;
for (
let nextPart = this.#rootParts[0], nextLength = nextPart.length;
nextPart != null &&
absolutePath.startsWith(nextPart, endOfMatchingPrefix) &&
(absolutePath.length === endOfMatchingPrefix + nextLength ||
absolutePath[endOfMatchingPrefix + nextLength] === path.sep);
) {
endOfMatchingPrefix += nextLength + 1;
nextPart = this.#rootParts[++lastMatchingPartIdx];
nextLength = nextPart?.length;
}
const upIndirectionsToPrepend =
this.#rootParts.length - lastMatchingPartIdx;
return (
this.#tryCollapseIndirectionsInSuffix(
absolutePath,
endOfMatchingPrefix,
upIndirectionsToPrepend,
)?.collapsedPath ?? this.#slowAbsoluteToNormal(absolutePath)
);
}
#slowAbsoluteToNormal(absolutePath) {
const endsWithSep = absolutePath.endsWith(path.sep);
const result = path.relative(this.#rootDir, absolutePath);
return endsWithSep && !result.endsWith(path.sep)
? result + path.sep
: result;
}
normalToAbsolute(normalPath) {
let left = this.#rootDir;
let i = 0;
let pos = 0;
while (
normalPath.startsWith(UP_FRAGMENT_SEP, pos) ||
(normalPath.endsWith("..") && normalPath.length === 2 + pos)
) {
left = this.#rootDirnames[i === this.#rootDepth ? this.#rootDepth : ++i];
pos += UP_FRAGMENT_SEP_LENGTH;
}
const right = pos === 0 ? normalPath : normalPath.slice(pos);
if (right.length === 0) {
return left;
}
if (i === this.#rootDepth) {
return left + right;
}
return left + path.sep + right;
}
relativeToNormal(relativePath) {
return (
this.#tryCollapseIndirectionsInSuffix(relativePath, 0, 0)
?.collapsedPath ??
path.relative(this.#rootDir, path.join(this.#rootDir, relativePath))
);
}
getAncestorOfRootIdx(normalPath) {
if (normalPath === "") {
return 0;
}
if (normalPath === "..") {
return 1;
}
if (normalPath.endsWith(SEP_UP_FRAGMENT)) {
return (normalPath.length + 1) / 3;
}
return null;
}
joinNormalToRelative(normalPath, relativePath) {
if (normalPath === "") {
return {
collapsedSegments: 0,
normalPath: relativePath,
};
}
if (relativePath === "") {
return {
collapsedSegments: 0,
normalPath,
};
}
const left = normalPath + path.sep;
const rawPath = left + relativePath;
if (normalPath === ".." || normalPath.endsWith(SEP_UP_FRAGMENT)) {
const collapsed = this.#tryCollapseIndirectionsInSuffix(rawPath, 0, 0);
(0, _invariant.default)(collapsed != null, "Failed to collapse");
return {
collapsedSegments: collapsed.collapsedSegments,
normalPath: collapsed.collapsedPath,
};
}
return {
collapsedSegments: 0,
normalPath: rawPath,
};
}
relative(from, to) {
return path.relative(from, to);
}
#tryCollapseIndirectionsInSuffix(
fullPath,
startOfRelativePart,
implicitUpIndirections,
) {
let totalUpIndirections = implicitUpIndirections;
let collapsedSegments = 0;
for (let pos = startOfRelativePart; ; pos += UP_FRAGMENT_SEP_LENGTH) {
const nextIndirection = fullPath.indexOf(CURRENT_FRAGMENT, pos);
if (nextIndirection === -1) {
while (totalUpIndirections > 0) {
const segmentToMaybeCollapse =
this.#rootParts[this.#rootParts.length - totalUpIndirections];
if (
fullPath.startsWith(segmentToMaybeCollapse, pos) &&
(fullPath.length === segmentToMaybeCollapse.length + pos ||
fullPath[segmentToMaybeCollapse.length + pos] === path.sep)
) {
pos += segmentToMaybeCollapse.length + 1;
collapsedSegments++;
totalUpIndirections--;
} else {
break;
}
}
if (pos >= fullPath.length) {
return {
collapsedPath:
totalUpIndirections > 0
? UP_FRAGMENT_SEP.repeat(totalUpIndirections - 1) +
".." +
fullPath.slice(pos - 1)
: "",
collapsedSegments,
};
}
const right = pos > 0 ? fullPath.slice(pos) : fullPath;
if (
right === ".." &&
totalUpIndirections >= this.#rootParts.length - 1
) {
return {
collapsedPath: UP_FRAGMENT_SEP.repeat(totalUpIndirections).slice(
0,
-1,
),
collapsedSegments,
};
}
if (totalUpIndirections === 0) {
return {
collapsedPath: right,
collapsedSegments,
};
}
return {
collapsedPath: UP_FRAGMENT_SEP.repeat(totalUpIndirections) + right,
collapsedSegments,
};
}
if (totalUpIndirections < this.#rootParts.length - 1) {
totalUpIndirections++;
}
if (nextIndirection !== pos + 1 || fullPath[pos] !== ".") {
return null;
}
}
}
}
exports.RootPathUtils = RootPathUtils;
@@ -0,0 +1,316 @@
/**
* 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
* @flow strict
*/
import invariant from 'invariant';
import * as path from 'path';
/**
* This module provides path utility functions - similar to `node:path` -
* optimised for Metro's use case (many paths, few roots) under assumptions
* typically safe to make within Metro - namely:
*
* - All input path separators must be system-native.
* - Double/redundant separators like '/foo//bar' are not supported.
* - All characters except separators are assumed to be valid in path segments.
*
* - A "well-formed" path is any path following the rules above.
* - A "normal" path is a root-relative well-formed path with no redundant
* indirections. Normal paths have no leading './`, and the normal path of
* the root is the empty string.
*
* Output and input paths are at least well-formed (normal where indicated by
* naming).
*
* Trailing path separators are preserved, except for fs roots in
* normalToAbsolute (fs roots always have a trailing separator), and the
* project root in absoluteToNormal and relativeToNormal (the project root is
* always the empty string, and is always a directory, so a trailing separator
* is redundant).
*
* As of Node 20, absoluteToNormal is ~8x faster than `path.relative` and
* `normalToAbsolute` is ~20x faster than `path.resolve`, benchmarked on the
* real inputs from building FB's product graph. Some well-formed inputs
* (e.g., /project/./foo/../bar), are handled but not optimised, and we fall
* back to `node:path` equivalents in those cases.
*/
const UP_FRAGMENT_SEP = '..' + path.sep;
const SEP_UP_FRAGMENT = path.sep + '..';
const UP_FRAGMENT_SEP_LENGTH = UP_FRAGMENT_SEP.length;
const CURRENT_FRAGMENT = '.' + path.sep;
export class RootPathUtils {
#rootDir: string;
#rootDirnames: $ReadOnlyArray<string>;
#rootParts: $ReadOnlyArray<string>;
#rootDepth: number;
constructor(rootDir: string) {
this.#rootDir = rootDir;
const rootDirnames = [];
for (
let next = rootDir, previous = null;
/* $FlowFixMe[invalid-compare] Error discovered during Constant Condition
* roll out. See https://fburl.com/workplace/5whu3i34. */
previous !== next;
previous = next, next = path.dirname(next)
) {
rootDirnames.push(next);
}
this.#rootDirnames = rootDirnames;
this.#rootParts = rootDir.split(path.sep);
this.#rootDepth = rootDirnames.length - 1;
// If rootDir is a filesystem root (C:\ or /), it will end in a separator and
// give a spurious empty entry at the end of rootParts.
if (this.#rootDepth === 0) {
this.#rootParts.pop();
}
}
getBasenameOfNthAncestor(n: number): string {
return this.#rootParts[this.#rootParts.length - 1 - n];
}
getParts(): $ReadOnlyArray<string> {
return this.#rootParts;
}
// absolutePath may be any well-formed absolute path.
absoluteToNormal(absolutePath: string): string {
let endOfMatchingPrefix = 0;
let lastMatchingPartIdx = 0;
for (
let nextPart = this.#rootParts[0], nextLength = nextPart.length;
nextPart != null &&
// Check that absolutePath is equal to nextPart + '/' or ends with
// nextPart, starting from endOfMatchingPrefix.
absolutePath.startsWith(nextPart, endOfMatchingPrefix) &&
(absolutePath.length === endOfMatchingPrefix + nextLength ||
absolutePath[endOfMatchingPrefix + nextLength] === path.sep);
) {
// Move our matching pointer forward and load the next part.
endOfMatchingPrefix += nextLength + 1;
nextPart = this.#rootParts[++lastMatchingPartIdx];
nextLength = nextPart?.length;
}
// If our root is /project/root and we're given /project/bar/foo.js, we
// have matched up to '/project', and will need to return a path
// beginning '../' (one prepended indirection, to go up from 'root').
//
// If we're given /project/../project2/otherroot, we have one level of
// indirection up to prepend in the same way as above. There's another
// explicit indirection already present in the input - we'll account for
// that in tryCollapseIndirectionsInSuffix.
const upIndirectionsToPrepend =
this.#rootParts.length - lastMatchingPartIdx;
return (
this.#tryCollapseIndirectionsInSuffix(
absolutePath,
endOfMatchingPrefix,
upIndirectionsToPrepend,
)?.collapsedPath ?? this.#slowAbsoluteToNormal(absolutePath)
);
}
#slowAbsoluteToNormal(absolutePath: string): string {
const endsWithSep = absolutePath.endsWith(path.sep);
const result = path.relative(this.#rootDir, absolutePath);
return endsWithSep && !result.endsWith(path.sep)
? result + path.sep
: result;
}
// `normalPath` is assumed to be normal (root-relative, no redundant
// indirection), per the definition above.
normalToAbsolute(normalPath: string): string {
let left = this.#rootDir;
let i = 0;
let pos = 0;
while (
normalPath.startsWith(UP_FRAGMENT_SEP, pos) ||
(normalPath.endsWith('..') && normalPath.length === 2 + pos)
) {
left = this.#rootDirnames[i === this.#rootDepth ? this.#rootDepth : ++i];
pos += UP_FRAGMENT_SEP_LENGTH;
}
const right = pos === 0 ? normalPath : normalPath.slice(pos);
if (right.length === 0) {
return left;
}
// left may already end in a path separator only if it is a filesystem root,
// '/' or 'X:\'.
if (i === this.#rootDepth) {
return left + right;
}
return left + path.sep + right;
}
relativeToNormal(relativePath: string): string {
return (
this.#tryCollapseIndirectionsInSuffix(relativePath, 0, 0)
?.collapsedPath ??
path.relative(this.#rootDir, path.join(this.#rootDir, relativePath))
);
}
// If a path is a direct ancestor of the project root (or the root itself),
// return a number with the degrees of separation, e.g. root=0, parent=1,..
// or null otherwise.
getAncestorOfRootIdx(normalPath: string): ?number {
if (normalPath === '') {
return 0;
}
if (normalPath === '..') {
return 1;
}
// Otherwise a *normal* path is only a root ancestor if it is a sequence of
// '../' segments followed by '..', so the length tells us the number of
// up fragments.
if (normalPath.endsWith(SEP_UP_FRAGMENT)) {
return (normalPath.length + 1) / 3;
}
return null;
}
// Takes a normal and relative path, and joins them efficiently into a normal
// path, including collapsing trailing '..' in the first part with leading
// project root segments in the relative part.
joinNormalToRelative(
normalPath: string,
relativePath: string,
): {normalPath: string, collapsedSegments: number} {
if (normalPath === '') {
return {collapsedSegments: 0, normalPath: relativePath};
}
if (relativePath === '') {
return {collapsedSegments: 0, normalPath};
}
const left = normalPath + path.sep;
const rawPath = left + relativePath;
if (normalPath === '..' || normalPath.endsWith(SEP_UP_FRAGMENT)) {
const collapsed = this.#tryCollapseIndirectionsInSuffix(rawPath, 0, 0);
invariant(collapsed != null, 'Failed to collapse');
return {
collapsedSegments: collapsed.collapsedSegments,
normalPath: collapsed.collapsedPath,
};
}
return {
collapsedSegments: 0,
normalPath: rawPath,
};
}
relative(from: string, to: string): string {
return path.relative(from, to);
}
// Internal: Tries to collapse sequences like `../root/foo` for root
// `/project/root` down to the normal 'foo'.
#tryCollapseIndirectionsInSuffix(
fullPath: string, // A string ending with the relative path to process
startOfRelativePart: number, // Index of the start of part to process
implicitUpIndirections: number, // 0=root-relative, 1=dirname(root)-relative...
): ?{collapsedPath: string, collapsedSegments: number} {
let totalUpIndirections = implicitUpIndirections;
let collapsedSegments = 0;
// Allow any sequence of indirection fragments at the start of the
// unmatched suffix e.g /project/[../../foo], but bail out to Node's
// path.relative if we find a possible indirection after any later segment,
// or on any "./" that isn't a "../".
for (let pos = startOfRelativePart; ; pos += UP_FRAGMENT_SEP_LENGTH) {
const nextIndirection = fullPath.indexOf(CURRENT_FRAGMENT, pos);
if (nextIndirection === -1) {
// If we have any indirections, they may "collapse" if a subsequent
// segment re-enters a directory we had previously exited, e.g:
// /project/root/../root/foo should collapse to /project/root/foo' and
// return foo, not ../root/foo.
//
// We match each segment following redirections, in turn, against the
// part of the root path they may collapse into, and break on the first
// mismatch.
while (totalUpIndirections > 0) {
const segmentToMaybeCollapse =
this.#rootParts[this.#rootParts.length - totalUpIndirections];
if (
fullPath.startsWith(segmentToMaybeCollapse, pos) &&
// The following character should be either a separator or end of
// string
(fullPath.length === segmentToMaybeCollapse.length + pos ||
fullPath[segmentToMaybeCollapse.length + pos] === path.sep)
) {
pos += segmentToMaybeCollapse.length + 1;
collapsedSegments++;
totalUpIndirections--;
} else {
break;
}
}
// After collapsing we may have no more segments remaining (following
// '..' indirections). Ensure that we don't drop or add a trailing
// separator in this case by taking .slice(pos-1). In any other case,
// we know that fullPath[pos] is a separator.
if (pos >= fullPath.length) {
return {
collapsedPath:
totalUpIndirections > 0
? UP_FRAGMENT_SEP.repeat(totalUpIndirections - 1) +
'..' +
fullPath.slice(pos - 1)
: '',
collapsedSegments,
};
}
const right = pos > 0 ? fullPath.slice(pos) : fullPath;
if (
right === '..' &&
totalUpIndirections >= this.#rootParts.length - 1
) {
// If we have no right side (or an indirection that would take us
// below the root), just ensure we don't include a trailing separtor.
return {
collapsedPath: UP_FRAGMENT_SEP.repeat(totalUpIndirections).slice(
0,
-1,
),
collapsedSegments,
};
}
// Optimisation for the common case, saves a concatenation.
if (totalUpIndirections === 0) {
return {collapsedPath: right, collapsedSegments};
}
return {
collapsedPath: UP_FRAGMENT_SEP.repeat(totalUpIndirections) + right,
collapsedSegments,
};
}
// Cap the number of indirections at the total number of root segments.
// File systems treat '..' at the root as '.'.
if (totalUpIndirections < this.#rootParts.length - 1) {
totalUpIndirections++;
}
if (
nextIndirection !== pos + 1 || // Fallback when ./ later in the path, or leading
fullPath[pos] !== '.' // and for anything other than a leading ../
) {
return null;
}
}
}
}
+835
View File
@@ -0,0 +1,835 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _constants = _interopRequireDefault(require("../constants"));
var _RootPathUtils = require("./RootPathUtils");
var _invariant = _interopRequireDefault(require("invariant"));
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
function isDirectory(node) {
return node instanceof Map;
}
function isRegularFile(node) {
return node[_constants.default.SYMLINK] === 0;
}
class TreeFS {
#cachedNormalSymlinkTargets = new WeakMap();
#rootDir;
#rootNode = new Map();
#pathUtils;
#processFile;
constructor({ rootDir, files, processFile }) {
this.#rootDir = rootDir;
this.#pathUtils = new _RootPathUtils.RootPathUtils(rootDir);
this.#processFile = processFile;
if (files != null) {
this.bulkAddOrModify(files);
}
}
getSerializableSnapshot() {
return this._cloneTree(this.#rootNode);
}
static fromDeserializedSnapshot({ rootDir, fileSystemData, processFile }) {
const tfs = new TreeFS({
rootDir,
processFile,
});
tfs.#rootNode = fileSystemData;
return tfs;
}
getModuleName(mixedPath) {
const fileMetadata = this._getFileData(mixedPath);
return (fileMetadata && fileMetadata[_constants.default.ID]) ?? null;
}
getSize(mixedPath) {
const fileMetadata = this._getFileData(mixedPath);
return (fileMetadata && fileMetadata[_constants.default.SIZE]) ?? null;
}
getDependencies(mixedPath) {
const fileMetadata = this._getFileData(mixedPath);
if (fileMetadata) {
return fileMetadata[_constants.default.DEPENDENCIES]
? fileMetadata[_constants.default.DEPENDENCIES].split(
_constants.default.DEPENDENCY_DELIM,
)
: [];
} else {
return null;
}
}
getDifference(files) {
const changedFiles = new Map(files);
const removedFiles = new Set();
for (const { canonicalPath, metadata } of this.metadataIterator({
includeSymlinks: true,
includeNodeModules: true,
})) {
const newMetadata = files.get(canonicalPath);
if (newMetadata) {
if (isRegularFile(newMetadata) !== isRegularFile(metadata)) {
continue;
}
if (
newMetadata[_constants.default.MTIME] != null &&
newMetadata[_constants.default.MTIME] != 0 &&
newMetadata[_constants.default.MTIME] ===
metadata[_constants.default.MTIME]
) {
changedFiles.delete(canonicalPath);
} else if (
newMetadata[_constants.default.SHA1] != null &&
newMetadata[_constants.default.SHA1] ===
metadata[_constants.default.SHA1] &&
metadata[_constants.default.VISITED] === 1
) {
const updatedMetadata = [...metadata];
updatedMetadata[_constants.default.MTIME] =
newMetadata[_constants.default.MTIME];
changedFiles.set(canonicalPath, updatedMetadata);
}
} else {
removedFiles.add(canonicalPath);
}
}
return {
changedFiles,
removedFiles,
};
}
getSha1(mixedPath) {
const fileMetadata = this._getFileData(mixedPath);
return (fileMetadata && fileMetadata[_constants.default.SHA1]) ?? null;
}
async getOrComputeSha1(mixedPath) {
const normalPath = this._normalizePath(mixedPath);
const result = this._lookupByNormalPath(normalPath, {
followLeaf: true,
});
if (!result.exists || isDirectory(result.node)) {
return null;
}
const { canonicalPath, node: fileMetadata } = result;
const existing = fileMetadata[_constants.default.SHA1];
if (existing != null && existing.length > 0) {
return {
sha1: existing,
};
}
const absolutePath = this.#pathUtils.normalToAbsolute(canonicalPath);
const maybeContent = await this.#processFile(absolutePath, fileMetadata, {
computeSha1: true,
});
const sha1 = fileMetadata[_constants.default.SHA1];
(0, _invariant.default)(
sha1 != null && sha1.length > 0,
"File processing didn't populate a SHA-1 hash for %s",
absolutePath,
);
return maybeContent
? {
sha1,
content: maybeContent,
}
: {
sha1,
};
}
exists(mixedPath) {
const result = this._getFileData(mixedPath);
return result != null;
}
lookup(mixedPath) {
const normalPath = this._normalizePath(mixedPath);
const links = new Set();
const result = this._lookupByNormalPath(normalPath, {
collectLinkPaths: links,
followLeaf: true,
});
if (!result.exists) {
const { canonicalMissingPath } = result;
return {
exists: false,
links,
missing: this.#pathUtils.normalToAbsolute(canonicalMissingPath),
};
}
const { canonicalPath, node } = result;
const type = isDirectory(node) ? "d" : isRegularFile(node) ? "f" : "l";
(0, _invariant.default)(
type !== "l",
"lookup follows symlinks, so should never return one (%s -> %s)",
mixedPath,
canonicalPath,
);
return {
exists: true,
links,
realPath: this.#pathUtils.normalToAbsolute(canonicalPath),
type,
};
}
getAllFiles() {
return Array.from(
this.metadataIterator({
includeSymlinks: false,
includeNodeModules: true,
}),
({ canonicalPath }) => this.#pathUtils.normalToAbsolute(canonicalPath),
);
}
linkStats(mixedPath) {
const fileMetadata = this._getFileData(mixedPath, {
followLeaf: false,
});
if (fileMetadata == null) {
return null;
}
const fileType = isRegularFile(fileMetadata) ? "f" : "l";
return {
fileType,
modifiedTime: fileMetadata[_constants.default.MTIME],
size: fileMetadata[_constants.default.SIZE],
};
}
*matchFiles({
filter = null,
filterCompareAbsolute = false,
filterComparePosix = false,
follow = false,
recursive = true,
rootDir = null,
}) {
const normalRoot = rootDir == null ? "" : this._normalizePath(rootDir);
const contextRootResult = this._lookupByNormalPath(normalRoot);
if (!contextRootResult.exists) {
return;
}
const {
ancestorOfRootIdx,
canonicalPath: rootRealPath,
node: contextRoot,
parentNode: contextRootParent,
} = contextRootResult;
if (!isDirectory(contextRoot)) {
return;
}
const contextRootAbsolutePath =
rootRealPath === ""
? this.#rootDir
: _path.default.join(this.#rootDir, rootRealPath);
const prefix = filterComparePosix ? "./" : "." + _path.default.sep;
const contextRootAbsolutePathForComparison =
filterComparePosix && _path.default.sep !== "/"
? contextRootAbsolutePath.replaceAll(_path.default.sep, "/")
: contextRootAbsolutePath;
for (const relativePathForComparison of this._pathIterator(
contextRoot,
contextRootParent,
ancestorOfRootIdx,
{
alwaysYieldPosix: filterComparePosix,
canonicalPathOfRoot: rootRealPath,
follow,
recursive,
subtreeOnly: rootDir != null,
},
)) {
if (
filter == null ||
filter.test(
filterCompareAbsolute === true
? _path.default.join(
contextRootAbsolutePathForComparison,
relativePathForComparison,
)
: prefix + relativePathForComparison,
)
) {
const relativePath =
filterComparePosix === true && _path.default.sep !== "/"
? relativePathForComparison.replaceAll("/", _path.default.sep)
: relativePathForComparison;
yield _path.default.join(contextRootAbsolutePath, relativePath);
}
}
}
addOrModify(mixedPath, metadata) {
const normalPath = this._normalizePath(mixedPath);
const parentDirNode = this._lookupByNormalPath(
_path.default.dirname(normalPath),
{
makeDirectories: true,
},
);
if (!parentDirNode.exists) {
throw new Error(
`TreeFS: Failed to make parent directory entry for ${mixedPath}`,
);
}
const canonicalPath = this._normalizePath(
parentDirNode.canonicalPath +
_path.default.sep +
_path.default.basename(normalPath),
);
this.bulkAddOrModify(new Map([[canonicalPath, metadata]]));
}
bulkAddOrModify(addedOrModifiedFiles) {
let lastDir;
let directoryNode;
for (const [normalPath, metadata] of addedOrModifiedFiles) {
const lastSepIdx = normalPath.lastIndexOf(_path.default.sep);
const dirname = lastSepIdx === -1 ? "" : normalPath.slice(0, lastSepIdx);
const basename =
lastSepIdx === -1 ? normalPath : normalPath.slice(lastSepIdx + 1);
if (directoryNode == null || dirname !== lastDir) {
const lookup = this._lookupByNormalPath(dirname, {
followLeaf: false,
makeDirectories: true,
});
if (!lookup.exists) {
throw new Error(
`TreeFS: Unexpected error adding ${normalPath}.\nMissing: ` +
lookup.canonicalMissingPath,
);
}
if (!isDirectory(lookup.node)) {
throw new Error(
`TreeFS: Could not add directory ${dirname}, adding ${normalPath}. ` +
`${dirname} already exists in the file map as a file.`,
);
}
lastDir = dirname;
directoryNode = lookup.node;
}
directoryNode.set(basename, metadata);
}
}
remove(mixedPath) {
const normalPath = this._normalizePath(mixedPath);
const result = this._lookupByNormalPath(normalPath, {
followLeaf: false,
});
if (!result.exists) {
return null;
}
const { parentNode, canonicalPath, node } = result;
if (isDirectory(node) && node.size > 0) {
throw new Error(
`TreeFS: remove called on a non-empty directory: ${mixedPath}`,
);
}
if (parentNode != null) {
parentNode.delete(_path.default.basename(canonicalPath));
if (parentNode.size === 0 && parentNode !== this.#rootNode) {
this.remove(_path.default.dirname(canonicalPath));
}
}
return isDirectory(node) ? null : node;
}
_lookupByNormalPath(
requestedNormalPath,
opts = {
followLeaf: true,
makeDirectories: false,
},
) {
let targetNormalPath = requestedNormalPath;
let seen;
let fromIdx = opts.start?.pathIdx ?? 0;
let parentNode = opts.start?.node ?? this.#rootNode;
let ancestorOfRootIdx = opts.start?.ancestorOfRootIdx ?? 0;
const collectAncestors = opts.collectAncestors;
let unseenPathFromIdx = 0;
while (targetNormalPath.length > fromIdx) {
const nextSepIdx = targetNormalPath.indexOf(_path.default.sep, fromIdx);
const isLastSegment = nextSepIdx === -1;
const segmentName = isLastSegment
? targetNormalPath.slice(fromIdx)
: targetNormalPath.slice(fromIdx, nextSepIdx);
const isUnseen = fromIdx >= unseenPathFromIdx;
fromIdx = !isLastSegment ? nextSepIdx + 1 : targetNormalPath.length;
if (segmentName === ".") {
continue;
}
let segmentNode = parentNode.get(segmentName);
if (segmentName === ".." && ancestorOfRootIdx != null) {
ancestorOfRootIdx++;
} else if (segmentNode != null) {
ancestorOfRootIdx = null;
}
if (segmentNode == null) {
if (opts.makeDirectories !== true && segmentName !== "..") {
return {
canonicalMissingPath: isLastSegment
? targetNormalPath
: targetNormalPath.slice(0, fromIdx - 1),
exists: false,
missingSegmentName: segmentName,
};
}
segmentNode = new Map();
if (opts.makeDirectories === true) {
parentNode.set(segmentName, segmentNode);
}
}
if (
(nextSepIdx === targetNormalPath.length - 1 &&
isDirectory(segmentNode)) ||
(isLastSegment &&
(isDirectory(segmentNode) ||
isRegularFile(segmentNode) ||
opts.followLeaf === false))
) {
return {
ancestorOfRootIdx,
canonicalPath: isLastSegment
? targetNormalPath
: targetNormalPath.slice(0, -1),
exists: true,
node: segmentNode,
parentNode,
};
}
if (isDirectory(segmentNode)) {
parentNode = segmentNode;
if (collectAncestors && isUnseen) {
const currentPath = isLastSegment
? targetNormalPath
: targetNormalPath.slice(0, fromIdx - 1);
collectAncestors.push({
ancestorOfRootIdx,
node: segmentNode,
normalPath: currentPath,
segmentName,
});
}
} else {
const currentPath = isLastSegment
? targetNormalPath
: targetNormalPath.slice(0, fromIdx - 1);
if (isRegularFile(segmentNode)) {
return {
canonicalMissingPath: currentPath,
exists: false,
missingSegmentName: segmentName,
};
}
const normalSymlinkTarget = this._resolveSymlinkTargetToNormalPath(
segmentNode,
currentPath,
);
if (opts.collectLinkPaths) {
opts.collectLinkPaths.add(
this.#pathUtils.normalToAbsolute(currentPath),
);
}
const remainingTargetPath = isLastSegment
? ""
: targetNormalPath.slice(fromIdx);
const joinedResult = this.#pathUtils.joinNormalToRelative(
normalSymlinkTarget.normalPath,
remainingTargetPath,
);
targetNormalPath = joinedResult.normalPath;
if (
collectAncestors &&
!isLastSegment &&
(normalSymlinkTarget.ancestorOfRootIdx === 0 ||
joinedResult.collapsedSegments > 0)
) {
let node = this.#rootNode;
let collapsedPath = "";
const reverseAncestors = [];
for (
let i = 0;
i <= joinedResult.collapsedSegments && isDirectory(node);
i++
) {
if (
i > 0 ||
normalSymlinkTarget.ancestorOfRootIdx === 0 ||
joinedResult.collapsedSegments > 0
) {
reverseAncestors.push({
ancestorOfRootIdx: i,
node,
normalPath: collapsedPath,
segmentName: this.#pathUtils.getBasenameOfNthAncestor(i),
});
}
node = node.get("..") ?? new Map();
collapsedPath =
collapsedPath === ""
? ".."
: collapsedPath + _path.default.sep + "..";
}
collectAncestors.push(...reverseAncestors.reverse());
}
unseenPathFromIdx = normalSymlinkTarget.startOfBasenameIdx;
if (seen == null) {
seen = new Set([requestedNormalPath]);
}
if (seen.has(targetNormalPath)) {
return {
canonicalMissingPath: targetNormalPath,
exists: false,
missingSegmentName: segmentName,
};
}
seen.add(targetNormalPath);
fromIdx = 0;
parentNode = this.#rootNode;
ancestorOfRootIdx = 0;
}
}
(0, _invariant.default)(
parentNode === this.#rootNode,
"Unexpectedly escaped traversal",
);
return {
ancestorOfRootIdx: 0,
canonicalPath: targetNormalPath,
exists: true,
node: this.#rootNode,
parentNode: null,
};
}
hierarchicalLookup(mixedStartPath, subpath, opts) {
const ancestorsOfInput = [];
const normalPath = this._normalizePath(mixedStartPath);
const invalidatedBy = opts.invalidatedBy;
const closestLookup = this._lookupByNormalPath(normalPath, {
collectAncestors: ancestorsOfInput,
collectLinkPaths: invalidatedBy,
});
if (closestLookup.exists && isDirectory(closestLookup.node)) {
const maybeAbsolutePathMatch = this.#checkCandidateHasSubpath(
closestLookup.canonicalPath,
subpath,
opts.subpathType,
invalidatedBy,
null,
);
if (maybeAbsolutePathMatch != null) {
return {
absolutePath: maybeAbsolutePathMatch,
containerRelativePath: "",
};
}
} else {
if (
invalidatedBy &&
(!closestLookup.exists || !isDirectory(closestLookup.node))
) {
invalidatedBy.add(
this.#pathUtils.normalToAbsolute(
closestLookup.exists
? closestLookup.canonicalPath
: closestLookup.canonicalMissingPath,
),
);
}
if (
opts.breakOnSegment != null &&
!closestLookup.exists &&
closestLookup.missingSegmentName === opts.breakOnSegment
) {
return null;
}
}
let commonRoot = this.#rootNode;
let commonRootDepth = 0;
if (closestLookup.exists && closestLookup.ancestorOfRootIdx != null) {
commonRootDepth = closestLookup.ancestorOfRootIdx;
(0, _invariant.default)(
isDirectory(closestLookup.node),
"ancestors of the root must be directories",
);
commonRoot = closestLookup.node;
} else {
for (const ancestor of ancestorsOfInput) {
if (ancestor.ancestorOfRootIdx == null) {
break;
}
commonRootDepth = ancestor.ancestorOfRootIdx;
commonRoot = ancestor.node;
}
}
for (
let candidateIdx = ancestorsOfInput.length - 1;
candidateIdx >= commonRootDepth;
--candidateIdx
) {
const candidate = ancestorsOfInput[candidateIdx];
if (candidate.segmentName === opts.breakOnSegment) {
return null;
}
const maybeAbsolutePathMatch = this.#checkCandidateHasSubpath(
candidate.normalPath,
subpath,
opts.subpathType,
invalidatedBy,
{
ancestorOfRootIdx: candidate.ancestorOfRootIdx,
node: candidate.node,
pathIdx:
candidate.normalPath.length > 0
? candidate.normalPath.length + 1
: 0,
},
);
if (maybeAbsolutePathMatch != null) {
let prefixLength = commonRootDepth * 3;
for (let i = commonRootDepth; i <= candidateIdx; i++) {
prefixLength = normalPath.indexOf(
_path.default.sep,
prefixLength + 1,
);
}
const containerRelativePath = normalPath.slice(prefixLength + 1);
return {
absolutePath: maybeAbsolutePathMatch,
containerRelativePath,
};
}
}
let candidateNormalPath =
commonRootDepth > 0 ? normalPath.slice(0, 3 * commonRootDepth - 1) : "";
const remainingNormalPath = normalPath.slice(commonRootDepth * 3);
let nextNode = commonRoot;
let depthBelowCommonRoot = 0;
while (isDirectory(nextNode)) {
const maybeAbsolutePathMatch = this.#checkCandidateHasSubpath(
candidateNormalPath,
subpath,
opts.subpathType,
invalidatedBy,
null,
);
if (maybeAbsolutePathMatch != null) {
const rootDirParts = this.#pathUtils.getParts();
const relativeParts =
depthBelowCommonRoot > 0
? rootDirParts.slice(
-(depthBelowCommonRoot + commonRootDepth),
commonRootDepth > 0 ? -commonRootDepth : undefined,
)
: [];
if (remainingNormalPath !== "") {
relativeParts.push(remainingNormalPath);
}
return {
absolutePath: maybeAbsolutePathMatch,
containerRelativePath: relativeParts.join(_path.default.sep),
};
}
depthBelowCommonRoot++;
candidateNormalPath =
candidateNormalPath === ""
? ".."
: candidateNormalPath + _path.default.sep + "..";
nextNode = nextNode.get("..");
}
return null;
}
#checkCandidateHasSubpath(
normalCandidatePath,
subpath,
subpathType,
invalidatedBy,
start,
) {
const lookupResult = this._lookupByNormalPath(
this.#pathUtils.joinNormalToRelative(normalCandidatePath, subpath)
.normalPath,
{
collectLinkPaths: invalidatedBy,
},
);
if (
lookupResult.exists &&
isDirectory(lookupResult.node) === (subpathType === "d")
) {
return this.#pathUtils.normalToAbsolute(lookupResult.canonicalPath);
} else if (invalidatedBy) {
invalidatedBy.add(
this.#pathUtils.normalToAbsolute(
lookupResult.exists
? lookupResult.canonicalPath
: lookupResult.canonicalMissingPath,
),
);
}
return null;
}
*metadataIterator(opts) {
yield* this._metadataIterator(this.#rootNode, opts);
}
*_metadataIterator(rootNode, opts, prefix = "") {
for (const [name, node] of rootNode) {
if (
!opts.includeNodeModules &&
isDirectory(node) &&
name === "node_modules"
) {
continue;
}
const prefixedName =
prefix === "" ? name : prefix + _path.default.sep + name;
if (isDirectory(node)) {
yield* this._metadataIterator(node, opts, prefixedName);
} else if (isRegularFile(node) || opts.includeSymlinks) {
yield {
canonicalPath: prefixedName,
metadata: node,
baseName: name,
};
}
}
}
_normalizePath(relativeOrAbsolutePath) {
return _path.default.isAbsolute(relativeOrAbsolutePath)
? this.#pathUtils.absoluteToNormal(relativeOrAbsolutePath)
: this.#pathUtils.relativeToNormal(relativeOrAbsolutePath);
}
*#directoryNodeIterator(node, parent, ancestorOfRootIdx) {
if (ancestorOfRootIdx != null && ancestorOfRootIdx > 0 && parent) {
yield [
this.#pathUtils.getBasenameOfNthAncestor(ancestorOfRootIdx - 1),
parent,
];
}
yield* node.entries();
}
*_pathIterator(
iterationRootNode,
iterationRootParentNode,
ancestorOfRootIdx,
opts,
pathPrefix = "",
followedLinks = new Set(),
) {
const pathSep = opts.alwaysYieldPosix ? "/" : _path.default.sep;
const prefixWithSep = pathPrefix === "" ? pathPrefix : pathPrefix + pathSep;
for (const [name, node] of this.#directoryNodeIterator(
iterationRootNode,
iterationRootParentNode,
ancestorOfRootIdx,
)) {
if (opts.subtreeOnly && name === "..") {
continue;
}
const nodePath = prefixWithSep + name;
if (!isDirectory(node)) {
if (isRegularFile(node)) {
yield nodePath;
} else {
const nodePathWithSystemSeparators =
pathSep === _path.default.sep
? nodePath
: nodePath.replaceAll(pathSep, _path.default.sep);
const normalPathOfSymlink = _path.default.join(
opts.canonicalPathOfRoot,
nodePathWithSystemSeparators,
);
const resolved = this._lookupByNormalPath(normalPathOfSymlink, {
followLeaf: true,
});
if (!resolved.exists) {
continue;
}
const target = resolved.node;
if (!isDirectory(target)) {
yield nodePath;
} else if (
opts.recursive &&
opts.follow &&
!followedLinks.has(node)
) {
yield* this._pathIterator(
target,
resolved.parentNode,
resolved.ancestorOfRootIdx,
opts,
nodePath,
new Set([...followedLinks, node]),
);
}
}
} else if (opts.recursive) {
yield* this._pathIterator(
node,
iterationRootParentNode,
ancestorOfRootIdx != null && ancestorOfRootIdx > 0
? ancestorOfRootIdx - 1
: null,
opts,
nodePath,
followedLinks,
);
}
}
}
_resolveSymlinkTargetToNormalPath(symlinkNode, canonicalPathOfSymlink) {
const cachedResult = this.#cachedNormalSymlinkTargets.get(symlinkNode);
if (cachedResult != null) {
return cachedResult;
}
const literalSymlinkTarget = symlinkNode[_constants.default.SYMLINK];
(0, _invariant.default)(
typeof literalSymlinkTarget === "string",
"Expected symlink target to be populated.",
);
const absoluteSymlinkTarget = _path.default.resolve(
this.#rootDir,
canonicalPathOfSymlink,
"..",
literalSymlinkTarget,
);
const normalSymlinkTarget = _path.default.relative(
this.#rootDir,
absoluteSymlinkTarget,
);
const result = {
ancestorOfRootIdx:
this.#pathUtils.getAncestorOfRootIdx(normalSymlinkTarget),
normalPath: normalSymlinkTarget,
startOfBasenameIdx:
normalSymlinkTarget.lastIndexOf(_path.default.sep) + 1,
};
this.#cachedNormalSymlinkTargets.set(symlinkNode, result);
return result;
}
_getFileData(
filePath,
opts = {
followLeaf: true,
},
) {
const normalPath = this._normalizePath(filePath);
const result = this._lookupByNormalPath(normalPath, {
followLeaf: opts.followLeaf,
});
if (!result.exists || isDirectory(result.node)) {
return null;
}
return result.node;
}
_cloneTree(root) {
const clone = new Map();
for (const [name, node] of root) {
if (isDirectory(node)) {
clone.set(name, this._cloneTree(node));
} else {
clone.set(name, [...node]);
}
}
return clone;
}
}
exports.default = TreeFS;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = checkWatchmanCapabilities;
var _child_process = require("child_process");
var _util = require("util");
async function checkWatchmanCapabilities(requiredCapabilities) {
const execFilePromise = (0, _util.promisify)(_child_process.execFile);
let rawResponse;
try {
const result = await execFilePromise("watchman", [
"list-capabilities",
"--output-encoding=json",
"--no-pretty",
"--no-spawn",
]);
rawResponse = result.stdout;
} catch (e) {
if (e?.code === "ENOENT") {
throw new Error("Watchman is not installed or not available on PATH");
}
throw e;
}
let parsedResponse;
try {
parsedResponse = JSON.parse(rawResponse);
} catch {
throw new Error(
"Failed to parse response from `watchman list-capabilities`",
);
}
if (
parsedResponse == null ||
typeof parsedResponse !== "object" ||
typeof parsedResponse.version !== "string" ||
!Array.isArray(parsedResponse.capabilities)
) {
throw new Error("Unexpected response from `watchman list-capabilities`");
}
const version = parsedResponse.version;
const capabilities = new Set(parsedResponse.capabilities);
const missingCapabilities = requiredCapabilities.filter(
(requiredCapability) => !capabilities.has(requiredCapability),
);
if (missingCapabilities.length > 0) {
throw new Error(
`The installed version of Watchman (${version}) is missing required capabilities: ${missingCapabilities.join(", ")}`,
);
}
return {
version,
};
}
@@ -0,0 +1,68 @@
/**
* 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
* @flow strict
*/
import {execFile} from 'child_process';
import {promisify} from 'util';
export default async function checkWatchmanCapabilities(
requiredCapabilities: $ReadOnlyArray<string>,
): Promise<{version: string}> {
const execFilePromise: (
cmd: string,
args: $ReadOnlyArray<string>,
) => Promise<{stdout: string}> = promisify(execFile);
let rawResponse;
try {
const result = await execFilePromise('watchman', [
'list-capabilities',
'--output-encoding=json',
'--no-pretty',
'--no-spawn', // The client can answer this, so don't spawn a server
]);
rawResponse = result.stdout;
} catch (e) {
if (e?.code === 'ENOENT') {
throw new Error('Watchman is not installed or not available on PATH');
}
throw e;
}
let parsedResponse;
try {
parsedResponse = (JSON.parse(rawResponse): mixed);
} catch {
throw new Error(
'Failed to parse response from `watchman list-capabilities`',
);
}
if (
parsedResponse == null ||
typeof parsedResponse !== 'object' ||
typeof parsedResponse.version !== 'string' ||
!Array.isArray(parsedResponse.capabilities)
) {
throw new Error('Unexpected response from `watchman list-capabilities`');
}
const version = parsedResponse.version;
const capabilities = new Set(parsedResponse.capabilities);
const missingCapabilities = requiredCapabilities.filter(
requiredCapability => !capabilities.has(requiredCapability),
);
if (missingCapabilities.length > 0) {
throw new Error(
`The installed version of Watchman (${version}) is missing required capabilities: ${missingCapabilities.join(
', ',
)}`,
);
}
return {version};
}
@@ -0,0 +1,73 @@
"use strict";
const NOT_A_DOT = "(?<!\\.\\s*)";
const CAPTURE_STRING_LITERAL = (pos) => `([\`'"])([^'"\`]*?)(?:\\${pos})`;
const WORD_SEPARATOR = "\\b";
const LEFT_PARENTHESIS = "\\(";
const RIGHT_PARENTHESIS = "\\)";
const WHITESPACE = "\\s*";
const OPTIONAL_COMMA = "(:?,\\s*)?";
function createRegExp(parts, flags) {
return new RegExp(parts.join(""), flags);
}
function alternatives(...parts) {
return `(?:${parts.join("|")})`;
}
function functionCallStart(...names) {
return [
NOT_A_DOT,
WORD_SEPARATOR,
alternatives(...names),
WHITESPACE,
LEFT_PARENTHESIS,
WHITESPACE,
];
}
const BLOCK_COMMENT_RE = /\/\*[^]*?\*\//g;
const LINE_COMMENT_RE = /\/\/.*/g;
const REQUIRE_OR_DYNAMIC_IMPORT_RE = createRegExp(
[
...functionCallStart("require", "import"),
CAPTURE_STRING_LITERAL(1),
WHITESPACE,
OPTIONAL_COMMA,
RIGHT_PARENTHESIS,
],
"g",
);
const IMPORT_OR_EXPORT_RE = createRegExp(
[
"\\b(?:import|export)\\s+(?!type(?:of)?\\s+)(?:[^'\"]+\\s+from\\s+)?",
CAPTURE_STRING_LITERAL(1),
],
"g",
);
const JEST_EXTENSIONS_RE = createRegExp(
[
...functionCallStart(
"jest\\s*\\.\\s*(?:requireActual|requireMock|genMockFromModule|createMockFromModule)",
),
CAPTURE_STRING_LITERAL(1),
WHITESPACE,
OPTIONAL_COMMA,
RIGHT_PARENTHESIS,
],
"g",
);
function extract(code) {
const dependencies = new Set();
const addDependency = (match, _, dep) => {
dependencies.add(dep);
return match;
};
code
.replace(BLOCK_COMMENT_RE, "")
.replace(LINE_COMMENT_RE, "")
.replace(IMPORT_OR_EXPORT_RE, addDependency)
.replace(REQUIRE_OR_DYNAMIC_IMPORT_RE, addDependency)
.replace(JEST_EXTENSIONS_RE, addDependency);
return dependencies;
}
module.exports = {
extract,
};
@@ -0,0 +1,104 @@
/**
* 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
* @flow strict
*/
// Required by worker, must be commonjs
/* eslint-disable import/no-commonjs */
'use strict';
const NOT_A_DOT = '(?<!\\.\\s*)';
const CAPTURE_STRING_LITERAL = (pos /*: number */) =>
`([\`'"])([^'"\`]*?)(?:\\${pos})`;
const WORD_SEPARATOR = '\\b';
const LEFT_PARENTHESIS = '\\(';
const RIGHT_PARENTHESIS = '\\)';
const WHITESPACE = '\\s*';
const OPTIONAL_COMMA = '(:?,\\s*)?';
function createRegExp(
parts /*: $ReadOnlyArray<string> */,
flags /*: string */,
) {
return new RegExp(parts.join(''), flags);
}
function alternatives(...parts /*: $ReadOnlyArray<string> */) {
return `(?:${parts.join('|')})`;
}
function functionCallStart(...names /*: $ReadOnlyArray<string> */) {
return [
NOT_A_DOT,
WORD_SEPARATOR,
alternatives(...names),
WHITESPACE,
LEFT_PARENTHESIS,
WHITESPACE,
];
}
const BLOCK_COMMENT_RE = /\/\*[^]*?\*\//g;
const LINE_COMMENT_RE = /\/\/.*/g;
const REQUIRE_OR_DYNAMIC_IMPORT_RE = createRegExp(
[
...functionCallStart('require', 'import'),
CAPTURE_STRING_LITERAL(1),
WHITESPACE,
OPTIONAL_COMMA,
RIGHT_PARENTHESIS,
],
'g',
);
const IMPORT_OR_EXPORT_RE = createRegExp(
[
'\\b(?:import|export)\\s+(?!type(?:of)?\\s+)(?:[^\'"]+\\s+from\\s+)?',
CAPTURE_STRING_LITERAL(1),
],
'g',
);
const JEST_EXTENSIONS_RE = createRegExp(
[
...functionCallStart(
'jest\\s*\\.\\s*(?:requireActual|requireMock|genMockFromModule|createMockFromModule)',
),
CAPTURE_STRING_LITERAL(1),
WHITESPACE,
OPTIONAL_COMMA,
RIGHT_PARENTHESIS,
],
'g',
);
function extract(code /*: string */) /*: Set<string> */ {
const dependencies /*: Set<string> */ = new Set();
const addDependency = (
match /*: string */,
_ /*: string */,
dep /*: string */,
) => {
dependencies.add(dep);
return match;
};
code
.replace(BLOCK_COMMENT_RE, '')
.replace(LINE_COMMENT_RE, '')
.replace(IMPORT_OR_EXPORT_RE, addDependency)
.replace(REQUIRE_OR_DYNAMIC_IMPORT_RE, addDependency)
.replace(JEST_EXTENSIONS_RE, addDependency);
return dependencies;
}
module.exports = {extract};
@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var path = _interopRequireWildcard(require("path"));
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);
}
let normalizePathSeparatorsToPosix;
if (path.sep === "/") {
normalizePathSeparatorsToPosix = (filePath) => filePath;
} else {
normalizePathSeparatorsToPosix = (filePath) => filePath.replace(/\\/g, "/");
}
var _default = (exports.default = normalizePathSeparatorsToPosix);
@@ -0,0 +1,21 @@
/**
* 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
* @flow strict
*/
import * as path from 'path';
let normalizePathSeparatorsToPosix: (string: string) => string;
if (path.sep === '/') {
normalizePathSeparatorsToPosix = (filePath: string): string => filePath;
} else {
normalizePathSeparatorsToPosix = (filePath: string): string =>
filePath.replace(/\\/g, '/');
}
export default normalizePathSeparatorsToPosix;
@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var path = _interopRequireWildcard(require("path"));
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);
}
let normalizePathSeparatorsToSystem;
if (path.sep === "/") {
normalizePathSeparatorsToSystem = (filePath) => filePath;
} else {
normalizePathSeparatorsToSystem = (filePath) =>
filePath.replace(/\//g, path.sep);
}
var _default = (exports.default = normalizePathSeparatorsToSystem);
@@ -0,0 +1,21 @@
/**
* 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
* @flow strict
*/
import * as path from 'path';
let normalizePathSeparatorsToSystem: (string: string) => string;
if (path.sep === '/') {
normalizePathSeparatorsToSystem = (filePath: string): string => filePath;
} else {
normalizePathSeparatorsToSystem = (filePath: string): string =>
filePath.replace(/\//g, path.sep);
}
export default normalizePathSeparatorsToSystem;
@@ -0,0 +1,75 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = rootRelativeCacheKeys;
var _normalizePathSeparatorsToPosix = _interopRequireDefault(
require("./normalizePathSeparatorsToPosix"),
);
var _RootPathUtils = require("./RootPathUtils");
var _crypto = require("crypto");
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
function moduleCacheKey(modulePath) {
if (modulePath == null) {
return null;
}
const moduleExports = require(modulePath);
if (typeof moduleExports?.getCacheKey !== "function") {
console.warn(
`metro-file-map: Expected \`${modulePath}\` to export ` +
"`getCacheKey: () => string`",
);
return null;
}
return moduleExports.getCacheKey();
}
function rootRelativeCacheKeys(buildParameters) {
const { rootDir, plugins, ...otherParameters } = buildParameters;
const rootDirHash = (0, _crypto.createHash)("md5")
.update((0, _normalizePathSeparatorsToPosix.default)(rootDir))
.digest("hex");
const pathUtils = new _RootPathUtils.RootPathUtils(rootDir);
const cacheComponents = Object.keys(otherParameters)
.sort()
.map((key) => {
switch (key) {
case "roots":
return buildParameters[key].map((root) =>
(0, _normalizePathSeparatorsToPosix.default)(
pathUtils.absoluteToNormal(root),
),
);
case "cacheBreaker":
case "extensions":
case "computeDependencies":
case "computeSha1":
case "enableHastePackages":
case "enableSymlinks":
case "forceNodeFilesystemAPI":
case "retainAllFiles":
case "skipPackageJson":
return buildParameters[key] ?? null;
case "ignorePattern":
return buildParameters[key].toString();
case "hasteImplModulePath":
case "dependencyExtractor":
return moduleCacheKey(buildParameters[key]);
default:
key;
throw new Error("Unrecognised key in build parameters: " + key);
}
});
for (const plugin of plugins) {
cacheComponents.push(plugin.getCacheKey());
}
const relativeConfigHash = (0, _crypto.createHash)("md5")
.update(JSON.stringify(cacheComponents))
.digest("hex");
return {
rootDirHash,
relativeConfigHash,
};
}
@@ -0,0 +1,90 @@
/**
* 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 {BuildParameters} from '../flow-types';
import normalizePathSeparatorsToPosix from './normalizePathSeparatorsToPosix';
import {RootPathUtils} from './RootPathUtils';
import {createHash} from 'crypto';
function moduleCacheKey(modulePath: ?string) {
if (modulePath == null) {
return null;
}
// $FlowFixMe[unsupported-syntax] - Dynamic require
const moduleExports = require(modulePath);
if (typeof moduleExports?.getCacheKey !== 'function') {
console.warn(
`metro-file-map: Expected \`${modulePath}\` to export ` +
'`getCacheKey: () => string`',
);
return null;
}
return moduleExports.getCacheKey();
}
export default function rootRelativeCacheKeys(
buildParameters: BuildParameters,
): {
rootDirHash: string,
relativeConfigHash: string,
} {
const {rootDir, plugins, ...otherParameters} = buildParameters;
const rootDirHash = createHash('md5')
.update(normalizePathSeparatorsToPosix(rootDir))
.digest('hex');
const pathUtils = new RootPathUtils(rootDir);
const cacheComponents = Object.keys(otherParameters)
.sort()
.map(key => {
switch (key) {
case 'roots':
return buildParameters[key].map(root =>
normalizePathSeparatorsToPosix(pathUtils.absoluteToNormal(root)),
);
case 'cacheBreaker':
case 'extensions':
case 'computeDependencies':
case 'computeSha1':
case 'enableHastePackages':
case 'enableSymlinks':
case 'forceNodeFilesystemAPI':
case 'retainAllFiles':
case 'skipPackageJson':
return buildParameters[key] ?? null;
case 'ignorePattern':
return buildParameters[key].toString();
case 'hasteImplModulePath':
case 'dependencyExtractor':
return moduleCacheKey(buildParameters[key]);
default:
(key: empty);
throw new Error('Unrecognised key in build parameters: ' + key);
}
});
for (const plugin of plugins) {
cacheComponents.push(plugin.getCacheKey());
}
// JSON.stringify is stable here because we only deal in (nested) arrays of
// primitives. Use a different approach if this is expanded to include
// objects/Sets/Maps, etc.
const relativeConfigHash = createHash('md5')
.update(JSON.stringify(cacheComponents))
.digest('hex');
return {
rootDirHash,
relativeConfigHash,
};
}
+27
View File
@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.chainComparators = chainComparators;
exports.compareStrings = compareStrings;
function compareStrings(a, b) {
if (a == null) {
return b == null ? 0 : -1;
}
if (b == null) {
return 1;
}
return a.localeCompare(b);
}
function chainComparators(...comparators) {
return (a, b) => {
for (const comparator of comparators) {
const result = comparator(a, b);
if (result !== 0) {
return result;
}
}
return 0;
};
}
+35
View File
@@ -0,0 +1,35 @@
/**
* 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
*/
// Utilities for working with Array.prototype.sort
export function compareStrings(a: null | string, b: null | string): number {
if (a == null) {
return b == null ? 0 : -1;
}
if (b == null) {
return 1;
}
return a.localeCompare(b);
}
export function chainComparators<T>(
...comparators: Array<(a: T, b: T) => number>
): (a: T, b: T) => number {
return (a, b) => {
for (const comparator of comparators) {
const result = comparator(a, b);
if (result !== 0) {
return result;
}
}
return 0;
};
}