Compare commits

..

97 Commits

Author SHA1 Message Date
Henry Zhu
ea3f2d9299 v7.0.0-beta.40 2018-02-12 11:41:13 -05:00
Vojtěch Štěpančík
88a0f52230 Fix CLI compilation callback calling (#7366) 2018-02-12 08:10:35 -05:00
Yeonghoon Park
4a2e1dbbc3 Fix stage-3 name in README.md (#7363)
[skip-ci] Fix a typo in preset-env doc: `@babel/preset-stage-3` package name.
2018-02-11 14:04:31 +02:00
Clar Roʒe
2979dd99ac Update browserslist for babel-preset-env. (#7365) 2018-02-11 09:57:50 +02:00
Suchipi Izumi
534ee4734c Extract @babel/highlight package from @babel/code-frame
This creates a new package called @babel/highlight which syntax highlights
JavaScript code for terminal output. This functionality was already
present in @babel/code-frame, but exposing it as a separate package lets
other projects leverage it. @babel/code-frame has been refactored
slightly so that it uses @babel/highlight to do its syntax highlighting.
2018-02-09 09:31:37 +01:00
Steven Hargrove
a01007a3d3 Allow falsey, yet valid options for codeFrameColumns() (#7341)
Allow for overriding default linesAbove/linesBelow values.
2018-02-08 16:52:12 -05:00
Logan Smyth
493996e02a Merge pull request #7345 from loganfsmyth/small-bug-fixes
Small tweaks to prep for coming .babelrc lookup work
2018-02-08 13:30:49 -08:00
Justin Ridgewell
c03a34e509 Typo in nullish-coalescing-operator README.md 2018-02-08 14:34:41 -05:00
Naveen jain
92580e750d Fixes issues regarding super in optionalChain (#7356) 2018-02-08 14:31:47 -05:00
Logan Smyth
213805f21e Avoid duplicating types in index-browser. 2018-02-08 09:19:16 -08:00
Logan Smyth
28d13cb09b Fix small bug in the new .parse function. 2018-02-08 00:22:50 -08:00
Logan Smyth
9a8ba76e1f Merge .babelrc and .babelignore searching into a single pass. 2018-02-08 00:22:49 -08:00
Logan Smyth
d88173b9f8 Ensure that tests don't leave mutated global state in the environment. 2018-02-08 00:22:49 -08:00
Logan Smyth
85174b6ce1 Remove unneeded param from buildRootConfig. 2018-02-07 23:23:19 -08:00
Logan Smyth
ec2e0b664a Properly allow undefined ignore patterns for test/include/exclude. 2018-02-07 23:23:19 -08:00
Naveen jain
a3ad518ce1 [BugFix] : OptionalChaining Bug fixes (#7288)
* Added optionalExpression types to babylon and babel-types

* OptionalChain transforms bug fix

* Added OptionalExpressions to babel-generator. Fixed OptionalChain Bugs

* Removed 'optionalChain' from newExpression and added test cases

* Added test cases for optionalChain

* Update index.js
2018-02-07 19:42:14 -05:00
Nicolò Ribaudo
dd0337cc85 Fix failing test (#7344) 2018-02-06 17:42:55 -06:00
Nicolò Ribaudo
4887d81929 Remove bindings of removed paths from scope 2018-02-06 23:59:12 +01:00
Ben Newman
22555cd15d Failing test involving object rest/spread and clearScope().
This failing test case demonstrates a regression between 7.0.0-beta.38 and
7.0.0-beta.39 in the @babel/plugin-proposal-object-rest-spread package.

I distilled this test case from a larger configuration of plugins in my
application, one of which calls api.traverse.cache.clearScope(). Although
calling clearScope() is an uncommon thing for a plugin to do, it was a
reliable way to reproduce the problem. If I can find other reliable
reproductions, I'll push some additional failing tests to this PR.
Regardless of how common it is, clearing the scope cache should be a safe
operation that only slows down the transform (because scopes have to be
recreated and re-crawled). Crashing due to a spurious duplicate
declaration seems like a bug worth fixing.

My hunch is that [these two lines](eb38ea2b10/packages/babel-plugin-proposal-object-rest-spread/src/index.js (L75-L76))
(which were changed in `7.0.0-beta.39`) are not actually removing the
original rest element as a binding from the enclosing `Scope`, in certain
circumstances, so the new variable declaration ends up colliding with the
old (removed) binding.

Possibly related: #7304 (reported by @julien-f)
2018-02-06 23:59:12 +01:00
Daniel Tschinder
593c1a0861 Add core-js as valid polyfill source (#7315) 2018-02-04 17:53:54 -06:00
Kai Cataldo
7234442fde Add location information to parsing errors (#7314) 2018-02-04 13:00:03 -06:00
Justin Ridgewell
5ea1bfe780 Do not optimize away async/gen arrow functions (#7319)
* Do not optimize away async/gen arrow functions

* Node version 8
2018-02-03 17:08:12 -05:00
Tauyekel Kunzhol
2254ed45d2 [Bug fix] Reaching maximum calls stack when copying large number of non-js files in babel-cli (#7320)
Maximum call stack occurs when you try to copy large number of non-js files using `babel-cli@7.0.0-beta.38` or `babel-cli@7.0.0-beta.39`
2018-02-02 20:56:57 -08:00
Logan Smyth
278cd5e572 Preserve identifier location information when mapping this and arguments. (#7312) 2018-02-01 18:54:15 -08:00
Mathias Bynens
96c0415c86 Remove outdated sentence from README (#7311)
Unicode property escapes are now part of ECMAScript proper.

[skip ci]
2018-02-01 14:27:13 -08:00
K Sashi Kumar
ed98d2491e [Typescript] - Fix SyntaxError in async arrow functions with rest params (#7297)
* Fix: [Typescript] - SyntaxError in async arrow functions with rest params

* Fix optional params and add test code in flow
2018-01-31 21:05:24 +01:00
Henry Zhu
eb38ea2b10 Update babel to beta.39 (#7302) 2018-01-30 22:59:00 -05:00
Nicolò Ribaudo
f19d559ff3 Compile Babylon with Gulp (#7240) 2018-01-30 23:13:40 +01:00
Henry Zhu
73e64c6cb0 v7.0.0-beta.39 2018-01-30 15:27:19 -05:00
Brian Ng
3deb246c7d Add some es5 features to babel-preset-env (#6526) 2018-01-30 13:53:38 -06:00
Henry Zhu
1ebc229fa5 Revert "make babel injectable in babel-register" (#7298)
Revert "make babel injectable in babel-register"
2018-01-30 14:16:02 -05:00
Nicolò Ribaudo
cc4913699b Update packages/babylon/README.md [skip ci]
https://github.com/babel/babel/pull/7292#discussion_r164765384
2018-01-30 20:08:15 +01:00
Henry Zhu
82b6ee734b Revert "make babel injectable in babel-register" 2018-01-30 12:39:38 -05:00
Kai Cataldo
22c8f6376c babel-core: Add parse method (#7291) 2018-01-30 12:38:58 -05:00
Raja Sekar
023550c87b Docs: updated link relative to babel/babylon (#7292) [skip ci] 2018-01-30 12:05:43 -05:00
Henry Zhu
8e0d247e8c Fix: fixup package name [skip ci] 2018-01-30 12:04:52 -05:00
Naveen jain
65ae4ff15b Fix: export default decorated class parsed as class expression (#7189) 2018-01-30 12:00:29 -05:00
Owen Buckley
2185256589 update substitution placeholder message in @babel/template (#7255) 2018-01-30 11:54:31 -05:00
Mateusz Burzyński
3316a554bf Support cjs shorthand for modules option in preset-es2015 & preset-env (#7283) 2018-01-30 11:46:21 -05:00
Nicolò Ribaudo
252ea5a966 Fix reused nodes - part 2 (#7149) 2018-01-29 22:59:06 +01:00
Mateusz Burzyński
912bcc186d Fix reused nodes - part 1 (#7149) 2018-01-29 22:59:06 +01:00
Nicolò Ribaudo
63ae923987 Add t.cloneNode and deprecate t.clone and t.cloneDeep (#7149) 2018-01-29 22:59:06 +01:00
Nicolò Ribaudo
dde9274986 Disallow duplicated nodes in tests output (#7149) 2018-01-29 22:59:06 +01:00
Mauro Bringolf
ba111c13b5 Add notice on constant checks to documentation (#7279) [skip ci] 2018-01-29 09:23:01 -05:00
Sven SAULEAU
967414d926 Merge pull request #7273 from Janpot/babel-register-inject
make babel injectable in babel-register
2018-01-26 17:50:53 +01:00
Mauro Bringolf
92fc26d399 Remove check-constants plugin (#6987)
* Rebased onto new version

* Moved constants check into a separate method
2018-01-26 10:43:09 -05:00
Brian Ng
fa5eb4f605 Make comment props more consistent (#7246) 2018-01-26 10:39:52 -05:00
Jan Potoms
d6a782b09c use @babel/core 2018-01-26 16:36:29 +01:00
Jan Potoms
567d25cfa5 Document the feature 2018-01-26 08:38:16 +01:00
Jan Potoms
1da831baa4 improve spec 2018-01-25 10:26:21 +01:00
Jan Potoms
b0d8c62d1c Fix issue where babel was retained 2018-01-25 10:18:02 +01:00
Jan Potoms
0e570eceb2 make babel injectable in babel-register 2018-01-25 08:16:34 +01:00
Justin Ridgewell
ca18ea5e79 Re-add optional chaining delete (#7257)
* Re-add optional chaining delete

* Move exec tests next to output tests

* Forgot to commit these
2018-01-24 11:26:02 -08:00
Alexander Pepper
63d9998aa4 babel-preset-env: Fixed links in readme and improved "Built-ins" example (#7271) 2018-01-24 10:02:03 -06:00
Raja Sekar
88e550c733 removed plugin transform eval (#7262) 2018-01-23 17:31:45 -05:00
Andy
b96fdf8780 typescript: Fix enum emit when values are strings (#7160) 2018-01-23 15:42:32 -06:00
Justin Ridgewell
180eda3211 Remove old optional chain features (#6345) 2018-01-22 14:03:43 -08:00
Kristofer Baxter
b3969d35fa Add preset-env target esmodules (#7212) 2018-01-22 15:44:10 -06:00
Andy
dccfed3601 TypeScript: Support parsing 'unique' type operator (#7239) 2018-01-22 16:09:22 -05:00
Jamie Kyle
5759c33b4c Add opts.message option to code frames (#7243)
* Add opts.message option to code frames

* Fix for missing loc.start in code-frame

* Add docs
2018-01-21 14:19:20 +11:00
Brian Ng
193bccc93c Ensure isPureAnnotated returns a boolean 2018-01-20 13:42:49 -06:00
Brian Ng
5ce54799ff Tweak and add tests to babel-helper-annotate-as-pure (#7245) 2018-01-20 13:29:38 -05:00
Brian Ng
064c17e03f Bump prettier and related deps (#7244) 2018-01-20 17:00:21 +01:00
Matt Ziemer
f9804e6beb Add 'loose' option link for babel-preset-env (#7241)
- Added a external link to a good explanation of “loose” transformations.
http://2ality.com/2015/12/babel6-loose-mode.html
2018-01-20 14:34:52 +02:00
Henry Zhu
47ce7e71c9 Update to beta.38 (#7231) 2018-01-17 18:03:11 -05:00
Luca
5ac8ba19a4 Fix typo [skip ci] (#7229) 2018-01-17 13:43:59 -05:00
Henry Zhu
b5d20ab171 v7.0.0-beta.38 2018-01-17 11:31:32 -05:00
Henry Zhu
539009a980 Remove old command [skip ci] 2018-01-17 10:59:53 -05:00
Boris Cherny
c3654d83c8 Generate TypeScript typings, and improve generated Flow typings (#7101)
* generate typescript types

* improve type generator output

* move generator scripts to scripts/generators

* use new stringifier for generating flow types too

* export summary types

* add support for oneOfNodeOrValueTypes to improve type generation

* export typescript types from top level, and remove module declaration

* generate typescript/flow types and copy typescript types to babel-types/lib as part of make build

* copy flow types to babel-types/lib as part of make build (fix #6839)

* improve typing: Identifier->name should be a string, not any

* avoid destructuring, to support node 4

* update doc generator to share more code, regenerate babel-types readme, pipe all generator output to stdout

* regenerate babel-types readme as part of make build

* improve typing: ClassProperty->key should be Identifier | StringLiteral | NumericLiteral | Expression, not any

* improve typing: optional node properties are nullable, not undefinedable

* improve docs: FlowClassImplements should be ClassImplements

* make ts usage more friendly: when using babel-types api, make optional params | undefined, and when reading nodes keep optional params | null

* rm lib/types.d.ts and lib/types.js in favor of packages/babel-types/lib

* add missing variance node type, address review comments

* add tests for flow variance

* Comment should be a disjoint union of tagged types

* update .flowconfig
2018-01-17 10:31:46 -05:00
Andy
667f5815c1 typescript: Properly set this.state.inType one token before parsing a type (#7225)
* typescript: Properly set this.state.inType one token before parsing a type

* Reuse tsParseTypeArguments and inline tsExpectLessThanThenParseInType
2018-01-17 08:36:04 -05:00
Sven SAULEAU
4f39e6ea4a Merge pull request #7219 from Andarist/fix/deps
Fix dependencies in @babel/traverse
2018-01-16 10:31:40 +01:00
Nicolò Ribaudo
64dfb7574e Remove old comment (#7220) 2018-01-15 14:57:43 -06:00
Mateusz Burzyński
d36b142e30 Moved @babel/generator to dependencies in @babel/traverse 2018-01-15 19:47:15 +01:00
Jorrit Schippers
3c8d831fe4 Prevent object shape change in jsx helper (#7170)
Keeping the shape of an object constant is a performance improvement for modern javascript engines. At the point of the code change it is certain that the `children` property will be set later, so the property can already be set to `undefined`.
2018-01-15 16:37:57 +01:00
Mateusz Burzyński
0a517b51cd Added custom NodePath.prototype.toString method as debug utility (#7218) 2018-01-15 13:07:05 +01:00
Mateusz Burzyński
79c84f2f9b Fixed _containerInsertAfter setting path key as stringified index (#7213) 2018-01-15 08:08:42 +01:00
Joe Haddad
ca86648726 bugfix: set color level when color is forced (#7216)
Color level 1 matches our usages, level 0 is no color
2018-01-14 12:43:20 -06:00
Raja Sekar
2d05487293 Add support for @@iterator (#7058) 2018-01-12 09:19:11 -06:00
Peri Nikhil
c3352ad2e0 Fix: unicode characters not allowed in regexes (#7179)
Issue #6691
2018-01-10 15:33:21 +01:00
Antoine Prieëls
26e4911eb2 Use the async version of transform in babel-cli (#6826)
* use the async version of transform in babel-cli

* Modify compile to use async version of transformFile

* Babel-CLI: transform files sequentially

* Remove useless res in callback
2018-01-09 19:17:07 -08:00
Henry Zhu
aa888e666a fix wording [skip ci] 2018-01-09 15:09:47 -05:00
Nicolò Ribaudo
8659e1a88c Remove old expected.{js,json} files (#7187) 2018-01-09 13:10:30 -06:00
Maaz Syed Adeeb
9e384f3915 Cleaning up some TS parsing tests (#7184) 2018-01-09 11:37:05 -06:00
Raja Sekar
f694b5d034 Doc changes for https://github.com/babel/babel/issues/7063 (#7185) 2018-01-09 11:10:00 -06:00
Artem Yavorsky
d765573c0b Remove excess check for hidden files. (#7183) 2018-01-09 10:21:49 -06:00
Henry Zhu
64161fa0b5 Fix syntax plugins in babylon readme [skip ci] (#7182) 2018-01-09 10:04:54 -06:00
Henry Zhu
52f22e9e1e Merge pull request #7181 from nicolo-ribaudo/pr-7169
Rename actual/expected to input/output in fixtures.
2018-01-09 10:43:33 -05:00
Brian Ng
3e5fce07e4 Regen lib/types (#7180) 2018-01-09 09:25:45 -06:00
Raja Sekar
0f42accb87 Renamed files 2018-01-09 15:36:42 +01:00
Raja Sekar
07e69c009b Code changes 2018-01-09 10:36:11 +01:00
Claudio Procida
ce420ba51c Fixes React isCompatTag validator accepting leading dash character (#7164) 2018-01-09 09:42:05 +01:00
Nicolò Ribaudo
9fe30b98a1 Remove "quotes" internal flag from babel-generator (#7174) 2018-01-08 23:37:33 -08:00
Mauro Bringolf
0a9f136d5f Minor improvements to block-scoping/tdz (#6782)
* Add test case for simple reference in tdz

* Add more examples from old issues as test cases

* Fix two testcases by excluding function declarations from being tdz checked

* Document the  option for block-scoping

* Add test cases with destructuring assignments

* Remove failing test cases

* [skip ci] Include type and default value for options
2018-01-08 21:49:05 -08:00
Mouad Debbar
e9ed687666 Bail out on JSX fragments instead of throwing (#7166)
* Bail out on JSX fragments instead of throwing

The `transform-react-inline-elements` plugin doesn't handle JSX fragments. It throws an exception because `node.openingElement` is undefined.

* Add a comment explaining `node.openingElement`
2018-01-08 21:38:52 -08:00
mtpc
63157159ab Preserve namespaced attributes when throwIfNamespace is false (#7173)
Previously that part would throw since it expects a JSXIdentifier but it (logically) gets a JSXNamespacedName when using a namespaced attribute.
2018-01-08 21:24:02 -08:00
Maaz Syed Adeeb
74682f33bc Support 'assert and assign' TypeScript syntax (#7098) 2018-01-08 15:29:27 -06:00
Henry Zhu
b1bf7798ab update to v7-beta.37 (#7104) 2018-01-08 12:05:49 -05:00
9327 changed files with 11544 additions and 6423 deletions

View File

@@ -1,6 +1,6 @@
"use strict";
// Blame Logan for this.
// Thanks Logan for this.
// This works around https://github.com/istanbuljs/istanbuljs/issues/92 until
// we have a version of Istanbul that actually works with 7.x.
function istanbulHacks() {
@@ -38,14 +38,23 @@ const config = {
comments: false,
presets: [
["@babel/env", envOpts],
"@babel/flow"
],
plugins: [
// TODO: Use @babel/preset-flow when
// https://github.com/babel/babel/issues/7233 is fixed
"@babel/plugin-transform-flow-strip-types",
["@babel/proposal-class-properties", { loose: true }],
"@babel/proposal-export-namespace-from",
"@babel/proposal-numeric-separator",
["@babel/proposal-object-rest-spread", { useBuiltIns: true }],
]
],
overrides: [{
test: "packages/babylon",
plugins: [
"babel-plugin-transform-charcodes",
["@babel/transform-for-of", { assumeArray: true }],
],
}],
};
if (process.env.BABEL_ENV === "cov") {

16
.babelrc.rollup.js Normal file
View File

@@ -0,0 +1,16 @@
"use strict";
const cloneDeep = require("lodash/cloneDeep");
const babelrc = require("./.babelrc.js");
const config = cloneDeep(babelrc);
const presetEnv = config.presets.find(preset => preset[0] === "@babel/env");
if (!presetEnv) {
throw new Error("Error while extracting @preset/env from .babelrc.js");
}
presetEnv[1].modules = false;
module.exports = config;

View File

@@ -13,7 +13,7 @@ codemods/*/src
[libs]
lib/file.js
lib/parser.js
lib/types.js
lib/packages/babel-types/lib/index.js.flow
lib/third-party-libs.js.flow
[options]

View File

@@ -175,21 +175,21 @@ For example, in [`@babel/plugin-transform-exponentiation-operator/test`](https:/
- In each subfolder, you can organize your directory structure by categories of tests. (Example: these folders can be named after the feature you are testing or can reference the issue number they fix)
- Generally, there are two kinds of tests for plugins
- The first is a simple test of the input and output produced by running Babel on some code. We do this by creating an [`actual.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/actual.js) file and an [`expected.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/expected.js) file.
- If you need to expect an error, you can ignore creating the `expected.js` file and pass a new `throws` key to the `options.json` that contains the error string that is created.
- The first is a simple test of the input and output produced by running Babel on some code. We do this by creating an [`input.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/input.js) file and an [`output.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/output.js) file.
- If you need to expect an error, you can ignore creating the `output.js` file and pass a new `throws` key to the `options.json` that contains the error string that is created.
- The second and preferred type is a test that actually evaluates the produced code and asserts that certain properties are true or false. We do this by creating an [`exec.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/comprehensive/exec.js) file.
In an actual/expected test, you simply write out the code you want transformed in `actual.js`.
In a fixture test, you simply write out the code you want transformed in `input.js`.
```js
// actual.js
// input.js
2 ** 2;
```
and the expected output after transforming it with your `options.json` in `expected.js`.
and the expected output after transforming it with your `options.json` in `output.js`.
```js
// expected.js
// output.js
Math.pow(2, 2);
```
In an `exec.js` test, we run or check that the code actually does what it's supposed to do rather than just check the static output.
@@ -227,9 +227,9 @@ Inside the `packages/babylon/tests/fixtures` folder are categories/groupings of
etc.). To add a test, create a folder under one of these groupings (or create a new one) with a
descriptive name, and add the following:
* Create an `actual.js` file that contains the code you want Babylon to parse.
* Create an `input.js` file that contains the code you want Babylon to parse.
* Add an `expected.json` file with the expected parser output. For added convenience, if there is no `expected.json` present, the test runner will generate one for you.
* Add an `output.json` file with the expected parser output. For added convenience, if there is no `output.json` present, the test runner will generate one for you.
After writing tests for babylon, just build it by running:
@@ -245,7 +245,7 @@ $ TEST_ONLY=babylon make test-only
#### Bootstrapping expected output
For both `@babel/plugin-x` and `babylon`, you can easily generate an `expected.js`/`expected.json` automatically by just providing `actual.js` and running the tests as you usually would.
For both `@babel/plugin-x` and `babylon`, you can easily generate an `output.js`/`output.json` automatically by just providing `input.js` and running the tests as you usually would.
```
// Example
@@ -256,8 +256,8 @@ For both `@babel/plugin-x` and `babylon`, you can easily generate an `expected.j
- comments
- basic
- block-trailing-comment
- actual.js
- expected.json (will be generated if not created)
- input.js
- output.json (will be generated if not created)
```
### Debugging code

View File

@@ -12,6 +12,11 @@ const gulp = require("gulp");
const path = require("path");
const webpack = require("webpack");
const merge = require("merge-stream");
const rollup = require("rollup-stream");
const source = require("vinyl-source-stream");
const buffer = require("vinyl-buffer");
const rollupBabel = require("rollup-plugin-babel");
const rollupNodeResolve = require("rollup-plugin-node-resolve");
const registerStandalonePackageTask = require("./scripts/gulp-tasks")
.registerStandalonePackageTask;
@@ -27,53 +32,100 @@ function getGlobFromSource(source) {
return `./${source}/*/src/**/*.js`;
}
gulp.task("default", ["build"]);
function getIndexFromPackage(name) {
return `${name}/src/index.js`;
}
gulp.task("build", function() {
function compilationLogger(rollup) {
return through.obj(function(file, enc, callback) {
gutil.log(
`Compiling '${chalk.cyan(file.relative)}'${
rollup ? " with rollup " : ""
}...`
);
callback(null, file);
});
}
function errorsLogger() {
return plumber({
errorHandler(err) {
gutil.log(err.stack);
},
});
}
function rename(fn) {
return through.obj(function(file, enc, callback) {
file.path = fn(file);
callback(null, file);
});
}
function buildBabel(exclude) {
return merge(
sources.map(source => {
const base = path.join(__dirname, source);
const f = filter(["**", "!**/packages/babylon/**"]);
return gulp
.src(getGlobFromSource(source), { base: base })
.pipe(f)
.pipe(
plumber({
errorHandler: function(err) {
gutil.log(err.stack);
},
})
)
.pipe(
newer({
dest: base,
map: swapSrcWithLib,
})
)
.pipe(
through.obj(function(file, enc, callback) {
gutil.log("Compiling", "'" + chalk.cyan(file.relative) + "'...");
callback(null, file);
})
)
let stream = gulp.src(getGlobFromSource(source), { base: base });
if (exclude) {
const filters = exclude.map(p => `!**/${p}/**`);
filters.unshift("**");
stream = stream.pipe(filter(filters));
}
return stream
.pipe(errorsLogger())
.pipe(newer({ dest: base, map: swapSrcWithLib }))
.pipe(compilationLogger())
.pipe(babel())
.pipe(
through.obj(function(file, enc, callback) {
// Passing 'file.relative' because newer() above uses a relative
// path and this keeps it consistent.
file.path = path.resolve(file.base, swapSrcWithLib(file.relative));
callback(null, file);
})
// Passing 'file.relative' because newer() above uses a relative
// path and this keeps it consistent.
rename(file => path.resolve(file.base, swapSrcWithLib(file.relative)))
)
.pipe(gulp.dest(base));
})
);
}
function buildRollup(packages) {
return merge(
packages.map(pkg => {
return rollup({
input: getIndexFromPackage(pkg),
format: "cjs",
plugins: [
rollupBabel({
babelrc: false,
extends: "./.babelrc.rollup.js",
}),
rollupNodeResolve(),
],
})
.pipe(source("index.js"))
.pipe(buffer())
.pipe(errorsLogger())
.pipe(compilationLogger(/* rollup */ true))
.pipe(gulp.dest(path.join(pkg, "lib")));
})
);
}
gulp.task("default", ["build"]);
gulp.task("build", function() {
const bundles = ["packages/babylon"];
return merge([buildBabel(/* exclude */ bundles), buildRollup(bundles)]);
});
gulp.task("watch", ["build"], function() {
gulp.task("build-no-bundle", () => buildBabel());
gulp.task("watch", ["build-no-bundle"], function() {
watch(sources.map(getGlobFromSource), { debounceDelay: 200 }, function() {
gulp.start("build");
gulp.start("build-no-bundle");
});
});

View File

@@ -13,21 +13,20 @@ SOURCES = packages codemods
build: clean
make clean-lib
# Build babylon before building all other projects
make build-babylon
./node_modules/.bin/gulp build
node ./packages/babel-types/scripts/generateTypeHelpers.js
# call build again as the generated files might need to be compiled again.
./node_modules/.bin/gulp build
# generate flow and typescript typings
node scripts/generators/flow.js > ./packages/babel-types/lib/index.js.flow
node scripts/generators/typescript.js > ./packages/babel-types/lib/index.d.ts
# generate docs
node scripts/generators/docs.js > ./packages/babel-types/README.md
ifneq ("$(BABEL_ENV)", "cov")
make build-standalone
make build-preset-env-standalone
endif
build-babylon:
cd packages/babylon; \
./node_modules/.bin/rollup -c
build-standalone:
./node_modules/.bin/gulp build-babel-standalone
@@ -39,16 +38,11 @@ build-dist: build
scripts/build-dist.sh
cd packages/babel-runtime; \
node scripts/build-dist.js
node scripts/generate-babel-types-docs.js
watch: clean
make clean-lib
BABEL_ENV=development ./node_modules/.bin/gulp watch
watch-babylon:
cd packages/babylon; \
./node_modules/.bin/rollup -c -w
flow:
./node_modules/.bin/flow check --strip-root

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-codemod-optional-catch-binding",
"version": "7.0.0-beta.37",
"version": "7.0.0-beta.40",
"description": "Remove unused catch bindings",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-remove-unused-catch-binding",
"license": "MIT",
@@ -9,13 +9,13 @@
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.37"
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.40"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.37"
"@babel/core": "7.0.0-beta.40"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.37",
"@babel/helper-plugin-test-runner": "7.0.0-beta.37"
"@babel/core": "7.0.0-beta.40",
"@babel/helper-plugin-test-runner": "7.0.0-beta.40"
}
}

View File

@@ -1,6 +1,6 @@
{
"lerna": "2.0.0-rc.4",
"version": "7.0.0-beta.37",
"version": "7.0.0-beta.40",
"changelog": {
"repo": "babel/babel",
"labels": {

File diff suppressed because it is too large Load Diff

View File

@@ -10,32 +10,33 @@
"test": "make test"
},
"devDependencies": {
"@babel/cli": "7.0.0-beta.33",
"@babel/core": "7.0.0-beta.33",
"@babel/plugin-proposal-export-namespace-from": "7.0.0-beta.33",
"@babel/preset-env": "7.0.0-beta.33",
"@babel/preset-flow": "7.0.0-beta.33",
"@babel/preset-stage-0": "7.0.0-beta.33",
"@babel/register": "7.0.0-beta.33",
"@babel/cli": "7.0.0-beta.39",
"@babel/core": "7.0.0-beta.39",
"@babel/preset-env": "7.0.0-beta.39",
"@babel/preset-flow": "7.0.0-beta.39",
"@babel/preset-stage-0": "7.0.0-beta.39",
"@babel/register": "7.0.0-beta.39",
"async": "^1.5.0",
"babel-eslint": "^8.0.1",
"babel-loader": "8.0.0-beta.0",
"babel-plugin-istanbul": "^4.1.4",
"babylon": "7.0.0-beta.33",
"babel-plugin-transform-charcodes": "0.0.10",
"babylon": "7.0.0-beta.39",
"browserify": "^13.1.1",
"bundle-collapser": "^1.2.1",
"chai": "^4.1.0",
"chalk": "^2.0.0",
"charcodes": "0.0.10",
"derequire": "^2.0.2",
"eslint": "^4.5.0",
"eslint-config-babel": "^7.0.2",
"eslint-plugin-flowtype": "^2.20.0",
"eslint-plugin-prettier": "^2.2.0",
"eslint-plugin-prettier": "^2.5.0",
"flow-bin": "^0.59.0",
"graceful-fs": "^4.1.11",
"gulp": "^3.9.0",
"gulp-babel": "^8.0.0-beta.0",
"gulp-filter": "^5.0.1",
"gulp-filter": "^5.1.0",
"gulp-newer": "^1.0.0",
"gulp-plumber": "^1.0.1",
"gulp-rename": "^1.2.2",
@@ -45,19 +46,24 @@
"husky": "^0.14.3",
"lerna": "2.0.0",
"lerna-changelog": "^0.5.0",
"lint-staged": "^4.2.3",
"lint-staged": "^6.0.1",
"lodash": "^4.2.0",
"merge-stream": "^1.0.1",
"mocha": "^3.0.0",
"nyc": "^11.0.3",
"output-file-sync": "^2.0.0",
"prettier": "1.9.1",
"prettier": "1.10.2",
"pump": "^1.0.2",
"rimraf": "^2.4.3",
"rollup-plugin-babel": "^4.0.0-beta.0",
"rollup-plugin-node-resolve": "^3.0.2",
"rollup-stream": "^1.24.1",
"semver": "^5.0.0",
"through2": "^2.0.0",
"uglify-js": "^2.4.16",
"util.promisify": "^1.0.0",
"vinyl-buffer": "^1.0.1",
"vinyl-source-stream": "^2.0.0",
"webpack": "^3.4.1",
"webpack-dependency-suite": "^2.4.4",
"webpack-stream": "^4.0.0"

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/cli",
"version": "7.0.0-beta.37",
"version": "7.0.0-beta.40",
"description": "Babel command line.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -29,11 +29,11 @@
"chokidar": "^1.6.1"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.37"
"@babel/core": "7.0.0-beta.40"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.37",
"@babel/helper-fixtures": "7.0.0-beta.37"
"@babel/core": "7.0.0-beta.40",
"@babel/helper-fixtures": "7.0.0-beta.40"
},
"bin": {
"babel": "./bin/babel.js",

View File

@@ -7,9 +7,13 @@ import fs from "fs";
import * as util from "./util";
export default function(commander, filenames, opts) {
function write(src, relative, base) {
function write(src, relative, base, callback) {
if (typeof base === "function") {
callback = base;
base = undefined;
}
if (!util.isCompilableExtension(relative, commander.extensions)) {
return false;
return process.nextTick(callback);
}
// remove extension and then append back on .js
@@ -17,7 +21,7 @@ export default function(commander, filenames, opts) {
const dest = getDest(commander, relative, base);
const data = util.compile(
util.compile(
src,
defaults(
{
@@ -26,23 +30,28 @@ export default function(commander, filenames, opts) {
},
opts,
),
function(err, res) {
if (err) return callback(err);
if (!res) return callback();
// we've requested explicit sourcemaps to be written to disk
if (
res.map &&
commander.sourceMaps &&
commander.sourceMaps !== "inline"
) {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
outputFileSync(dest, res.code);
util.chmod(src, dest);
util.log(src + " -> " + dest);
return callback(null, true);
},
);
if (!data) return false;
// we've requested explicit sourcemaps to be written to disk
if (data.map && commander.sourceMaps && commander.sourceMaps !== "inline") {
const mapLoc = dest + ".map";
data.code = util.addSourceMappingUrl(data.code, mapLoc);
outputFileSync(mapLoc, JSON.stringify(data.map));
}
outputFileSync(dest, data.code);
util.chmod(src, dest);
util.log(src + " -> " + dest);
return true;
}
function getDest(commander, filename, base) {
@@ -50,17 +59,45 @@ export default function(commander, filenames, opts) {
return path.join(commander.outDir, filename);
}
function handleFile(src, filename, base) {
const didWrite = write(src, filename, base);
if (!didWrite && commander.copyFiles) {
const dest = getDest(commander, filename, base);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
function handleFile(src, filename, base, callback) {
if (typeof base === "function") {
callback = base;
base = undefined;
}
write(src, filename, base, function(err, res) {
if (err) return callback(err);
if (!res && commander.copyFiles) {
const dest = getDest(commander, filename, base);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
}
return callback();
});
}
function handle(filename) {
function sequentialHandleFile(files, dirname, index, callback) {
if (typeof index === "function") {
callback = index;
index = 0;
}
const filename = files[index];
const src = path.join(dirname, filename);
handleFile(src, filename, dirname, function(err) {
if (err) return callback(err);
index++;
if (index !== files.length) {
sequentialHandleFile(files, dirname, index, callback);
} else {
callback();
}
});
}
function handle(filename, callback) {
if (!fs.existsSync(filename)) return;
const stat = fs.statSync(filename);
@@ -72,19 +109,32 @@ export default function(commander, filenames, opts) {
util.deleteDir(commander.outDir);
}
util
.readdir(dirname, commander.includeDotfiles)
.forEach(function(filename) {
const src = path.join(dirname, filename);
handleFile(src, filename, dirname);
});
const files = util.readdir(dirname, commander.includeDotfiles);
sequentialHandleFile(files, dirname, callback);
} else {
write(filename, path.basename(filename), path.dirname(filename));
write(
filename,
path.basename(filename),
path.dirname(filename),
callback,
);
}
}
function sequentialHandle(filenames, index = 0) {
const filename = filenames[index];
handle(filename, function(err) {
if (err) throw err;
index++;
if (index !== filenames.length) {
sequentialHandle(filenames, index);
}
});
}
if (!commander.skipInitialBuild) {
filenames.forEach(handle);
sequentialHandle(filenames);
}
if (commander.watch) {
@@ -104,7 +154,9 @@ export default function(commander, filenames, opts) {
watcher.on(type, function(filename) {
const relative = path.relative(dirname, filename) || filename;
try {
handleFile(filename, relative);
handleFile(filename, relative, function(err) {
if (err) throw err;
});
} catch (err) {
console.error(err.stack);
}

View File

@@ -103,19 +103,21 @@ export default function(commander, filenames, opts) {
});
process.stdin.on("end", function() {
results.push(
util.transform(
commander.filename,
code,
defaults(
{
sourceFileName: "stdin",
},
opts,
),
util.transform(
commander.filename,
code,
defaults(
{
sourceFileName: "stdin",
},
opts,
),
function(err, res) {
if (err) throw err;
results.push(res);
output();
},
);
output();
});
};
@@ -140,7 +142,9 @@ export default function(commander, filenames, opts) {
}
});
_filenames.forEach(function(filename) {
let filesProcessed = 0;
_filenames.forEach(function(filename, index) {
let sourceFilename = filename;
if (commander.outFile) {
sourceFilename = path.relative(
@@ -150,7 +154,7 @@ export default function(commander, filenames, opts) {
}
sourceFilename = slash(sourceFilename);
const data = util.compile(
util.compile(
filename,
defaults(
{
@@ -158,14 +162,18 @@ export default function(commander, filenames, opts) {
},
opts,
),
function(err, res) {
if (err) throw err;
filesProcessed++;
if (res) results[index] = res;
if (filesProcessed === _filenames.length) {
output();
}
},
);
if (!data) return;
results.push(data);
});
output();
};
const files = function() {

View File

@@ -50,25 +50,26 @@ export function log(msg) {
if (!commander.quiet) console.log(msg);
}
export function transform(filename, code, opts) {
export function transform(filename, code, opts, callback) {
opts = Object.assign({}, opts, {
filename,
});
return babel.transform(code, opts);
babel.transform(code, opts, callback);
}
export function compile(filename, opts) {
try {
return babel.transformFileSync(filename, opts);
} catch (err) {
if (commander.watch) {
console.error(err);
return { ignored: true };
} else {
throw err;
export function compile(filename, opts, callback) {
babel.transformFile(filename, opts, function(err, res) {
if (err) {
if (commander.watch) {
console.error(err);
return callback(null, null);
} else {
return callback(err);
}
}
}
return callback(null, res);
});
}
export function deleteDir(path) {

View File

@@ -68,6 +68,7 @@ console.log(result);
Toggles syntax highlighting the code as JavaScript for terminals.
### `linesAbove`
`number`, defaults to `2`.
@@ -86,6 +87,21 @@ Adjust the number of lines to show below the error.
Enable this to forcibly syntax highlight the code as JavaScript (for non-terminals); overrides `highlightCode`.
### `message`
`string`, otherwise nothing
Pass in a string to be displayed inline (if possible) next to the highlighted
location in the code. If it can't be positioned inline, it will be placed above
the code frame.
```
1 | class Foo {
> 2 | constructor()
| ^ Missing {
3 | };
```
## Upgrading from prior versions
Prior to version 7, the only API exposed by this module was for a single line and optional column pointer. The old API will now log a deprecation warning.

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/code-frame",
"version": "7.0.0-beta.37",
"version": "7.0.0-beta.40",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,11 +8,10 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-code-frame",
"main": "lib/index.js",
"dependencies": {
"chalk": "^2.0.0",
"esutils": "^2.0.2",
"js-tokens": "^3.0.0"
"@babel/highlight": "7.0.0-beta.40"
},
"devDependencies": {
"chalk": "^2.0.0",
"strip-ansi": "^4.0.0"
}
}

View File

@@ -1,6 +1,4 @@
import jsTokens, { matchToToken } from "js-tokens";
import esutils from "esutils";
import Chalk from "chalk";
import highlight, { shouldHighlight, getChalk } from "@babel/highlight";
let deprecationWarningShown = false;
@@ -15,23 +13,13 @@ type NodeLocation = {
};
/**
* Chalk styles for token types.
* Chalk styles for code frame token types.
*/
function getDefs(chalk) {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
// bracket: intentionally omitted.
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
gutter: chalk.grey,
marker: chalk.red.bold,
message: chalk.red.bold,
};
}
@@ -41,76 +29,6 @@ function getDefs(chalk) {
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
/**
* RegExp to test for what seems to be a JSX tag name.
*/
const JSX_TAG = /^[a-z][\w-]*$/i;
/**
* RegExp to test for the three types of brackets.
*/
const BRACKET = /^[()[\]{}]$/;
/**
* Get the type of token, specifying punctuator type.
*/
function getTokenType(match) {
const [offset, text] = match.slice(-2);
const token = matchToToken(match);
if (token.type === "name") {
if (esutils.keyword.isReservedWordES6(token.value)) {
return "keyword";
}
if (
JSX_TAG.test(token.value) &&
(text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")
) {
return "jsx_tag";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (
token.type === "invalid" &&
(token.value === "@" || token.value === "#")
) {
return "punctuator";
}
return token.type;
}
/**
* Highlight `text`.
*/
function highlight(defs: Object, text: string) {
return text.replace(jsTokens, function(...args) {
const type = getTokenType(args);
const colorize = defs[type];
if (colorize) {
return args[0]
.split(NEWLINE)
.map(str => colorize(str))
.join("\n");
} else {
return args[0];
}
});
}
/**
* Extract what lines should be marked and highlighted.
*/
@@ -126,9 +44,7 @@ function getMarkerLines(
loc.start,
);
const endLoc: Location = Object.assign({}, startLoc, loc.end);
const linesAbove = opts.linesAbove || 2;
const linesBelow = opts.linesBelow || 3;
const { linesAbove = 2, linesBelow = 3 } = opts || {};
const startLine = startLoc.line;
const startColumn = startLoc.column;
const endLine = endLoc.line;
@@ -187,29 +103,28 @@ export function codeFrameColumns(
opts: Object = {},
): string {
const highlighted =
(opts.highlightCode && Chalk.supportsColor) || opts.forceColor;
let chalk = Chalk;
if (opts.forceColor) {
chalk = new Chalk.constructor({ enabled: true });
}
(opts.highlightCode || opts.forceColor) && shouldHighlight(opts);
const chalk = getChalk(opts);
const defs = getDefs(chalk);
const maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
};
const defs = getDefs(chalk);
if (highlighted) rawLines = highlight(defs, rawLines);
if (highlighted) rawLines = highlight(rawLines, opts);
const lines = rawLines.split(NEWLINE);
const { start, end, markerLines } = getMarkerLines(loc, lines, opts);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end).length;
const frame = lines
let frame = lines
.slice(start, end)
.map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} | `;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
@@ -224,6 +139,10 @@ export function codeFrameColumns(
markerSpacing,
maybeHighlight(defs.marker, "^").repeat(numberOfMarkers),
].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + maybeHighlight(defs.message, opts.message);
}
}
return [
maybeHighlight(defs.marker, ">"),
@@ -237,6 +156,10 @@ export function codeFrameColumns(
})
.join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (highlighted) {
return chalk.reset(frame);
} else {

View File

@@ -184,6 +184,57 @@ describe("@babel/code-frame", function() {
);
});
it("opts.linesAbove no lines above", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
assert.equal(
codeFrameColumns(rawLines, { start: { line: 2 } }, { linesAbove: 0 }),
[
"> 2 | constructor() {",
" 3 | console.log(arguments);",
" 4 | }",
" 5 | };",
].join("\n"),
);
});
it("opts.linesBelow no lines below", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
assert.equal(
codeFrameColumns(rawLines, { start: { line: 2 } }, { linesBelow: 0 }),
[" 1 | class Foo {", "> 2 | constructor() {"].join("\n"),
);
});
it("opts.linesBelow single line", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
assert.equal(
codeFrameColumns(
rawLines,
{ start: { line: 2 } },
{ linesAbove: 0, linesBelow: 0 },
),
["> 2 | constructor() {"].join("\n"),
);
});
it("opts.forceColor", function() {
const marker = chalk.red.bold;
const gutter = chalk.grey;
@@ -299,4 +350,101 @@ describe("@babel/code-frame", function() {
].join("\n"),
);
});
it("opts.message", function() {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
assert.equal(
codeFrameColumns(
rawLines,
{ start: { line: 2, column: 16 } },
{
message: "Missing {",
},
),
[
" 1 | class Foo {",
"> 2 | constructor()",
" | ^ Missing {",
" 3 | };",
].join("\n"),
);
});
it("opts.message without column", function() {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
assert.equal(
codeFrameColumns(
rawLines,
{ start: { line: 2 } },
{
message: "Missing {",
},
),
[
" Missing {",
" 1 | class Foo {",
"> 2 | constructor()",
" 3 | };",
].join("\n"),
);
});
it("opts.message with multiple lines", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
assert.equal(
codeFrameColumns(
rawLines,
{
start: { line: 2, column: 17 },
end: { line: 4, column: 3 },
},
{
message: "something about the constructor body",
},
),
[
" 1 | class Foo {",
"> 2 | constructor() {",
" | ^",
"> 3 | console.log(arguments);",
" | ^^^^^^^^^^^^^^^^^^^^^^^^^^^",
"> 4 | }",
" | ^^^ something about the constructor body",
" 5 | };",
].join("\n"),
);
});
it("opts.message with multiple lines without columns", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
assert.equal(
codeFrameColumns(
rawLines,
{ start: { line: 2 }, end: { line: 4 } },
{
message: "something about the constructor body",
},
),
[
" something about the constructor body",
" 1 | class Foo {",
"> 2 | constructor() {",
"> 3 | console.log(arguments);",
"> 4 | }",
" 5 | };",
].join("\n"),
);
});
});

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/core",
"version": "7.0.0-beta.37",
"version": "7.0.0-beta.40",
"description": "Babel compiler core.",
"main": "./lib/index.js",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
@@ -28,13 +28,13 @@
"./lib/transform-file-sync.js": "./lib/transform-file-sync-browser.js"
},
"dependencies": {
"@babel/code-frame": "7.0.0-beta.37",
"@babel/generator": "7.0.0-beta.37",
"@babel/helpers": "7.0.0-beta.37",
"@babel/template": "7.0.0-beta.37",
"@babel/traverse": "7.0.0-beta.37",
"@babel/types": "7.0.0-beta.37",
"babylon": "7.0.0-beta.37",
"@babel/code-frame": "7.0.0-beta.40",
"@babel/generator": "7.0.0-beta.40",
"@babel/helpers": "7.0.0-beta.40",
"@babel/template": "7.0.0-beta.40",
"@babel/traverse": "7.0.0-beta.40",
"@babel/types": "7.0.0-beta.40",
"babylon": "7.0.0-beta.40",
"convert-source-map": "^1.1.0",
"debug": "^3.0.1",
"json5": "^0.5.0",
@@ -44,7 +44,7 @@
"source-map": "^0.5.0"
},
"devDependencies": {
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.37",
"@babel/register": "7.0.0-beta.37"
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.40",
"@babel/register": "7.0.0-beta.40"
}
}

View File

@@ -12,12 +12,7 @@ import {
const debug = buildDebug("babel:config:config-chain");
import {
findBabelrc,
findBabelignore,
loadConfig,
type ConfigFile,
} from "./files";
import { findRelativeConfig, loadConfig, type ConfigFile } from "./files";
import { makeWeakCache, makeStrongCache } from "./caching";
@@ -108,7 +103,6 @@ const loadPresetOverridesEnvDescriptors = makeWeakCache(
* Build a config chain for Babel's full root configuration.
*/
export function buildRootChain(
cwd: string,
opts: ValidatedOptions,
context: ConfigContext,
): ConfigChain | null {
@@ -125,22 +119,15 @@ export function buildRootChain(
// resolve all .babelrc files
if (opts.babelrc !== false && context.filename !== null) {
const filename = context.filename;
const babelignoreFile = findBabelignore(filename);
if (
babelignoreFile &&
shouldIgnore(
context,
babelignoreFile.ignore,
null,
babelignoreFile.dirname,
)
) {
const { ignore, config } = findRelativeConfig(filename, context.envName);
if (ignore && shouldIgnore(context, ignore.ignore, null, ignore.dirname)) {
return null;
}
const babelrcFile = findBabelrc(filename, context.envName);
if (babelrcFile) {
const result = loadFileChain(babelrcFile, context);
if (config) {
const result = loadFileChain(config, context);
if (!result) return null;
mergeChain(fileChain, result);

View File

@@ -21,41 +21,58 @@ export type IgnoreFile = {
ignore: Array<string>,
};
export type RelativeConfig = {
config: ConfigFile | null,
ignore: IgnoreFile | null,
};
const BABELRC_FILENAME = ".babelrc";
const BABELRC_JS_FILENAME = ".babelrc.js";
const PACKAGE_FILENAME = "package.json";
const BABELIGNORE_FILENAME = ".babelignore";
export function findBabelrc(
export function findRelativeConfig(
filepath: string,
envName: string,
): ConfigFile | null {
): RelativeConfig {
let config = null;
let ignore = null;
const dirname = path.dirname(filepath);
let loc = dirname;
while (true) {
const conf = [
BABELRC_FILENAME,
BABELRC_JS_FILENAME,
PACKAGE_FILENAME,
].reduce((previousConfig: ConfigFile | null, name) => {
const filepath = path.join(loc, name);
const config = readConfig(filepath, envName);
if (!config) {
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME, PACKAGE_FILENAME].reduce(
(previousConfig: ConfigFile | null, name) => {
const filepath = path.join(loc, name);
const config = readConfig(filepath, envName);
if (config && previousConfig) {
throw new Error(
`Multiple configuration files found. Please remove one:\n` +
` - ${path.basename(previousConfig.filepath)}\n` +
` - ${name}\n` +
`from ${loc}`,
);
if (config && previousConfig) {
throw new Error(
`Multiple configuration files found. Please remove one:\n` +
` - ${path.basename(previousConfig.filepath)}\n` +
` - ${name}\n` +
`from ${loc}`,
);
}
return config || previousConfig;
},
null,
);
if (config) {
debug("Found configuration %o from %o.", config.filepath, dirname);
}
}
return config || previousConfig;
}, null);
if (!ignore) {
const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
ignore = readIgnoreConfig(ignoreLoc);
if (conf) {
debug("Found configuration %o from %o.", conf.filepath, dirname);
return conf;
if (ignore) {
debug("Found ignore %o from %o.", ignore.filepath, dirname);
}
}
const nextLoc = path.dirname(loc);
@@ -63,27 +80,7 @@ export function findBabelrc(
loc = nextLoc;
}
return null;
}
export function findBabelignore(filepath: string): IgnoreFile | null {
const dirname = path.dirname(filepath);
let loc = dirname;
while (true) {
const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
const ignore = readIgnoreConfig(ignoreLoc);
if (ignore) {
debug("Found ignore %o from %o.", ignore.filepath, dirname);
return ignore;
}
const nextLoc = path.dirname(loc);
if (loc === nextLoc) break;
loc = nextLoc;
}
return null;
return { config, ignore };
}
export function loadConfig(
@@ -106,7 +103,7 @@ export function loadConfig(
* Read the given config file, returning the result. Returns null if no config was found, but will
* throw if there are parsing errors while loading a config.
*/
function readConfig(filepath, envName) {
function readConfig(filepath, envName): ConfigFile | null {
return path.extname(filepath) === ".js"
? readConfigJS(filepath, { envName })
: readConfigFile(filepath);

View File

@@ -1,27 +1,14 @@
// @flow
export type ConfigFile = {
filepath: string,
dirname: string,
options: {},
};
import type { ConfigFile, IgnoreFile, RelativeConfig } from "./configuration";
export type IgnoreFile = {
filepath: string,
dirname: string,
ignore: Array<string>,
};
export type { ConfigFile, IgnoreFile, RelativeConfig };
export function findBabelrc(
export function findRelativeConfig(
filepath: string,
envName: string, // eslint-disable-line no-unused-vars
): ConfigFile | null {
return null;
}
// eslint-disable-next-line no-unused-vars
export function findBabelignore(filepath: string): IgnoreFile | null {
return null;
): RelativeConfig {
return { config: null, ignore: null };
}
export function loadConfig(name: string, dirname: string): ConfigFile {

View File

@@ -62,7 +62,7 @@ export default function loadConfig(inputOpts: mixed): ResolvedConfig | null {
envName,
};
const configChain = buildRootChain(absoluteCwd, args, context);
const configChain = buildRootChain(args, context);
if (!configChain) return null;
const optionDefaults = {};

View File

@@ -140,6 +140,8 @@ export function assertConfigApplicableTest(
key: string,
value: mixed,
): ConfigApplicableTest | void {
if (value === undefined) return value;
if (Array.isArray(value)) {
value.forEach((item, i) => {
if (!checkValidTest(item)) {

View File

@@ -43,6 +43,8 @@ export { default as transformFileSync } from "./transform-file-sync";
export { default as transformFromAst } from "./transform-ast";
export { default as transformFromAstSync } from "./transform-ast-sync";
export { default as parse } from "./parse";
/**
* Recommended set of compilable extensions. Not used in @babel/core directly, but meant as
* as an easy source for tooling making use of @babel/core.

View File

@@ -0,0 +1,22 @@
// @flow
import loadConfig, { type InputOptions } from "./config";
import normalizeFile from "./transformation/normalize-file";
import normalizeOptions from "./transformation/normalize-opts";
type AstRoot = BabelNodeFile | BabelNodeProgram;
export default function parse(
code: string,
opts: InputOptions,
): AstRoot | null {
const config = loadConfig(opts);
if (config === null) {
return null;
}
const file = normalizeFile(config.passes, normalizeOptions(config), code);
return file.ast;
}

View File

@@ -69,7 +69,7 @@ function buildModule(whitelist) {
t.exportNamedDeclaration(
null,
Object.keys(refs).map(name => {
return t.exportSpecifier(t.clone(refs[name]), t.identifier(name));
return t.exportSpecifier(t.cloneNode(refs[name]), t.identifier(name));
}),
),
);

View File

@@ -123,7 +123,7 @@ export default class File {
addHelper(name: string): Object {
const declar = this.declarations[name];
if (declar) return declar;
if (declar) return t.cloneNode(declar);
const generator = this.get("helperGenerator");
const runtime = this.get("helpersNamespace");
@@ -131,7 +131,7 @@ export default class File {
const res = generator(name);
if (res) return res;
} else if (runtime) {
return t.memberExpression(runtime, t.identifier(name));
return t.memberExpression(t.cloneNode(runtime), t.identifier(name));
}
const uid = (this.declarations[name] = this.scope.generateUidIdentifier(

View File

@@ -91,7 +91,6 @@ function parser(pluginPasses, options, code) {
} catch (err) {
const { loc, missingPlugin } = err;
if (loc) {
err.loc = null;
const codeFrame = codeFrameColumns(
code,
{
@@ -110,6 +109,7 @@ function parser(pluginPasses, options, code) {
err.message =
`${options.filename || "unknown"}: ${err.message}\n\n` + codeFrame;
}
err.code = "BABEL_PARSE_ERROR";
}
throw err;
}

View File

@@ -0,0 +1,3 @@
{
"plugins": ["@babel/syntax-decorators"]
}

View File

@@ -0,0 +1,6 @@
@annotation
class MyClass { }
function annotation(target) {
target.annotated = true;
}

View File

@@ -0,0 +1,286 @@
{
"type": "File",
"start": 0,
"end": 90,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 6,
"column": 1
}
},
"program": {
"type": "Program",
"start": 0,
"end": 90,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 6,
"column": 1
}
},
"sourceType": "module",
"body": [
{
"type": "ClassDeclaration",
"start": 0,
"end": 29,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 2,
"column": 17
}
},
"decorators": [
{
"type": "Decorator",
"start": 0,
"end": 11,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 11
}
},
"expression": {
"type": "Identifier",
"start": 1,
"end": 11,
"loc": {
"start": {
"line": 1,
"column": 1
},
"end": {
"line": 1,
"column": 11
},
"identifierName": "annotation"
},
"name": "annotation"
}
}
],
"id": {
"type": "Identifier",
"start": 18,
"end": 25,
"loc": {
"start": {
"line": 2,
"column": 6
},
"end": {
"line": 2,
"column": 13
},
"identifierName": "MyClass"
},
"name": "MyClass"
},
"superClass": null,
"body": {
"type": "ClassBody",
"start": 26,
"end": 29,
"loc": {
"start": {
"line": 2,
"column": 14
},
"end": {
"line": 2,
"column": 17
}
},
"body": []
}
},
{
"type": "FunctionDeclaration",
"start": 31,
"end": 90,
"loc": {
"start": {
"line": 4,
"column": 0
},
"end": {
"line": 6,
"column": 1
}
},
"id": {
"type": "Identifier",
"start": 40,
"end": 50,
"loc": {
"start": {
"line": 4,
"column": 9
},
"end": {
"line": 4,
"column": 19
},
"identifierName": "annotation"
},
"name": "annotation"
},
"generator": false,
"async": false,
"params": [
{
"type": "Identifier",
"start": 51,
"end": 57,
"loc": {
"start": {
"line": 4,
"column": 20
},
"end": {
"line": 4,
"column": 26
},
"identifierName": "target"
},
"name": "target"
}
],
"body": {
"type": "BlockStatement",
"start": 59,
"end": 90,
"loc": {
"start": {
"line": 4,
"column": 28
},
"end": {
"line": 6,
"column": 1
}
},
"body": [
{
"type": "ExpressionStatement",
"start": 64,
"end": 88,
"loc": {
"start": {
"line": 5,
"column": 3
},
"end": {
"line": 5,
"column": 27
}
},
"expression": {
"type": "AssignmentExpression",
"start": 64,
"end": 87,
"loc": {
"start": {
"line": 5,
"column": 3
},
"end": {
"line": 5,
"column": 26
}
},
"operator": "=",
"left": {
"type": "MemberExpression",
"start": 64,
"end": 80,
"loc": {
"start": {
"line": 5,
"column": 3
},
"end": {
"line": 5,
"column": 19
}
},
"object": {
"type": "Identifier",
"start": 64,
"end": 70,
"loc": {
"start": {
"line": 5,
"column": 3
},
"end": {
"line": 5,
"column": 9
},
"identifierName": "target"
},
"name": "target"
},
"property": {
"type": "Identifier",
"start": 71,
"end": 80,
"loc": {
"start": {
"line": 5,
"column": 10
},
"end": {
"line": 5,
"column": 19
},
"identifierName": "annotated"
},
"name": "annotated"
},
"computed": false
},
"right": {
"type": "BooleanLiteral",
"start": 83,
"end": 87,
"loc": {
"start": {
"line": 5,
"column": 22
},
"end": {
"line": 5,
"column": 26
}
},
"value": true
}
}
}
],
"directives": []
}
}
],
"directives": []
},
"comments": []
}

View File

@@ -1,7 +1,7 @@
{
"version": 3,
"file": "source-maps/full/expected.js",
"sources": ["source-maps/full/actual.js"],
"file": "source-maps/full/output.js",
"sources": ["source-maps/full/input.js"],
"names": [
"arr",
"map",

View File

@@ -1,4 +0,0 @@
arr.map(function (x) {
return x * x;
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNvdXJjZS1tYXBzL2lubGluZS9hY3R1YWwuanMiXSwibmFtZXMiOlsiYXJyIiwibWFwIiwieCJdLCJtYXBwaW5ncyI6IkFBQUFBLElBQUlDLEdBQUosQ0FBUTtBQUFBLFNBQUtDLElBQUlBLENBQVQ7QUFBQSxDQUFSIiwiZmlsZSI6InNvdXJjZS1tYXBzL2lubGluZS9leHBlY3RlZC5qcyIsInNvdXJjZXNDb250ZW50IjpbImFyci5tYXAoeCA9PiB4ICogeCk7Il19

View File

@@ -0,0 +1,4 @@
arr.map(function (x) {
return x * x;
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNvdXJjZS1tYXBzL2lubGluZS9pbnB1dC5qcyJdLCJuYW1lcyI6WyJhcnIiLCJtYXAiLCJ4Il0sIm1hcHBpbmdzIjoiQUFBQUEsSUFBSUMsR0FBSixDQUFRO0FBQUEsU0FBS0MsSUFBSUEsQ0FBVDtBQUFBLENBQVIiLCJmaWxlIjoic291cmNlLW1hcHMvaW5saW5lL291dHB1dC5qcyIsInNvdXJjZXNDb250ZW50IjpbImFyci5tYXAoeCA9PiB4ICogeCk7Il19

View File

@@ -0,0 +1,25 @@
import assert from "assert";
import fs from "fs";
import path from "path";
import { parse } from "../lib";
function fixture(...args) {
return path.join(__dirname, "fixtures", "parse", ...args);
}
describe("parse", function() {
it("should parse using configuration from .babelrc when a filename is provided", function() {
const input = fs.readFileSync(fixture("input.js"), "utf8");
const output = fs.readFileSync(fixture("output.json"), "utf8");
assert(
parse(input, { filename: fixture("input.js"), cwd: fixture() }),
output,
);
});
it("should parse using passed in configuration", function() {
const input = fs.readFileSync(fixture("input.js"), "utf8");
const output = fs.readFileSync(fixture("output.json"), "utf8");
assert(parse(input, { parserOpts: { plugins: ["decorators"] } }), output);
});
});

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/generator",
"version": "7.0.0-beta.37",
"version": "7.0.0-beta.40",
"description": "Turns an AST into code.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -11,14 +11,14 @@
"lib"
],
"dependencies": {
"@babel/types": "7.0.0-beta.37",
"@babel/types": "7.0.0-beta.40",
"jsesc": "^2.5.1",
"lodash": "^4.2.0",
"source-map": "^0.5.0",
"trim-right": "^1.0.1"
},
"devDependencies": {
"@babel/helper-fixtures": "7.0.0-beta.37",
"babylon": "7.0.0-beta.37"
"@babel/helper-fixtures": "7.0.0-beta.40",
"babylon": "7.0.0-beta.40"
}
}

View File

@@ -95,7 +95,34 @@ export function Decorator(node: Object) {
this.newline();
}
export function CallExpression(node: Object) {
export function OptionalMemberExpression(node: Object) {
this.print(node.object, node);
if (!node.computed && t.isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
}
let computed = node.computed;
if (t.isLiteral(node.property) && typeof node.property.value === "number") {
computed = true;
}
if (node.optional) {
this.token("?.");
}
if (computed) {
this.token("[");
this.print(node.property, node);
this.token("]");
} else {
if (!node.optional) {
this.token(".");
}
this.print(node.property, node);
}
}
export function OptionalCallExpression(node: Object) {
this.print(node.callee, node);
this.print(node.typeParameters, node); // TS
@@ -108,6 +135,15 @@ export function CallExpression(node: Object) {
this.token(")");
}
export function CallExpression(node: Object) {
this.print(node.callee, node);
this.print(node.typeParameters, node); // TS
this.token("(");
this.printList(node.arguments, node);
this.token(")");
}
export function Import() {
this.word("import");
}
@@ -203,17 +239,12 @@ export function MemberExpression(node: Object) {
computed = true;
}
if (node.optional) {
this.token("?.");
}
if (computed) {
this.token("[");
this.print(node.property, node);
this.token("]");
} else {
if (!node.optional) {
this.token(".");
}
this.token(".");
this.print(node.property, node);
}
}

View File

@@ -475,6 +475,14 @@ export function TypeCastExpression(node: Object) {
this.token(")");
}
export function Variance(node: Object) {
if (node.kind === "plus") {
this.token("+");
} else {
this.token("-");
}
}
export function VoidTypeAnnotation() {
this.word("void");
}

View File

@@ -124,7 +124,7 @@ export function NumericLiteral(node: Object) {
}
}
export function StringLiteral(node: Object, parent: Object) {
export function StringLiteral(node: Object) {
const raw = this.getPossibleRaw(node);
if (!this.format.minified && raw != null) {
this.token(raw);
@@ -133,7 +133,7 @@ export function StringLiteral(node: Object, parent: Object) {
// ensure the output is ASCII-safe
const opts = {
quotes: t.isJSX(parent) ? "double" : this.format.quotes,
quotes: "double",
wrap: true,
};
if (this.format.jsonCompatibleStrings) {

View File

@@ -46,7 +46,6 @@ function normalizeOptions(code, opts): Format {
compact: opts.compact,
minified: opts.minified,
concise: opts.concise,
quotes: "double",
jsonCompatibleStrings: opts.jsonCompatibleStrings,
indent: {
adjustMultilineComment: true,

View File

@@ -19,7 +19,6 @@ export type Format = {
auxiliaryCommentAfter: string,
compact: boolean | "auto",
minified: boolean,
quotes: "single" | "double",
concise: boolean,
indent: {
adjustMultilineComment: boolean,

Some files were not shown because too many files have changed in this diff Show More