@react-native/metro-babel-transformer 0.73.5 → 0.73.7

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/.babelrc ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "plugins": [
3
+ "@babel/plugin-proposal-object-rest-spread",
4
+ "@babel/plugin-transform-async-to-generator",
5
+ "@babel/plugin-transform-destructuring",
6
+ "@babel/plugin-transform-flow-strip-types",
7
+ "@babel/plugin-syntax-dynamic-import",
8
+ "@babel/plugin-proposal-class-properties",
9
+ "@babel/plugin-proposal-nullish-coalescing-operator",
10
+ "@babel/plugin-proposal-optional-chaining"
11
+ ]
12
+ }
package/.prettierrc ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "arrowParens": "avoid",
3
+ "bracketSameLine": true,
4
+ "bracketSpacing": false,
5
+ "requirePragma": true,
6
+ "singleQuote": true,
7
+ "trailingComma": "all"
8
+ }
package/index.js.flow ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow strict
8
+ * @format
9
+ * @oncall react_native
10
+ */
11
+
12
+ export * from './src';
package/package.json CHANGED
@@ -1,13 +1,21 @@
1
1
  {
2
2
  "name": "@react-native/metro-babel-transformer",
3
- "version": "0.73.5",
3
+ "version": "0.73.7",
4
4
  "description": "Babel transformer for React Native applications.",
5
- "main": "dst/index.js",
5
+ "main": "src/index.js",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git@github.com:facebook/react-native.git",
9
9
  "directory": "packages/react-native-babel-transformer"
10
10
  },
11
+ "scripts": {
12
+ "prepare-release": "test -d lib && mv src src.real && mv lib src",
13
+ "cleanup-release": "test ! -e lib && mv src lib && mv src.real src && rimraf lib",
14
+ "build-clean": "rimraf build && rimraf src.real",
15
+ "build": " node scripts/build.js --verbose",
16
+ "prepare": "yarn run build-clean && yarn run build && yarn run prepare-release",
17
+ "postpublish": "yarn run cleanup-release"
18
+ },
11
19
  "keywords": [
12
20
  "transformer",
13
21
  "react-native",
@@ -21,6 +29,24 @@
21
29
  "hermes-parser": "0.14.0",
22
30
  "nullthrows": "^1.1.1"
23
31
  },
