metro 0.71.0 → 0.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js.flow CHANGED
@@ -10,471 +10,13 @@
10
10
 
11
11
  'use strict';
12
12
 
13
- import type {Graph} from './DeltaBundler';
14
- import type {ServerOptions} from './Server';
15
- import type {OutputOptions, RequestOptions} from './shared/types.flow.js';
16
- import type {Server as HttpServer} from 'http';
17
- import type {Server as HttpsServer} from 'https';
18
- import type {
19
- ConfigT,
20
- InputConfigT,
21
- Middleware,
22
- } from 'metro-config/src/configTypes.flow';
23
- import type {CustomTransformOptions} from 'metro-transform-worker';
24
- import typeof Yargs from 'yargs';
13
+ /*::
14
+ export type * from './index.flow';
15
+ */
25
16
 
26
- const makeBuildCommand = require('./commands/build');
27
- const makeDependenciesCommand = require('./commands/dependencies');
28
- const makeServeCommand = require('./commands/serve');
29
- const MetroHmrServer = require('./HmrServer');
30
- const IncrementalBundler = require('./IncrementalBundler');
31
- const createWebsocketServer = require('./lib/createWebsocketServer');
32
- const MetroServer = require('./Server');
33
- const outputBundle = require('./shared/output/bundle');
34
- const chalk = require('chalk');
35
- const fs = require('fs');
36
- const http = require('http');
37
- const https = require('https');
38
- const {getDefaultConfig, loadConfig, mergeConfig} = require('metro-config');
39
- const {InspectorProxy} = require('metro-inspector-proxy');
40
- const net = require('net');
41
- const {parse} = require('url');
42
- const ws = require('ws');
17
+ try {
18
+ // $FlowFixMe[untyped-import]
19
+ require('metro-babel-register').unstable_registerForMetroMonorepo();
20
+ } catch {}
43
21
 
