first commit

This commit is contained in:
2026-03-10 16:18:05 +00:00
commit 11f9c069b5
31635 changed files with 3187747 additions and 0 deletions

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

@@ -0,0 +1,3 @@
# Metro Config
🚇 Config resolver and transformer for [Metro](https://metrobundler.dev/).

38
node_modules/metro-config/package.json generated vendored Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "metro-config",
"version": "0.83.3",
"description": "🚇 Config parser for Metro.",
"main": "src/index.js",
"exports": {
".": "./src/index.js",
"./package.json": "./package.json",
"./private/*": "./src/*.js"
},
"repository": {
"type": "git",
"url": "git@github.com:facebook/metro.git"
},
"scripts": {
"prepare-release": "test -d build && rm -rf src.real && mv src src.real && mv build src",
"cleanup-release": "test ! -e build && mv src build && mv src.real src"
},
"license": "MIT",
"dependencies": {
"connect": "^3.6.5",
"flow-enums-runtime": "^0.0.6",
"jest-validate": "^29.7.0",
"metro": "0.83.3",
"metro-cache": "0.83.3",
"metro-core": "0.83.3",
"metro-runtime": "0.83.3",
"yaml": "^2.6.1"
},
"devDependencies": {
"@types/connect": "^3.4.35",
"metro-babel-register": "0.83.3",
"pretty-format": "^29.7.0"
},
"engines": {
"node": ">=20.19.4"
}
}

View File

@@ -0,0 +1,5 @@
"use strict";
module.exports = (defaultConfig) => ({
projectRoot: ["array"],
});

View File

@@ -0,0 +1,18 @@
/**
* 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
*/
/*::
import type {ConfigT, InputConfigT} from '../types';
*/
module.exports = (defaultConfig /*: ConfigT */) /*:InputConfigT*/ => ({
// $FlowExpectedError[incompatible-type] testing bad config
projectRoot: ['array'],
});

View File

@@ -0,0 +1,7 @@
"use strict";
module.exports = (defaultConfig) => ({
server: {
useGlobalHotkey: "test",
},
});

View File

@@ -0,0 +1,20 @@
/**
* 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
*/
/*::
import type {ConfigT, InputConfigT} from '../types';
*/
module.exports = (defaultConfig /*: ConfigT */) /*:InputConfigT*/ => ({
server: {
// $FlowExpectedError[incompatible-type] testing bad config
useGlobalHotkey: 'test',
},
});

View File

@@ -0,0 +1,5 @@
"use strict";
module.exports = {
cacheVersion: "basic-config",
};

View File

@@ -0,0 +1,14 @@
/**
* 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
*/
module.exports = {
// Use cacheVersion as a dummy free text field to check we've read the config
cacheVersion: 'basic-config',
};

View File

@@ -0,0 +1,11 @@
"use strict";
module.exports = {
cacheStores: ({ FileStore }) => {
return [
new FileStore({
root: __dirname,
}),
];
},
};

View File

@@ -0,0 +1,19 @@
/**
* 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
*/
/*::
import type {InputConfigT} from '../types';
*/
module.exports = {
cacheStores: ({FileStore}) => {
return [new FileStore({root: __dirname})];
},
} /*:: as InputConfigT*/;

View File

@@ -0,0 +1,5 @@
"use strict";
module.exports = Promise.resolve({
cacheVersion: "cjs-promise-config",
});

View File

@@ -0,0 +1,17 @@
/**
* 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
*/
/*::
import type {InputConfigT} from '../types';
*/
module.exports = Promise.resolve({
cacheVersion: 'cjs-promise-config',
}) /*:: as Promise<InputConfigT> */;

View File

@@ -0,0 +1,12 @@
"use strict";
module.exports = (defaultConfig) => ({
cacheStores: [],
reporter: undefined,
maxWorkers: 2,
resolver: {
sourceExts: [...defaultConfig.resolver.sourceExts, "tsx"],
hasteImplModulePath: "test",
},
transformerPath: "",
});

View File

@@ -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.
*
* @flow strict-local
* @format
*/
/*::
import type {ConfigT, InputConfigT} from '../types';
*/
module.exports = (defaultConfig /*: ConfigT */) /*:InputConfigT*/ => ({
cacheStores: [],
reporter: undefined,
maxWorkers: 2,
resolver: {
sourceExts: [...defaultConfig.resolver.sourceExts, 'tsx'],
hasteImplModulePath: 'test',
},
transformerPath: '',
});

View File

@@ -0,0 +1,5 @@
"use strict";
module.exports = {
cacheVersion: "custom-path",
};

View File

@@ -0,0 +1,14 @@
/**
* 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
*/
module.exports = {
// Use cacheVersion as a dummy free text field to check we've read the config
cacheVersion: 'custom-path',
};

View File

@@ -0,0 +1,15 @@
"use strict";
const { mergeConfig } = require("../loadConfig");
const secondConfig = (previous) => ({
resolver: {
sourceExts: ["before", ...previous.resolver.sourceExts],
},
});
const thirdConfig = (previous) => ({
resolver: {
sourceExts: [...previous.resolver.sourceExts, "after"],
},
});
module.exports = (metroDefaults) =>
mergeConfig(metroDefaults, secondConfig, thirdConfig);

View File

@@ -0,0 +1,32 @@
/**
* 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
*/
/*::
import type {ConfigT, InputConfigT} from '../types';
type ConfigFn = (previous: ConfigT) => InputConfigT
*/
const {mergeConfig} = require('../loadConfig');
const secondConfig /*:ConfigFn */ = previous => ({
resolver: {
sourceExts: ['before', ...previous.resolver.sourceExts],
},
});
const thirdConfig /*:ConfigFn */ = previous => ({
resolver: {
sourceExts: [...previous.resolver.sourceExts, 'after'],
},
});
module.exports = (metroDefaults /*:ConfigT*/): ConfigT =>
mergeConfig(metroDefaults, secondConfig, thirdConfig);

View File

@@ -0,0 +1,5 @@
"use strict";
module.exports = {
cacheVersion: "default-config",
};

View File

@@ -0,0 +1,14 @@
/**
* 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
*/
module.exports = {
// Use cacheVersion as a dummy free text field to check we've read the config
cacheVersion: 'default-config',
};

View File

@@ -0,0 +1,2 @@
# Use cacheVersion as a dummy free text field to check we've read the config
cacheVersion: yaml-extensionless

View File

@@ -0,0 +1,35 @@
"use strict";
var _loadConfig = require("../loadConfig");
config;
({});
({
resolver: {},
transformer: {},
serializer: {},
server: {},
symbolicator: {},
});
isMutableArray(config.cacheStores);
if (
inputConfig.cacheStores != null &&
typeof inputConfig.cacheStores !== "function"
) {
isMutableArray(inputConfig.cacheStores);
}
config.resolver.unstable_conditionsByPlatform["foo"];
config.transformer.assetPlugins[0];
(0, _loadConfig.mergeConfig)(config, {});
(0, _loadConfig.mergeConfig)(inputConfig, {});
(0, _loadConfig.mergeConfig)(
config,
() => ({}),
{},
() => ({}),
);
(0, _loadConfig.mergeConfig)(
config,
() => ({}),
{},
async () => ({}),
).catch(() => {});

View File

@@ -0,0 +1,69 @@
/**
* 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, InputConfigT} from 'metro-config';
import {mergeConfig} from '../loadConfig';
declare var config: ConfigT;
declare var inputConfig: InputConfigT;
declare function isMutableArray<T: $ReadOnlyArray<mixed>>(
arr: T,
): T extends Array<mixed> ? true : false;
// Ensure ConfigT satisfies InputConfigT
(config: InputConfigT);
// Ensure empty config satisfies InputConfigT
({}: InputConfigT);
// And it may be partial
({
resolver: {},
transformer: {},
serializer: {},
server: {},
symbolicator: {},
}: InputConfigT);
// Both are deep read-only
(isMutableArray(config.cacheStores): false);
if (
inputConfig.cacheStores != null &&
typeof inputConfig.cacheStores !== 'function'
) {
(isMutableArray(inputConfig.cacheStores): false);
}
// ConfigT is completely hydrated (no errors accessing deep props)
config.resolver.unstable_conditionsByPlatform['foo'];
config.transformer.assetPlugins[0];
// A mergeConfig returns a full config only if the base is a full config
mergeConfig(config, {}) as ConfigT;
// $FlowExpectedError[incompatible-type]
mergeConfig(inputConfig, {}) as ConfigT;
// And is synchronous with any number of sync arguments
mergeConfig(
config,
() => ({}),
{},
() => ({}),
) as ConfigT;
// But async if any function returns a promise
mergeConfig(
config,
() => ({}),
{},
async () => ({}),
).catch(() => {});

View File

@@ -0,0 +1,12 @@
/**
* 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
*/
declare function createModuleIdFactory(): (path: string) => number;
export default createModuleIdFactory;

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = createModuleIdFactory;
function createModuleIdFactory() {
const fileToIdMap = new Map();
let nextId = 0;
return (path) => {
let id = fileToIdMap.get(path);
if (typeof id !== "number") {
id = nextId++;
fileToIdMap.set(path, id);
}
return id;
};
}

View File

@@ -0,0 +1,23 @@
/**
* 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
*/
export default function createModuleIdFactory(): (path: string) => number {
const fileToIdMap: Map<string, number> = new Map();
let nextId = 0;
return (path: string) => {
let id = fileToIdMap.get(path);
if (typeof id !== 'number') {
id = nextId++;
fileToIdMap.set(path, id);
}
return id;
};
}

30
node_modules/metro-config/src/defaults/defaults.d.ts generated vendored Normal file
View File