32
+ "devDependencies": {
33
+ "@babel/plugin-proposal-class-properties": "^7.18.0",
34
+ "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.0",
35
+ "@babel/plugin-proposal-object-rest-spread": "^7.20.0",
36
+ "@babel/plugin-proposal-optional-chaining": "^7.20.0",
37
+ "@babel/plugin-syntax-dynamic-import": "^7.8.0",
38
+ "@babel/plugin-transform-async-to-generator": "^7.20.0",
39
+ "@babel/plugin-transform-destructuring": "^7.20.0",
40
+ "@babel/plugin-transform-flow-strip-types": "^7.20.0",
41
+ "@babel/preset-env": "^7.20.0",
42
+ "chalk": "^4.0.0",
43
+ "glob": "^7.1.1",
44
+ "invariant": "^2.2.4",
45
+ "micromatch": "^4.0.4",
46
+ "mkdirp": "^0.5.1",
47
+ "prettier": "2.8.8",
48
+ "rimraf": "^3.0.2"
49
+ },
24
50
  "peerDependencies": {
25
51
  "@babel/core": "*"
26
52
  },
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @format
8
+ */
9
+
10
+ /**
11
+ * script to build (transpile) files.
12
+ *
13
+ * Based off of the build script from Metro, and tweaked to run in just one
14
+ * package instead of in a monorepo. Just run `build.js` and the JS files in
15
+ * `src/` will be built in `lib/`, and the original source files will be copied
16
+ * over as `Example.js.flow`, so consumers of this module can still make use of
17
+ * type checking.
18
+ *
19
+ * Call this script with the `--verbose` flag to show the full output of this
20
+ * script.
21
+ */
22
+
23
+ 'use strict';
24
+
25
+ const babel = require('@babel/core');
26
+ const chalk = require('chalk');
27
+ const fs = require('fs');
28
+ const glob = require('glob');
29
+ const micromatch = require('micromatch');
30
+ const mkdirp = require('mkdirp');
31
+ const path = require('path');
32
+ const prettier = require('prettier');
33
+ const prettierConfig = JSON.parse(
34
+ fs.readFileSync(path.resolve(__dirname, '..', '.prettierrc'), 'utf8'),
35
+ );
36
+
37
+ const SRC_DIR = 'src';
38
+ const BUILD_DIR = 'lib';
39
+ const JS_FILES_PATTERN = '**/*.js';
40
+ const IGNORE_PATTERN = '**/__tests__/**';
41
+ const PACKAGE_DIR = path.resolve(__dirname, '../');
42
+
43
+ const fixedWidth = str => {
44
+ const WIDTH = 80;
45
+ const strs = str.match(new RegExp(`(.{1,${WIDTH}})`, 'g')) || [str];
46
+ let lastString = strs[strs.length - 1];
47
+ if (lastString.length < WIDTH) {
48
+ lastString += Array(WIDTH - lastString.length).join(chalk.dim('.'));
49
+ }
50
+ return strs.slice(0, -1).concat(lastString).join('\n');
51
+ };
52
+
53
+ function getBuildPath(file, buildFolder) {
54
+ const pkgSrcPath = path.resolve(PACKAGE_DIR, SRC_DIR);
55
+ const pkgBuildPath = path.resolve(PACKAGE_DIR, BUILD_DIR);
56
+ const relativeToSrcPath = path.relative(pkgSrcPath, file);
57
+ return path.resolve(pkgBuildPath, relativeToSrcPath);
58
+ }
59
+
60
+ function buildFile(file, silent) {
61
+ const destPath = getBuildPath(file, BUILD_DIR);
62
+
63
+ mkdirp.sync(path.dirname(destPath));
64
+ if (micromatch.isMatch(file, IGNORE_PATTERN)) {
65
+ silent ||
66
+ process.stdout.write(
67
+ chalk.dim(' \u2022 ') +
68
+ path.relative(PACKAGE_DIR, file) +
69
+ ' (ignore)\n',
70
+ );
71
+ } else if (!micromatch.isMatch(file, JS_FILES_PATTERN)) {
72
+ fs.createReadStream(file).pipe(fs.createWriteStream(destPath));
73
+ silent ||
74
+ process.stdout.write(
75
+ chalk.red(' \u2022 ') +
76
+ path.relative(PACKAGE_DIR, file) +
77
+ chalk.red(' \u21D2 ') +
78
+ path.relative(PACKAGE_DIR, destPath) +
79
+ ' (copy)' +
80
+ '\n',
81
+ );
82
+ } else {
83
+ const transformed = prettier.format(
84
+ babel.transformFileSync(file, {}).code,
85
+ {
86
+ ...prettierConfig,
87
+ parser: 'babel',
88
+ },
89
+ );
90
+ fs.writeFileSync(destPath, transformed);
91
+ const source = fs.readFileSync(file).toString('utf-8');
92
+ if (/@flow/.test(source)) {
93
+ fs.createReadStream(file).pipe(fs.createWriteStream(destPath + '.flow'));
94
+ }
95
+ silent ||
96
+ process.stdout.write(
97
+ chalk.green(' \u2022 ') +
98
+ path.relative(PACKAGE_DIR, file) +
99
+ chalk.green(' \u21D2 ') +
100
+ path.relative(PACKAGE_DIR, destPath) +
101
+ '\n',
102
+ );
103
+ }
104
+ }
105
+
106
+ const srcDir = path.resolve(__dirname, '..', SRC_DIR);
107
+ const pattern = path.resolve(srcDir, '**/*');
108
+ const files = glob.sync(pattern, {nodir: true});
109
+
110
+ process.stdout.write(fixedWidth(`${path.basename(PACKAGE_DIR)}\n`));
111
+
112
+ files.forEach(file => buildFile(file, !process.argv.includes('--verbose')));
113
+
114
+ process.stdout.write(`[ ${chalk.green('OK')} ]\n`);
package/src/index.js CHANGED
@@ -4,7 +4,7 @@
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
  * @oncall react_native
10
10
  */
@@ -22,15 +22,106 @@ import type {
22
22
  MetroBabelFileMetadata,
23
23
  } from 'metro-babel-transformer';
24
24
  */
