metro-transform-worker 0.63.0 → 0.64.0

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.real/index.js CHANGED
@@ -4,219 +4,288 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  *
7
- * @flow
7
+ *
8
8
  * @format
9
9
  */
10
+ "use strict";
11
+
12
+ function _toConsumableArray(arr) {
13
+ return (
14
+ _arrayWithoutHoles(arr) ||
15
+ _iterableToArray(arr) ||
16
+ _unsupportedIterableToArray(arr) ||
17
+ _nonIterableSpread()
18
+ );
19
+ }
10
20
 
11
- 'use strict';
12
-
13
- const HermesCompiler = require('metro-hermes-compiler');
14
- const JsFileWrapping = require('metro/src/ModuleGraph/worker/JsFileWrapping');
15
-
16
- const assetTransformer = require('./utils/assetTransformer');
17
- const babylon = require('@babel/parser');
18
- const collectDependencies = require('metro/src/ModuleGraph/worker/collectDependencies');
19
- const generateImportNames = require('metro/src/ModuleGraph/worker/generateImportNames');
20
- const generate = require('@babel/generator').default;
21
- const getCacheKey = require('metro-cache-key');
22
- const getMinifier = require('./utils/getMinifier');
23
- const {
24
- constantFoldingPlugin,
25
- getTransformPluginCacheKeyFiles,
26
- importExportPlugin,
27
- inlinePlugin,
28
- normalizePseudoGlobals,
29
- } = require('metro-transform-plugins');
30
- const inlineRequiresPlugin = require('babel-preset-fbjs/plugins/inline-requires');
31
- const {transformFromAstSync} = require('@babel/core');
32
- const {stableHash} = require('metro-cache');
33
- const types = require('@babel/types');
34
- const countLines = require('metro/src/lib/countLines');
35
-
36
- const {
37
- fromRawMappings,
38
- toBabelSegments,
39
- toSegmentTuple,
40
- } = require('metro-source-map');
41
- import type {TransformResultDependency} from 'metro/src/DeltaBundler';
42
- import type {AllowOptionalDependencies} from 'metro/src/DeltaBundler/types.flow.js';
43
- import type {DynamicRequiresBehavior} from 'metro/src/ModuleGraph/worker/collectDependencies';
44
- import type {
45
- BasicSourceMap,
46
- FBSourceFunctionMap,
47
- MetroSourceMapSegmentTuple,
48
- } from 'metro-source-map';
49
- import type {
50
- HermesCompilerResult,
51
- Options as HermesCompilerOptions,
52
- } from 'metro-hermes-compiler';
53
- import type {
54
- CustomTransformOptions,
55
- TransformProfile,
56
- } from 'metro-babel-transformer';
57
-
58
- type MinifierConfig = $ReadOnly<{[string]: mixed, ...}>;
59
-
60
- export type MinifierOptions = {
61
- code: string,
62
- map: ?BasicSourceMap,
63
- filename: string,
64
- reserved: $ReadOnlyArray<string>,
65
- config: MinifierConfig,
66
- ...
67
- };
21
+ function _nonIterableSpread() {
22
+ throw new TypeError(
23
+ "Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
24
+ );
25
+ }
68
26
 