44
- type MetroMiddleWare = {
45
- attachHmrServer: (httpServer: HttpServer | HttpsServer) => void,
46
- end: () => void,
47
- metroServer: MetroServer,
48
- middleware: Middleware,
49
- };
50
-
51
- export type RunMetroOptions = {
52
- ...ServerOptions,
53
- waitForBundler?: boolean,
54
- };
55
-
56
- export type RunServerOptions = {
57
- hasReducedPerformance?: boolean,
58
- host?: string,
59
- onError?: (Error & {code?: string}) => void,
60
- onReady?: (server: HttpServer | HttpsServer) => void,
61
- runInspectorProxy?: boolean,
62
- secureServerOptions?: Object,
63
- secure?: boolean, // deprecated
64
- secureCert?: string, // deprecated
65
- secureKey?: string, // deprecated
66
- waitForBundler?: boolean,
67
- websocketEndpoints?: {
68
- [path: string]: typeof ws.Server,
69
- },
70
- };
71
-
72
- type BuildGraphOptions = {
73
- entries: $ReadOnlyArray<string>,
74
- customTransformOptions?: CustomTransformOptions,
75
- dev?: boolean,
76
- minify?: boolean,
77
- onProgress?: (transformedFileCount: number, totalFileCount: number) => void,
78
- platform?: string,
79
- type?: 'module' | 'script',
80
- };
81
-
82
- export type RunBuildOptions = {
83
- entry: string,
84
- dev?: boolean,
85
- out?: string,
86
- onBegin?: () => void,
87
- onComplete?: () => void,
88
- onProgress?: (transformedFileCount: number, totalFileCount: number) => void,
89
- minify?: boolean,
90
- output?: {
91
- build: (
92
- MetroServer,
93
- RequestOptions,
94
- ) => Promise<{
95
- code: string,
96
- map: string,
97
- ...
98
- }>,
99
- save: (
100
- {
101
- code: string,
102
- map: string,
103
- ...
104
- },
105
- OutputOptions,
106
- (...args: Array<string>) => void,
107
- ) => Promise<mixed>,
108
- ...
109
- },
110
- platform?: string,
111
- sourceMap?: boolean,
112
- sourceMapUrl?: string,
113
- };
114
-
115
- type BuildCommandOptions = {} | null;
116
- type ServeCommandOptions = {} | null;
117
-
118
- async function getConfig(config: InputConfigT): Promise<ConfigT> {
119
- const defaultConfig = await getDefaultConfig(config.projectRoot);
120
- return mergeConfig(defaultConfig, config);
121
- }
122
-
123
- async function runMetro(
124
- config: InputConfigT,
125
- options?: RunMetroOptions,
126
- ): Promise<MetroServer> {
127
- const mergedConfig = await getConfig(config);
128
- const {
129
- reporter,
130
- server: {port},
131
- } = mergedConfig;
132
-
133
- reporter.update({
134
- hasReducedPerformance: options
135
- ? Boolean(options.hasReducedPerformance)
136
- : false,
137
- port,
138
- type: 'initialize_started',
139
- });
140
-
141
- const {waitForBundler = false, ...serverOptions} = options ?? {};
142
- const server = new MetroServer(mergedConfig, serverOptions);
143
-
144
- const readyPromise = server
145
- .ready()
146
- .then(() => {
147
- reporter.update({
148
- type: 'initialize_done',
149
- port,
150
- });
151
- })
152
- .catch(error => {
153
- reporter.update({
154
- type: 'initialize_failed',
155
- port,
156
- error,
157
- });
158
- });
159
- if (waitForBundler) {
160
- await readyPromise;
161
- }
162
-
163
- return server;
164
- }
165
-
166
- exports.runMetro = runMetro;
167
- exports.loadConfig = loadConfig;
168
-
169
- const createConnectMiddleware = async function (
170
- config: ConfigT,
171
- options?: RunMetroOptions,
172
- ): Promise<MetroMiddleWare> {
173
- const metroServer = await runMetro(config, options);
174
-
175
- let enhancedMiddleware: Middleware = metroServer.processRequest;
176
-
177
- // Enhance the resulting middleware using the config options
178
- if (config.server.enhanceMiddleware) {
179
- enhancedMiddleware = config.server.enhanceMiddleware(
180
- enhancedMiddleware,
181
- metroServer,
182
- );
183
- }
184
-
185
- return {
186
- attachHmrServer(httpServer: HttpServer | HttpsServer): void {
187
- const wss = createWebsocketServer({
188
- websocketServer: new MetroHmrServer(
189
- metroServer.getBundler(),
190
- metroServer.getCreateModuleId(),
191
- config,
192
- ),
193
- });
194
- httpServer.on('upgrade', (request, socket, head) => {
195
- const {pathname} = parse(request.url);
196
- if (pathname === '/hot') {
197
- wss.handleUpgrade(request, socket, head, ws => {
198
- wss.emit('connection', ws, request);
199
- });
200
- } else {
201
- socket.destroy();
202
- }
203
- });
204
- },
205
- metroServer,
206
- middleware: enhancedMiddleware,
207
- end(): void {
208
- metroServer.end();
209
- },
210
- };
211
- };
212
- exports.createConnectMiddleware = createConnectMiddleware;
213
-
214
- exports.runServer = async (
215
- config: ConfigT,
216
- {
217
- hasReducedPerformance = false,
218
- host,
219
- onError,
220
- onReady,
221
- secureServerOptions,
222
- secure, //deprecated
223
- secureCert, // deprecated
224
- secureKey, // deprecated
225
- waitForBundler = false,
226
- websocketEndpoints = {},
227
- }: RunServerOptions,
228
- ): Promise<HttpServer | HttpsServer> => {
229
- await earlyPortCheck(host, config.server.port);
230
-
231
- if (secure != null || secureCert != null || secureKey != null) {
232
- // eslint-disable-next-line no-console
233
- console.warn(
234
- chalk.inverse.yellow.bold(' DEPRECATED '),
235
- 'The `secure`, `secureCert`, and `secureKey` options are now deprecated. ' +
236
- 'Please use the `secureServerOptions` object instead to pass options to ' +
237
- "Metro's https development server.",
238
- );
239
- }
240
- // Lazy require
241
- const connect = require('connect');
242
-
243
- const serverApp = connect();
244
-
245
- const {middleware, end, metroServer} = await createConnectMiddleware(config, {
246
- hasReducedPerformance,
247
- waitForBundler,
248
- });
249
-
250
- serverApp.use(middleware);
251
-
252
- let inspectorProxy: ?InspectorProxy = null;
253
- if (config.server.runInspectorProxy) {
254
- inspectorProxy = new InspectorProxy(config.projectRoot);
255
- }
256
-
257
- let httpServer;
258
-
259
- if (secure || secureServerOptions != null) {
260
- let options = secureServerOptions;
261
- if (typeof secureKey === 'string' && typeof secureCert === 'string') {
262
- options = {
263
- key: fs.readFileSync(secureKey),
264
- cert: fs.readFileSync(secureCert),
265
- ...secureServerOptions,
266
- };
267
- }
268
- httpServer = https.createServer(options, serverApp);
269
- } else {
270
- httpServer = http.createServer(serverApp);
271
- }
272
- return new Promise(
273
- (
274
- resolve: (result: HttpServer | HttpsServer) => void,
275
- reject: mixed => mixed,
276
- ) => {
277
- httpServer.on('error', error => {
278
- if (onError) {
279
- onError(error);
280
- }
281
- reject(error);
282
- end();
283
- });
284
-
285
- httpServer.listen(config.server.port, host, () => {
286
- if (onReady) {
287
- onReady(httpServer);
288
- }
289
-
290
- Object.assign(websocketEndpoints, {
291
- ...(inspectorProxy
292
- ? {...inspectorProxy.createWebSocketListeners(httpServer)}
293
- : {}),
294
- '/hot': createWebsocketServer({
295
- websocketServer: new MetroHmrServer(
296
- metroServer.getBundler(),
297
- metroServer.getCreateModuleId(),
298
- config,
299
- ),
300
- }),
301
- });
302
-
303
- httpServer.on('upgrade', (request, socket, head) => {
304
- const {pathname} = parse(request.url);
305
- if (pathname != null && websocketEndpoints[pathname]) {
306
- websocketEndpoints[pathname].handleUpgrade(
307
- request,
308
- socket,
309
- head,
310
- ws => {
311
- websocketEndpoints[pathname].emit('connection', ws, request);
312
- },
313
- );
314
- } else {
315
- socket.destroy();
316
- }
317
- });
318
-
319
- if (inspectorProxy) {
320
- // TODO(hypuk): Refactor inspectorProxy.processRequest into separate request handlers
321
- // so that we could provide routes (/json/list and /json/version) here.
322
- // Currently this causes Metro to give warning about T31407894.
323
- // $FlowFixMe[method-unbinding] added when improving typing for this parameters
324
- serverApp.use(inspectorProxy.processRequest.bind(inspectorProxy));
325
- }
326
-
327
- resolve(httpServer);
328
- });
329
-
330
- // Disable any kind of automatic timeout behavior for incoming
331
- // requests in case it takes the packager more than the default
332
- // timeout of 120 seconds to respond to a request.
333
- httpServer.timeout = 0;
334
-
335
- httpServer.on('close', () => {
336
- end();
337
- });
338
- },
339
- );
340
- };
341
-
342
- exports.runBuild = async (
343
- config: ConfigT,
344
- {
345
- dev = false,
346
- entry,
347
- onBegin,
348
- onComplete,
349
- onProgress,
350
- minify = true,
351
- output = outputBundle,
352
- out,
353
- platform = 'web',
354
- sourceMap = false,
355
- sourceMapUrl,
356
- }: RunBuildOptions,
357
- ): Promise<{
358
- code: string,
359
- map: string,
360
- ...
361
- }> => {
362
- const metroServer = await runMetro(config, {
363
- watch: false,
364
- });
365
-
366
- try {
367
- const requestOptions: RequestOptions = {
368
- dev,
369
- entryFile: entry,
370
- inlineSourceMap: sourceMap && !sourceMapUrl,
371
- minify,
372
- platform,
373
- sourceMapUrl: sourceMap === false ? undefined : sourceMapUrl,
374
- createModuleIdFactory: config.serializer.createModuleIdFactory,
375
- onProgress,
376
- };
377
-
378
- if (onBegin) {
379
- onBegin();
380
- }
381
-
382
- const metroBundle = await output.build(metroServer, requestOptions);
383
-
384
- if (onComplete) {
385
- onComplete();
386
- }
387
-
388
- if (out) {
389
- const bundleOutput = out.replace(/(\.js)?$/, '.js');
390
- const sourcemapOutput =
391
- sourceMap === false ? undefined : out.replace(/(\.js)?$/, '.map');
392
-
393
- const outputOptions: OutputOptions = {
394
- bundleOutput,
395
- sourcemapOutput,
396
- dev,
397
- platform,
398
- };
399
-
400
- // eslint-disable-next-line no-console
401
- await output.save(metroBundle, outputOptions, console.log);
402
- }
403
-
404
- return metroBundle;
405
- } finally {
406
- await metroServer.end();
407
- }
408
- };
409
-
410
- exports.buildGraph = async function (
411
- config: InputConfigT,
412
- {
413
- customTransformOptions = Object.create(null),
414
- dev = false,
415
- entries,
416
- minify = false,
417
- onProgress,
418
- platform = 'web',
419
- type = 'module',
420
- }: BuildGraphOptions,
421
- ): Promise<Graph<>> {
422
- const mergedConfig = await getConfig(config);
423
-
424
- const bundler = new IncrementalBundler(mergedConfig);
425
-
426
- try {
427
- return await bundler.buildGraphForEntries(entries, {
428
- ...MetroServer.DEFAULT_GRAPH_OPTIONS,
429
- customTransformOptions,
430
- dev,
431
- minify,
432
- platform,
433
- type,
434
- });
435
- } finally {
436
- bundler.end();
437
- }
438
- };
439
-
440
- exports.attachMetroCli = function (
441
- yargs: Yargs,
442
- {
443
- build = {},
444
- serve = {},
445
- dependencies = {},
446
- }: {
447
- build: BuildCommandOptions,
448
- serve: ServeCommandOptions,
449
- dependencies: any,
450
- ...
451
- } = {},
452
- ): Yargs {
453
- if (build) {
454
- const {command, description, builder, handler} = makeBuildCommand();
455
- yargs.command(command, description, builder, handler);
456
- }
457
- if (serve) {
458
- const {command, description, builder, handler} = makeServeCommand();
459
- yargs.command(command, description, builder, handler);
460
- }
461
- if (dependencies) {
462
- const {command, description, builder, handler} = makeDependenciesCommand();
463
- yargs.command(command, description, builder, handler);
464
- }
465
- return yargs;
466
- };
467
-
468
- async function earlyPortCheck(host: void | string, port: number) {
469
- const server = net.createServer(c => c.end());
470
- try {
471
- await new Promise((resolve, reject) => {
472
- server.on('error', err => {
473
- reject(err);
474
- });
475
- server.listen(port, host, undefined, () => resolve());
476
- });
477
- } finally {
478
- await new Promise(resolve => server.close(() => resolve()));
479
- }
480
- }
22
+ module.exports = require('./index.flow');
@@ -144,7 +144,10 @@ class ModuleResolver {
144
144
  ` * ${Resolver.formatFileCandidates(
145
145
  this._removeRoot(candidates.dir)
146
146
  )}`,
147
- ].join("\n")
147
+ ].join("\n"),
148
+ {
149
+ cause: error,
150
+ }
148
151
  );