25
-
26
- const {parseSync, transformFromAstSync} = require('@babel/core');
25
+ const _excluded = ['projectRoot', 'extendsBabelConfigPath'],
26
+ _excluded2 = ['experimentalImportSupport'];
27
+ function ownKeys(object, enumerableOnly) {
28
+ var keys = Object.keys(object);
29
+ if (Object.getOwnPropertySymbols) {
30
+ var symbols = Object.getOwnPropertySymbols(object);
31
+ enumerableOnly &&
32
+ (symbols = symbols.filter(function (sym) {
33
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
34
+ })),
35
+ keys.push.apply(keys, symbols);
36
+ }
37
+ return keys;
38
+ }
39
+ function _objectSpread(target) {
40
+ for (var i = 1; i < arguments.length; i++) {
41
+ var source = null != arguments[i] ? arguments[i] : {};
42
+ i % 2
43
+ ? ownKeys(Object(source), !0).forEach(function (key) {
44
+ _defineProperty(target, key, source[key]);
45
+ })
46
+ : Object.getOwnPropertyDescriptors
47
+ ? Object.defineProperties(
48
+ target,
49
+ Object.getOwnPropertyDescriptors(source),
50
+ )
51
+ : ownKeys(Object(source)).forEach(function (key) {
52
+ Object.defineProperty(
53
+ target,
54
+ key,
55
+ Object.getOwnPropertyDescriptor(source, key),
56
+ );
57
+ });
58
+ }
59
+ return target;
60
+ }
61
+ function _defineProperty(obj, key, value) {
62
+ key = _toPropertyKey(key);
63
+ if (key in obj) {
64
+ Object.defineProperty(obj, key, {
65
+ value: value,
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ });
70
+ } else {
71
+ obj[key] = value;
72
+ }
73
+ return obj;
74
+ }
75
+ function _toPropertyKey(arg) {
76
+ var key = _toPrimitive(arg, 'string');
77
+ return typeof key === 'symbol' ? key : String(key);
78
+ }
79
+ function _toPrimitive(input, hint) {
80
+ if (typeof input !== 'object' || input === null) return input;
81
+ var prim = input[Symbol.toPrimitive];
82
+ if (prim !== undefined) {
83
+ var res = prim.call(input, hint || 'default');
84
+ if (typeof res !== 'object') return res;
85
+ throw new TypeError('@@toPrimitive must return a primitive value.');
86
+ }
87
+ return (hint === 'string' ? String : Number)(input);
88
+ }
89
+ function _objectWithoutProperties(source, excluded) {
90
+ if (source == null) return {};
91
+ var target = _objectWithoutPropertiesLoose(source, excluded);
92
+ var key, i;
93
+ if (Object.getOwnPropertySymbols) {
94
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
95
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
96
+ key = sourceSymbolKeys[i];
97
+ if (excluded.indexOf(key) >= 0) continue;
98
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
99
+ target[key] = source[key];
100
+ }
101
+ }
102
+ return target;
103
+ }
104
+ function _objectWithoutPropertiesLoose(source, excluded) {
105
+ if (source == null) return {};
106
+ var target = {};
107
+ var sourceKeys = Object.keys(source);
108
+ var key, i;
109
+ for (i = 0; i < sourceKeys.length; i++) {
110
+ key = sourceKeys[i];
111
+ if (excluded.indexOf(key) >= 0) continue;
112
+ target[key] = source[key];
113
+ }
114
+ return target;
115
+ }
116
+ const _require = require('@babel/core'),
117
+ parseSync = _require.parseSync,
118
+ transformFromAstSync = _require.transformFromAstSync;
27
119
  const inlineRequiresPlugin = require('babel-preset-fbjs/plugins/inline-requires');
28
120
  const crypto = require('crypto');
29
121
  const fs = require('fs');
30
122
  const makeHMRConfig = require('@react-native/babel-preset/src/configs/hmr');
31
123
  const nullthrows = require('nullthrows');
32
124
  const path = require('path');
