forked from MetaMask/metamask-mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetro.config.js
More file actions
260 lines (250 loc) · 10.2 KB
/
Copy pathmetro.config.js
File metadata and controls
260 lines (250 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/* eslint-disable import-x/no-commonjs */
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* @type {import('metro-config').MetroConfig}
*/
const { getDefaultConfig } = require('expo/metro-config');
const { mergeConfig } = require('@react-native/metro-config');
const { lockdownSerializer } = require('@lavamoat/react-native-lockdown');
// eslint-disable-next-line import-x/no-nodejs-modules
const { parseArgs } = require('node:util');
// eslint-disable-next-line import-x/no-nodejs-modules
const os = require('node:os');
const parsedArgs = parseArgs({
options: {
platform: {
type: 'string',
},
},
allowPositionals: true,
strict: false,
});
const getPolyfills = () => [
// eslint-disable-next-line import-x/no-extraneous-dependencies
...require('@react-native/js-polyfills')(),
require.resolve('reflect-metadata'),
// Expo's `expo/fetch` (used by @metamask/bridge-controller for SSE
// `getQuoteStream`) constructs a `ReadableStream` for the response
// body. Hermes does not ship `ReadableStream`, and Expo expects Metro
// to inject one as a global (see
// node_modules/expo/src/winter/runtime.native.ts L17-18:
// "// ReadableStream is injected by Metro as a global").
// The official `expo/metro-config` defaults wire this in
// automatically; because we bootstrap from `@react-native/js-polyfills`
// we have to opt in explicitly. Without this, `expo/fetch` rejects
// every request with `ReferenceError: Property 'ReadableStream'
// doesn't exist`, breaking bridge SSE quotes silently on iOS Hermes
// (and every other expo/fetch consumer).
require.resolve('expo/virtual/streams'),
];
// We should replace path for react-native-fs
// eslint-disable-next-line import-x/no-nodejs-modules
const path = require('path');
const {
wrapWithReanimatedMetroConfig,
} = require('react-native-reanimated/metro-config');
module.exports = function (baseConfig) {
const defaultConfig = mergeConfig(baseConfig, getDefaultConfig(__dirname));
const {
resolver: { assetExts, sourceExts },
} = defaultConfig;
// IS_PERFORMANCE_TEST opts out of E2E startup overhead (ReadOnlyNetworkStore,
// command polling, Sentry mock) while keeping METAMASK_ENVIRONMENT='e2e' so
// the build still works on feature branches with e2e signing/secrets.
const isPerformanceTest = process.env.IS_PERFORMANCE_TEST === 'true';
const hasTestOverrides =
!isPerformanceTest && process.env.HAS_TEST_OVERRIDES === 'true';
/**
* E2E Metro redirects under tests/module-mocking.
* Enables both: seedless-onboarding-controller + OAuthLoginHandlers mocks.
* True when HAS_TEST_OVERRIDES OR E2E_MOCK_OAUTH.
* Performance builds set E2E_MOCK_OAUTH=true to keep this mock active
* even though hasTestOverrides is false (preventing real OAuth calls to production).
*/
const isE2EMockOAuth = process.env.E2E_MOCK_OAUTH === 'true';
const e2eAllowsSeedlessOAuthMetroMocks = hasTestOverrides || isE2EMockOAuth;
// For less powerful machines, leave room to do other tasks. For instance,
// if you have 10 cores but only 16GB, only 3 workers would get used.
// Also forces maxWorkers value to be no less than 2, ensuring
// worker code runs concurrently and not on the main Metro process
//
// CI Override: Set METRO_MAX_WORKERS env var to limit workers on constrained runners
// Example: METRO_MAX_WORKERS=4 for 48GB runners to prevent OOM kills
const maxWorkers = process.env.METRO_MAX_WORKERS
? Math.max(2, parseInt(process.env.METRO_MAX_WORKERS, 10))
: Math.ceil(
Math.max(
2,
os.availableParallelism() *
Math.min(1, os.totalmem() / (64 * 1024 * 1024 * 1024)),
),
);
return wrapWithReanimatedMetroConfig(
mergeConfig(defaultConfig, {
resolver: {
unstable_enablePackageExports: true,
assetExts: [...assetExts.filter((ext) => ext !== 'svg'), 'riv'],
sourceExts: [...sourceExts, 'svg', 'cjs', 'mjs'],
resolverMainFields: ['sbmodern', 'react-native', 'browser', 'main'],
extraNodeModules: {
...defaultConfig.resolver.extraNodeModules,
'node:crypto': require.resolve('react-native-crypto'),
crypto: require.resolve('react-native-crypto'),
stream: require.resolve('stream-browserify'),
_stream_transform: require.resolve('readable-stream/transform'),
_stream_readable: require.resolve('readable-stream/readable'),
_stream_writable: require.resolve('readable-stream/writable'),
_stream_duplex: require.resolve('readable-stream/duplex'),
_stream_passthrough: require.resolve('readable-stream/passthrough'),
http: require.resolve('@tradle/react-native-http'),
https: require.resolve('https-browserify'),
vm: require.resolve('vm-browserify'),
os: require.resolve('react-native-os'),
zlib: require.resolve('browserify-zlib'),
net: require.resolve('react-native-tcp-socket'),
fs: require.resolve('react-native-level-fs'),
images: path.resolve(__dirname, 'app/images'),
'base64-js': 'react-native-quick-base64',
base64: 'react-native-quick-base64',
'js-base64': 'react-native-quick-base64',
buffer: '@craftzdog/react-native-buffer',
'node:buffer': '@craftzdog/react-native-buffer',
},
resolveRequest: (context, moduleName, platform) => {
// MYXProvider is intentionally excluded from @metamask/perps-controller's
// published dist (extension-only). The dynamic import() uses webpackIgnore
// but babel's dynamicImportToRequire rewrites it to require(), causing Metro
// to resolve it statically. Return an empty module stub.
if (
moduleName === './providers/MYXProvider' &&
context.originModulePath?.includes('@metamask/perps-controller')
) {
return { type: 'empty' };
}
// @ledgerhq packages use exports field subpath mapping (e.g. ./signers/index -> ./lib/signers/index.js)
// which doesn't work with unstable_enablePackageExports: false — manually replicate the lib/ mapping
// Affected: domain-service, evm-tools, devices, cryptoassets-evm-signatures
const ledgerhqSubpathMatch = moduleName.match(
/^(@ledgerhq\/[^/]+)\/(.+)$/,
);
if (ledgerhqSubpathMatch) {
const [, pkgName, subpath] = ledgerhqSubpathMatch;
try {
return {
filePath: require.resolve(`${pkgName}/lib/${subpath}`),
type: 'sourceFile',
};
} catch {
// fall through to default resolution if lib/ mapping doesn't exist
}
}
// Use axios browser build so Node-only deps (e.g. http2) are never pulled in
if (
moduleName === 'axios' ||
moduleName.includes('axios/dist/node/')
) {
return {
filePath: require.resolve('axios/dist/browser/axios.cjs'),
type: 'sourceFile',
};
}
// Use contentful browser build so Node-only built-ins (tty, zlib, etc.) are never pulled in
if (moduleName === 'contentful') {
return {
filePath: require.resolve(
'contentful/dist/contentful.browser.js',
),
type: 'sourceFile',
};
}
if (hasTestOverrides) {
if (moduleName === '@sentry/react-native') {
return {
type: 'sourceFile',
filePath: path.resolve(
__dirname,
'tests/module-mocking/sentry/react-native.ts',
),
};
}
if (moduleName === '@sentry/core') {
return {
type: 'sourceFile',
filePath: path.resolve(
__dirname,
'tests/module-mocking/sentry/core.ts',
),
};
}
}
if (e2eAllowsSeedlessOAuthMetroMocks) {
if (
moduleName.endsWith(
'controllers/seedless-onboarding-controller',
) ||
moduleName.endsWith(
'controllers/seedless-onboarding-controller/index',
) ||
moduleName === './seedless-onboarding-controller' ||
moduleName === '../seedless-onboarding-controller'
) {
return {
type: 'sourceFile',
filePath: path.resolve(
__dirname,
'tests/module-mocking/seedless/index.ts',
),
};
}
// Skips native Google/Apple UI; tokens still hit auth server (see module mock).
if (
moduleName.endsWith('OAuthService/OAuthLoginHandlers') ||
moduleName.endsWith('OAuthService/OAuthLoginHandlers/index') ||
moduleName === './OAuthLoginHandlers' ||
moduleName === '../OAuthLoginHandlers'
) {
return {
type: 'sourceFile',
filePath: path.resolve(
__dirname,
'tests/module-mocking/oauth/OAuthLoginHandlers/index.ts',
),
};
}
}
return context.resolveRequest(context, moduleName, platform);
},
},
transformer: {
babelTransformerPath: require.resolve('./metro.transform.js'),
assetPlugins: [
'react-native-svg-asset-plugin',
'expo-asset/tools/hashAssetFiles',
],
svgAssetPlugin: {
pngCacheDir: '.png-cache',
scales: [1],
output: {
compressionLevel: 6,
},
},
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: true,
inlineRequires: true,
},
}),
},
serializer: lockdownSerializer(
{ hermesRuntime: true },
{
getPolyfills,
},
),
resetCache: process.env.METRO_RESET_CACHE !== 'false',
maxWorkers,
}),
);
};