69
- export type MinifierResult = {
70
- code: string,
71
- map?: BasicSourceMap,
72
- ...
73
- };
27
+ function _unsupportedIterableToArray(o, minLen) {
28
+ if (!o) return;
29
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
30
+ var n = Object.prototype.toString.call(o).slice(8, -1);
31
+ if (n === "Object" && o.constructor) n = o.constructor.name;
32
+ if (n === "Map" || n === "Set") return Array.from(o);
33
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
34
+ return _arrayLikeToArray(o, minLen);
35
+ }
36
+
37
+ function _iterableToArray(iter) {
38
+ if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter))
39
+ return Array.from(iter);
40
+ }
41
+
42
+ function _arrayWithoutHoles(arr) {
43
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
44
+ }
45
+
46
+ function _arrayLikeToArray(arr, len) {
47
+ if (len == null || len > arr.length) len = arr.length;
48
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
49
+ return arr2;
50
+ }
51
+
52
+ function _objectWithoutProperties(source, excluded) {
53
+ if (source == null) return {};
54
+ var target = _objectWithoutPropertiesLoose(source, excluded);
55
+ var key, i;
56
+ if (Object.getOwnPropertySymbols) {
57
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
58
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
59
+ key = sourceSymbolKeys[i];
60
+ if (excluded.indexOf(key) >= 0) continue;
61
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
62
+ target[key] = source[key];
63
+ }
64
+ }
65
+ return target;
66
+ }
67
+
68
+ function _objectWithoutPropertiesLoose(source, excluded) {
69
+ if (source == null) return {};
70
+ var target = {};
71
+ var sourceKeys = Object.keys(source);
72
+ var key, i;
73
+ for (i = 0; i < sourceKeys.length; i++) {
74
+ key = sourceKeys[i];
75
+ if (excluded.indexOf(key) >= 0) continue;
76
+ target[key] = source[key];
77
+ }
78
+ return target;
79
+ }
80
+
81
+ function ownKeys(object, enumerableOnly) {
82
+ var keys = Object.keys(object);
83
+ if (Object.getOwnPropertySymbols) {
84
+ var symbols = Object.getOwnPropertySymbols(object);
85
+ if (enumerableOnly)
86
+ symbols = symbols.filter(function(sym) {
87
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
88
+ });
89
+ keys.push.apply(keys, symbols);
90
+ }
91
+ return keys;
92
+ }
93
+
94
+ function _objectSpread(target) {
95
+ for (var i = 1; i < arguments.length; i++) {
96
+ var source = arguments[i] != null ? arguments[i] : {};
97
+ if (i % 2) {
98
+ ownKeys(Object(source), true).forEach(function(key) {
99
+ _defineProperty(target, key, source[key]);
100
+ });
101
+ } else if (Object.getOwnPropertyDescriptors) {
102
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
103
+ } else {
104
+ ownKeys(Object(source)).forEach(function(key) {
105
+ Object.defineProperty(
106
+ target,
107
+ key,
108
+ Object.getOwnPropertyDescriptor(source, key)
109
+ );
110
+ });
111
+ }
112
+ }
113
+ return target;
114
+ }
115
+
116
+ function _defineProperty(obj, key, value) {
117
+ if (key in obj) {
118
+ Object.defineProperty(obj, key, {
119
+ value: value,
120
+ enumerable: true,
121
+ configurable: true,
122
+ writable: true
123
+ });
124
+ } else {
125
+ obj[key] = value;
126
+ }
127
+ return obj;
128
+ }
129
+
130
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
131
+ try {
132
+ var info = gen[key](arg);
133
+ var value = info.value;
134
+ } catch (error) {
135
+ reject(error);
136
+ return;
137
+ }
138
+ if (info.done) {
139
+ resolve(value);
140
+ } else {
141
+ Promise.resolve(value).then(_next, _throw);
142
+ }
143
+ }
144
+
145
+ function _asyncToGenerator(fn) {
146
+ return function() {
147
+ var self = this,
148
+ args = arguments;
149
+ return new Promise(function(resolve, reject) {
150
+ var gen = fn.apply(self, args);
151
+ function _next(value) {
152
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
153
+ }
154
+ function _throw(err) {
155
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
156
+ }
157
+ _next(undefined);
158
+ });
159
+ };
160
+ }
161
+
162
+ const HermesCompiler = require("metro-hermes-compiler");
163
+
164
+ const JsFileWrapping = require("metro/src/ModuleGraph/worker/JsFileWrapping");
165
+
166
+ const assetTransformer = require("./utils/assetTransformer");
167
+
168
+ const babylon = require("@babel/parser");
169
+
170
+ const collectDependencies = require("metro/src/ModuleGraph/worker/collectDependencies");
74
171
 