33
-
34
125
  const cacheKeyParts = [
35
126
  fs.readFileSync(__filename),
36
127
  require('babel-preset-fbjs/package.json').version,
@@ -40,7 +131,6 @@ const cacheKeyParts = [
40
131
  function isTypeScriptSource(fileName /*: string */) {
41
132
  return !!fileName && fileName.endsWith('.ts');
42
133
  }
43
-
44
134
  function isTSXSource(fileName /*: string */) {
45
135
  return !!fileName && fileName.endsWith('.tsx');
46
136
  }
@@ -55,20 +145,17 @@ const getBabelRC = (function () {
55
145
 
56
146
  /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
57
147
  * LTI update could not be added via codemod */
58
- return function _getBabelRC({
59
- projectRoot,
60
- extendsBabelConfigPath,
61
- ...options
62
- }) {
148
+ return function _getBabelRC(_ref) {
149
+ let projectRoot = _ref.projectRoot,
150
+ extendsBabelConfigPath = _ref.extendsBabelConfigPath,
151
+ options = _objectWithoutProperties(_ref, _excluded);
63
152
  if (babelRC != null) {
64
153
  return babelRC;
65
154
  }
66
-
67
155
  babelRC = {
68
156
  plugins: [],
69
157
  extends: extendsBabelConfigPath,
70
158
  };
71
-
72
159
  if (extendsBabelConfigPath) {
73
160
  return babelRC;
74
161
  }
@@ -80,7 +167,6 @@ const getBabelRC = (function () {
80
167
  if (projectRoot) {
81
168
  projectBabelRCPath = path.resolve(projectRoot, '.babelrc');
82
169
  }
83
-
84
170
  if (projectBabelRCPath) {
85
171
  // .babelrc.js
86
172
  if (!fs.existsSync(projectBabelRCPath)) {
@@ -105,22 +191,29 @@ const getBabelRC = (function () {
105
191
  // $FlowFixMe[incompatible-use] `extends` is missing in null or undefined.
106
192
  // $FlowFixMe[incompatible-type] `extends` is missing in null or undefined.
107
193
  if (!babelRC.extends) {
108
- const {experimentalImportSupport, ...presetOptions} = options;
194
+ const experimentalImportSupport = options.experimentalImportSupport,
195
+ presetOptions = _objectWithoutProperties(options, _excluded2);
109
196
 
110
197
  // $FlowFixMe[incompatible-use] `presets` is missing in null or undefined.
111
198
  babelRC.presets = [
112
199
  [
113
200
  require('@react-native/babel-preset'),
114
- {
115
- projectRoot,
116
- ...presetOptions,
117
- disableImportExportTransform: experimentalImportSupport,
118
- enableBabelRuntime: options.enableBabelRuntime,
119
- },
201
+ _objectSpread(
202
+ _objectSpread(
203
+ {
204
+ projectRoot,
205
+ },
206
+ presetOptions,
207
+ ),
208
+ {},
209
+ {
210
+ disableImportExportTransform: experimentalImportSupport,
211
+ enableBabelRuntime: options.enableBabelRuntime,
212
+ },
213
+ ),
120
214
  ],
121
215
  ];
122
216
  }
123
-
124
217
  return babelRC;
125
218
  };
126
219
  })();
@@ -137,7 +230,6 @@ function buildBabelConfig(
137
230
  plugins /*:: ?: Plugins*/ = [],
138
231
  ) /*: BabelCoreOptions*/ {
139
232
  const babelRC = getBabelRC(options);
140
-
141
233
  const extraConfig /*: BabelCoreOptions */ = {
142
234
  babelrc:
143
235
  typeof options.enableBabelRCLookup === 'boolean'
@@ -148,24 +240,20 @@ function buildBabelConfig(
148
240
  filename,
149
241
  highlightCode: true,
150
242
  };
151
-
152
- let config /*: BabelCoreOptions */ = {
153
- ...babelRC,
154
- ...extraConfig,
155
- };
243
+ let config /*: BabelCoreOptions */ = _objectSpread(
244
+ _objectSpread({}, babelRC),
245
+ extraConfig,
246
+ );
156
247
 
157
248
  // Add extra plugins
158
249
  const extraPlugins = [];
159
-
160
250
  if (options.inlineRequires) {
161
251
  extraPlugins.push(inlineRequiresPlugin);
162
252
  }
163
-
164
253
  const withExtrPlugins = (config.plugins = extraPlugins.concat(
165
254
  config.plugins,
166
255
  plugins,
167
256
  ));
168
-
169
257
  if (options.dev && options.hot) {
170
258
  // Note: this intentionally doesn't include the path separator because
171
259
  // I'm not sure which one it should use on Windows, and false positives
@@ -174,20 +262,14 @@ function buildBabelConfig(
174
262
  // the first one often won't be there.
175
263
  const mayContainEditableReactComponents =
176
264
  filename.indexOf('node_modules') === -1;
177
-
178
265
  if (mayContainEditableReactComponents) {
179
266
  const hmrConfig = makeHMRConfig();
180
267
  hmrConfig.plugins = withExtrPlugins.concat(hmrConfig.plugins);
181
- config = {...config, ...hmrConfig};
268
+ config = _objectSpread(_objectSpread({}, config), hmrConfig);
182
269
  }
183
270
  }
184
-
185
- return {
186
- ...babelRC,
187
- ...config,
188
- };
271
+ return _objectSpread(_objectSpread({}, babelRC), config);
189
272
  }
190
-
191
273
  const transform /*: BabelTransformer['transform'] */ = ({
192
274
  filename,
193
275
  options,
@@ -198,21 +280,30 @@ const transform /*: BabelTransformer['transform'] */ = ({
198
280
  process.env.BABEL_ENV = options.dev
199
281
  ? 'development'
200
282
  : process.env.BABEL_ENV || 'production';
201
-
202
283
  try {
203
- const babelConfig = {
204
- // ES modules require sourceType='module' but OSS may not always want that
205
- sourceType: 'unambiguous',
206
- ...buildBabelConfig(filename, options, plugins),
207
- caller: {name: 'metro', bundler: 'metro', platform: options.platform},
208
- ast: true,
209
-
210
- // NOTE(EvanBacon): We split the parse/transform steps up to accommodate
211
- // Hermes parsing, but this defaults to cloning the AST which increases
212
- // the transformation time by a fair amount.
213
- // You get this behavior by default when using Babel's `transform` method directly.
214
- cloneInputAst: false,
215
- };
284
+ const babelConfig = _objectSpread(
285
+ _objectSpread(
286
+ {
287
+ // ES modules require sourceType='module' but OSS may not always want that
288
+ sourceType: 'unambiguous',
289
+ },
290
+ buildBabelConfig(filename, options, plugins),
291
+ ),
292
+ {},
293
+ {
294
+ caller: {
295
+ name: 'metro',
296
+ bundler: 'metro',
297
+ platform: options.platform,
298
+ },
299
+ ast: true,
300
+ // NOTE(EvanBacon): We split the parse/transform steps up to accommodate
301
+ // Hermes parsing, but this defaults to cloning the AST which increases
302
+ // the transformation time by a fair amount.
303
+ // You get this behavior by default when using Babel's `transform` method directly.
304
+ cloneInputAst: false,
305
+ },
306
+ );
216
307
  const sourceAst =
217
308
  isTypeScriptSource(filename) ||
218
309
  isTSXSource(filename) ||
@@ -222,7 +313,6 @@ const transform /*: BabelTransformer['transform'] */ = ({
222
313
  babel: true,
223
314
  sourceType: babelConfig.sourceType,
224
315
  });
225
-
226
316
  const result /*: TransformResult<MetroBabelFileMetadata> */ =
227
317
  transformFromAstSync(sourceAst, src, babelConfig);
228
318
 
@@ -230,26 +320,27 @@ const transform /*: BabelTransformer['transform'] */ = ({
230
320
  if (!result) {
231
321
  /* $FlowFixMe BabelTransformer specifies that the `ast` can never be null but
232
322
  * the function returns here. Discovered when typing `BabelNode`. */
233
- return {ast: null};
323
+ return {
324
+ ast: null,
325
+ };
234
326
  }
235
-
236
- return {ast: nullthrows(result.ast), metadata: result.metadata};
327
+ return {
328
+ ast: nullthrows(result.ast),
329
+ metadata: result.metadata,
330
+ };
237
331
  } finally {
238
332
  if (OLD_BABEL_ENV) {
239
333
  process.env.BABEL_ENV = OLD_BABEL_ENV;
240
334
  }
241
335
  }
242
336
  };
243
-
244
337
  function getCacheKey() {
245
338
  var key = crypto.createHash('md5');
246
339
  cacheKeyParts.forEach(part => key.update(part));
247
340
  return key.digest('hex');
248
341
  }
249
-
250
342
  const babelTransformer /*: BabelTransformer */ = {
251
343
  transform,
252
344
  getCacheKey,
253
345
  };
254
-
255
346
  module.exports = babelTransformer;
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ * @format
9
+ * @oncall react_native
10
+ */
11
+
12
+ // This file uses Flow comment syntax so that it may be used from source as a
13
+ // transformer without itself requiring transformation, such as in
14
+ // facebook/react-native's own tests.
15
+
16
+ 'use strict';
17
+
18
+ /*::
19
+ import type {BabelCoreOptions, Plugins, TransformResult} from '@babel/core';
20
+ import type {
21
+ BabelTransformer,
22
+ MetroBabelFileMetadata,
23
+ } from 'metro-babel-transformer';
24
+ */
25
+
26
+ const {parseSync, transformFromAstSync} = require('@babel/core');
27
+ const inlineRequiresPlugin = require('babel-preset-fbjs/plugins/inline-requires');
28
+ const crypto = require('crypto');
29
+ const fs = require('fs');
30
+ const makeHMRConfig = require('@react-native/babel-preset/src/configs/hmr');
31
+ const nullthrows = require('nullthrows');
32
+ const path = require('path');
33
+
34
+ const cacheKeyParts = [
35
+ fs.readFileSync(__filename),
36
+ require('babel-preset-fbjs/package.json').version,
37
+ ];
38
+
39
+ // TS detection conditions copied from @react-native/babel-preset
40
+ function isTypeScriptSource(fileName /*: string */) {
41
+ return !!fileName && fileName.endsWith('.ts');
42
+ }
43
+
44
+ function isTSXSource(fileName /*: string */) {
45
+ return !!fileName && fileName.endsWith('.tsx');
46
+ }
47
+
48
+ /**
49
+ * Return a memoized function that checks for the existence of a
50
+ * project level .babelrc file, and if it doesn't exist, reads the
51
+ * default RN babelrc file and uses that.
52
+ */
53
+ const getBabelRC = (function () {
54
+ let babelRC /*: ?BabelCoreOptions */ = null;
55
+
56
+ /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
57
+ * LTI update could not be added via codemod */
58
+ return function _getBabelRC({
59
+ projectRoot,
60
+ extendsBabelConfigPath,
61
+ ...options
62
+ }) {
63
+ if (babelRC != null) {
64
+ return babelRC;
65
+ }
66
+
67
+ babelRC = {
68
+ plugins: [],
69
+ extends: extendsBabelConfigPath,
70
+ };
71
+
72
+ if (extendsBabelConfigPath) {
73
+ return babelRC;
74
+ }
75
+
76
+ // Let's look for a babel config file in the project root.
77
+ let projectBabelRCPath;
78
+
79
+ // .babelrc
80
+ if (projectRoot) {
81
+ projectBabelRCPath = path.resolve(projectRoot, '.babelrc');
82
+ }
83
+
84
+ if (projectBabelRCPath) {
85
+ // .babelrc.js
86
+ if (!fs.existsSync(projectBabelRCPath)) {
87
+ projectBabelRCPath = path.resolve(projectRoot, '.babelrc.js');
88
+ }
89
+
90
+ // babel.config.js
91
+ if (!fs.existsSync(projectBabelRCPath)) {
92
+ projectBabelRCPath = path.resolve(projectRoot, 'babel.config.js');
93
+ }
94
+
95
+ // If we found a babel config file, extend our config off of it
96
+ // otherwise the default config will be used
97
+ if (fs.existsSync(projectBabelRCPath)) {
98
+ // $FlowFixMe[incompatible-use] `extends` is missing in null or undefined.
99
+ babelRC.extends = projectBabelRCPath;
100
+ }
101
+ }
102
+
103
+ // If a babel config file doesn't exist in the project then
104
+ // the default preset for react-native will be used instead.
105
+ // $FlowFixMe[incompatible-use] `extends` is missing in null or undefined.
106
+ // $FlowFixMe[incompatible-type] `extends` is missing in null or undefined.
107
+ if (!babelRC.extends) {
108
+ const {experimentalImportSupport, ...presetOptions} = options;
109
+
110
+ // $FlowFixMe[incompatible-use] `presets` is missing in null or undefined.
111
+ babelRC.presets = [
112
+ [
113
+ require('@react-native/babel-preset'),
114
+ {
115
+ projectRoot,
116
+ ...presetOptions,
117
+ disableImportExportTransform: experimentalImportSupport,
118
+ enableBabelRuntime: options.enableBabelRuntime,
119
+ },
120
+ ],
121
+ ];
122
+ }
123
+
124
+ return babelRC;
125
+ };
126
+ })();
127
+
128
+ /**
129
+ * Given a filename and options, build a Babel
130
+ * config object with the appropriate plugins.
131
+ */
132
+ function buildBabelConfig(
133
+ filename /*: string */,
134
+ /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
135
+ * LTI update could not be added via codemod */
136
+ options,
137
+ plugins /*:: ?: Plugins*/ = [],
138
+ ) /*: BabelCoreOptions*/ {
139
+ const babelRC = getBabelRC(options);
140
+
141
+ const extraConfig /*: BabelCoreOptions */ = {
142
+ babelrc:
143
+ typeof options.enableBabelRCLookup === 'boolean'
144
+ ? options.enableBabelRCLookup
145
+ : true,
146
+ code: false,
147
+ cwd: options.projectRoot,
148
+ filename,
149
+ highlightCode: true,
150
+ };
151
+
152
+ let config /*: BabelCoreOptions */ = {
153
+ ...babelRC,
154
+ ...extraConfig,
155
+ };
156
+
157
+ // Add extra plugins
158
+ const extraPlugins = [];
159
+
160
+ if (options.inlineRequires) {
161
+ extraPlugins.push(inlineRequiresPlugin);
162
+ }
163
+
164
+ const withExtrPlugins = (config.plugins = extraPlugins.concat(
165
+ config.plugins,
166
+ plugins,
167
+ ));
168
+
169
+ if (options.dev && options.hot) {
170
+ // Note: this intentionally doesn't include the path separator because
171
+ // I'm not sure which one it should use on Windows, and false positives
172
+ // are unlikely anyway. If you later decide to include the separator,
173
+ // don't forget that the string usually *starts* with "node_modules" so
174
+ // the first one often won't be there.
175
+ const mayContainEditableReactComponents =
176
+ filename.indexOf('node_modules') === -1;
177
+
178
+ if (mayContainEditableReactComponents) {
179
+ const hmrConfig = makeHMRConfig();
180
+ hmrConfig.plugins = withExtrPlugins.concat(hmrConfig.plugins);
181
+ config = {...config, ...hmrConfig};
182
+ }
183
+ }
184
+
185
+ return {
186
+ ...babelRC,
187
+ ...config,
188
+ };
189
+ }
190
+
191
+ const transform /*: BabelTransformer['transform'] */ = ({
192
+ filename,
193
+ options,
194
+ src,
195
+ plugins,
196
+ }) => {
197
+ const OLD_BABEL_ENV = process.env.BABEL_ENV;
198
+ process.env.BABEL_ENV = options.dev
199
+ ? 'development'
200
+ : process.env.BABEL_ENV || 'production';
201
+
202
+ try {
203
+ const babelConfig = {
204
+ // ES modules require sourceType='module' but OSS may not always want that
205
+ sourceType: 'unambiguous',
206
+ ...buildBabelConfig(filename, options, plugins),
207
+ caller: {name: 'metro', bundler: 'metro', platform: options.platform},
208
+ ast: true,
209
+
210
+ // NOTE(EvanBacon): We split the parse/transform steps up to accommodate
211
+ // Hermes parsing, but this defaults to cloning the AST which increases
212
+ // the transformation time by a fair amount.
213
+ // You get this behavior by default when using Babel's `transform` method directly.
214
+ cloneInputAst: false,
215
+ };
216
+ const sourceAst =
217
+ isTypeScriptSource(filename) ||
218
+ isTSXSource(filename) ||
219
+ !options.hermesParser
220
+ ? parseSync(src, babelConfig)
221
+ : require('hermes-parser').parse(src, {
222
+ babel: true,
223
+ sourceType: babelConfig.sourceType,
224
+ });
225
+
226
+ const result /*: TransformResult<MetroBabelFileMetadata> */ =
227
+ transformFromAstSync(sourceAst, src, babelConfig);
228
+
229
+ // The result from `transformFromAstSync` can be null (if the file is ignored)
230
+ if (!result) {
231
+ /* $FlowFixMe BabelTransformer specifies that the `ast` can never be null but
232
+ * the function returns here. Discovered when typing `BabelNode`. */
233
+ return {ast: null};
234
+ }
235
+
236
+ return {ast: nullthrows(result.ast), metadata: result.metadata};
237
+ } finally {
238
+ if (OLD_BABEL_ENV) {
239
+ process.env.BABEL_ENV = OLD_BABEL_ENV;
240
+ }
241
+ }
242
+ };
243
+
244
+ function getCacheKey() {
245
+ var key = crypto.createHash('md5');
246
+ cacheKeyParts.forEach(part => key.update(part));
247
+ return key.digest('hex');
248
+ }
249
+
250
+ const babelTransformer /*: BabelTransformer */ = {
251
+ transform,
252
+ getCacheKey,
253
+ };
254
+
255
+ module.exports = babelTransformer;