@@ -0,0 +1,30 @@
/**
* 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 {RootPerfLogger} from '../types';
export {default as defaultCreateModuleIdFactory} from './createModuleIdFactory';
export declare const assetExts: Array<string>;
export declare type assetExts = typeof assetExts;
export declare const assetResolutions: Array<string>;
export declare type assetResolutions = typeof assetResolutions;
export declare const sourceExts: Array<string>;
export declare type sourceExts = typeof sourceExts;
export declare const additionalExts: Array<string>;
export declare type additionalExts = typeof additionalExts;
export declare const moduleSystem: string;
export declare type moduleSystem = typeof moduleSystem;
export declare const platforms: Array<string>;
export declare type platforms = typeof platforms;
export declare const DEFAULT_METRO_MINIFIER_PATH: 'metro-minify-terser';
export declare type DEFAULT_METRO_MINIFIER_PATH =
typeof DEFAULT_METRO_MINIFIER_PATH;
export declare const noopPerfLoggerFactory: () => RootPerfLogger;
export declare type noopPerfLoggerFactory = typeof noopPerfLoggerFactory;

85
node_modules/metro-config/src/defaults/defaults.js generated vendored Normal file
View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.assetResolutions =
exports.assetExts =
exports.additionalExts =
exports.DEFAULT_METRO_MINIFIER_PATH =
void 0;
Object.defineProperty(exports, "defaultCreateModuleIdFactory", {
enumerable: true,
get: function () {
return _createModuleIdFactory.default;
},
});
exports.sourceExts =
exports.platforms =
exports.noopPerfLoggerFactory =
exports.moduleSystem =
void 0;
var _createModuleIdFactory = _interopRequireDefault(
require("./createModuleIdFactory"),
);
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
const assetExts = (exports.assetExts = [
"bmp",
"gif",
"jpg",
"jpeg",
"png",
"psd",
"svg",
"webp",
"xml",
"m4v",
"mov",
"mp4",
"mpeg",
"mpg",
"webm",
"aac",
"aiff",
"caf",
"m4a",
"mp3",
"wav",
"html",
"pdf",
"yaml",
"yml",
"otf",
"ttf",
"zip",
]);
const assetResolutions = (exports.assetResolutions = [
"1",
"1.5",
"2",
"3",
"4",
]);
const sourceExts = (exports.sourceExts = ["js", "jsx", "json", "ts", "tsx"]);
const additionalExts = (exports.additionalExts = ["cjs", "mjs"]);
const moduleSystem = (exports.moduleSystem = require.resolve(
"metro-runtime/src/polyfills/require.js",
));
const platforms = (exports.platforms = ["ios", "android", "windows", "web"]);
const DEFAULT_METRO_MINIFIER_PATH = (exports.DEFAULT_METRO_MINIFIER_PATH =
"metro-minify-terser");
const noopPerfLoggerFactory = () => {
class Logger {
start() {}
end() {}
annotate() {}
point() {}
subSpan() {
return this;
}
}
return new Logger();
};
exports.noopPerfLoggerFactory = noopPerfLoggerFactory;

View File

@@ -0,0 +1,78 @@
/**
* 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 {PerfLogger, RootPerfLogger} from '../types';
export {default as defaultCreateModuleIdFactory} from './createModuleIdFactory';
export const assetExts: Array<string> = [
// Image formats
'bmp',
'gif',
'jpg',
'jpeg',
'png',
'psd',
'svg',
'webp',
'xml',
// Video formats
'm4v',
'mov',
'mp4',
'mpeg',
'mpg',
'webm',
// Audio formats
'aac',
'aiff',
'caf',
'm4a',
'mp3',
'wav',
// Document formats
'html',
'pdf',
'yaml',
'yml',
// Font formats
'otf',
'ttf',
// Archives (virtual files)
'zip',
];
export const assetResolutions: Array<string> = ['1', '1.5', '2', '3', '4'];
export const sourceExts: Array<string> = ['js', 'jsx', 'json', 'ts', 'tsx'];
export const additionalExts: Array<string> = ['cjs', 'mjs'];
export const moduleSystem = (require.resolve(
'metro-runtime/src/polyfills/require.js',
): string);
export const platforms: Array<string> = ['ios', 'android', 'windows', 'web'];
export const DEFAULT_METRO_MINIFIER_PATH = 'metro-minify-terser';
export const noopPerfLoggerFactory = (): RootPerfLogger => {
class Logger {
start() {}
end() {}
annotate() {}
point() {}
subSpan(): PerfLogger {
return this;
}
}
return new Logger();
};

View File

@@ -0,0 +1,14 @@
/**
* 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
*/
declare function exclusionList(
additionalExclusions?: ReadonlyArray<RegExp | string>,
): RegExp;
export default exclusionList;

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = exclusionList;
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
const list = [/\/__tests__\/.*/];
function escapeRegExp(pattern) {
if (pattern instanceof RegExp) {
return pattern.source.replace(/\/|\\\//g, "\\" + _path.default.sep);
} else if (typeof pattern === "string") {
const escaped = pattern.replace(
/[\-\[\]\{\}\(\)\*\+\?\.\\\^\$\|]/g,
"\\$&",
);
return escaped.replaceAll("/", "\\" + _path.default.sep);
} else {
throw new Error(
`Expected exclusionList to be called with RegExp or string, got: ${typeof pattern}`,
);
}
}
function exclusionList(additionalExclusions) {
return new RegExp(
"(" +
(additionalExclusions || []).concat(list).map(escapeRegExp).join("|") +
")$",
);
}

View File

@@ -0,0 +1,51 @@
/**
* 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 path from 'path';
const list = [/\/__tests__\/.*/];
function escapeRegExp(pattern: RegExp | string) {
if (pattern instanceof RegExp) {
// the forward slash may or may not be escaped in regular expression depends
// on if it's in brackets. See this post for details
// https://github.com/nodejs/help/issues/3039. The or condition in string
// replace regexp is to cover both use cases.
// We should replace all forward slashes to proper OS specific separators.
// The separator needs to be escaped in the regular expression source string,
// hence the '\\' prefix.
return pattern.source.replace(/\/|\\\//g, '\\' + path.sep);
} else if (typeof pattern === 'string') {
// Make sure all the special characters used by regular expression are properly
// escaped. The string inputs are supposed to match as is.
const escaped = pattern.replace(
/[\-\[\]\{\}\(\)\*\+\?\.\\\^\$\|]/g,
'\\$&',
);
// convert the '/' into an escaped local file separator. The separator needs
// to be escaped in the regular expression source string, hence the '\\' prefix.
return escaped.replaceAll('/', '\\' + path.sep);
} else {
throw new Error(
`Expected exclusionList to be called with RegExp or string, got: ${typeof pattern}`,
);
}
}
export default function exclusionList(
additionalExclusions?: $ReadOnlyArray<RegExp | string>,
): RegExp {
return new RegExp(
'(' +
(additionalExclusions || []).concat(list).map(escapeRegExp).join('|') +
')$',
);
}

View File

@@ -0,0 +1,12 @@
/**
* 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
*/
declare function getMaxWorkers(workers: null | undefined | number): number;
export default getMaxWorkers;

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = getMaxWorkers;
var _os = _interopRequireDefault(require("os"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
function getMaxWorkers(workers) {
const cores = _os.default.availableParallelism();
return typeof workers === "number" && Number.isInteger(workers)
? Math.min(cores, workers > 0 ? workers : 1)
: Math.max(1, Math.ceil(cores * (0.5 + 0.5 * Math.exp(-cores * 0.07)) - 1));
}

View File

@@ -0,0 +1,20 @@
/**
* 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 os from 'os';
export default function getMaxWorkers(workers: ?number): number {
// $FlowFixMe[prop-missing] Missing Flow lib def for availableParallelism
const cores = os.availableParallelism();
return typeof workers === 'number' && Number.isInteger(workers)
? Math.min(cores, workers > 0 ? workers : 1)
: Math.max(1, Math.ceil(cores * (0.5 + 0.5 * Math.exp(-cores * 0.07)) - 1));
}

19
node_modules/metro-config/src/defaults/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
/**
* 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 {ConfigT} from '../types';
declare const $$EXPORT_DEFAULT_DECLARATION$$: {
(rootPath?: string): Promise<ConfigT>;
getDefaultValues: (rootPath?: string) => ConfigT;
};
declare type $$EXPORT_DEFAULT_DECLARATION$$ =
typeof $$EXPORT_DEFAULT_DECLARATION$$;
export default $$EXPORT_DEFAULT_DECLARATION$$;

185
node_modules/metro-config/src/defaults/index.js generated vendored Normal file
View File

@@ -0,0 +1,185 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _defaults = require("./defaults");
var _exclusionList = _interopRequireDefault(require("./exclusionList"));
var _getMaxWorkers = _interopRequireDefault(require("./getMaxWorkers"));
var _metroCache = require("metro-cache");
var _metroCore = require("metro-core");
var _TerminalReporter = _interopRequireDefault(
require("metro/private/lib/TerminalReporter"),
);
var os = _interopRequireWildcard(require("os"));
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 getDefaultValues = (projectRoot) => ({
resolver: {
assetExts: _defaults.assetExts,
assetResolutions: _defaults.assetResolutions,
platforms: _defaults.platforms,
sourceExts: _defaults.sourceExts,
blockList: (0, _exclusionList.default)(),
dependencyExtractor: undefined,
disableHierarchicalLookup: false,
emptyModulePath: require.resolve(
"metro-runtime/src/modules/empty-module.js",
),
enableGlobalPackages: false,
extraNodeModules: {},
hasteImplModulePath: undefined,
nodeModulesPaths: [],
resolveRequest: null,
resolverMainFields: ["browser", "main"],
unstable_conditionNames: [],
unstable_conditionsByPlatform: {
web: ["browser"],
},
unstable_enablePackageExports: true,
useWatchman: true,
requireCycleIgnorePatterns: [/(^|\/|\\)node_modules($|\/|\\)/],
},
serializer: {
polyfillModuleNames: [],
getRunModuleStatement: (moduleId, globalPrefix) =>
`__r(${JSON.stringify(moduleId)});`,
getPolyfills: () => [],
getModulesRunBeforeMainModule: () => [],
processModuleFilter: (module) => true,
createModuleIdFactory: _defaults.defaultCreateModuleIdFactory,
experimentalSerializerHook: () => {},
customSerializer: null,
isThirdPartyModule: (module) =>
/(?:^|[/\\])node_modules[/\\]/.test(module.path),
},
server: {
enhanceMiddleware: (middleware, _) => middleware,
forwardClientLogs: true,
port: 8081,
rewriteRequestUrl: (url) => url,
unstable_serverRoot: null,
useGlobalHotkey: true,
verifyConnections: false,
},
symbolicator: {
customizeFrame: () => {},
customizeStack: async (stack, _) => stack,
},
transformer: {
assetPlugins: [],
asyncRequireModulePath: "metro-runtime/src/modules/asyncRequire",
assetRegistryPath: "missing-asset-registry-path",
babelTransformerPath: "metro-babel-transformer",
dynamicDepsInPackages: "throwAtRuntime",
enableBabelRCLookup: true,
enableBabelRuntime: true,
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
preloadedModules: false,
ramGroups: [],
}),
globalPrefix: "",
hermesParser: false,
minifierConfig: {
mangle: {
toplevel: false,
},
output: {
ascii_only: true,
quote_style: 3,
wrap_iife: true,
},
sourceMap: {
includeSources: false,
},
toplevel: false,
compress: {
reduce_funcs: false,
},
},
minifierPath: _defaults.DEFAULT_METRO_MINIFIER_PATH,
optimizationSizeLimit: 150 * 1024,
transformVariants: {
default: {},
},
publicPath: "/assets",
allowOptionalDependencies: false,
unstable_allowRequireContext: false,
unstable_dependencyMapReservedName: null,
unstable_disableModuleWrapping: false,
unstable_disableNormalizePseudoGlobals: false,
unstable_renameRequire: true,
unstable_compactOutput: false,
unstable_memoizeInlineRequires: false,
unstable_workerThreads: false,
},
watcher: {
additionalExts: _defaults.additionalExts,
healthCheck: {
enabled: false,
filePrefix: ".metro-health-check",
interval: 30000,
timeout: 5000,
},
unstable_lazySha1: true,
unstable_workerThreads: false,
unstable_autoSaveCache: {
enabled: true,
debounceMs: 5000,
},
watchman: {
deferStates: ["hg.update"],
},
},
cacheStores: [
new _metroCache.FileStore({
root: path.join(os.tmpdir(), "metro-cache"),
}),
],
cacheVersion: "1.0",
projectRoot: projectRoot || path.resolve(__dirname, "../../.."),
stickyWorkers: true,
watchFolders: [],
transformerPath: "metro-transform-worker",
maxWorkers: (0, _getMaxWorkers.default)(),
resetCache: false,
reporter: new _TerminalReporter.default(
new _metroCore.Terminal(process.stdout),
),
unstable_perfLoggerFactory: _defaults.noopPerfLoggerFactory,
});
async function getDefaultConfig(rootPath) {
return getDefaultValues(rootPath);
}
getDefaultConfig.getDefaultValues = getDefaultValues;
var _default = (exports.default = getDefaultConfig);

186
node_modules/metro-config/src/defaults/index.js.flow generated vendored Normal file
View File

@@ -0,0 +1,186 @@
/**
* 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 {ConfigT} from '../types';
import {
DEFAULT_METRO_MINIFIER_PATH,
additionalExts,
assetExts,
assetResolutions,
defaultCreateModuleIdFactory,
noopPerfLoggerFactory,
platforms,
sourceExts,
} from './defaults';
import exclusionList from './exclusionList';
import getMaxWorkers from './getMaxWorkers';
import {FileStore} from 'metro-cache';
import {Terminal} from 'metro-core';
import TerminalReporter from 'metro/private/lib/TerminalReporter';
import * as os from 'os';
import * as path from 'path';
const getDefaultValues = (projectRoot: ?string): ConfigT => ({
resolver: {
assetExts,
assetResolutions,
platforms,
sourceExts,
blockList: exclusionList(),
dependencyExtractor: undefined,
disableHierarchicalLookup: false,
emptyModulePath: require.resolve(
'metro-runtime/src/modules/empty-module.js',
),
enableGlobalPackages: false,
extraNodeModules: {},
hasteImplModulePath: undefined,
nodeModulesPaths: [],
resolveRequest: null,
resolverMainFields: ['browser', 'main'],
unstable_conditionNames: [],
unstable_conditionsByPlatform: {
web: ['browser'],
},
unstable_enablePackageExports: true,
useWatchman: true,
requireCycleIgnorePatterns: [/(^|\/|\\)node_modules($|\/|\\)/],
},
serializer: {
polyfillModuleNames: [],
getRunModuleStatement: (moduleId: number | string, globalPrefix: string) =>
`__r(${JSON.stringify(moduleId)});`,
getPolyfills: () => [],
getModulesRunBeforeMainModule: () => [],
processModuleFilter: module => true,
createModuleIdFactory: defaultCreateModuleIdFactory,
experimentalSerializerHook: () => {},
customSerializer: null,
isThirdPartyModule: module =>
/(?:^|[/\\])node_modules[/\\]/.test(module.path),
},
server: {
enhanceMiddleware: (middleware, _) => middleware,
forwardClientLogs: true,
port: 8081,
rewriteRequestUrl: url => url,
unstable_serverRoot: null,
useGlobalHotkey: true,
verifyConnections: false,
},
symbolicator: {
customizeFrame: () => {},
customizeStack: async (stack, _) => stack,
},
transformer: {
assetPlugins: [],
asyncRequireModulePath: 'metro-runtime/src/modules/asyncRequire',
assetRegistryPath: 'missing-asset-registry-path',
babelTransformerPath: 'metro-babel-transformer',
dynamicDepsInPackages: 'throwAtRuntime',
enableBabelRCLookup: true,
enableBabelRuntime: true,
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
preloadedModules: false,
ramGroups: [],
}),
globalPrefix: '',
hermesParser: false,
minifierConfig: {
mangle: {
toplevel: false,
},
output: {
ascii_only: true,
quote_style: 3,
wrap_iife: true,
},
sourceMap: {
includeSources: false,
},
toplevel: false,
compress: {
// reduce_funcs inlines single-use functions, which cause perf regressions.
reduce_funcs: false,
},
},
minifierPath: DEFAULT_METRO_MINIFIER_PATH,
optimizationSizeLimit: 150 * 1024, // 150 KiB.
transformVariants: {default: {}},
publicPath: '/assets',
allowOptionalDependencies: false,
unstable_allowRequireContext: false,
unstable_dependencyMapReservedName: null,
unstable_disableModuleWrapping: false,
unstable_disableNormalizePseudoGlobals: false,
unstable_renameRequire: true,
unstable_compactOutput: false,
unstable_memoizeInlineRequires: false,
unstable_workerThreads: false,
},
watcher: {
additionalExts,
healthCheck: {
enabled: false,
filePrefix: '.metro-health-check',
interval: 30000,
timeout: 5000,
},
unstable_lazySha1: true,
unstable_workerThreads: false,
unstable_autoSaveCache: {
enabled: true,
debounceMs: 5000,
},
watchman: {
deferStates: ['hg.update'],
},
},
cacheStores: [
new FileStore({
root: path.join(os.tmpdir(), 'metro-cache'),
}),
],
cacheVersion: '1.0',
// We assume the default project path is two levels up from
// node_modules/metro/
projectRoot: projectRoot || path.resolve(__dirname, '../../..'),
stickyWorkers: true,
watchFolders: [],
transformerPath: 'metro-transform-worker',
maxWorkers: getMaxWorkers(),
resetCache: false,
reporter: new TerminalReporter(new Terminal(process.stdout)),
unstable_perfLoggerFactory: noopPerfLoggerFactory,
});
async function getDefaultConfig(rootPath: ?string): Promise<ConfigT> {
// We can add more logic here to get a sensible default configuration, for
// now we just return a stub.
return getDefaultValues(rootPath);
}
getDefaultConfig.getDefaultValues = getDefaultValues;
export default getDefaultConfig as interface {
(rootPath?: string): Promise<ConfigT>,
getDefaultValues: (rootPath?: string) => ConfigT,
};

View File

@@ -0,0 +1,14 @@
/**
* 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 {InputConfigT} from '../types';
declare function validConfig(): Promise<InputConfigT>;
export default validConfig;

36
node_modules/metro-config/src/defaults/validConfig.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = validConfig;
async function validConfig() {
const defaultConfig = await require("./index").default("/path/to/project");
const validConfig = {
...defaultConfig,
resolver: {
...defaultConfig.resolver,
resolveRequest: function CustomResolver() {
throw new Error("Not implemented");
},
hasteImplModulePath: "./path",
},
server: {
...defaultConfig.server,
unstable_serverRoot: "",
},
transformer: {
...defaultConfig.transformer,
getTransformOptions: function getTransformOptions() {
throw new Error("Not implemented");
},
},
serializer: {
...defaultConfig.serializer,
customSerializer: function customSerializer() {
throw new Error("Not implemented");
},
},
};
return validConfig;
}

View File

@@ -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
* @format
* @oncall react_native
*/
import type {InputConfigT} from '../types';
export default async function validConfig(): Promise<InputConfigT> {
const defaultConfig = await require('./index').default('/path/to/project');
const validConfig = {
...defaultConfig,
resolver: {
...defaultConfig.resolver,
resolveRequest: function CustomResolver() {
throw new Error('Not implemented');
},
hasteImplModulePath: './path',
},
server: {
...defaultConfig.server,
unstable_serverRoot: '',
},
transformer: {
...defaultConfig.transformer,
getTransformOptions: function getTransformOptions() {
throw new Error('Not implemented');
},
},
serializer: {
...defaultConfig.serializer,
customSerializer: function customSerializer() {
throw new Error('Not implemented');
},
},
};
return validConfig;
}

30
node_modules/metro-config/src/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,30 @@
/**
* 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
*/
export type * from './types';
import getDefaultConfig from './defaults';
import {loadConfig, mergeConfig, resolveConfig} from './loadConfig';
export {getDefaultConfig, loadConfig, mergeConfig, resolveConfig};
/**
* Backwards-compatibility with CommonJS consumers using interopRequireDefault.
* Do not add to this list.
*
* @deprecated Default import from 'metro-config' is deprecated, use named exports.
*/
declare const $$EXPORT_DEFAULT_DECLARATION$$: {
getDefaultConfig: typeof getDefaultConfig;
loadConfig: typeof loadConfig;
mergeConfig: typeof mergeConfig;
resolveConfig: typeof resolveConfig;
};
declare type $$EXPORT_DEFAULT_DECLARATION$$ =
typeof $$EXPORT_DEFAULT_DECLARATION$$;
export default $$EXPORT_DEFAULT_DECLARATION$$;

41
node_modules/metro-config/src/index.flow.js generated vendored Normal file
View File

@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
Object.defineProperty(exports, "getDefaultConfig", {
enumerable: true,
get: function () {
return _defaults.default;
},
});
Object.defineProperty(exports, "loadConfig", {
enumerable: true,
get: function () {
return _loadConfig.loadConfig;
},
});
Object.defineProperty(exports, "mergeConfig", {
enumerable: true,
get: function () {
return _loadConfig.mergeConfig;
},
});
Object.defineProperty(exports, "resolveConfig", {
enumerable: true,
get: function () {
return _loadConfig.resolveConfig;
},
});
var _defaults = _interopRequireDefault(require("./defaults"));
var _loadConfig = require("./loadConfig");
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
var _default = (exports.default = {
getDefaultConfig: _defaults.default,
loadConfig: _loadConfig.loadConfig,
mergeConfig: _loadConfig.mergeConfig,
resolveConfig: _loadConfig.resolveConfig,
});

25
node_modules/metro-config/src/index.flow.js.flow generated vendored Normal file
View File

@@ -0,0 +1,25 @@
/**
* 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
*/
export type * from './types';
import getDefaultConfig from './defaults';
import {loadConfig, mergeConfig, resolveConfig} from './loadConfig';
export {getDefaultConfig, loadConfig, mergeConfig, resolveConfig};
/**
* Backwards-compatibility with CommonJS consumers using interopRequireDefault.
* Do not add to this list.
*
* @deprecated Default import from 'metro-config' is deprecated, use named exports.
*/
export default {getDefaultConfig, loadConfig, mergeConfig, resolveConfig};

6
node_modules/metro-config/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
try {
require("metro-babel-register").unstable_registerForMetroMonorepo();
} catch {}
module.exports = require("./index.flow");

24
node_modules/metro-config/src/index.js.flow generated vendored Normal file
View File

@@ -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.
*
* @flow strict-local
* @format
* @oncall react_native
*/
/* eslint-disable import/no-commonjs */
'use strict';
/*::
export type * from './index.flow';
*/
try {
require('metro-babel-register').unstable_registerForMetroMonorepo();
} catch {}
module.exports = require('./index.flow');

61
node_modules/metro-config/src/loadConfig.d.ts generated vendored Normal file
View File

@@ -0,0 +1,61 @@
/**
* 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 {ConfigT, InputConfigT, YargArguments} from './types';
type ResolveConfigResult = {
filepath: string;
isEmpty: boolean;
config:
| ((baseConfig: ConfigT) => Promise<ConfigT>)
| ((baseConfig: ConfigT) => ConfigT)
| InputConfigT;
};
declare function resolveConfig(
filePath?: string,
cwd?: string,
): Promise<ResolveConfigResult>;
/**
* Merge two or more partial config objects (or functions returning partial
* configs) together, with arguments to the right overriding the left.
*
* Functions will be parsed the current config (the merge of all configs to the
* left).
*
* Functions may be async, in which case this function will return a promise.
* Otherwise it will return synchronously.
*/
declare function mergeConfig<
T extends InputConfigT,
R extends ReadonlyArray<
| InputConfigT
| ((baseConfig: T) => InputConfigT)
| ((baseConfig: T) => Promise<InputConfigT>)
>,
>(
base: T | (() => T),
...configs: R
): R extends ReadonlyArray<InputConfigT | ((baseConfig: T) => InputConfigT)>
? T
: Promise<T>;
/**
* Load the metro configuration from disk
* @param {object} argv Arguments coming from the CLI, can be empty
* @param {object} defaultConfigOverrides A configuration that can override the default config
* @return {object} Configuration returned
*/
declare function loadConfig(
argvInput?: YargArguments,
defaultConfigOverrides?: InputConfigT,
): Promise<ConfigT>;
export declare function loadConfigFile(
absolutePath: string,
): Promise<ResolveConfigResult>;
export {loadConfig, resolveConfig, mergeConfig};

347
node_modules/metro-config/src/loadConfig.js generated vendored Normal file
View File

@@ -0,0 +1,347 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.loadConfig = loadConfig;
exports.loadConfigFile = loadConfigFile;
exports.mergeConfig = mergeConfig;
exports.resolveConfig = resolveConfig;
var _defaults = _interopRequireDefault(require("./defaults"));
var _validConfig = _interopRequireDefault(require("./defaults/validConfig"));
var fs = _interopRequireWildcard(require("fs"));
var _jestValidate = require("jest-validate");
var MetroCache = _interopRequireWildcard(require("metro-cache"));
var _os = require("os");
var path = _interopRequireWildcard(require("path"));
var _yaml = require("yaml");
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 overrideArgument(arg) {
if (arg == null) {
return arg;
}
if (Array.isArray(arg)) {
return arg[arg.length - 1];
}
return arg;
}
const SEARCH_JS_EXTS = [".js", ".cjs", ".mjs", ".json"];
const SEARCH_TS_EXTS = [".ts", ".cts", ".mts"];
const SEARCH_PLACES = [
...["metro.config", path.join(".config", "metro")].flatMap((prefix) =>
[...SEARCH_JS_EXTS, ...SEARCH_TS_EXTS].map((ext) => prefix + ext),
),
"package.json",
];
const JS_EXTENSIONS = new Set([...SEARCH_JS_EXTS, ".es6"]);
const TS_EXTENSIONS = new Set(SEARCH_TS_EXTS);
const YAML_EXTENSIONS = new Set([".yml", ".yaml", ""]);
const PACKAGE_JSON = path.sep + "package.json";
const PACKAGE_JSON_PROP_NAME = "metro";
const isFile = (filePath) =>
fs.existsSync(filePath) && !fs.lstatSync(filePath).isDirectory();
const resolve = (filePath) => {
try {
return require.resolve(filePath);
} catch (error) {
if (path.isAbsolute(filePath) || error.code !== "MODULE_NOT_FOUND") {
throw error;
}
}
const possiblePath = path.resolve(process.cwd(), filePath);
return isFile(possiblePath) ? possiblePath : filePath;
};
async function resolveConfig(filePath, cwd) {
const configPath =
filePath != null
? resolve(filePath)
: searchForConfigFile(
path.resolve(process.cwd(), cwd ?? ""),
(0, _os.homedir)(),
);
if (configPath == null) {
return {
isEmpty: true,
filepath: path.join(cwd || process.cwd(), "metro.config.stub.js"),
config: {},
};
}
return await loadConfigFile(configPath);
}
function mergeConfigObjects(base, overrides) {
return {
...base,
...overrides,
...(overrides.cacheStores != null
? {
cacheStores:
typeof overrides.cacheStores === "function"
? overrides.cacheStores(MetroCache)
: overrides.cacheStores,
}
: null),
resolver: {
...base.resolver,
...overrides.resolver,
...(overrides.resolver?.dependencyExtractor != null
? {
dependencyExtractor: resolve(
overrides.resolver.dependencyExtractor,
),
}
: null),
...(overrides.resolver?.hasteImplModulePath != null
? {
hasteImplModulePath: resolve(
overrides.resolver.hasteImplModulePath,
),
}
: null),
},
serializer: {
...base.serializer,
...overrides.serializer,
},
transformer: {
...base.transformer,
...overrides.transformer,
...(overrides.transformer?.babelTransformerPath != null
? {
babelTransformerPath: resolve(
overrides.transformer.babelTransformerPath,
),
}
: null),
},
server: {
...base.server,
...overrides.server,
},
symbolicator: {
...base.symbolicator,
...overrides.symbolicator,
},
watcher: {
...base.watcher,
...overrides.watcher,
watchman: {
...base.watcher?.watchman,
...overrides.watcher?.watchman,
},
healthCheck: {
...base.watcher?.healthCheck,
...overrides.watcher?.healthCheck,
},
unstable_autoSaveCache: {
...base.watcher?.unstable_autoSaveCache,
...overrides.watcher?.unstable_autoSaveCache,
},
},
};
}
async function mergeConfigAsync(baseConfig, ...reversedConfigs) {
let currentConfig = await baseConfig;
for (const next of reversedConfigs) {
const nextConfig = await (typeof next === "function"
? next(currentConfig)
: next);
currentConfig = mergeConfigObjects(currentConfig, nextConfig);
}
return currentConfig;
}
function mergeConfig(base, ...configs) {
let currentConfig = typeof base === "function" ? base() : base;
const reversedConfigs = configs.toReversed();
let next;
while ((next = reversedConfigs.pop())) {
const nextConfig = typeof next === "function" ? next(currentConfig) : next;
if (nextConfig instanceof Promise) {
return mergeConfigAsync(nextConfig, reversedConfigs.toReversed());
}
currentConfig = mergeConfigObjects(currentConfig, nextConfig);
}
return currentConfig;
}
async function loadMetroConfigFromDisk(
pathToLoad,
cwd,
defaultConfigOverrides,
) {
const resolvedConfigResults = await resolveConfig(pathToLoad, cwd);
const { config: configModule, filepath } = resolvedConfigResults;
let rootPath = path.dirname(filepath);
if (path.basename(rootPath) === ".config") {
rootPath = path.dirname(rootPath);
}
const defaults = await (0, _defaults.default)(rootPath);
const defaultConfig = mergeConfig(defaults, defaultConfigOverrides);
if (typeof configModule === "function") {
const resultedConfig = await configModule(defaultConfig);
return mergeConfig(defaultConfig, resultedConfig);
}
return mergeConfig(defaultConfig, configModule);
}
function overrideConfigWithArguments(config, argv) {
const output = {
resolver: {},
serializer: {},
server: {},
transformer: {},
};
if (argv.port != null) {
output.server.port = Number(argv.port);
}
if (argv.projectRoot != null) {
output.projectRoot = argv.projectRoot;
}
if (argv.watchFolders != null) {
output.watchFolders = argv.watchFolders;
}
if (argv.assetExts != null) {
output.resolver.assetExts = argv.assetExts;
}
if (argv.sourceExts != null) {
output.resolver.sourceExts = argv.sourceExts;
}
if (argv.platforms != null) {
output.resolver.platforms = argv.platforms;
}
if (argv["max-workers"] != null || argv.maxWorkers != null) {
output.maxWorkers = Number(argv["max-workers"] || argv.maxWorkers);
}
if (argv.transformer != null) {
output.transformer.babelTransformerPath = argv.transformer;
}
if (argv["reset-cache"] != null) {
output.resetCache = argv["reset-cache"];
}
if (argv.resetCache != null) {
output.resetCache = argv.resetCache;
}
if (argv.verbose === false) {
output.reporter = {
update: () => {},
};
}
return mergeConfig(config, output);
}
async function loadConfig(argvInput = {}, defaultConfigOverrides = {}) {
const argv = {
...argvInput,
config: overrideArgument(argvInput.config),
};
const configuration = await loadMetroConfigFromDisk(
argv.config,
argv.cwd,
defaultConfigOverrides,
);
(0, _jestValidate.validate)(configuration, {
exampleConfig: await (0, _validConfig.default)(),
recursiveDenylist: ["reporter", "resolver", "transformer"],
deprecatedConfig: {
blacklistRE:
() => `Warning: Metro config option \`blacklistRE\` is deprecated.
Please use \`blockList\` instead.`,
},
});
const configWithArgs = overrideConfigWithArguments(configuration, argv);
return mergeConfig(configWithArgs, {
watchFolders: [configWithArgs.projectRoot, ...configWithArgs.watchFolders],
});
}
async function loadConfigFile(absolutePath) {
let config;
const extension = path.extname(absolutePath);
if (JS_EXTENSIONS.has(extension) || TS_EXTENSIONS.has(extension)) {
try {
const configModule = require(absolutePath);
if (absolutePath.endsWith(PACKAGE_JSON)) {
config = configModule[PACKAGE_JSON_PROP_NAME];
} else {
config = await (configModule.__esModule
? configModule.default
: configModule);
}
} catch (e) {
try {
const configModule = await import(absolutePath);
config = await configModule.default;
} catch (error) {
let prefix = `Error loading Metro config at: ${absolutePath}\n`;
if (
error.code === "ERR_UNKNOWN_FILE_EXTENSION" &&
TS_EXTENSIONS.has(extension)
) {
prefix +=
"Ensure your Node.js version supports loading TypeScript. (>=24.0.0 or >=22.6.0 with --experimental-strip-types).\n";
}
error.stack;
error.message = prefix + error.message;
throw error;
}
}
} else if (YAML_EXTENSIONS.has(extension)) {
console.warn(
"YAML config is deprecated, please migrate to JavaScript config (e.g. metro.config.js)",
);
config = (0, _yaml.parse)(fs.readFileSync(absolutePath, "utf8"));
} else {
throw new Error(
`Unsupported config file extension: ${extension}. ` +
`Supported extensions are ${[...JS_EXTENSIONS, ...TS_EXTENSIONS, ...YAML_EXTENSIONS].map((ext) => (ext === "" ? "none" : `${ext}`)).join()})}.`,
);
}
return {
isEmpty: false,
filepath: absolutePath,
config,
};
}
function searchForConfigFile(absoluteStartDir, absoluteStopDir) {
for (
let currentDir = absoluteStartDir, prevDir;
prevDir !== currentDir && prevDir !== absoluteStopDir;
currentDir = path.dirname(prevDir)
) {
for (const candidate of SEARCH_PLACES) {
const candidatePath = path.join(currentDir, candidate);
if (isFile(candidatePath)) {
if (candidatePath.endsWith(path.sep + "package.json")) {
const content = require(candidatePath);
if (Object.hasOwn(content, PACKAGE_JSON_PROP_NAME)) {
return candidatePath;
}
} else {
return candidatePath;
}
}
}
prevDir = currentDir;
}
return null;
}

473
node_modules/metro-config/src/loadConfig.js.flow generated vendored Normal file
View File

@@ -0,0 +1,473 @@
/**
* 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 {ConfigT, InputConfigT, YargArguments} from './types';
import getDefaultConfig from './defaults';
import validConfig from './defaults/validConfig';
import * as fs from 'fs';
import {validate} from 'jest-validate';
import * as MetroCache from 'metro-cache';
import {homedir} from 'os';
import * as path from 'path';
import {parse as parseYaml} from 'yaml';
type ResolveConfigResult = {
filepath: string,
isEmpty: boolean,
config:
| ((baseConfig: ConfigT) => Promise<ConfigT>)
| ((baseConfig: ConfigT) => ConfigT)
| InputConfigT,
...
};
/**
* Takes the last argument if multiple of the same argument are given
*/
function overrideArgument<T>(arg: Array<T> | T): T {
if (arg == null) {
return arg;
}
if (Array.isArray(arg)) {
// $FlowFixMe[incompatible-type]
return arg[arg.length - 1];
}
return arg;
}
const SEARCH_JS_EXTS = ['.js', '.cjs', '.mjs', '.json'];
const SEARCH_TS_EXTS = ['.ts', '.cts', '.mts'];
const SEARCH_PLACES = [
...['metro.config', path.join('.config', 'metro')].flatMap(prefix =>
[...SEARCH_JS_EXTS, ...SEARCH_TS_EXTS].map(ext => prefix + ext),
),
'package.json',
];
const JS_EXTENSIONS = new Set([
...SEARCH_JS_EXTS,
'.es6', // Deprecated
]);
const TS_EXTENSIONS = new Set(SEARCH_TS_EXTS);
const YAML_EXTENSIONS = new Set(['.yml', '.yaml', '']); // Deprecated
const PACKAGE_JSON = path.sep + 'package.json';
const PACKAGE_JSON_PROP_NAME = 'metro';
const isFile = (filePath: string) =>
fs.existsSync(filePath) && !fs.lstatSync(filePath).isDirectory();
const resolve = (filePath: string) => {
// Attempt to resolve the path with the node resolution algorithm but fall back to resolving
// the file relative to the current working directory if the input is not an absolute path.
try {
return require.resolve(filePath);
} catch (error) {
if (path.isAbsolute(filePath) || error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
}
const possiblePath = path.resolve(process.cwd(), filePath);
return isFile(possiblePath) ? possiblePath : filePath;
};
async function resolveConfig(
filePath?: string,
cwd?: string,
): Promise<ResolveConfigResult> {
const configPath: ?string =
filePath != null
? resolve(filePath)
: searchForConfigFile(path.resolve(process.cwd(), cwd ?? ''), homedir());
if (configPath == null) {
// No config file found, return a default
return {
isEmpty: true,
filepath: path.join(cwd || process.cwd(), 'metro.config.stub.js'),
config: {},
};
}
return await loadConfigFile(configPath);
}
function mergeConfigObjects<T: InputConfigT>(
base: T,
overrides: InputConfigT,
): T {
return {
...base,
...overrides,
...(overrides.cacheStores != null
? {
cacheStores:
typeof overrides.cacheStores === 'function'
? overrides.cacheStores(MetroCache)
: overrides.cacheStores,
}
: null),
resolver: {
...base.resolver,
...overrides.resolver,
// $FlowFixMe[exponential-spread]
...(overrides.resolver?.dependencyExtractor != null
? {dependencyExtractor: resolve(overrides.resolver.dependencyExtractor)}
: null),
...(overrides.resolver?.hasteImplModulePath != null
? {hasteImplModulePath: resolve(overrides.resolver.hasteImplModulePath)}
: null),
},
serializer: {
...base.serializer,
// $FlowFixMe[exponential-spread]
...overrides.serializer,
},
transformer: {
...base.transformer,
// $FlowFixMe[exponential-spread]
...overrides.transformer,
// $FlowFixMe[exponential-spread]
...(overrides.transformer?.babelTransformerPath != null
? {
babelTransformerPath: resolve(
overrides.transformer.babelTransformerPath,
),
}
: null),
},
server: {
...base.server,
// $FlowFixMe[exponential-spread]
...overrides.server,
},
symbolicator: {
...base.symbolicator,
// $FlowFixMe[exponential-spread]
...overrides.symbolicator,
},
watcher: {
...base.watcher,
// $FlowFixMe[exponential-spread]
...overrides.watcher,
watchman: {
// $FlowFixMe[exponential-spread]
...base.watcher?.watchman,
...overrides.watcher?.watchman,
},
healthCheck: {
// $FlowFixMe[exponential-spread]
...base.watcher?.healthCheck,
...overrides.watcher?.healthCheck,
},
unstable_autoSaveCache: {
// $FlowFixMe[exponential-spread]
...base.watcher?.unstable_autoSaveCache,
...overrides.watcher?.unstable_autoSaveCache,
},
},
};
}
async function mergeConfigAsync<T: InputConfigT>(
baseConfig: Promise<T>,
...reversedConfigs: $ReadOnlyArray<
InputConfigT | (T => InputConfigT) | (T => Promise<InputConfigT>),
>
): Promise<T> {
let currentConfig: T = await baseConfig;
for (const next of reversedConfigs) {
const nextConfig: InputConfigT = await (typeof next === 'function'
? next(currentConfig)
: next);
currentConfig = mergeConfigObjects(currentConfig, nextConfig);
}
return currentConfig;
}
/**
* Merge two or more partial config objects (or functions returning partial
* configs) together, with arguments to the right overriding the left.
*
* Functions will be parsed the current config (the merge of all configs to the
* left).
*
* Functions may be async, in which case this function will return a promise.
* Otherwise it will return synchronously.
*/
function mergeConfig<
T: InputConfigT,
R: $ReadOnlyArray<
| InputConfigT
| ((baseConfig: T) => InputConfigT)
| ((baseConfig: T) => Promise<InputConfigT>),
>,
>(
base: T | (() => T),
...configs: R
): R extends $ReadOnlyArray<InputConfigT | ((baseConfig: T) => InputConfigT)>
? T
: Promise<T> {
let currentConfig: T = typeof base === 'function' ? base() : base;
// Reverse for easy popping
const reversedConfigs = configs.toReversed();
let next;
while ((next = reversedConfigs.pop())) {
const nextConfig: InputConfigT | Promise<InputConfigT> =
typeof next === 'function' ? next(currentConfig) : next;
if (nextConfig instanceof Promise) {
// $FlowFixMe[incompatible-type] Not clear why Flow doesn't like this
return mergeConfigAsync(nextConfig, reversedConfigs.toReversed());
}
currentConfig = mergeConfigObjects(currentConfig, nextConfig) as T;
}
// $FlowFixMe[incompatible-type] Not clear why Flow doesn't like this
return currentConfig;
}
async function loadMetroConfigFromDisk(
pathToLoad?: string,
cwd?: string,
defaultConfigOverrides: InputConfigT,
): Promise<ConfigT> {
const resolvedConfigResults: ResolveConfigResult = await resolveConfig(
pathToLoad,
cwd,
);
const {config: configModule, filepath} = resolvedConfigResults;
let rootPath = path.dirname(filepath);
// Special case .config directories, which are assumed to be a child of the
// project root.
if (path.basename(rootPath) === '.config') {
rootPath = path.dirname(rootPath);
}
const defaults = await getDefaultConfig(rootPath);
const defaultConfig: ConfigT = mergeConfig(defaults, defaultConfigOverrides);
if (typeof configModule === 'function') {
// Get a default configuration based on what we know, which we in turn can pass
// to the function.
const resultedConfig = await configModule(defaultConfig);
return mergeConfig(defaultConfig, resultedConfig);
}
return mergeConfig(defaultConfig, configModule);
}
function overrideConfigWithArguments(
config: ConfigT,
argv: YargArguments,
): ConfigT {
// We override some config arguments here with the argv
const output: {
// Spread to remove invariance so that `output` is mutable.
...Partial<ConfigT>,
resolver: {...Partial<ConfigT['resolver']>},
serializer: {...Partial<ConfigT['serializer']>},
server: {...Partial<ConfigT['server']>},
transformer: {...Partial<ConfigT['transformer']>},
} = {
resolver: {},
serializer: {},
server: {},
transformer: {},
};
if (argv.port != null) {
output.server.port = Number(argv.port);
}
if (argv.projectRoot != null) {
output.projectRoot = argv.projectRoot;
}
if (argv.watchFolders != null) {
output.watchFolders = argv.watchFolders;
}
if (argv.assetExts != null) {
output.resolver.assetExts = argv.assetExts;
}
if (argv.sourceExts != null) {
output.resolver.sourceExts = argv.sourceExts;
}
if (argv.platforms != null) {
output.resolver.platforms = argv.platforms;
}
if (argv['max-workers'] != null || argv.maxWorkers != null) {
output.maxWorkers = Number(argv['max-workers'] || argv.maxWorkers);
}
if (argv.transformer != null) {
output.transformer.babelTransformerPath = argv.transformer;
}
if (argv['reset-cache'] != null) {
output.resetCache = argv['reset-cache'];
}
if (argv.resetCache != null) {
output.resetCache = argv.resetCache;
}
if (argv.verbose === false) {
output.reporter = {update: () => {}};
// TODO: Ask if this is the way to go
}
return mergeConfig(config, output);
}
/**
* Load the metro configuration from disk
* @param {object} argv Arguments coming from the CLI, can be empty
* @param {object} defaultConfigOverrides A configuration that can override the default config
* @return {object} Configuration returned
*/
async function loadConfig(
argvInput?: YargArguments = {},
defaultConfigOverrides?: InputConfigT = {},
): Promise<ConfigT> {
const argv = {...argvInput, config: overrideArgument(argvInput.config)};
const configuration = await loadMetroConfigFromDisk(
argv.config,
argv.cwd,
defaultConfigOverrides,
);
validate(configuration, {
exampleConfig: await validConfig(),
recursiveDenylist: ['reporter', 'resolver', 'transformer'],
deprecatedConfig: {
blacklistRE: () =>
`Warning: Metro config option \`blacklistRE\` is deprecated.
Please use \`blockList\` instead.`,
},
});
// Override the configuration with cli parameters
const configWithArgs = overrideConfigWithArguments(configuration, argv);
// Set the watchfolders to include the projectRoot, as Metro assumes that is
// the case
return mergeConfig(configWithArgs, {
watchFolders: [configWithArgs.projectRoot, ...configWithArgs.watchFolders],
});
}
export async function loadConfigFile(
absolutePath: string,
): Promise<ResolveConfigResult> {
// Config should be JSON, CommonJS, ESM or YAML (deprecated)
let config;
const extension = path.extname(absolutePath);
if (JS_EXTENSIONS.has(extension) || TS_EXTENSIONS.has(extension)) {
try {
// $FlowExpectedError[unsupported-syntax]
const configModule = require(absolutePath);
if (absolutePath.endsWith(PACKAGE_JSON)) {
config = configModule[PACKAGE_JSON_PROP_NAME];
} else {
config = await (configModule.__esModule
? configModule.default
: configModule);
}
} catch (e) {
try {
// $FlowExpectedError[unsupported-syntax]
const configModule = await import(absolutePath);
// The default export is a promise in the case of top-level await
config = await configModule.default;
} catch (error) {
let prefix = `Error loading Metro config at: ${absolutePath}\n`;
if (
error.code === 'ERR_UNKNOWN_FILE_EXTENSION' &&
TS_EXTENSIONS.has(extension)
) {
prefix +=
'Ensure your Node.js version supports loading TypeScript. (>=24.0.0 or >=22.6.0 with --experimental-strip-types).\n';
}
// error.stack is a getter that includes error.message. Access it now
// to cache the current value before modifying message, so that we
// don't repeat the prefix when printing message and stack later.
error.stack;
error.message = prefix + error.message;
throw error;
}
}
} else if (YAML_EXTENSIONS.has(extension)) {
console.warn(
'YAML config is deprecated, please migrate to JavaScript config (e.g. metro.config.js)',
);
config = parseYaml(fs.readFileSync(absolutePath, 'utf8'));
} else {
throw new Error(
`Unsupported config file extension: ${extension}. ` +
`Supported extensions are ${[...JS_EXTENSIONS, ...TS_EXTENSIONS, ...YAML_EXTENSIONS].map(ext => (ext === '' ? 'none' : `${ext}`)).join()})}.`,
);
}
return {
isEmpty: false,
filepath: absolutePath,
config,
};
}
function searchForConfigFile(
absoluteStartDir: string,
absoluteStopDir: string,
): ?string {
for (
let currentDir: string = absoluteStartDir, prevDir: string;
prevDir !== currentDir && prevDir !== absoluteStopDir;
currentDir = path.dirname(prevDir)
) {
for (const candidate of SEARCH_PLACES) {
const candidatePath = path.join(currentDir, candidate);
if (isFile(candidatePath)) {
if (candidatePath.endsWith(path.sep + 'package.json')) {
// package.json is a special case - we only find a config if
// the json has a top-level `metro` key.
//
// By using `require`, we'll add the json to the Node.js module
// cache, so we don't incur further parse cost after returning the
// manifest's path.
// $FlowFixMe[unsupported-syntax] dynamic require
const content = require(candidatePath);
if (Object.hasOwn(content, PACKAGE_JSON_PROP_NAME)) {
return candidatePath;
}
} else {
return candidatePath;
}
}
}
prevDir = currentDir;
}
return null;
}
export {loadConfig, resolveConfig, mergeConfig};

264
node_modules/metro-config/src/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,264 @@
/**
* 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 {HandleFunction, Server} from 'connect';
import type {CacheStore, MetroCache} from 'metro-cache';
import type {CacheManagerFactory} from 'metro-file-map';
import type {CustomResolver} from 'metro-resolver';
import type {JsTransformerConfig} from 'metro-transform-worker';
import type {
DeltaResult,
Module,
ReadOnlyGraph,
SerializerOptions,
TransformResult,
} from 'metro/private/DeltaBundler/types';
import type {Reporter} from 'metro/private/lib/reporting';
import type MetroServer from 'metro/private/Server';
import type {IntermediateStackFrame} from 'metro/private/Server/symbolicate';
export type ExtraTransformOptions = Readonly<{
preloadedModules?: Readonly<{[path: string]: true}> | false;
ramGroups?: ReadonlyArray<string>;
transform?: Readonly<{
experimentalImportSupport?: boolean;
inlineRequires?:
| Readonly<{
blockList: Readonly<{[absoluteModulePath: string]: true}>;
}>
| boolean;
nonInlinedRequires?: ReadonlyArray<string>;
unstable_memoizeInlineRequires?: boolean;
unstable_nonMemoizedInlineRequires?: ReadonlyArray<string>;
}>;
}>;
export type GetTransformOptionsOpts = {
dev: boolean;
/**
* @deprecated Always true
*/
hot: true;
platform: null | undefined | string;
};
export type GetTransformOptions = (
entryPoints: ReadonlyArray<string>,
options: GetTransformOptionsOpts,
getDependenciesOf: (absoluteFilePath: string) => Promise<Array<string>>,
) => Promise<Partial<ExtraTransformOptions>>;
export type Middleware = HandleFunction;
type PerfAnnotations = Partial<{
string: Readonly<{[key: string]: string}>;
int: Readonly<{[key: string]: number}>;
double: Readonly<{[key: string]: number}>;
bool: Readonly<{[key: string]: boolean}>;
string_array: Readonly<{[key: string]: ReadonlyArray<string>}>;
int_array: Readonly<{[key: string]: ReadonlyArray<number>}>;
double_array: Readonly<{[key: string]: ReadonlyArray<number>}>;
bool_array: Readonly<{[key: string]: ReadonlyArray<boolean>}>;
}>;
type PerfLoggerPointOptions = Readonly<{timestamp?: number}>;
export interface PerfLogger {
point(name: string, opts?: PerfLoggerPointOptions): void;
annotate(annotations: PerfAnnotations): void;
subSpan(label: string): PerfLogger;
}
export interface RootPerfLogger extends PerfLogger {
start(opts?: PerfLoggerPointOptions): void;
end(
status: 'SUCCESS' | 'FAIL' | 'CANCEL',
opts?: PerfLoggerPointOptions,
): void;
}
export type PerfLoggerFactoryOptions = Readonly<{key?: number}>;
export type PerfLoggerFactory = (
type: 'START_UP' | 'BUNDLING_REQUEST' | 'HMR',
opts?: PerfLoggerFactoryOptions,
) => RootPerfLogger;
type ResolverConfigT = {
assetExts: ReadonlyArray<string>;
assetResolutions: ReadonlyArray<string>;
blacklistRE?: RegExp | Array<RegExp>;
blockList: RegExp | Array<RegExp>;
disableHierarchicalLookup: boolean;
dependencyExtractor: null | undefined | string;
emptyModulePath: string;
enableGlobalPackages: boolean;
extraNodeModules: {[name: string]: string};
hasteImplModulePath: null | undefined | string;
nodeModulesPaths: ReadonlyArray<string>;
platforms: ReadonlyArray<string>;
resolveRequest: null | undefined | CustomResolver;
resolverMainFields: ReadonlyArray<string>;
sourceExts: ReadonlyArray<string>;
unstable_conditionNames: ReadonlyArray<string>;
unstable_conditionsByPlatform: Readonly<{
[platform: string]: ReadonlyArray<string>;
}>;
unstable_enablePackageExports: boolean;
useWatchman: boolean;
requireCycleIgnorePatterns: ReadonlyArray<RegExp>;
};
type SerializerConfigT = {
createModuleIdFactory: () => (path: string) => number;
customSerializer:
| null
| undefined
| ((
entryPoint: string,
preModules: ReadonlyArray<Module>,
graph: ReadOnlyGraph,
options: SerializerOptions,
) => Promise<string | {code: string; map: string}>);
experimentalSerializerHook: (
graph: ReadOnlyGraph,
delta: DeltaResult,
) => unknown;
getModulesRunBeforeMainModule: (entryFilePath: string) => Array<string>;
getPolyfills: ($$PARAM_0$$: {
platform: null | undefined | string;
}) => ReadonlyArray<string>;
getRunModuleStatement: (
moduleId: number | string,
globalPrefix: string,
) => string;
polyfillModuleNames: ReadonlyArray<string>;
processModuleFilter: (modules: Module) => boolean;
isThirdPartyModule: (module: Readonly<{path: string}>) => boolean;
};
type TransformerConfigT = Omit<
JsTransformerConfig,
keyof {
getTransformOptions: GetTransformOptions;
transformVariants: {
readonly [name: string]: Partial<ExtraTransformOptions>;
};
publicPath: string;
unstable_workerThreads: boolean;
}
> & {
getTransformOptions: GetTransformOptions;
transformVariants: {
readonly [name: string]: Partial<ExtraTransformOptions>;
};
publicPath: string;
unstable_workerThreads: boolean;
};
type MetalConfigT = {
cacheVersion: string;
fileMapCacheDirectory?: string;
hasteMapCacheDirectory?: string;
unstable_fileMapCacheManagerFactory?: CacheManagerFactory;
maxWorkers: number;
unstable_perfLoggerFactory?: null | undefined | PerfLoggerFactory;
projectRoot: string;
stickyWorkers: boolean;
transformerPath: string;
reporter: Reporter;
resetCache: boolean;
watchFolders: ReadonlyArray<string>;
};
type CacheStoresConfigT = ReadonlyArray<CacheStore<TransformResult>>;
type ServerConfigT = {
/** @deprecated */
enhanceMiddleware: (
$$PARAM_0$$: Middleware,
$$PARAM_1$$: MetroServer,
) => Middleware | Server;
forwardClientLogs: boolean;
port: number;
rewriteRequestUrl: ($$PARAM_0$$: string) => string;
unstable_serverRoot: null | undefined | string;
useGlobalHotkey: boolean;
verifyConnections: boolean;
};
type SymbolicatorConfigT = {
customizeFrame: ($$PARAM_0$$: {
readonly file: null | undefined | string;
readonly lineNumber: null | undefined | number;
readonly column: null | undefined | number;
readonly methodName: null | undefined | string;
}) =>
| (null | undefined | {readonly collapse?: boolean})
| Promise<null | undefined | {readonly collapse?: boolean}>;
customizeStack: (
$$PARAM_0$$: Array<IntermediateStackFrame>,
$$PARAM_1$$: unknown,
) => Array<IntermediateStackFrame> | Promise<Array<IntermediateStackFrame>>;
};
type WatcherConfigT = {
additionalExts: ReadonlyArray<string>;
healthCheck: Readonly<{
enabled: boolean;
interval: number;
timeout: number;
filePrefix: string;
}>;
unstable_autoSaveCache: Readonly<{enabled: boolean; debounceMs?: number}>;
unstable_lazySha1: boolean;
unstable_workerThreads: boolean;
watchman: Readonly<{deferStates: ReadonlyArray<string>}>;
};
export type InputConfigT = Partial<
Readonly<
MetalConfigT & {
cacheStores:
| CacheStoresConfigT
| (($$PARAM_0$$: MetroCache) => CacheStoresConfigT);
resolver: Readonly<Partial<ResolverConfigT>>;
server: Readonly<Partial<ServerConfigT>>;
serializer: Readonly<Partial<SerializerConfigT>>;
symbolicator: Readonly<Partial<SymbolicatorConfigT>>;
transformer: Readonly<Partial<TransformerConfigT>>;
watcher: Partial<
Readonly<
Omit<
WatcherConfigT,
'healthCheck' | 'unstable_autoSaveCache' | 'watchman'
> & {
healthCheck: Partial<Readonly<WatcherConfigT['healthCheck']>>;
unstable_autoSaveCache: Partial<
Readonly<WatcherConfigT['unstable_autoSaveCache']>
>;
watchman: Partial<Readonly<WatcherConfigT['watchman']>>;
}
>
>;
}
>
>;
export type MetroConfig = InputConfigT;
export type ConfigT = Readonly<
MetalConfigT & {
cacheStores: CacheStoresConfigT;
resolver: Readonly<ResolverConfigT>;
server: Readonly<ServerConfigT>;
serializer: Readonly<SerializerConfigT>;
symbolicator: Readonly<SymbolicatorConfigT>;
transformer: Readonly<TransformerConfigT>;
watcher: Readonly<WatcherConfigT>;
}
>;
export type YargArguments = Readonly<{
config?: string;
cwd?: string;
port?: string | number;
host?: string;
projectRoot?: string;
watchFolders?: Array<string>;
assetExts?: Array<string>;
sourceExts?: Array<string>;
platforms?: Array<string>;
'max-workers'?: string | number;
maxWorkers?: string | number;
transformer?: string;
'reset-cache'?: boolean;
resetCache?: boolean;
verbose?: boolean;
}>;

1
node_modules/metro-config/src/types.js generated vendored Normal file
View File

@@ -0,0 +1 @@
"use strict";

278
node_modules/metro-config/src/types.js.flow generated vendored Normal file
View File

@@ -0,0 +1,278 @@
/**
* 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 {HandleFunction, Server} from 'connect';
import type {CacheStore, MetroCache} from 'metro-cache';
import type {CacheManagerFactory} from 'metro-file-map';
import type {CustomResolver} from 'metro-resolver';
import type {JsTransformerConfig} from 'metro-transform-worker';
import type {
DeltaResult,
Module,
ReadOnlyGraph,
SerializerOptions,
TransformResult,
} from 'metro/private/DeltaBundler/types';
import type {Reporter} from 'metro/private/lib/reporting';
import type MetroServer from 'metro/private/Server';
import type {IntermediateStackFrame} from 'metro/private/Server/symbolicate';
export type ExtraTransformOptions = $ReadOnly<{
preloadedModules?: $ReadOnly<{[path: string]: true, ...}> | false,
ramGroups?: $ReadOnlyArray<string>,
transform?: $ReadOnly<{
experimentalImportSupport?: boolean,
inlineRequires?:
| $ReadOnly<{
blockList: $ReadOnly<{[absoluteModulePath: string]: true, ...}>,
...
}>
| boolean,
nonInlinedRequires?: $ReadOnlyArray<string>,
unstable_memoizeInlineRequires?: boolean,
unstable_nonMemoizedInlineRequires?: $ReadOnlyArray<string>,
}>,
...
}>;
export type GetTransformOptionsOpts = {
dev: boolean,
/**
* @deprecated Always true
*/
hot: true,
platform: ?string,
};
export type GetTransformOptions = (
entryPoints: $ReadOnlyArray<string>,
options: GetTransformOptionsOpts,
getDependenciesOf: (absoluteFilePath: string) => Promise<Array<string>>,
) => Promise<Partial<ExtraTransformOptions>>;
export type Middleware = HandleFunction;
type PerfAnnotations = Partial<{
string: $ReadOnly<{[key: string]: string}>,
int: $ReadOnly<{[key: string]: number}>,
double: $ReadOnly<{[key: string]: number}>,
bool: $ReadOnly<{[key: string]: boolean}>,
string_array: $ReadOnly<{[key: string]: $ReadOnlyArray<string>}>,
int_array: $ReadOnly<{[key: string]: $ReadOnlyArray<number>}>,
double_array: $ReadOnly<{[key: string]: $ReadOnlyArray<number>}>,
bool_array: $ReadOnly<{[key: string]: $ReadOnlyArray<boolean>}>,
}>;
type PerfLoggerPointOptions = $ReadOnly<{
// The time this event point occurred, if it differs from the time the point was logged.
timestamp?: number,
}>;
export interface PerfLogger {
point(name: string, opts?: PerfLoggerPointOptions): void;
annotate(annotations: PerfAnnotations): void;
subSpan(label: string): PerfLogger;
}
export interface RootPerfLogger extends PerfLogger {
start(opts?: PerfLoggerPointOptions): void;
end(
status: 'SUCCESS' | 'FAIL' | 'CANCEL',
opts?: PerfLoggerPointOptions,
): void;
}
export type PerfLoggerFactoryOptions = $ReadOnly<{
key?: number,
}>;
export type PerfLoggerFactory = (
type: 'START_UP' | 'BUNDLING_REQUEST' | 'HMR',
opts?: PerfLoggerFactoryOptions,
) => RootPerfLogger;
type ResolverConfigT = {
assetExts: $ReadOnlyArray<string>,
assetResolutions: $ReadOnlyArray<string>,
blacklistRE?: RegExp | Array<RegExp>,
blockList: RegExp | Array<RegExp>,
disableHierarchicalLookup: boolean,
dependencyExtractor: ?string,
emptyModulePath: string,
enableGlobalPackages: boolean,
extraNodeModules: {[name: string]: string, ...},
hasteImplModulePath: ?string,
nodeModulesPaths: $ReadOnlyArray<string>,
platforms: $ReadOnlyArray<string>,
resolveRequest: ?CustomResolver,
resolverMainFields: $ReadOnlyArray<string>,
sourceExts: $ReadOnlyArray<string>,
unstable_conditionNames: $ReadOnlyArray<string>,
unstable_conditionsByPlatform: $ReadOnly<{
[platform: string]: $ReadOnlyArray<string>,
}>,
unstable_enablePackageExports: boolean,
useWatchman: boolean,
requireCycleIgnorePatterns: $ReadOnlyArray<RegExp>,
};
type SerializerConfigT = {
createModuleIdFactory: () => (path: string) => number,
customSerializer: ?(
entryPoint: string,
preModules: $ReadOnlyArray<Module<>>,
graph: ReadOnlyGraph<>,
options: SerializerOptions,
) => Promise<string | {code: string, map: string}>,
experimentalSerializerHook: (
graph: ReadOnlyGraph<>,
delta: DeltaResult<>,
) => mixed,
getModulesRunBeforeMainModule: (entryFilePath: string) => Array<string>,
getPolyfills: ({platform: ?string, ...}) => $ReadOnlyArray<string>,
getRunModuleStatement: (
moduleId: number | string,
globalPrefix: string,
) => string,
polyfillModuleNames: $ReadOnlyArray<string>,
processModuleFilter: (modules: Module<>) => boolean,
isThirdPartyModule: (module: $ReadOnly<{path: string, ...}>) => boolean,
};
type TransformerConfigT = {
...JsTransformerConfig,
getTransformOptions: GetTransformOptions,
// TODO(moti): Remove this Meta-internal option from Metro's public config
transformVariants: {+[name: string]: Partial<ExtraTransformOptions>},
publicPath: string,
unstable_workerThreads: boolean,
};
type MetalConfigT = {
cacheVersion: string,
fileMapCacheDirectory?: string,
hasteMapCacheDirectory?: string, // Deprecated, alias of fileMapCacheDirectory
unstable_fileMapCacheManagerFactory?: CacheManagerFactory,
maxWorkers: number,
unstable_perfLoggerFactory?: ?PerfLoggerFactory,
projectRoot: string,
stickyWorkers: boolean,
transformerPath: string,
reporter: Reporter,
resetCache: boolean,
watchFolders: $ReadOnlyArray<string>,
};
type CacheStoresConfigT = $ReadOnlyArray<CacheStore<TransformResult<>>>;
type ServerConfigT = {
/** @deprecated */
enhanceMiddleware: (Middleware, MetroServer) => Middleware | Server,
forwardClientLogs: boolean,
port: number,
rewriteRequestUrl: string => string,
unstable_serverRoot: ?string,
useGlobalHotkey: boolean,
verifyConnections: boolean,
};
type SymbolicatorConfigT = {
customizeFrame: ({
+file: ?string,
+lineNumber: ?number,
+column: ?number,
+methodName: ?string,
...
}) => ?{+collapse?: boolean} | Promise<?{+collapse?: boolean}>,
customizeStack: (
Array<IntermediateStackFrame>,
mixed,
) => Array<IntermediateStackFrame> | Promise<Array<IntermediateStackFrame>>,
};
type WatcherConfigT = {
additionalExts: $ReadOnlyArray<string>,
healthCheck: $ReadOnly<{
enabled: boolean,
interval: number,
timeout: number,
filePrefix: string,
}>,
unstable_autoSaveCache: $ReadOnly<{
enabled: boolean,
debounceMs?: number,
}>,
unstable_lazySha1: boolean,
unstable_workerThreads: boolean,
watchman: $ReadOnly<{
deferStates: $ReadOnlyArray<string>,
}>,
};
export type InputConfigT = Partial<
$ReadOnly<
MetalConfigT & {
cacheStores: CacheStoresConfigT | (MetroCache => CacheStoresConfigT),
resolver: $ReadOnly<Partial<ResolverConfigT>>,
server: $ReadOnly<Partial<ServerConfigT>>,
serializer: $ReadOnly<Partial<SerializerConfigT>>,
symbolicator: $ReadOnly<Partial<SymbolicatorConfigT>>,
transformer: $ReadOnly<Partial<TransformerConfigT>>,
watcher: Partial<
$ReadOnly<
Omit<
WatcherConfigT,
'healthCheck' | 'unstable_autoSaveCache' | 'watchman',
> & {
healthCheck: Partial<$ReadOnly<WatcherConfigT['healthCheck']>>,
unstable_autoSaveCache: Partial<
$ReadOnly<WatcherConfigT['unstable_autoSaveCache']>,
>,
watchman: Partial<$ReadOnly<WatcherConfigT['watchman']>>,
},
>,
>,
},
>,
>;
export type MetroConfig = InputConfigT;
export type ConfigT = $ReadOnly<
MetalConfigT & {
cacheStores: CacheStoresConfigT,
resolver: $ReadOnly<ResolverConfigT>,
server: $ReadOnly<ServerConfigT>,
serializer: $ReadOnly<SerializerConfigT>,
symbolicator: $ReadOnly<SymbolicatorConfigT>,
transformer: $ReadOnly<TransformerConfigT>,
watcher: $ReadOnly<WatcherConfigT>,
},
>;
export type YargArguments = $ReadOnly<{
config?: string,
cwd?: string,
port?: string | number,
host?: string,
projectRoot?: string,
watchFolders?: Array<string>,
assetExts?: Array<string>,
sourceExts?: Array<string>,
platforms?: Array<string>,
'max-workers'?: string | number,
maxWorkers?: string | number,
transformer?: string,
'reset-cache'?: boolean,
resetCache?: boolean,
verbose?: boolean,
...
}>;