75
- export type Minifier = MinifierOptions => MinifierResult;
76
-
77
- export type Type = 'script' | 'module' | 'asset';
78
-
79
- export type JsTransformerConfig = $ReadOnly<{|
80
- assetPlugins: $ReadOnlyArray<string>,
81
- assetRegistryPath: string,
82
- asyncRequireModulePath: string,
83
- babelTransformerPath: string,
84
- dynamicDepsInPackages: DynamicRequiresBehavior,
85
- enableBabelRCLookup: boolean,
86
- enableBabelRuntime: boolean,
87
- experimentalImportBundleSupport: boolean,
88
- globalPrefix: string,
89
- minifierConfig: MinifierConfig,
90
- minifierPath: string,
91
- optimizationSizeLimit: number,
92
- publicPath: string,
93
- allowOptionalDependencies: AllowOptionalDependencies,
94
- |}>;
95
-
96
- export type {CustomTransformOptions} from 'metro-babel-transformer';
97
-
98
- export type JsTransformOptions = $ReadOnly<{|
99
- customTransformOptions?: CustomTransformOptions,
100
- dev: boolean,
101
- experimentalImportSupport?: boolean,
102
- hot: boolean,
103
- inlinePlatform: boolean,
104
- inlineRequires: boolean,
105
- minify: boolean,
106
- nonInlinedRequires?: $ReadOnlyArray<string>,
107
- platform: ?string,
108
- runtimeBytecodeVersion: ?number,
109
- type: Type,
110
- unstable_disableES6Transforms?: boolean,
111
- unstable_transformProfile: TransformProfile,
112
- |}>;
113
-
114
- export type JsOutput = $ReadOnly<{|
115
- data: $ReadOnly<{|
116
- code: string,
117
- lineCount: number,
118
- map: Array<MetroSourceMapSegmentTuple>,
119
- functionMap: ?FBSourceFunctionMap,
120
- |}>,
121
- type: string,
122
- |}>;
123
-
124
- export type BytecodeOutput = $ReadOnly<{|
125
- data: HermesCompilerResult,
126
- type: 'bytecode/module' | 'bytecode/module/asset' | 'bytecode/script',
127
- |}>;
128
-
129
- type Result = {|
130
- dependencies: $ReadOnlyArray<TransformResultDependency>,
131
- output: $ReadOnlyArray<JsOutput | BytecodeOutput>,
132
- |};
133
-
134
- function getDynamicDepsBehavior(
135
- inPackages: DynamicRequiresBehavior,
136
- filename: string,
137
- ): DynamicRequiresBehavior {
172
+ const generateImportNames = require("metro/src/ModuleGraph/worker/generateImportNames");
173
+
174
+ const nullthrows = require("nullthrows");
175
+
176
+ const generate = require("@babel/generator").default;
177
+
178
+ const getCacheKey = require("metro-cache-key");
179
+
180
+ const getMinifier = require("./utils/getMinifier");
181
+
182
+ const _require = require("metro-transform-plugins"),
183
+ constantFoldingPlugin = _require.constantFoldingPlugin,
184
+ getTransformPluginCacheKeyFiles = _require.getTransformPluginCacheKeyFiles,
185
+ importExportPlugin = _require.importExportPlugin,
186
+ inlinePlugin = _require.inlinePlugin,
187
+ normalizePseudoGlobals = _require.normalizePseudoGlobals;
188
+
189
+ const inlineRequiresPlugin = require("babel-preset-fbjs/plugins/inline-requires");
190
+
191
+ const _require2 = require("@babel/core"),
192
+ transformFromAstSync = _require2.transformFromAstSync;
193
+
194
+ const _require3 = require("metro-cache"),
195
+ stableHash = _require3.stableHash;
196
+
197
+ const types = require("@babel/types");
198
+
199
+ const countLines = require("metro/src/lib/countLines");
200
+
201
+ const _require4 = require("metro-source-map"),
202
+ fromRawMappings = _require4.fromRawMappings,
203
+ toBabelSegments = _require4.toBabelSegments,
204
+ toSegmentTuple = _require4.toSegmentTuple;
205
+
206
+ function getDynamicDepsBehavior(inPackages, filename) {
138
207
  switch (inPackages) {
139
- case 'reject':
140
- return 'reject';
141
- case 'throwAtRuntime':
208
+ case "reject":
209
+ return "reject";
210
+
211
+ case "throwAtRuntime":
142
212
  const isPackage = /(?:^|[/\\])node_modules[/\\]/.test(filename);
143
- return isPackage ? inPackages : 'reject';
213
+ return isPackage ? inPackages : "reject";
214
+
144
215
  default:
145
- (inPackages: empty);
216
+ inPackages;
146
217
  throw new Error(
147
- `invalid value for dynamic deps behavior: \`${inPackages}\``,
218
+ `invalid value for dynamic deps behavior: \`${inPackages}\``
148
219
  );
149
220
  }
150
221
  }
151
222
 
152
- const minifyCode = async (
153
- config: JsTransformerConfig,
154
- projectRoot: string,
155
- filename: string,
156
- code: string,
157
- source: string,
158
- map: Array<MetroSourceMapSegmentTuple>,
159
- reserved?: $ReadOnlyArray<string> = [],
160
- ): Promise<{
161
- code: string,
162
- map: Array<MetroSourceMapSegmentTuple>,
163
- ...
164
- }> => {
165
- const sourceMap = fromRawMappings([
166
- {code, source, map, functionMap: null, path: filename},
167
- ]).toMap(undefined, {});
168
-
169
- const minify = getMinifier(config.minifierPath);
223
+ const minifyCode = /*#__PURE__*/ (function() {
224
+ var _ref = _asyncToGenerator(function*(
225
+ config,
226
+ projectRoot,
227
+ filename,
228
+ code,
229
+ source,
230
+ map
231
+ ) {
232
+ let reserved =
233
+ arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : [];
234
+ const sourceMap = fromRawMappings([
235
+ {
236
+ code,
237
+ source,
238
+ map,
239
+ functionMap: null,
240
+ path: filename
241
+ }
242
+ ]).toMap(undefined, {});
243
+ const minify = getMinifier(config.minifierPath);
170
244
 
171
- try {
172
- const minified = minify({
173
- code,
174
- map: sourceMap,
175
- filename,
176
- reserved,
177
- config: config.minifierConfig,
178
- });
245
+ try {
246
+ const minified = minify({
247
+ code,
248
+ map: sourceMap,
249
+ filename,
250
+ reserved,
251
+ config: config.minifierConfig
252
+ });
253
+ return {
254
+ code: minified.code,
255
+ map: minified.map
256
+ ? toBabelSegments(minified.map).map(toSegmentTuple)
257
+ : []
258
+ };
259
+ } catch (error) {
260
+ if (error.constructor.name === "JS_Parse_Error") {
261
+ throw new Error(
262
+ `${error.message} in file ${filename} at ${error.line}:${error.col}`
263
+ );
264
+ }
179
265
 
180
- return {
181
- code: minified.code,
182
- map: minified.map
183
- ? toBabelSegments(minified.map).map(toSegmentTuple)
184
- : [],
185
- };
186
- } catch (error) {
187
- if (error.constructor.name === 'JS_Parse_Error') {
188
- throw new Error(
189
- `${error.message} in file ${filename} at ${error.line}:${error.col}`,
190
- );
266
+ throw error;
191
267
  }
268
+ });
192
269
 
193
- throw error;
194
- }
195
- };
270
+ return function minifyCode(_x, _x2, _x3, _x4, _x5, _x6) {
271
+ return _ref.apply(this, arguments);
272
+ };
273
+ })();
196
274
 
197
- const compileToBytecode = (
198
- code: string,
199
- type: string,
200
- options: HermesCompilerOptions,
201
- ): HermesCompilerResult => {
202
- if (type.startsWith('js/module')) {
203
- const index = code.lastIndexOf(')');
275
+ const compileToBytecode = (code, type, options) => {
276
+ if (type.startsWith("js/module")) {
277
+ const index = code.lastIndexOf(")");
204
278
  code =
205
279
  code.slice(0, index) +
206
- ',$$METRO_D[0],$$METRO_D[1],$$METRO_D[2]' +
280
+ ",$$METRO_D[0],$$METRO_D[1],$$METRO_D[2]" +
207
281
  code.slice(index);
208
282
  }
283
+
209
284
  return HermesCompiler.compile(code, options);
210
285
  };
211
286
 
212
287
  class InvalidRequireCallError extends Error {
213
- innerError: collectDependencies.InvalidRequireCallError;
214
- filename: string;
215
-
216
- constructor(
217
- innerError: collectDependencies.InvalidRequireCallError,
218
- filename: string,
219
- ) {
288
+ constructor(innerError, filename) {
220
289
  super(`${filename}:${innerError.message}`);
221
290
  this.innerError = innerError;
222
291
  this.filename = filename;
@@ -224,50 +293,290 @@ class InvalidRequireCallError extends Error {
224
293
  }
225
294
 
226
295
  module.exports = {
227
- transform: async (
228
- config: JsTransformerConfig,
229
- projectRoot: string,
230
- filename: string,
231
- data: Buffer,
232
- options: JsTransformOptions,
233
- ): Promise<Result> => {
234
- const sourceCode = data.toString('utf8');
235
- let type = 'js/module';
236
- let bytecodeType = 'bytecode/module';
237
-
238
- if (options.type === 'asset') {
239
- type = 'js/module/asset';
240
- bytecodeType = 'bytecode/module/asset';
241
- }
242
- if (options.type === 'script') {
243
- type = 'js/script';
244
- bytecodeType = 'bytecode/script';
245
- }
296
+ transform: (function() {
297
+ var _ref2 = _asyncToGenerator(function*(
298
+ config,
299
+ projectRoot,
300
+ filename,
301
+ data,
302
+ options
303
+ ) {
304
+ const sourceCode = data.toString("utf8");
305
+ let type = "js/module";
306
+ let bytecodeType = "bytecode/module";
307
+
308
+ if (options.type === "asset") {
309
+ type = "js/module/asset";
310
+ bytecodeType = "bytecode/module/asset";
311
+ }
312
+
313
+ if (options.type === "script") {
314
+ type = "js/script";
315
+ bytecodeType = "bytecode/script";
316
+ }
246
317
 
247
- if (filename.endsWith('.json')) {
248
- let code = JsFileWrapping.wrapJson(sourceCode, config.globalPrefix);
249
- let map = [];
318
+ if (filename.endsWith(".json")) {
319
+ let code = JsFileWrapping.wrapJson(sourceCode, config.globalPrefix);
320
+ let map = [];
321
+
322
+ if (options.minify) {
323
+ var _yield$minifyCode = yield minifyCode(
324
+ config,
325
+ projectRoot,
326
+ filename,
327
+ code,
328
+ sourceCode,
329
+ map
330
+ );
331
+
332
+ map = _yield$minifyCode.map;
333
+ code = _yield$minifyCode.code;
334
+ }
335
+
336
+ const output = [
337
+ {
338
+ data: {
339
+ code,
340
+ lineCount: countLines(code),
341
+ map,
342
+ functionMap: null
343
+ },
344
+ type
345
+ }
346
+ ];
347
+
348
+ if (options.runtimeBytecodeVersion) {
349
+ output.push({
350
+ data: compileToBytecode(code, type, {
351
+ sourceURL: filename,
352
+ sourceMap: fromRawMappings([
353
+ {
354
+ code,
355
+ source: sourceCode,
356
+ map,
357
+ functionMap: null,
358
+ path: filename
359
+ }
360
+ ]).toString()
361
+ }),
362
+ type: bytecodeType
363
+ });
364
+ }
365
+
366
+ return {
367
+ dependencies: [],
368
+ output
369
+ };
370
+ } // $FlowFixMe TODO t26372934 Plugin system
371
+
372
+ const transformer = require(config.babelTransformerPath);
373
+
374
+ const transformerArgs = {
375
+ filename,
376
+ options: _objectSpread(
377
+ _objectSpread({}, options),
378
+ {},
379
+ {
380
+ enableBabelRCLookup: config.enableBabelRCLookup,
381
+ enableBabelRuntime: config.enableBabelRuntime,
382
+ globalPrefix: config.globalPrefix,
383
+ // Inline requires are now performed at a secondary step. We cannot
384
+ // unfortunately remove it from the internal transformer, since this one
385
+ // is used by other tooling, and this would affect it.
386
+ inlineRequires: false,
387
+ nonInlinedRequires: [],
388
+ projectRoot,
389
+ publicPath: config.publicPath
390
+ }
391
+ ),
392
+ plugins: [],
393
+ src: sourceCode
394
+ };
395
+ const transformResult =
396
+ type === "js/module/asset"
397
+ ? _objectSpread(
398
+ _objectSpread(
399
+ {},
400
+ yield assetTransformer.transform(
401
+ transformerArgs,
402
+ config.assetRegistryPath,
403
+ config.assetPlugins
404
+ )
405
+ ),
406
+ {},
407
+ {
408
+ functionMap: null
409
+ }
410
+ )
411
+ : yield transformer.transform(transformerArgs); // Transformers can ouptut null ASTs (if they ignore the file). In that case
412
+ // we need to parse the module source code to get their AST.
413
+
414
+ let ast =
415
+ transformResult.ast ||
416
+ babylon.parse(sourceCode, {
417
+ sourceType: "unambiguous"
418
+ });
419
+
420
+ const _generateImportNames = generateImportNames(ast),
421
+ importDefault = _generateImportNames.importDefault,
422
+ importAll = _generateImportNames.importAll; // Add "use strict" if the file was parsed as a module, and the directive did
423
+ // not exist yet.
424
+
425
+ const directives = ast.program.directives;
426
+
427
+ if (
428
+ ast.program.sourceType === "module" &&
429
+ directives.findIndex(d => d.value.value === "use strict") === -1
430
+ ) {
431
+ directives.push(types.directive(types.directiveLiteral("use strict")));
432
+ } // Perform the import-export transform (in case it's still needed), then
433
+ // fold requires and perform constant folding (if in dev).
434
+
435
+ const plugins = [];
436
+
437
+ const opts = _objectSpread(
438
+ _objectSpread({}, options),
439
+ {},
440
+ {
441
+ inlineableCalls: [importDefault, importAll],
442
+ importDefault,
443
+ importAll
444
+ }
445
+ );
446
+
447
+ if (options.experimentalImportSupport) {
448
+ plugins.push([importExportPlugin, opts]);
449
+ }
450
+
451
+ if (options.inlineRequires) {
452
+ plugins.push([
453
+ inlineRequiresPlugin,
454
+ _objectSpread(
455
+ _objectSpread({}, opts),
456
+ {},
457
+ {
458
+ ignoredRequires: options.nonInlinedRequires
459
+ }
460
+ )
461
+ ]);
462
+ }
463
+
464
+ if (!options.dev) {
465
+ plugins.push([constantFoldingPlugin, opts]);
466
+ }
467
+
468
+ plugins.push([inlinePlugin, opts]);
469
+ ast = nullthrows(
470
+ transformFromAstSync(ast, "", {
471
+ ast: true,
472
+ babelrc: false,
473
+ code: false,
474
+ configFile: false,
475
+ comments: false,
476
+ compact: false,
477
+ filename,
478
+ plugins,
479
+ sourceMaps: false
480
+ }).ast
481
+ );
482
+ let dependencyMapName = "";
483
+ let dependencies;
484
+ let wrappedAst; // If the module to transform is a script (meaning that is not part of the
485
+ // dependency graph and it code will just be prepended to the bundle modules),
486
+ // we need to wrap it differently than a commonJS module (also, scripts do
487
+ // not have dependencies).
488
+
489
+ if (type === "js/script") {
490
+ dependencies = [];
491
+ wrappedAst = JsFileWrapping.wrapPolyfill(ast);
492
+ } else {
493
+ try {
494
+ const opts = {
495
+ asyncRequireModulePath: config.asyncRequireModulePath,
496
+ dynamicRequires: getDynamicDepsBehavior(
497
+ config.dynamicDepsInPackages,
498
+ filename
499
+ ),
500
+ inlineableCalls: [importDefault, importAll],
501
+ keepRequireNames: options.dev,
502
+ allowOptionalDependencies: config.allowOptionalDependencies
503
+ };
504
+
505
+ var _collectDependencies = collectDependencies(ast, opts);
506
+
507
+ ast = _collectDependencies.ast;
508
+ dependencies = _collectDependencies.dependencies;
509
+ dependencyMapName = _collectDependencies.dependencyMapName;
510
+ } catch (error) {
511
+ if (error instanceof collectDependencies.InvalidRequireCallError) {
512
+ throw new InvalidRequireCallError(error, filename);
513
+ }
514
+
515
+ throw error;
516
+ }
517
+
518
+ var _JsFileWrapping$wrapM = JsFileWrapping.wrapModule(
519
+ ast,
520
+ importDefault,
521
+ importAll,
522
+ dependencyMapName,
523
+ config.globalPrefix
524
+ );
525
+
526
+ wrappedAst = _JsFileWrapping$wrapM.ast;
527
+ }
528
+
529
+ const reserved =
530
+ options.minify && data.length <= config.optimizationSizeLimit
531
+ ? normalizePseudoGlobals(wrappedAst)
532
+ : [];
533
+ const result = generate(
534
+ wrappedAst,
535
+ {
536
+ comments: false,
537
+ compact: false,
538
+ filename,
539
+ retainLines: false,
540
+ sourceFileName: filename,
541
+ sourceMaps: true
542
+ },
543
+ sourceCode
544
+ );
545
+ let map = result.rawMappings
546
+ ? result.rawMappings.map(toSegmentTuple)
547
+ : [];
548
+ let code = result.code;
250
549
 
251
550
  if (options.minify) {
252
- ({map, code} = await minifyCode(
551
+ var _yield$minifyCode2 = yield minifyCode(
253
552
  config,
254
553
  projectRoot,
255
554
  filename,
256
- code,
555
+ result.code,
257
556
  sourceCode,
258
557
  map,
259
- ));
558
+ reserved
559
+ );
560
+
561
+ map = _yield$minifyCode2.map;
562
+ code = _yield$minifyCode2.code;
260
563
  }
261
564
 
262
565
  const output = [
263
566
  {
264
- data: {code, lineCount: countLines(code), map, functionMap: null},
265
- type,
266
- },
567
+ data: {
568
+ code,
569
+ lineCount: countLines(code),
570
+ map,
571
+ functionMap: transformResult.functionMap
572
+ },
573
+ type
574
+ }
267
575
  ];
576
+
268
577
  if (options.runtimeBytecodeVersion) {
269
578
  output.push({
270
- data: (compileToBytecode(code, type, {
579
+ data: compileToBytecode(code, type, {
271
580
  sourceURL: filename,
272
581
  sourceMap: fromRawMappings([
273
582
  {
@@ -275,240 +584,50 @@ module.exports = {
275
584
  source: sourceCode,
276
585
  map,
277
586
  functionMap: null,
278
- path: filename,
279
- },
280
- ]).toString(),
281
- }): HermesCompilerResult),
282
- type: bytecodeType,
587
+ path: filename
588
+ }
589
+ ]).toString()
590
+ }),
591
+ type: bytecodeType
283
592
  });
284
593
  }
285
594
 
286
595
  return {
287
- dependencies: [],
288
- output,
596
+ dependencies,
597
+ output
289
598
  };
290
- }
291
-
292
- // $FlowFixMe TODO t26372934 Plugin system
293
- const transformer: Transformer<*> = require(config.babelTransformerPath);
294
-
295
- const transformerArgs = {
296
- filename,
297
- options: {
298
- ...options,
299
- enableBabelRCLookup: config.enableBabelRCLookup,
300
- enableBabelRuntime: config.enableBabelRuntime,
301
- globalPrefix: config.globalPrefix,
302
- // Inline requires are now performed at a secondary step. We cannot
303
- // unfortunately remove it from the internal transformer, since this one
304
- // is used by other tooling, and this would affect it.
305
- inlineRequires: false,
306
- nonInlinedRequires: [],
307
- projectRoot,
308
- publicPath: config.publicPath,
309
- },
310
- plugins: [],
311
- src: sourceCode,
312
- };
313
-
314
- const transformResult =
315
- type === 'js/module/asset'
316
- ? {
317
- ...(await assetTransformer.transform(
318
- transformerArgs,
319
- config.assetRegistryPath,
320
- config.assetPlugins,
321
- )),
322
- functionMap: null,
323
- }
324
- : await transformer.transform(transformerArgs);
325
-
326
- // Transformers can ouptut null ASTs (if they ignore the file). In that case
327
- // we need to parse the module source code to get their AST.
328
- let ast =
329
- transformResult.ast ||
330
- babylon.parse(sourceCode, {sourceType: 'unambiguous'});
331
-
332
- const {importDefault, importAll} = generateImportNames(ast);
333
-
334
- // Add "use strict" if the file was parsed as a module, and the directive did
335
- // not exist yet.
336
- const {directives} = ast.program;
337
-
338
- if (
339
- ast.program.sourceType === 'module' &&
340
- directives.findIndex(d => d.value.value === 'use strict') === -1
341
- ) {
342
- directives.push(types.directive(types.directiveLiteral('use strict')));
343
- }
599
+ });
344
600
 
345
- // Perform the import-export transform (in case it's still needed), then
346
- // fold requires and perform constant folding (if in dev).
347
- const plugins = [];
348
- const opts = {
349
- ...options,
350
- inlineableCalls: [importDefault, importAll],
351
- importDefault,
352
- importAll,
601
+ return function transform(_x7, _x8, _x9, _x10, _x11) {
602
+ return _ref2.apply(this, arguments);
353
603
  };
354
-
355
- if (options.experimentalImportSupport) {
356
- plugins.push([importExportPlugin, opts]);
357
- }
358
-
359
- if (options.inlineRequires) {
360
- plugins.push([
361
- inlineRequiresPlugin,
362
- {
363
- ...opts,
364
- ignoredRequires: options.nonInlinedRequires,
365
- },
604
+ })(),
605
+ getCacheKey: config => {
606
+ const babelTransformerPath = config.babelTransformerPath,
607
+ minifierPath = config.minifierPath,
608
+ remainingConfig = _objectWithoutProperties(config, [
609
+ "babelTransformerPath",
610
+ "minifierPath"
366
611
  ]);
367
- }
368
-
369
- if (!options.dev) {
370
- plugins.push([constantFoldingPlugin, opts]);
371
- }
372
-
373
- plugins.push([inlinePlugin, opts]);
374
612
 
375
- ({ast} = transformFromAstSync(ast, '', {
376
- ast: true,
377
- babelrc: false,
378
- code: false,
379
- configFile: false,
380
- comments: false,
381
- compact: false,
382
- filename,
383
- plugins,
384
- sourceMaps: false,
385
- }));
386
-
387
- let dependencyMapName = '';
388
- let dependencies;
389
- let wrappedAst;
390
-
391
- // If the module to transform is a script (meaning that is not part of the
392
- // dependency graph and it code will just be prepended to the bundle modules),
393
- // we need to wrap it differently than a commonJS module (also, scripts do
394
- // not have dependencies).
395
- if (type === 'js/script') {
396
- dependencies = [];
397
- wrappedAst = JsFileWrapping.wrapPolyfill(ast);
398
- } else {
399
- try {
400
- const opts = {
401
- asyncRequireModulePath: config.asyncRequireModulePath,
402
- dynamicRequires: getDynamicDepsBehavior(
403
- config.dynamicDepsInPackages,
404
- filename,
405
- ),
406
- inlineableCalls: [importDefault, importAll],
407
- keepRequireNames: options.dev,
408
- allowOptionalDependencies: config.allowOptionalDependencies,
409
- };
410
- ({ast, dependencies, dependencyMapName} = collectDependencies(
411
- ast,
412
- opts,
413
- ));
414
- } catch (error) {
415
- if (error instanceof collectDependencies.InvalidRequireCallError) {
416
- throw new InvalidRequireCallError(error, filename);
417
- }
418
- throw error;
419
- }
420
-
421
- ({ast: wrappedAst} = JsFileWrapping.wrapModule(
422
- ast,
423
- importDefault,
424
- importAll,
425
- dependencyMapName,
426
- config.globalPrefix,
427
- ));
428
- }
429
-
430
- const reserved =
431
- options.minify && data.length <= config.optimizationSizeLimit
432
- ? normalizePseudoGlobals(wrappedAst)
433
- : [];
434
-
435
- const result = generate(
436
- wrappedAst,
437
- {
438
- comments: false,
439
- compact: false,
440
- filename,
441
- retainLines: false,
442
- sourceFileName: filename,
443
- sourceMaps: true,
444
- },
445
- sourceCode,
613
+ const filesKey = getCacheKey(
614
+ [
615
+ require.resolve(babelTransformerPath),
616
+ require.resolve(minifierPath),
617
+ require.resolve("./utils/getMinifier"),
618
+ require.resolve("./utils/assetTransformer"),
619
+ require.resolve("metro/src/ModuleGraph/worker/collectDependencies"),
620
+ require.resolve("metro/src/ModuleGraph/worker/generateImportNames"),
621
+ require.resolve("metro/src/ModuleGraph/worker/JsFileWrapping")
622
+ ].concat(_toConsumableArray(getTransformPluginCacheKeyFiles()))
446
623
  );
447
624
 
448
- let map = result.rawMappings ? result.rawMappings.map(toSegmentTuple) : [];
449
- let code = result.code;
450
-
451
- if (options.minify) {
452
- ({map, code} = await minifyCode(
453
- config,
454
- projectRoot,
455
- filename,
456
- result.code,
457
- sourceCode,
458
- map,
459
- reserved,
460
- ));
461
- }
462
-
463
- const output = [
464
- {
465
- data: {
466
- code,
467
- lineCount: countLines(code),
468
- map,
469
- functionMap: transformResult.functionMap,
470
- },
471
- type,
472
- },
473
- ];
474
-
475
- if (options.runtimeBytecodeVersion) {
476
- output.push({
477
- data: (compileToBytecode(code, type, {
478
- sourceURL: filename,
479
- sourceMap: fromRawMappings([
480
- {code, source: sourceCode, map, functionMap: null, path: filename},
481
- ]).toString(),
482
- }): HermesCompilerResult),
483
- type: bytecodeType,
484
- });
485
- }
486
-
487
- return {
488
- dependencies,
489
- output,
490
- };
491
- },
492
-
493
- getCacheKey: (config: JsTransformerConfig): string => {
494
- const {babelTransformerPath, minifierPath, ...remainingConfig} = config;
495
-
496
- const filesKey = getCacheKey([
497
- require.resolve(babelTransformerPath),
498
- require.resolve(minifierPath),
499
- require.resolve('./utils/getMinifier'),
500
- require.resolve('./utils/assetTransformer'),
501
- require.resolve('metro/src/ModuleGraph/worker/collectDependencies'),
502
- require.resolve('metro/src/ModuleGraph/worker/generateImportNames'),
503
- require.resolve('metro/src/ModuleGraph/worker/JsFileWrapping'),
504
- ...getTransformPluginCacheKeyFiles(),
505
- ]);
506
-
507
625
  const babelTransformer = require(babelTransformerPath);
626
+
508
627
  return [
509
628
  filesKey,
510
- stableHash(remainingConfig).toString('hex'),
511
- babelTransformer.getCacheKey ? babelTransformer.getCacheKey() : '',
512
- ].join('$');
513
- },
629
+ stableHash(remainingConfig).toString("hex"),
630
+ babelTransformer.getCacheKey ? babelTransformer.getCacheKey() : ""
631
+ ].join("$");
632
+ }
514
633
  };