@parcel/transformer-babel 2.0.0-nightly.142 → 2.0.0-nightly.1421

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/flow.js CHANGED
@@ -1,19 +1,66 @@
1
1
  // @flow
2
2
 
3
- import type {Config} from '@parcel/types';
3
+ import type {Config, PluginOptions, PackageJSON} from '@parcel/types';
4
4
  import type {BabelConfig} from './types';
5
+ import typeof * as BabelCore from '@babel/core';
6
+
7
+ import {BABEL_CORE_RANGE} from './constants';
8
+ import path from 'path';
5
9
 
6
10
  /**
7
11
  * Generates a babel config for stripping away Flow types.
8
12
  */
9
- export default function getFlowOptions(config: Config): ?BabelConfig {
13
+ export default async function getFlowOptions(
14
+ config: Config,
15
+ options: PluginOptions,
16
+ ): Promise<?BabelConfig> {
10
17
  if (!config.isSource) {
11
18
  return null;
12
19
  }
13
20
 
21
+ // Only add flow plugin if `flow-bin` is listed as a dependency in the root package.json
22
+ let conf = await config.getConfigFrom<PackageJSON>(
23
+ options.projectRoot + '/index',
24
+ ['package.json'],
25
+ );
26
+ let pkg = conf?.contents;
27
+ if (
28
+ !pkg ||
29
+ (!(pkg.dependencies && pkg.dependencies['flow-bin']) &&
30
+ !(pkg.devDependencies && pkg.devDependencies['flow-bin']))
31
+ ) {
32
+ return null;
33
+ }
34
+
35
+ const babelCore: BabelCore = await options.packageManager.require(
36
+ '@babel/core',
37
+ config.searchPath,
38
+ {
39
+ range: BABEL_CORE_RANGE,
40
+ saveDev: true,
41
+ shouldAutoInstall: options.shouldAutoInstall,
42
+ },
43
+ );
44
+
45
+ await options.packageManager.require(
46
+ '@babel/plugin-transform-flow-strip-types',
47
+ config.searchPath,
48
+ {
49
+ range: '^7.0.0',
50
+ saveDev: true,
51
+ shouldAutoInstall: options.shouldAutoInstall,
52
+ },
53
+ );
54
+
14
55
  return {
15
56
  plugins: [
16
- ['@babel/plugin-transform-flow-strip-types', {requireDirective: true}],
57
+ babelCore.createConfigItem(
58
+ ['@babel/plugin-transform-flow-strip-types', {requireDirective: true}],
59
+ {
60
+ type: 'plugin',
61
+ dirname: path.dirname(config.searchPath),
62
+ },
63
+ ),
17
64
  ],
18
65
  };
19
66
  }
package/src/jsx.js CHANGED
@@ -1,55 +1,40 @@
1
- // @flow
2
- import type {Config} from '@parcel/types';
3
- import path from 'path';
1
+ // @flow strict-local
2
+
3
+ import type {Config, PluginOptions} from '@parcel/types';
4
4
 
5
- const JSX_EXTENSIONS = {
6
- '.jsx': true,
7
- '.tsx': true,
8
- };
5
+ import path from 'path';
9
6
 
10
- const JSX_PRAGMA = {
11
- react: {
12
- pragma: 'React.createElement',
13
- pragmaFrag: 'React.Fragment',
14
- },
15
- preact: {
16
- pragma: 'h',
17
- pragmaFrag: 'Fragment',
18
- },
19
- nervjs: {
20
- pragma: 'Nerv.createElement',
21
- pragmaFrag: undefined,
22
- },
23
- hyperapp: {
24
- pragma: 'h',
25
- pragmaFrag: undefined,
26
- },
27
- };
7
+ const JSX_EXTENSIONS = new Set(['.jsx', '.tsx']);
8
+ const JSX_LIBRARIES = ['react', 'preact', 'nervejs', 'hyperapp'];
28
9
 
29
10
  /**
30
- * Generates a babel config for JSX. Attempts to detect react or react-like libraries
31
- * and changes the pragma accordingly.
11
+ * Returns whether an asset is likely JSX. Attempts to detect react or react-like libraries
12
+ * along with
32
13
  */
33
- export default async function getJSXOptions(config: Config) {
14
+ export default async function isJSX(
15
+ options: PluginOptions,
16
+ config: Config,
17
+ ): Promise<boolean> {
34
18
  if (!config.isSource) {
35
- return null;
19
+ return false;
36
20
  }
37
21
 
38
- // Find a dependency that we can map to a JSX pragma
39
- const pkg = await config.getPackage();
40
- const reactLib = Object.keys(JSX_PRAGMA).find(
41
- libName =>
42
- pkg &&
43
- ((pkg.dependencies && pkg.dependencies[libName]) ||
44
- (pkg.devDependencies && pkg.devDependencies[libName])),
45
- );
46
-
47
- const pragma = reactLib ? JSX_PRAGMA[reactLib].pragma : undefined;
48
- const pragmaFrag = reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined;
22
+ if (JSX_EXTENSIONS.has(path.extname(config.searchPath))) {
23
+ return true;
24
+ }
49
25
 
50
- if (pragma || JSX_EXTENSIONS[path.extname(config.searchPath)]) {
51
- return {
52
- plugins: [['@babel/plugin-transform-react-jsx', {pragma, pragmaFrag}]],
53
- };
26
+ let pkg = await config.getPackage();
27
+ if (pkg?.alias && pkg.alias['react']) {
28
+ // e.g.: `{ alias: { "react": "preact/compat" } }`
29
+ return true;
30
+ } else {
31
+ // Find a dependency that implies JSX syntax.
32
+ return JSX_LIBRARIES.some(
33
+ libName =>
34
+ pkg &&
35
+ ((pkg.dependencies && pkg.dependencies[libName]) ||
36
+ (pkg.devDependencies && pkg.devDependencies[libName]) ||
37
+ (pkg.peerDependencies && pkg.peerDependencies[libName])),
38
+ );
54
39
  }
55
40
  }
@@ -0,0 +1,70 @@
1
+ // @flow strict-local
2
+
3
+ import type {File as BabelNodeFile} from '@babel/types';
4
+ import type SourceMap from '@parcel/source-map';
5
+ import type {Node} from '@babel/types';
6
+ import typeof * as BabelTypes from '@babel/types';
7
+
8
+ export function remapAstLocations(
9
+ t: BabelTypes,
10
+ ast: BabelNodeFile,
11
+ map: SourceMap,
12
+ ) {
13
+ // remap ast to original mappings
14
+ // This improves sourcemap accuracy and fixes sourcemaps when scope-hoisting
15
+ traverseAll(t, ast.program, node => {
16
+ if (node.loc) {
17
+ if (node.loc?.start) {
18
+ let mapping = map.findClosestMapping(
19
+ node.loc.start.line,
20
+ node.loc.start.column,
21
+ );
22
+
23
+ if (mapping?.original) {
24
+ // $FlowFixMe
25
+ node.loc.start.line = mapping.original.line;
26
+ // $FlowFixMe
27
+ node.loc.start.column = mapping.original.column;
28
+
29
+ // $FlowFixMe
30
+ let length = node.loc.end.column - node.loc.start.column;
31
+
32
+ // $FlowFixMe
33
+ node.loc.end.line = mapping.original.line;
34
+ // $FlowFixMe
35
+ node.loc.end.column = mapping.original.column + length;
36
+
37
+ // $FlowFixMe
38
+ node.loc.filename = mapping.source;
39
+ } else {
40
+ // Maintain null mappings?
41
+ node.loc = null;
42
+ }
43
+ }
44
+ }
45
+ });
46
+ }
47
+
48
+ function traverseAll(
49
+ t: BabelTypes,
50
+ node: Node,
51
+ visitor: (node: Node) => void,
52
+ ): void {
53
+ if (!node) {
54
+ return;
55
+ }
56
+
57
+ visitor(node);
58
+
59
+ for (let key of t.VISITOR_KEYS[node.type] || []) {
60
+ // $FlowFixMe
61
+ let subNode: Node | Array<Node> = node[key];
62
+ if (Array.isArray(subNode)) {
63
+ for (let i = 0; i < subNode.length; i++) {
64
+ traverseAll(t, subNode[i], visitor);
65
+ }
66
+ } else {
67
+ traverseAll(t, subNode, visitor);
68
+ }
69
+ }
70
+ }
package/src/types.js CHANGED
@@ -4,10 +4,3 @@ export type BabelConfig = {|
4
4
  plugins?: Array<any>,
5
5
  presets?: Array<any>,
6
6
  |};
7
-
8
- export type BabelTargets = {
9
- browsers?: string | Array<string>,
10
- esmodules?: boolean,
11
- [string]: string,
12
- ...
13
- };
package/src/utils.js CHANGED
@@ -1,11 +1,26 @@
1
1
  // @flow
2
2
 
3
3
  import type {Environment} from '@parcel/types';
4
- import type {BabelTargets} from './types';
4
+ import type {Targets as BabelTargets} from '@babel/preset-env';
5
5
 
6
6
  import invariant from 'assert';
7
7
  import semver from 'semver';
8
- import {TargetNames} from '@babel/helper-compilation-targets/lib/options';
8
+
9
+ // Copied from @babel/helper-compilation-targets/lib/options.js
10
+ const TargetNames = {
11
+ node: 'node',
12
+ chrome: 'chrome',
13
+ opera: 'opera',
14
+ edge: 'edge',
15
+ firefox: 'firefox',
16
+ safari: 'safari',
17
+ ie: 'ie',
18
+ ios: 'ios',
19
+ android: 'android',
20
+ electron: 'electron',
21
+ samsung: 'samsung',
22
+ rhino: 'rhino',
23
+ };
9
24
 
10
25
  // List of browsers to exclude when the esmodule target is specified.
11
26
  // Based on https://caniuse.com/#feat=es6-module
@@ -47,7 +62,7 @@ export function enginesToBabelTargets(env: Environment): BabelTargets {
47
62
  } else {
48
63
  invariant(typeof engineValue === 'string');
49
64
  if (!TargetNames.hasOwnProperty(engineName)) continue;
50
- let minVersion = getMinSemver(engineValue);
65
+ let minVersion = semver.minVersion(engineValue)?.toString();
51
66
  targets[engineName] = minVersion ?? engineValue;
52
67
  }
53
68
  }
@@ -69,15 +84,3 @@ export function enginesToBabelTargets(env: Environment): BabelTargets {
69
84
 
70
85
  return targets;
71
86
  }
72
-
73
- // TODO: Replace with `minVersion` (https://github.com/npm/node-semver#ranges-1)
74
- // once semver has been upgraded across Parcel.
75
- export function getMinSemver(version: string) {
76
- try {
77
- let range = new semver.Range(version);
78
- let sorted = range.set.sort((a, b) => a[0].semver.compare(b[0].semver));
79
- return sorted[0][0].semver.version;
80
- } catch (err) {
81
- return null;
82
- }
83
- }
@@ -1,106 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.babel7toBabel6 = babel7toBabel6;
7
- exports.babel6toBabel7 = babel6toBabel7;
8
-
9
- var _traverse = _interopRequireDefault(require("@babel/traverse"));
10
-
11
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
-
13
- // Convert between babel 7 and babel 6 AST
14
- // More info on the AST Changes: https://babeljs.io/docs/en/v7-migration-api#ast-changes
15
- function babel7toBabel6(ast) {
16
- const visitor = {
17
- ArrowFunctionExpression: node => {
18
- node.expression = node.body.type !== 'BlockStatement';
19
- },
20
- ExistsTypeAnnotation: node => {
21
- node.type = 'ExistentialTypeParam';
22
- },
23
- NumberLiteralTypeAnnotation: node => {
24
- node.type = 'NumericLiteralTypeAnnotation';
25
- },
26
- ObjectTypeIndexer: node => {
27
- node.end++;
28
- node.loc.end.column++;
29
- },
30
- ForOfStatement: node => {
31
- node.type = 'ForAwaitStatement';
32
- delete node.await;
33
- },
34
- SpreadElement: (node, path) => {
35
- if (path.parentPath.isObjectExpression() || path.parentPath.isArrayExpression()) {
36
- node.type = 'SpreadProperty';
37
- }
38
- },
39
- RestElement: (node, path) => {
40
- if (path.parentPath.isObjectPattern() || path.parentPath.isArrayPattern()) {
41
- node.type = 'RestProperty';
42
- }
43
- }
44
- };
45
- (0, _traverse.default)(ast, {
46
- enter(path) {
47
- if (path.node.variance && path.node.variance.type === 'Variance') {
48
- path.node.variance = path.node.variance.kind;
49
- }
50
-
51
- let visitorFunc = visitor[path.node.type];
52
-
53
- if (visitorFunc) {
54
- visitorFunc(path.node, path);
55
- }
56
- }
57
-
58
- });
59
- return ast;
60
- }
61
-
62
- function babel6toBabel7(ast) {
63
- const visitor = {
64
- ArrowFunctionExpression: node => {
65
- delete node.expression;
66
- },
67
- ExistentialTypeParam: node => {
68
- node.type = 'ExistsTypeAnnotation';
69
- },
70
- NumericLiteralTypeAnnotation: node => {
71
- node.type = 'NumberLiteralTypeAnnotation';
72
- },
73
- ObjectTypeIndexer: node => {
74
- node.end--;
75
- node.loc.end.column--;
76
- },
77
- ForAwaitStatement: node => {
78
- node.type = 'ForOfStatement';
79
- node.await = true;
80
- },
81
- SpreadProperty: node => {
82
- node.type = 'SpreadElement';
83
- },
84
- RestProperty: node => {
85
- node.type = 'RestElement';
86
- }
87
- };
88
- (0, _traverse.default)(ast, {
89
- enter(path) {
90
- if (path.node.variance && typeof path.node.variance === 'string') {
91
- path.node.variance = {
92
- type: 'VarianceNode',
93
- kind: path.node.variance
94
- };
95
- }
96
-
97
- let visitorFunc = visitor[path.node.type];
98
-
99
- if (visitorFunc) {
100
- visitorFunc(path.node);
101
- }
102
- }
103
-
104
- });
105
- return ast;
106
- }
package/lib/babel6.js DELETED
@@ -1,47 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = babel6;
7
-
8
- var _astConverter = require("./astConverter");
9
-
10
- async function babel6(asset, options, babelOptions) {
11
- let babel = await options.packageManager.require('babel-core', asset.filePath);
12
- let config = babelOptions.config;
13
- config.code = false;
14
- config.ast = true;
15
- config.filename = asset.filePath;
16
- config.babelrc = false;
17
- config.parserOpts = Object.assign({}, config.parserOpts, {
18
- allowReturnOutsideFunction: true,
19
- allowHashBang: true,
20
- ecmaVersion: Infinity,
21
- strictMode: false,
22
- sourceType: 'module',
23
- locations: true
24
- }); // Passing a list of plugins as part of parserOpts seems to override any custom
25
- // syntax plugins a user might have added (e.g. decorators). We add dynamicImport
26
- // using a plugin instead.
27
-
28
- config.plugins = (config.plugins || []).concat(dynamicImport);
29
- let res = babel.transform((await asset.getCode()), config);
30
-
31
- if (res.ast) {
32
- return {
33
- type: 'babel',
34
- version: '7.0.0',
35
- program: (0, _astConverter.babel6toBabel7)(res.ast)
36
- };
37
- }
38
- }
39
-
40
- function dynamicImport() {
41
- return {
42
- manipulateOptions(opts, parserOpts) {
43
- parserOpts.plugins.push('dynamicImport');
44
- }
45
-
46
- };
47
- }
package/lib/env.js DELETED
@@ -1,63 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = getEnvOptions;
7
-
8
- var _presetEnv = _interopRequireDefault(require("@babel/preset-env"));
9
-
10
- var _getBabelTargets = _interopRequireDefault(require("./getBabelTargets"));
11
-
12
- var _utils = require("./utils");
13
-
14
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
-
16
- /**
17
- * Generates a @babel/preset-env config for an asset.
18
- * This is done by finding the source module's target engines, and the app's
19
- * target engines, and doing a diff to include only the necessary plugins.
20
- */
21
- async function getEnvOptions(config) {
22
- // Load the target engines for the app and generate a @babel/preset-env config
23
- let appBabelTargets = (0, _utils.enginesToBabelTargets)(config.env); // If this is the app module, the source and target will be the same, so just compile everything.
24
- // Otherwise, load the source engines and generate a babel-present-env config.
25
-
26
- if (!config.isSource) {
27
- let sourceBabelTargets = await (0, _getBabelTargets.default)(config);
28
-
29
- if (!sourceBabelTargets || !shouldCompileFurther(sourceBabelTargets, appBabelTargets)) {
30
- return null;
31
- }
32
- }
33
-
34
- return {
35
- targets: appBabelTargets,
36
- presets: [['@parcel/babel-preset-env', {
37
- useBuiltIns: 'entry',
38
- corejs: 3,
39
- shippedProposals: true,
40
- ignoreBrowserslistConfig: true,
41
- targets: appBabelTargets
42
- }]]
43
- };
44
- }
45
-
46
- function getNeededPlugins(targets) {
47
- return (0, _presetEnv.default)({
48
- assertVersion: () => true
49
- }, {
50
- targets: targets
51
- }).plugins.filter(p => p[0]);
52
- }
53
-
54
- function shouldCompileFurther(sourceBabelTargets, appBabelTargets) {
55
- let sourcePlugins = new Set(getNeededPlugins(sourceBabelTargets));
56
- let appPlugins = getNeededPlugins(appBabelTargets); // If there is any app plugin present that was not used to compile the source,
57
- // then the asset was built to a higher target and will need to be compiled
58
- // further
59
-
60
- return appPlugins.some(plugin => {
61
- return !sourcePlugins.has(plugin);
62
- });
63
- }
@@ -1,86 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = getBabelTargets;
7
-
8
- var _browserslist = _interopRequireDefault(require("browserslist"));
9
-
10
- var _semver = _interopRequireDefault(require("semver"));
11
-
12
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
-
14
- const BROWSER_CONTEXT = new Set(['browser', 'web-worker', 'service-worker']); // https://github.com/browserslist/browserslist/blob/04d7b3cc6ebeb62baf6d62aeb90f1bfd0c11117c/test/config.test.js#L23
15
-
16
- /**
17
- * Loads target node and browser versions from the following locations:
18
- * - package.json engines field
19
- * - package.json browserslist field
20
- * - browserslist or .browserslistrc files
21
- *
22
- * "Targets" is the name @babel/preset-env uses for what Parcel calls engines.
23
- * This should not be confused with Parcel's own targets.
24
- * Unlike Parcel's engines, @babel/preset-env expects to work with minimum
25
- * versions, not semver ranges, of its targets.
26
- */
27
- async function getBabelTargets(config) {
28
- let targets = {};
29
- let compileTarget = BROWSER_CONTEXT.has(config.env.context) ? 'browsers' : config.env.context;
30
- let pkg = await config.getPackage();
31
- let packageEngines = pkg === null || pkg === void 0 ? void 0 : pkg.engines;
32
-
33
- if (compileTarget === 'node') {
34
- let nodeVersion = packageEngines === null || packageEngines === void 0 ? void 0 : packageEngines.node; // Use package.engines.node by default if we are compiling for node.
35
-
36
- if (typeof nodeVersion === 'string') {
37
- try {
38
- //$FlowFixMe catch error when minVersion() returned null
39
- targets.node = _semver.default.minVersion(nodeVersion).version;
40
- } catch (e) {
41
- throw new Error("Expected 'node' engine to be a valid Semver Range");
42
- }
43
- }
44
- } else {
45
- let browsers;
46
-
47
- if (packageEngines && (typeof packageEngines.browsers === 'string' || Array.isArray(packageEngines.browsers))) {
48
- browsers = packageEngines.browsers;
49
- } else if (pkg && pkg.browserslist) {
50
- browsers = pkg.browserslist;
51
- } else {
52
- let browserslist = await loadBrowserslist(config);
53
-
54
- if (browserslist) {
55
- browsers = browserslist;
56
- }
57
- } // Parse browser targets
58
-
59
-
60
- if (typeof browsers === 'object' && browsers != null && !Array.isArray(browsers)) {
61
- let env = process.env.NODE_ENV || 'development';
62
- browsers = browsers[env] || browsers.defaults;
63
- }
64
-
65
- if (browsers) {
66
- targets.browsers = (0, _browserslist.default)(browsers).sort();
67
- }
68
- } // Dont compile if we couldn't find any targets
69
-
70
-
71
- if (Object.keys(targets).length === 0) {
72
- return null;
73
- }
74
-
75
- return targets;
76
- }
77
-
78
- async function loadBrowserslist(config) {
79
- let browserslistConfig = await config.getConfig(['browserslist', '.browserslistrc'], {
80
- parse: false
81
- });
82
-
83
- if (browserslistConfig) {
84
- return _browserslist.default.parseConfig(browserslistConfig);
85
- }
86
- }
package/lib/typescript.js DELETED
@@ -1,18 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = getTypescriptOptions;
7
-
8
- var _path = _interopRequireDefault(require("path"));
9
-
10
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
-
12
- function getTypescriptOptions(config) {
13
- return {
14
- plugins: [['@babel/plugin-transform-typescript', {
15
- isTSX: _path.default.extname(config.searchPath) === '.tsx'
16
- }]]
17
- };
18
- }