149
152
  }
150
153
 
@@ -162,7 +165,10 @@ class ModuleResolver {
162
165
  [
163
166
  `${moduleName} could not be found within the project${hint || "."}`,
164
167
  ...displayDirPaths.map((dirPath) => ` ${dirPath}`),
165
- ].join("\n")
168
+ ].join("\n"),
169
+ {
170
+ cause: error,
171
+ }
166
172
  );
167
173
  }
168
174
 
@@ -238,7 +244,11 @@ class UnableToResolveError extends Error {
238
244
  * The name of the module that was required, no necessarily a path,
239
245
  * ex. `./bar`, or `invariant`.
240
246
  */
241
- constructor(originModulePath, targetModuleName, message) {
247
+
248
+ /**
249
+ * Original error that causes this error
250
+ */
251
+ constructor(originModulePath, targetModuleName, message, options) {
242
252
  super();
243
253
  this.originModulePath = originModulePath;
244
254
  this.targetModuleName = targetModuleName;
@@ -250,6 +260,8 @@ class UnableToResolveError extends Error {
250
260
  originModulePath,
251
261
  message
252
262
  ) + (codeFrameMessage ? "\n" + codeFrameMessage : "");
263
+ this.cause =
264
+ options === null || options === void 0 ? void 0 : options.cause;
253
265
  }
254
266
 
255
267
  buildCodeFrameMessage() {
@@ -201,6 +201,9 @@ class ModuleResolver<TModule: Moduleish, TPackage: Packageish> {
201
201
  this._removeRoot(candidates.dir),
202
202
  )}`,
203
203
  ].join('\n'),
204
+ {
205
+ cause: error,
206
+ },
204
207
  );
205
208
  }
206
209
  if (error instanceof Resolver.FailedToResolveNameError) {
@@ -220,6 +223,9 @@ class ModuleResolver<TModule: Moduleish, TPackage: Packageish> {
220
223
  `${moduleName} could not be found within the project${hint || '.'}`,
221
224
  ...displayDirPaths.map((dirPath: string) => ` ${dirPath}`),
222
225
  ].join('\n'),
226
+ {
227
+ cause: error,
228
+ },
223
229
  );
224
230
  }
225
231
  throw error;
@@ -287,11 +293,18 @@ class UnableToResolveError extends Error {
287
293
  * ex. `./bar`, or `invariant`.
288
294
  */
289
295
  targetModuleName: string;
296
+ /**
297
+ * Original error that causes this error
298
+ */
299
+ cause: ?Error;
290
300
 
291
301
  constructor(
292
302
  originModulePath: string,
293
303
  targetModuleName: string,
294
304
  message: string,
305
+ options?: $ReadOnly<{
306
+ cause?: Error,
307
+ }>,
295
308
  ) {
296
309
  super();
297
310
  this.originModulePath = originModulePath;
@@ -304,6 +317,8 @@ class UnableToResolveError extends Error {
304
317
  originModulePath,
305
318
  message,
306
319
  ) + (codeFrameMessage ? '\n' + codeFrameMessage : '');
320
+
321
+ this.cause = options?.cause;
307
322
  }
308
323
 
309
324
  buildCodeFrameMessage(): ?string {
@@ -1,9 +1,47 @@
1
1
  "use strict";
2
2
 
3
- var _metroFileMap = _interopRequireDefault(require("metro-file-map"));
3
+ var _metroFileMap = _interopRequireWildcard(require("metro-file-map"));
4
4
 
5
- function _interopRequireDefault(obj) {
6
- return obj && obj.__esModule ? obj : { default: obj };
5
+ function _getRequireWildcardCache(nodeInterop) {
6
+ if (typeof WeakMap !== "function") return null;
7
+ var cacheBabelInterop = new WeakMap();
8
+ var cacheNodeInterop = new WeakMap();
9
+ return (_getRequireWildcardCache = function (nodeInterop) {
10
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
11
+ })(nodeInterop);
12
+ }
13
+
14
+ function _interopRequireWildcard(obj, nodeInterop) {
15
+ if (!nodeInterop && obj && obj.__esModule) {
16
+ return obj;
17
+ }
18
+ if (obj === null || (typeof obj !== "object" && typeof obj !== "function")) {
19
+ return { default: obj };
20
+ }
21
+ var cache = _getRequireWildcardCache(nodeInterop);
22
+ if (cache && cache.has(obj)) {
23
+ return cache.get(obj);
24
+ }
25
+ var newObj = {};
26
+ var hasPropertyDescriptor =
27
+ Object.defineProperty && Object.getOwnPropertyDescriptor;
28
+ for (var key in obj) {
29
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
30
+ var desc = hasPropertyDescriptor
31
+ ? Object.getOwnPropertyDescriptor(obj, key)
32
+ : null;
33
+ if (desc && (desc.get || desc.set)) {
34
+ Object.defineProperty(newObj, key, desc);
35
+ } else {
36
+ newObj[key] = obj[key];
37
+ }
38
+ }
39
+ }
40
+ newObj.default = obj;
41
+ if (cache) {
42
+ cache.set(obj, newObj);
43
+ }
44
+ return newObj;
7
45
  }
8
46
 
9
47
  /**
@@ -19,8 +57,6 @@ const ci = require("ci-info");
19
57
 
20
58
  const path = require("path");
21
59
 
22
- const JEST_HASTE_MAP_CACHE_BREAKER = 5;
23
-
24
60
  function getIgnorePattern(config) {
25
61
  // For now we support both options
26
62
  const { blockList, blacklistRE } = config.resolver;
@@ -45,7 +81,10 @@ function getIgnorePattern(config) {
45
81
  }
46
82
 
47
83
  function createHasteMap(config, options) {
48
- var _config$fileMapCacheD, _options$name, _options$throwOnModul;
84
+ var _config$unstable_file,
85
+ _config$unstable_perf,
86
+ _config$unstable_perf2,
87
+ _options$throwOnModul;
49
88
 
50
89
  const dependencyExtractor =
51
90
  (options === null || options === void 0
@@ -55,28 +94,47 @@ function createHasteMap(config, options) {
55
94
  : config.resolver.dependencyExtractor;
56
95
  const computeDependencies = dependencyExtractor != null;
57
96
  return _metroFileMap.default.create({
58
- cacheDirectory:
59
- (_config$fileMapCacheD = config.fileMapCacheDirectory) !== null &&
60
- _config$fileMapCacheD !== void 0
61
- ? _config$fileMapCacheD
62
- : config.hasteMapCacheDirectory,
97
+ cacheManagerFactory:
98
+ (_config$unstable_file =
99
+ config === null || config === void 0
100
+ ? void 0
101
+ : config.unstable_fileMapCacheManagerFactory) !== null &&
102
+ _config$unstable_file !== void 0
103
+ ? _config$unstable_file
104
+ : (buildParameters) => {
105
+ var _config$fileMapCacheD;
106
+
107
+ return new _metroFileMap.DiskCacheManager({
108
+ buildParameters,
109
+ cacheDirectory:
110
+ (_config$fileMapCacheD = config.fileMapCacheDirectory) !==
111
+ null && _config$fileMapCacheD !== void 0
112
+ ? _config$fileMapCacheD
113
+ : config.hasteMapCacheDirectory,
114
+ cacheFilePrefix:
115
+ options === null || options === void 0
116
+ ? void 0
117
+ : options.cacheFilePrefix,
118
+ });
119
+ },
120
+ perfLogger:
121
+ (_config$unstable_perf =
122
+ (_config$unstable_perf2 = config.unstable_perfLogger) === null ||
123
+ _config$unstable_perf2 === void 0
124
+ ? void 0
125
+ : _config$unstable_perf2.subSpan("hasteMap")) !== null &&
126
+ _config$unstable_perf !== void 0
127
+ ? _config$unstable_perf
128
+ : null,
63
129
  computeDependencies,
64
130
  computeSha1: true,
65
131
  dependencyExtractor: config.resolver.dependencyExtractor,
66
132
  extensions: config.resolver.sourceExts.concat(config.resolver.assetExts),
67
133
  forceNodeFilesystemAPI: !config.resolver.useWatchman,
68
134
  hasteImplModulePath: config.resolver.hasteImplModulePath,
69
- hasteMapModulePath: config.resolver.unstable_hasteMapModulePath,
70
135
  ignorePattern: getIgnorePattern(config),
71
136
  maxWorkers: config.maxWorkers,
72
137
  mocksPattern: "",
73
- name: `${
74
- (_options$name =
75
- options === null || options === void 0 ? void 0 : options.name) !==
76
- null && _options$name !== void 0
77
- ? _options$name
78
- : "metro"
79
- }-${JEST_HASTE_MAP_CACHE_BREAKER}`,
80
138
  platforms: config.resolver.platforms,
81
139
  retainAllFiles: true,
82
140
  resetCache: config.resetCache,